cangyeone commited on
Commit
a0d589c
·
verified ·
1 Parent(s): 55d0147

Validate multi-output phase-candidate extension

Browse files

Add output eligibility and registry files, support-stratified manual-reference validation, build scripts, and query documentation.

README.md CHANGED
@@ -78,7 +78,7 @@ The repository is organized as follows:
78
  data/
79
  hdf5/ # 14 daily HDF5 waveform files
80
  index/ # SQLite waveform index
81
- label/ # annotations, reference tables, optional consensus and all-model catalogue
82
  response/ # instrument-response JSON for dataloader correction/simulation
83
  validation/ # machine-readable audits and optional phase-matching diagnostics
84
  notebooks/ # interactive quickstart notebook
@@ -115,11 +115,15 @@ non-standardized example outputs. Regenerate it with
115
  consistency and interoperability check, not a model comparison or ground truth.
116
  The script reads versioned C0 flags from `reference_arrivals.sqlite`, which was
117
  independently generated from exact NSLC intervals and finite HDF5 samples.
118
- The optional compressed all-model catalogue under `data/label/` retains every
119
  source pick from nine non-standardized example runs and groups station-phase
120
  records with a strict span below 1.5 s. It provides compact JSONL and normalized
121
- SQLite representations for querying output agreement; multi-model support is
122
- not ground truth or a relative model assessment. See
 
 
 
 
123
  `data/label/README_all_model_phase_picks.md` for the schema and examples.
124
  The quickstart notebook
125
  `notebooks/seismicx_cont_quickstart.ipynb` demonstrates file checks, SQLite
@@ -134,7 +138,8 @@ Current `scripts/` contents:
134
  | `scripts/README_event_comparison.md` | Event-comparison workflow notes and metric definitions. |
135
  | `scripts/README_real_association.md` | REAL association setup, inputs, outputs, and tuning notes. |
136
  | `scripts/build_consensus_picks_json.py` | Build consensus picker annotations from model pick outputs. |
137
- | `scripts/build_all_model_phase_catalog.py` | Build the compact all-model phase-candidate JSONL and SQLite products. |
 
138
  | `scripts/build_waveform_index.sh` | Build the full-release SQLite waveform index from HDF5 files. |
139
  | `scripts/compare_associated_events.py` | Compare associated events against catalog/reference events. |
140
  | `scripts/download_instrument_responses.py` | Download station instrument-response metadata. |
@@ -156,7 +161,8 @@ Current `scripts/` contents:
156
  | `scripts/upload_files_to_ms.py` | Upload selected full-release data files to ModelScope. |
157
  | `scripts/upload_restfiles_hf.py` | Upload non-bulk release files to Hugging Face. |
158
  | `scripts/upload_restfiles_ms.py` | Upload `scripts/` and `utils/` updates to ModelScope. |
159
- | `scripts/upload_all_model_phase_catalog.py` | Upload the compressed all-model catalogue and its documentation. |
 
160
  | `scripts/verify_full_dataset.py` | Verify full-release required files and basic structure. |
161
  | `scripts/write_manifest.sh` | Regenerate release checksum and file-size manifests. |
162
 
@@ -187,9 +193,12 @@ Recommended quickstart and reproducibility order:
187
  6. If the optional source picker JSONL files are present, regenerate the
188
  multi-output agreement layer with
189
  `./essd_scripts/regenerate_multimodel_phase_matching.sh`.
190
- 7. Query the optional all-model candidate catalogue after decompressing
191
  `data/label/all_model_phase_picks.sqlite.zst`; schema and examples are in
192
  `data/label/README_all_model_phase_picks.md`.
 
 
 
193
 
194
  ---
195
 
 
78
  data/
79
  hdf5/ # 14 daily HDF5 waveform files
80
  index/ # SQLite waveform index
81
+ label/ # annotations, reference tables, optional consensus and multi-output catalogue
82
  response/ # instrument-response JSON for dataloader correction/simulation
83
  validation/ # machine-readable audits and optional phase-matching diagnostics
84
  notebooks/ # interactive quickstart notebook
 
115
  consistency and interoperability check, not a model comparison or ground truth.
116
  The script reads versioned C0 flags from `reference_arrivals.sqlite`, which was
117
  independently generated from exact NSLC intervals and finite HDF5 samples.
118
+ The optional compressed multi-output catalogue under `data/label/` retains every
119
  source pick from nine non-standardized example runs and groups station-phase
120
  records with a strict span below 1.5 s. It provides compact JSONL and normalized
121
+ SQLite representations for querying output agreement. The adjacent
122
+ `output_eligibility.sqlite` records processed station-time intervals, and
123
+ `output_registry.tsv` documents the nine source output streams. The released
124
+ support-stratified validation table reports agreement with C0 manual references,
125
+ not conventional precision. Output support is not ground truth or a relative
126
+ model assessment. See
127
  `data/label/README_all_model_phase_picks.md` for the schema and examples.
128
  The quickstart notebook
129
  `notebooks/seismicx_cont_quickstart.ipynb` demonstrates file checks, SQLite
 
138
  | `scripts/README_event_comparison.md` | Event-comparison workflow notes and metric definitions. |
139
  | `scripts/README_real_association.md` | REAL association setup, inputs, outputs, and tuning notes. |
140
  | `scripts/build_consensus_picks_json.py` | Build consensus picker annotations from model pick outputs. |
141
+ | `scripts/build_all_model_phase_catalog.py` | Build the compact multi-output phase-candidate JSONL and SQLite products. |
142
+ | `scripts/build_output_eligibility.py` | Build processed station-time eligibility intervals and the output registry. |
143
  | `scripts/build_waveform_index.sh` | Build the full-release SQLite waveform index from HDF5 files. |
144
  | `scripts/compare_associated_events.py` | Compare associated events against catalog/reference events. |
145
  | `scripts/download_instrument_responses.py` | Download station instrument-response metadata. |
 
161
  | `scripts/upload_files_to_ms.py` | Upload selected full-release data files to ModelScope. |
162
  | `scripts/upload_restfiles_hf.py` | Upload non-bulk release files to Hugging Face. |
163
  | `scripts/upload_restfiles_ms.py` | Upload `scripts/` and `utils/` updates to ModelScope. |
164
+ | `scripts/upload_all_model_phase_catalog.py` | Upload the compressed multi-output catalogue and its documentation. |
165
+ | `scripts/validate_multi_output_candidates.py` | Reproduce support-stratified C0 manual-reference agreement. |
166
  | `scripts/verify_full_dataset.py` | Verify full-release required files and basic structure. |
167
  | `scripts/write_manifest.sh` | Regenerate release checksum and file-size manifests. |
168
 
 
193
  6. If the optional source picker JSONL files are present, regenerate the
194
  multi-output agreement layer with
195
  `./essd_scripts/regenerate_multimodel_phase_matching.sh`.
196
+ 7. Query the optional multi-output candidate catalogue after decompressing
197
  `data/label/all_model_phase_picks.sqlite.zst`; schema and examples are in
198
  `data/label/README_all_model_phase_picks.md`.
199
+ 8. Use `data/label/output_eligibility.sqlite` for processed-domain queries and
200
+ `data/validation/multi_output_manual_reference_match.tsv` for the released
201
+ support-stratified catalogue-agreement summary.
202
 
203
  ---
204
 
README.zh.md CHANGED
@@ -30,7 +30,7 @@ quick-start notebook,便于对发布文件进行可复现访问。
30
  data/
31
  hdf5/ # 14 个 daily HDF5 波形文件
32
  index/ # SQLite 波形索引
33
- label/ # annotation、reference 表、可选 consensus 与全模型候选目录
34
  response/ # 仪器响应 JSON,用于 dataloader 去响应/仿真
35
  validation/ # 机器可读审计与可选多输出震相匹配诊断
36
  notebooks/ # 交互式 quickstart notebook
@@ -56,10 +56,13 @@ utils/ # 可复用 HDF5 dataloader 和 waveform-index API
56
  与文件互操作检查,不是模型比较,也不构成 ground truth。该脚本复用
57
  `reference_arrivals.sqlite` 中已经由精确 NSLC 区间和有限 HDF5 样点生成的版本化
58
  C0 标志,避免对每个输出重复扫描完整波形归档。
59
- `data/label/` 下的可选全模型候选目录保留九个非标准化示例运行的全部源拾取,
60
  并在同一台站、同一 canonical 震相且严格小于 1.5 秒的时间跨度内聚合。
61
- 发布格式包括压缩 JSONL 和规范化 SQLite,便于查询输出一致性;多模型支持不等同于
62
- ground truth也不能用于相对模型评估。字段和查询示例见
 
 
 
63
  `data/label/README_all_model_phase_picks.md`。
64
  `notebooks/seismicx_cont_quickstart.ipynb` 提供文件检查、SQLite 查询、HDF5 波形绘图、annotation 检查和评估命令模板。
65
 
@@ -71,7 +74,8 @@ ground truth,也不能用于相对模型评估。字段和查询示例见
71
  | `scripts/README_event_comparison.md` | 事件对比流程说明和指标定义。 |
72
  | `scripts/README_real_association.md` | REAL 关联的配置、输入输出和参数说明。 |
73
  | `scripts/build_consensus_picks_json.py` | 从多个模型拾取结果构建 consensus pick annotation。 |
74
- | `scripts/build_all_model_phase_catalog.py` | 构建紧凑的全模型候选 JSONL 和 SQLite 数据产品。 |
 
75
  | `scripts/build_waveform_index.sh` | 从 HDF5 文件构建完整发布的 SQLite 波形索引。 |
76
  | `scripts/compare_associated_events.py` | 将关联事件与目录/参考事件进行对比。 |
77
  | `scripts/download_instrument_responses.py` | 下载台站仪器响应元数据。 |
@@ -93,7 +97,8 @@ ground truth,也不能用于相对模型评估。字段和查询示例见
93
  | `scripts/upload_files_to_ms.py` | 上传指定完整发布数据文件到 ModelScope。 |
94
  | `scripts/upload_restfiles_hf.py` | 上传非大体量发布文件到 Hugging Face。 |
95
  | `scripts/upload_restfiles_ms.py` | 上传 `scripts/` 和 `utils/` 更新到 ModelScope。 |
96
- | `scripts/upload_all_model_phase_catalog.py` | 上传压缩的全模型候选目录及其说明。 |
 
97
  | `scripts/verify_full_dataset.py` | 检查完整发布的必需文件和基本结构。 |
98
  | `scripts/write_manifest.sh` | 重新生成发布 checksum 和 file-size manifest。 |
99
 
@@ -119,8 +124,10 @@ ground truth,也不能用于相对模型评估。字段和查询示例见
119
  5. 用 `./essd_scripts/reproduce_manuscript_outputs.sh` 一键复现 ESSD 论文表格和图。
120
  6. 如已下载可选的 picker JSONL 源文件,用
121
  `./essd_scripts/regenerate_multimodel_phase_matching.sh` 重建多输出匹配诊断层。
122
- 7. 解压 `data/label/all_model_phase_picks.sqlite.zst` 后查询可选全模型候选目录;
123
  字段和示例见 `data/label/README_all_model_phase_picks.md`。
 
 
124
 
125
  ---
126
 
 
30
  data/
31
  hdf5/ # 14 个 daily HDF5 波形文件
32
  index/ # SQLite 波形索引
33
+ label/ # annotation、reference 表、可选 consensus 与多输出候选目录
34
  response/ # 仪器响应 JSON,用于 dataloader 去响应/仿真
35
  validation/ # 机器可读审计与可选多输出震相匹配诊断
36
  notebooks/ # 交互式 quickstart notebook
 
56
  与文件互操作检查,不是模型比较,也不构成 ground truth。该脚本复用
57
  `reference_arrivals.sqlite` 中已经由精确 NSLC 区间和有限 HDF5 样点生成的版本化
58
  C0 标志,避免对每个输出重复扫描完整波形归档。
59
+ `data/label/` 下的可选多输出候选目录保留九个非标准化示例运行的全部源拾取,
60
  并在同一台站、同一 canonical 震相且严格小于 1.5 秒的时间跨度内聚合。
61
+ 发布格式包括压缩 JSONL 和规范化 SQLite,便于查询输出一致性;
62
+ `output_eligibility.sqlite` 记录各输出实际处理的台站-时间区间
63
+ `output_registry.tsv` 记录九组源输出的组成和处理范围。分层验证表给出与 C0
64
+ 人工参考震相的一致比例,而不是传统 precision。多输出支持不等同于 ground truth,
65
+ 也不能用于相对模型评估。字段和查询示例见
66
  `data/label/README_all_model_phase_picks.md`。
67
  `notebooks/seismicx_cont_quickstart.ipynb` 提供文件检查、SQLite 查询、HDF5 波形绘图、annotation 检查和评估命令模板。
68
 
 
74
  | `scripts/README_event_comparison.md` | 事件对比流程说明和指标定义。 |
75
  | `scripts/README_real_association.md` | REAL 关联的配置、输入输出和参数说明。 |
76
  | `scripts/build_consensus_picks_json.py` | 从多个模型拾取结果构建 consensus pick annotation。 |
77
+ | `scripts/build_all_model_phase_catalog.py` | 构建紧凑的多输出候选 JSONL 和 SQLite 数据产品。 |
78
+ | `scripts/build_output_eligibility.py` | 构建输出处理区间 eligibility 数据库和 output registry。 |
79
  | `scripts/build_waveform_index.sh` | 从 HDF5 文件构建完整发布的 SQLite 波形索引。 |
80
  | `scripts/compare_associated_events.py` | 将关联事件与目录/参考事件进行对比。 |
81
  | `scripts/download_instrument_responses.py` | 下载台站仪器响应元数据。 |
 
97
  | `scripts/upload_files_to_ms.py` | 上传指定完整发布数据文件到 ModelScope。 |
98
  | `scripts/upload_restfiles_hf.py` | 上传非大体量发布文件到 Hugging Face。 |
99
  | `scripts/upload_restfiles_ms.py` | 上传 `scripts/` 和 `utils/` 更新到 ModelScope。 |
100
+ | `scripts/upload_all_model_phase_catalog.py` | 上传压缩的多输出候选目录及其说明。 |
101
+ | `scripts/validate_multi_output_candidates.py` | 复现按支持层级划分的 C0 人工参考一致性统计。 |
102
  | `scripts/verify_full_dataset.py` | 检查完整发布的必需文件和基本结构。 |
103
  | `scripts/write_manifest.sh` | 重新生成发布 checksum 和 file-size manifest。 |
104
 
 
124
  5. 用 `./essd_scripts/reproduce_manuscript_outputs.sh` 一键复现 ESSD 论文表格和图。
125
  6. 如已下载可选的 picker JSONL 源文件,用
126
  `./essd_scripts/regenerate_multimodel_phase_matching.sh` 重建多输出匹配诊断层。
127
+ 7. 解压 `data/label/all_model_phase_picks.sqlite.zst` 后查询可选多输出候选目录;
128
  字段和示例见 `data/label/README_all_model_phase_picks.md`。
129
+ 8. 使用 `data/label/output_eligibility.sqlite` 查询各输出的实际处理域,并用
130
+ `data/validation/multi_output_manual_reference_match.tsv` 检查发布的支持分层结果。
131
 
132
  ---
133
 
data/label/README_all_model_phase_picks.md CHANGED
@@ -1,4 +1,4 @@
1
- # All-model phase-candidate catalogue
2
 
3
  This optional layer combines all released automatic-pick streams into a compact,
4
  queryable candidate catalogue. It is intended for output inspection,
@@ -12,10 +12,17 @@ ground truth, or a standardized comparison of the contributing pickers.
12
  - `all_model_phase_picks.sqlite.zst`: the same candidates and all contributing
13
  source records in a normalized SQLite database;
14
  - `all_model_phase_picks.metadata.json`: schema, model dictionary, build policy,
15
- source counts, and output sizes; and
 
 
 
 
16
  - `../preview/all_model_phase_picks.preview.jsonl`: 100 uncompressed example
17
  records.
18
 
 
 
 
19
  The current build contains 49,689,373 candidates from 124,403,181 source picks
20
  produced by nine non-standardized picker runs. Of these candidates, 35,638,688
21
  have one contributing model and 14,050,685 have at least two. These support
@@ -33,12 +40,46 @@ model additional weight. All source records are retained. The model-support
33
  count is the number of unique contributing models, and single-model candidates
34
  are retained explicitly.
35
 
 
 
 
 
36
  The contributing runs used different checkpoints, preprocessing, channel
37
  choices, thresholds, training domains, and inference settings. The catalogue
38
  must therefore not be used as a picker leaderboard or as evidence of relative
39
  model performance. Catalogue-unmatched picks are likewise not confirmed false
40
  detections.
41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  ## Compact JSONL schema
43
 
44
  Each decompressed line has the following keys:
@@ -92,6 +133,9 @@ WHERE c.n_models >= 3
92
  ORDER BY c.time_us;
93
  ```
94
 
95
- Regenerate the layer with `scripts/run_all_model_phase_catalog.sh`. The build is
 
 
 
96
  resumable and records legacy non-standard JSON constants found in ancillary
97
  source diagnostic fields without discarding otherwise valid phase picks.
 
1
+ # Multi-output phase-candidate catalogue
2
 
3
  This optional layer combines all released automatic-pick streams into a compact,
4
  queryable candidate catalogue. It is intended for output inspection,
 
12
  - `all_model_phase_picks.sqlite.zst`: the same candidates and all contributing
13
  source records in a normalized SQLite database;
14
  - `all_model_phase_picks.metadata.json`: schema, model dictionary, build policy,
15
+ source counts, and output sizes;
16
+ - `output_eligibility.sqlite`: processed station-location/time intervals for
17
+ each source output;
18
+ - `output_registry.tsv`: output family/checkpoint fields, processing scope, and
19
+ pick counts; and
20
  - `../preview/all_model_phase_picks.preview.jsonl`: 100 uncompressed example
21
  records.
22
 
23
+ Support-stratified matching to C0 manual references is released as
24
+ `../validation/multi_output_manual_reference_match.json` and `.tsv`.
25
+
26
  The current build contains 49,689,373 candidates from 124,403,181 source picks
27
  produced by nine non-standardized picker runs. Of these candidates, 35,638,688
28
  have one contributing model and 14,050,685 have at least two. These support
 
40
  count is the number of unique contributing models, and single-model candidates
41
  are retained explicitly.
42
 
43
+ Here a "model" field identifies a source output stream. It is not necessarily a
44
+ statistically independent architecture or model family. Use
45
+ `output_registry.tsv` when family-level interpretation is needed.
46
+
47
  The contributing runs used different checkpoints, preprocessing, channel
48
  choices, thresholds, training domains, and inference settings. The catalogue
49
  must therefore not be used as a picker leaderboard or as evidence of relative
50
  model performance. Catalogue-unmatched picks are likewise not confirmed false
51
  detections.
52
 
53
+ ## Output eligibility
54
+
55
+ Raw candidate support is directly available as JSONL key `n` or SQLite column
56
+ `n_models`. Normalizing support requires the number of external outputs that
57
+ actually processed the same station-location and time. The
58
+ `output_eligibility.sqlite` database supplies those intervals; eligibility is
59
+ derived from a processed sample record, never from the absence of a pick.
60
+
61
+ ```sql
62
+ SELECT COUNT(DISTINCT output_id) AS n_eligible_outputs
63
+ FROM output_eligibility
64
+ WHERE station_id = 'BK.BDM.00'
65
+ AND processed_start_us <= 1561999764604538
66
+ AND processed_end_us >= 1561999764604538
67
+ AND valid_input = 1
68
+ AND (phase_mask & 1) != 0; -- P=1, S=2
69
+ ```
70
+
71
+ The eligibility intervals document channel family and components but cannot
72
+ recover undocumented internal preprocessing or training-data overlap. When an
73
+ assessed workflow contributed to the catalogue, remove its members and rebuild
74
+ the affected candidate groups before calculating leave-one-output-out support.
75
+
76
+ ## Manual-reference agreement
77
+
78
+ Run `scripts/validate_multi_output_candidates.py` to reproduce the 0.5 s,
79
+ one-to-one matches to C0-covered manual reference arrivals. The released table
80
+ reports `manual_reference_match_fraction`, not precision: the event catalogue
81
+ is not an exhaustive truth set for continuous signals.
82
+
83
  ## Compact JSONL schema
84
 
85
  Each decompressed line has the following keys:
 
133
  ORDER BY c.time_us;
134
  ```
135
 
136
+ Regenerate the layer with `scripts/run_all_model_phase_catalog.sh`, construct
137
+ eligibility intervals with `scripts/build_output_eligibility.py`, and regenerate
138
+ manual-reference agreement with `scripts/validate_multi_output_candidates.py`.
139
+ The candidate build is
140
  resumable and records legacy non-standard JSON constants found in ancillary
141
  source diagnostic fields without discarding otherwise valid phase picks.
data/label/output_eligibility.sqlite ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d14b19914f75ebff6c60afca93d61a661bc86583685f4647696a9f27071481d8
3
+ size 73695232
data/label/output_registry.tsv ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ output_id output_name model_workflow_family checkpoint training_domain possible_evaluation_overlap threshold phase_classes channel_families processed_intervals processed_station_location_keys processed_station_hours source_pick_count
2
+ 0 lppnm LPPNM not documented not documented not documented not documented P,S HN,BH,HH,EH 21200 994 245641.129 4628109
3
+ 1 phasenet PhaseNet not documented not documented not documented not documented P,S BH,HH,HN,EH 20884 993 238245.223 41503939
4
+ 2 pnsn_v1 PNSN v1 (from output identifier) not documented not documented not documented P,S BH,HH,HN,EH 21200 994 243937.369 6783670
5
+ 3 pnsn_v3_5120 PNSN v3_5120 (from output identifier) not documented not documented not documented P,S BH,HH,HN,EH 21200 994 242308.583 17933533
6
+ 4 pnsn.v3.diff PNSN v3.diff (from output identifier) not documented not documented not documented P,S BH,HH,HN,EH 21200 994 242794.026 17805916
7
+ 5 seismicxm.01 SeismicXM 01 (from output identifier) not documented not documented not documented P,S HH,HN,BH,EH 21200 994 241676.952 17309291
8
+ 6 seist SeisT not documented not documented not documented not documented P,S BH,HN,EH,HH 21200 994 241588.796 13027713
9
+ 7 skynet SkyNet not documented not documented not documented not documented P,S HN,BH,HH,EH 21200 994 248646.072 4302639
10
+ 8 ustc_sc USTC-SC not documented not documented not documented not documented P,S BH,HH,HN,EH 289 111 2664.0 1108371
data/preview/seismicx_cont_file_index.csv CHANGED
@@ -17,8 +17,12 @@ index,coverage,coverage,"CI;NC;BK",data/index/waveform_index.sqlite,SQLite wavef
17
  metadata,annotations,annotations,"CI;NC;BK",data/label/,metadata,Annotation station and consensus-pick metadata tables
18
  metadata,response,response,"CI;NC;BK",data/response/instrument_responses.json,metadata,Instrument-response metadata used for response removal and simulation
19
  validation,phase_matching,phase_matching,"CI;NC;BK",data/validation/multimodel_phase_matching/,validation,Optional non-standardized one-to-one phase-agreement and interoperability records
20
- optional_output,all_model_phases,all_model_phases,"CI;NC;BK",data/label/all_model_phase_picks.jsonl.zst,Zstandard JSONL,Compact all-model phase candidates with one candidate per decompressed line
21
- optional_output,all_model_phases,all_model_phases,"CI;NC;BK",data/label/all_model_phase_picks.sqlite.zst,Zstandard SQLite,Queryable all-model phase candidates and contributing source picks
 
 
 
 
22
  documentation,docs,docs,"CI;NC;BK",README.md,documentation,Dataset documentation and usage instructions
23
  code,scripts,scripts,"CI;NC;BK",scripts/,code,Conversion indexing validation picker association and upload scripts
24
  code,utils,utils,"CI;NC;BK",utils/,code,Reusable HDF5 dataloader and waveform-index APIs
 
17
  metadata,annotations,annotations,"CI;NC;BK",data/label/,metadata,Annotation station and consensus-pick metadata tables
18
  metadata,response,response,"CI;NC;BK",data/response/instrument_responses.json,metadata,Instrument-response metadata used for response removal and simulation
19
  validation,phase_matching,phase_matching,"CI;NC;BK",data/validation/multimodel_phase_matching/,validation,Optional non-standardized one-to-one phase-agreement and interoperability records
20
+ optional_output,multi_output_phases,multi_output_phases,"CI;NC;BK",data/label/all_model_phase_picks.jsonl.zst,Zstandard JSONL,Compact multi-output phase candidates with one candidate per decompressed line
21
+ optional_output,multi_output_phases,multi_output_phases,"CI;NC;BK",data/label/all_model_phase_picks.sqlite.zst,Zstandard SQLite,Queryable multi-output phase candidates and contributing source picks
22
+ optional_output,output_eligibility,output_eligibility,"CI;NC;BK",data/label/output_eligibility.sqlite,SQLite eligibility index,Processed station-location and time intervals for each contributing output
23
+ optional_output,output_registry,output_registry,"CI;NC;BK",data/label/output_registry.tsv,TSV registry,Output family checkpoint processing-scope and source-pick registry
24
+ validation,multi_output_manual_match,multi_output_manual_match,"CI;NC;BK",data/validation/multi_output_manual_reference_match.tsv,TSV validation,Support-stratified one-to-one agreement with C0 manual reference arrivals
25
+ validation,output_eligibility_summary,output_eligibility_summary,"CI;NC;BK",data/validation/output_eligibility_summary.json,JSON validation,Machine-readable eligibility database build and count summary
26
  documentation,docs,docs,"CI;NC;BK",README.md,documentation,Dataset documentation and usage instructions
27
  code,scripts,scripts,"CI;NC;BK",scripts/,code,Conversion indexing validation picker association and upload scripts
28
  code,utils,utils,"CI;NC;BK",utils/,code,Reusable HDF5 dataloader and waveform-index APIs
data/validation/multi_output_manual_reference_match.json ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "candidate_file": "data/label/all_model_phase_picks.jsonl.zst",
3
+ "candidate_records_checked": 49689373,
4
+ "interpretation": "Manual-reference match fraction is a catalogue-agreement diagnostic, not conventional precision; source annotations are not exhaustive.",
5
+ "matching": {
6
+ "canonical_phase_exact": true,
7
+ "objective": "maximize matches, then minimize total absolute residual",
8
+ "one_to_one": true,
9
+ "station_location_exact": true,
10
+ "tolerance_s": 0.5
11
+ },
12
+ "outside_selected_period_count": 2,
13
+ "outside_selected_period_examples": [
14
+ {
15
+ "candidate_id": 1763169,
16
+ "phase": "P",
17
+ "station_id": "BK.KARE.00",
18
+ "support": 1,
19
+ "time_us": 1562544015200000
20
+ },
21
+ {
22
+ "candidate_id": 43730351,
23
+ "phase": "P",
24
+ "station_id": "NC.MDPB.--",
25
+ "support": 1,
26
+ "time_us": 1636934415245000
27
+ }
28
+ ],
29
+ "reference_definition": "C0-covered manual_primary_reference arrivals",
30
+ "reference_file": "data/label/reference_arrivals.sqlite",
31
+ "rows": [
32
+ {
33
+ "c0_manual_reference_count": 89345,
34
+ "candidate_count": 13040519,
35
+ "manual_reference_match_fraction": 0.0002525973084353468,
36
+ "matched_candidate_count": 3294,
37
+ "median_absolute_residual_s": 0.0687,
38
+ "period": "2019",
39
+ "phase": "P",
40
+ "support_stratum": "support_1"
41
+ },
42
+ {
43
+ "c0_manual_reference_count": 89345,
44
+ "candidate_count": 3587802,
45
+ "manual_reference_match_fraction": 0.01940603188247289,
46
+ "matched_candidate_count": 69625,
47
+ "median_absolute_residual_s": 0.0377,
48
+ "period": "2019",
49
+ "phase": "P",
50
+ "support_stratum": "support_ge_2"
51
+ },
52
+ {
53
+ "c0_manual_reference_count": 89345,
54
+ "candidate_count": 1781088,
55
+ "manual_reference_match_fraction": 0.03775894284841625,
56
+ "matched_candidate_count": 67252,
57
+ "median_absolute_residual_s": 0.037336,
58
+ "period": "2019",
59
+ "phase": "P",
60
+ "support_stratum": "support_ge_3"
61
+ },
62
+ {
63
+ "c0_manual_reference_count": 106193,
64
+ "candidate_count": 7817926,
65
+ "manual_reference_match_fraction": 0.0006651380430052677,
66
+ "matched_candidate_count": 5200,
67
+ "median_absolute_residual_s": 0.0791,
68
+ "period": "2019",
69
+ "phase": "S",
70
+ "support_stratum": "support_1"
71
+ },
72
+ {
73
+ "c0_manual_reference_count": 106193,
74
+ "candidate_count": 5014983,
75
+ "manual_reference_match_fraction": 0.016275229646840278,
76
+ "matched_candidate_count": 81620,
77
+ "median_absolute_residual_s": 0.083992,
78
+ "period": "2019",
79
+ "phase": "S",
80
+ "support_stratum": "support_ge_2"
81
+ },
82
+ {
83
+ "c0_manual_reference_count": 106193,
84
+ "candidate_count": 2816294,
85
+ "manual_reference_match_fraction": 0.02757489097374067,
86
+ "matched_candidate_count": 77659,
87
+ "median_absolute_residual_s": 0.083921,
88
+ "period": "2019",
89
+ "phase": "S",
90
+ "support_stratum": "support_ge_3"
91
+ },
92
+ {
93
+ "c0_manual_reference_count": 1128,
94
+ "candidate_count": 9039351,
95
+ "manual_reference_match_fraction": 3.318822335807073e-07,
96
+ "matched_candidate_count": 3,
97
+ "median_absolute_residual_s": 0.0587,
98
+ "period": "2021",
99
+ "phase": "P",
100
+ "support_stratum": "support_1"
101
+ },
102
+ {
103
+ "c0_manual_reference_count": 1128,
104
+ "candidate_count": 2108343,
105
+ "manual_reference_match_fraction": 0.0004548595745568914,
106
+ "matched_candidate_count": 959,
107
+ "median_absolute_residual_s": 0.03616,
108
+ "period": "2021",
109
+ "phase": "P",
110
+ "support_stratum": "support_ge_2"
111
+ },
112
+ {
113
+ "c0_manual_reference_count": 1128,
114
+ "candidate_count": 916423,
115
+ "manual_reference_match_fraction": 0.0010453687871212311,
116
+ "matched_candidate_count": 958,
117
+ "median_absolute_residual_s": 0.036173,
118
+ "period": "2021",
119
+ "phase": "P",
120
+ "support_stratum": "support_ge_3"
121
+ },
122
+ {
123
+ "c0_manual_reference_count": 1246,
124
+ "candidate_count": 5740890,
125
+ "manual_reference_match_fraction": 8.709450973629525e-07,
126
+ "matched_candidate_count": 5,
127
+ "median_absolute_residual_s": 0.2997,
128
+ "period": "2021",
129
+ "phase": "S",
130
+ "support_stratum": "support_1"
131
+ },
132
+ {
133
+ "c0_manual_reference_count": 1246,
134
+ "candidate_count": 3339557,
135
+ "manual_reference_match_fraction": 0.00031411351864932984,
136
+ "matched_candidate_count": 1049,
137
+ "median_absolute_residual_s": 0.08141,
138
+ "period": "2021",
139
+ "phase": "S",
140
+ "support_stratum": "support_ge_2"
141
+ },
142
+ {
143
+ "c0_manual_reference_count": 1246,
144
+ "candidate_count": 1716295,
145
+ "manual_reference_match_fraction": 0.0006094523377391416,
146
+ "matched_candidate_count": 1046,
147
+ "median_absolute_residual_s": 0.081398,
148
+ "period": "2021",
149
+ "phase": "S",
150
+ "support_stratum": "support_ge_3"
151
+ }
152
+ ],
153
+ "schema": "seismicx-cont-multi-output-manual-match-v1",
154
+ "selected_period_candidate_records": 49689371
155
+ }
data/validation/multi_output_manual_reference_match.tsv ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ period phase support_stratum candidate_count c0_manual_reference_count matched_candidate_count manual_reference_match_fraction median_absolute_residual_s
2
+ 2019 P support_1 13040519 89345 3294 0.0002525973084353468 0.0687
3
+ 2019 P support_ge_2 3587802 89345 69625 0.01940603188247289 0.0377
4
+ 2019 P support_ge_3 1781088 89345 67252 0.03775894284841625 0.037336
5
+ 2019 S support_1 7817926 106193 5200 0.0006651380430052677 0.0791
6
+ 2019 S support_ge_2 5014983 106193 81620 0.016275229646840278 0.083992
7
+ 2019 S support_ge_3 2816294 106193 77659 0.02757489097374067 0.083921
8
+ 2021 P support_1 9039351 1128 3 3.318822335807073e-07 0.0587
9
+ 2021 P support_ge_2 2108343 1128 959 0.0004548595745568914 0.03616
10
+ 2021 P support_ge_3 916423 1128 958 0.0010453687871212311 0.036173
11
+ 2021 S support_1 5740890 1246 5 8.709450973629525e-07 0.2997
12
+ 2021 S support_ge_2 3339557 1246 1049 0.00031411351864932984 0.08141
13
+ 2021 S support_ge_3 1716295 1246 1046 0.0006094523377391416 0.081398
data/validation/output_eligibility_summary.json ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "database": "data/label/output_eligibility.sqlite",
3
+ "definition": "An interval is eligible when the source output contains a processed sample record for the station-location and time. Absence of a pick is not used to infer eligibility.",
4
+ "eligibility_intervals": 169573,
5
+ "outputs": 9,
6
+ "quick_check": "ok",
7
+ "registry": "data/label/output_registry.tsv",
8
+ "rows": [
9
+ {
10
+ "channel_families": "HN,BH,HH,EH",
11
+ "checkpoint": "not documented",
12
+ "model_workflow_family": "LPPNM",
13
+ "output_id": 0,
14
+ "output_name": "lppnm",
15
+ "phase_classes": "P,S",
16
+ "possible_evaluation_overlap": "not documented",
17
+ "processed_intervals": 21200,
18
+ "processed_station_hours": 245641.129,
19
+ "processed_station_location_keys": 994,
20
+ "source_pick_count": 4628109,
21
+ "threshold": "not documented",
22
+ "training_domain": "not documented"
23
+ },
24
+ {
25
+ "channel_families": "BH,HH,HN,EH",
26
+ "checkpoint": "not documented",
27
+ "model_workflow_family": "PhaseNet",
28
+ "output_id": 1,
29
+ "output_name": "phasenet",
30
+ "phase_classes": "P,S",
31
+ "possible_evaluation_overlap": "not documented",
32
+ "processed_intervals": 20884,
33
+ "processed_station_hours": 238245.223,
34
+ "processed_station_location_keys": 993,
35
+ "source_pick_count": 41503939,
36
+ "threshold": "not documented",
37
+ "training_domain": "not documented"
38
+ },
39
+ {
40
+ "channel_families": "BH,HH,HN,EH",
41
+ "checkpoint": "v1 (from output identifier)",
42
+ "model_workflow_family": "PNSN",
43
+ "output_id": 2,
44
+ "output_name": "pnsn_v1",
45
+ "phase_classes": "P,S",
46
+ "possible_evaluation_overlap": "not documented",
47
+ "processed_intervals": 21200,
48
+ "processed_station_hours": 243937.369,
49
+ "processed_station_location_keys": 994,
50
+ "source_pick_count": 6783670,
51
+ "threshold": "not documented",
52
+ "training_domain": "not documented"
53
+ },
54
+ {
55
+ "channel_families": "BH,HH,HN,EH",
56
+ "checkpoint": "v3_5120 (from output identifier)",
57
+ "model_workflow_family": "PNSN",
58
+ "output_id": 3,
59
+ "output_name": "pnsn_v3_5120",
60
+ "phase_classes": "P,S",
61
+ "possible_evaluation_overlap": "not documented",
62
+ "processed_intervals": 21200,
63
+ "processed_station_hours": 242308.583,
64
+ "processed_station_location_keys": 994,
65
+ "source_pick_count": 17933533,
66
+ "threshold": "not documented",
67
+ "training_domain": "not documented"
68
+ },
69
+ {
70
+ "channel_families": "BH,HH,HN,EH",
71
+ "checkpoint": "v3.diff (from output identifier)",
72
+ "model_workflow_family": "PNSN",
73
+ "output_id": 4,
74
+ "output_name": "pnsn.v3.diff",
75
+ "phase_classes": "P,S",
76
+ "possible_evaluation_overlap": "not documented",
77
+ "processed_intervals": 21200,
78
+ "processed_station_hours": 242794.026,
79
+ "processed_station_location_keys": 994,
80
+ "source_pick_count": 17805916,
81
+ "threshold": "not documented",
82
+ "training_domain": "not documented"
83
+ },
84
+ {
85
+ "channel_families": "HH,HN,BH,EH",
86
+ "checkpoint": "01 (from output identifier)",
87
+ "model_workflow_family": "SeismicXM",
88
+ "output_id": 5,
89
+ "output_name": "seismicxm.01",
90
+ "phase_classes": "P,S",
91
+ "possible_evaluation_overlap": "not documented",
92
+ "processed_intervals": 21200,
93
+ "processed_station_hours": 241676.952,
94
+ "processed_station_location_keys": 994,
95
+ "source_pick_count": 17309291,
96
+ "threshold": "not documented",
97
+ "training_domain": "not documented"
98
+ },
99
+ {
100
+ "channel_families": "BH,HN,EH,HH",
101
+ "checkpoint": "not documented",
102
+ "model_workflow_family": "SeisT",
103
+ "output_id": 6,
104
+ "output_name": "seist",
105
+ "phase_classes": "P,S",
106
+ "possible_evaluation_overlap": "not documented",
107
+ "processed_intervals": 21200,
108
+ "processed_station_hours": 241588.796,
109
+ "processed_station_location_keys": 994,
110
+ "source_pick_count": 13027713,
111
+ "threshold": "not documented",
112
+ "training_domain": "not documented"
113
+ },
114
+ {
115
+ "channel_families": "HN,BH,HH,EH",
116
+ "checkpoint": "not documented",
117
+ "model_workflow_family": "SkyNet",
118
+ "output_id": 7,
119
+ "output_name": "skynet",
120
+ "phase_classes": "P,S",
121
+ "possible_evaluation_overlap": "not documented",
122
+ "processed_intervals": 21200,
123
+ "processed_station_hours": 248646.072,
124
+ "processed_station_location_keys": 994,
125
+ "source_pick_count": 4302639,
126
+ "threshold": "not documented",
127
+ "training_domain": "not documented"
128
+ },
129
+ {
130
+ "channel_families": "BH,HH,HN,EH",
131
+ "checkpoint": "not documented",
132
+ "model_workflow_family": "USTC-SC",
133
+ "output_id": 8,
134
+ "output_name": "ustc_sc",
135
+ "phase_classes": "P,S",
136
+ "possible_evaluation_overlap": "not documented",
137
+ "processed_intervals": 289,
138
+ "processed_station_hours": 2664.0,
139
+ "processed_station_location_keys": 111,
140
+ "source_pick_count": 1108371,
141
+ "threshold": "not documented",
142
+ "training_domain": "not documented"
143
+ }
144
+ ],
145
+ "schema": "seismicx-cont-output-eligibility-v1"
146
+ }
scripts/build_output_eligibility.py ADDED
@@ -0,0 +1,409 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Build output processing-eligibility intervals and a compact registry.
3
+
4
+ The source picker JSONL files contain one or more records for every processed
5
+ station-day input. Phase-pick records retain exact sample geometry; ``no_pick``
6
+ records retain a pipe-delimited sample key. This script converts those records
7
+ into auditable output/station/time intervals. It does not infer eligibility from
8
+ the absence of picks.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ import calendar
15
+ import csv
16
+ import json
17
+ import sqlite3
18
+ from datetime import datetime, timezone
19
+ from pathlib import Path
20
+ from typing import Any, Iterable
21
+
22
+ try:
23
+ import orjson
24
+ except ImportError: # pragma: no cover - slower portability fallback
25
+ orjson = None
26
+
27
+
28
+ ROOT = Path(__file__).resolve().parents[1]
29
+ DEFAULT_METADATA = ROOT / "data/label/all_model_phase_picks.metadata.json"
30
+ DEFAULT_DB = ROOT / "data/label/output_eligibility.sqlite"
31
+ DEFAULT_REGISTRY = ROOT / "data/label/output_registry.tsv"
32
+ DEFAULT_SUMMARY = ROOT / "data/validation/output_eligibility_summary.json"
33
+
34
+ OUTPUT_REGISTRY = {
35
+ "lppnm": ("LPPNM", "not documented"),
36
+ "phasenet": ("PhaseNet", "not documented"),
37
+ "pnsn_v1": ("PNSN", "v1 (from output identifier)"),
38
+ "pnsn_v3_5120": ("PNSN", "v3_5120 (from output identifier)"),
39
+ "pnsn.v3.diff": ("PNSN", "v3.diff (from output identifier)"),
40
+ "seismicxm.01": ("SeismicXM", "01 (from output identifier)"),
41
+ "seist": ("SeisT", "not documented"),
42
+ "skynet": ("SkyNet", "not documented"),
43
+ "ustc_sc": ("USTC-SC", "not documented"),
44
+ }
45
+
46
+
47
+ def release_path(path: Path) -> str:
48
+ try:
49
+ return path.resolve().relative_to(ROOT).as_posix()
50
+ except ValueError:
51
+ return str(path.resolve())
52
+
53
+
54
+ def parse_json(line: bytes) -> dict[str, Any]:
55
+ if orjson is not None:
56
+ try:
57
+ return orjson.loads(line)
58
+ except orjson.JSONDecodeError:
59
+ pass
60
+ return json.loads(line)
61
+
62
+
63
+ def iso_to_us(value: str) -> int:
64
+ text = str(value)
65
+ if len(text) >= 19 and text[4] == "-" and text[10] == "T":
66
+ y = int(text[0:4])
67
+ m = int(text[5:7])
68
+ d = int(text[8:10])
69
+ hh = int(text[11:13])
70
+ mm = int(text[14:16])
71
+ ss = int(text[17:19])
72
+ fraction = 0
73
+ if len(text) > 19 and text[19] == ".":
74
+ digits = []
75
+ for char in text[20:]:
76
+ if not char.isdigit():
77
+ break
78
+ digits.append(char)
79
+ if len(digits) == 6:
80
+ break
81
+ fraction = int("".join(digits).ljust(6, "0")) if digits else 0
82
+ return (
83
+ calendar.timegm((y, m, d, hh, mm, ss)) * 1_000_000 + fraction
84
+ )
85
+ iso = text[:-1] + "+00:00" if text.endswith("Z") else text
86
+ dt = datetime.fromisoformat(iso)
87
+ if dt.tzinfo is None:
88
+ dt = dt.replace(tzinfo=timezone.utc)
89
+ return int(round(dt.timestamp() * 1_000_000))
90
+
91
+
92
+ def station_identifier(record: dict[str, Any]) -> str:
93
+ direct = record.get("station_id")
94
+ info = record.get("station_info") or {}
95
+ value = direct or info.get("station_id")
96
+ if not value:
97
+ network = info.get("network")
98
+ station = info.get("station")
99
+ location = info.get("location") or "--"
100
+ if not network or not station:
101
+ raise ValueError("record has no station identifier")
102
+ value = f"{network}.{station}.{location}"
103
+ parts = str(value).split(".")
104
+ if len(parts) >= 3 and not parts[2]:
105
+ parts[2] = "--"
106
+ return ".".join(parts[:3]) if len(parts) >= 3 else str(value)
107
+
108
+
109
+ def phase_pick_sample(record: dict[str, Any]) -> dict[str, Any]:
110
+ station = station_identifier(record)
111
+ h5_file = str(record["h5_file"])
112
+ day_id = str(record["day_id"])
113
+ family = str(record.get("channel_family") or "--")
114
+ channels = tuple(str(item) for item in (record.get("channels") or []))
115
+ sample_key = "|".join((h5_file, day_id, station, family, ",".join(channels)))
116
+ phase_time_us = iso_to_us(str(record["phase_time"]))
117
+ relative_us = int(round(float(record["phase_relative_time"]) * 1_000_000))
118
+ start_us = phase_time_us - relative_us
119
+ shape = record.get("waveform_shape") or []
120
+ sample_rate = float(record.get("sampling_rate") or 0.0)
121
+ if not shape or sample_rate <= 0:
122
+ raise ValueError("phase-pick record has no valid sample geometry")
123
+ end_us = start_us + int(round((int(shape[0]) - 1) * 1_000_000 / sample_rate))
124
+ return {
125
+ "sample_key": sample_key,
126
+ "station_id": station,
127
+ "start_us": start_us,
128
+ "end_us": end_us,
129
+ "channel_family": family,
130
+ "channels": ",".join(channels),
131
+ "h5_file": h5_file,
132
+ "day_id": day_id,
133
+ "interval_source": "sample_geometry",
134
+ }
135
+
136
+
137
+ def no_pick_sample(record: dict[str, Any]) -> dict[str, Any]:
138
+ value = str(record["sample_key"])
139
+ parts = value.split("|")
140
+ if len(parts) != 6:
141
+ raise ValueError(f"unexpected no_pick sample key: {value}")
142
+ h5_file, _year_id, day_id, station, family, channels = parts
143
+ start_us = iso_to_us(day_id)
144
+ return {
145
+ "sample_key": value,
146
+ "station_id": station,
147
+ "start_us": start_us,
148
+ "end_us": start_us + 86_400_000_000 - 1,
149
+ "channel_family": family,
150
+ "channels": channels,
151
+ "h5_file": h5_file,
152
+ "day_id": day_id,
153
+ "interval_source": "day_identifier_fallback",
154
+ }
155
+
156
+
157
+ def iter_samples(path: Path) -> Iterable[dict[str, Any]]:
158
+ current: dict[str, Any] | None = None
159
+ with path.open("rb") as stream:
160
+ for line_number, line in enumerate(stream, 1):
161
+ if not line.strip():
162
+ continue
163
+ record = parse_json(line)
164
+ record_type = record.get("record_type")
165
+ if record_type == "phase_pick":
166
+ sample = phase_pick_sample(record)
167
+ elif record_type == "no_pick":
168
+ sample = no_pick_sample(record)
169
+ else:
170
+ continue
171
+ if current is not None and sample["sample_key"] == current["sample_key"]:
172
+ current["start_us"] = min(current["start_us"], sample["start_us"])
173
+ current["end_us"] = max(current["end_us"], sample["end_us"])
174
+ continue
175
+ if current is not None:
176
+ yield current
177
+ current = sample
178
+ if current is not None:
179
+ yield current
180
+
181
+
182
+ def create_database(path: Path) -> sqlite3.Connection:
183
+ if path.exists():
184
+ path.unlink()
185
+ path.parent.mkdir(parents=True, exist_ok=True)
186
+ con = sqlite3.connect(path)
187
+ con.executescript(
188
+ """
189
+ PRAGMA page_size=32768;
190
+ PRAGMA journal_mode=WAL;
191
+ PRAGMA synchronous=NORMAL;
192
+ CREATE TABLE outputs (
193
+ output_id INTEGER PRIMARY KEY,
194
+ output_name TEXT NOT NULL UNIQUE,
195
+ model_workflow_family TEXT NOT NULL,
196
+ checkpoint TEXT NOT NULL,
197
+ training_domain TEXT NOT NULL,
198
+ possible_evaluation_overlap TEXT NOT NULL,
199
+ threshold TEXT NOT NULL,
200
+ phase_classes TEXT NOT NULL,
201
+ source_file TEXT NOT NULL,
202
+ source_pick_count INTEGER NOT NULL
203
+ );
204
+ CREATE TABLE eligibility_intervals (
205
+ interval_id INTEGER PRIMARY KEY,
206
+ output_id INTEGER NOT NULL REFERENCES outputs(output_id),
207
+ sample_key TEXT NOT NULL,
208
+ station_id TEXT NOT NULL,
209
+ processed_start_us INTEGER NOT NULL,
210
+ processed_end_us INTEGER NOT NULL,
211
+ phase_mask INTEGER NOT NULL,
212
+ channel_family TEXT NOT NULL,
213
+ channels TEXT NOT NULL,
214
+ h5_file TEXT NOT NULL,
215
+ day_id TEXT NOT NULL,
216
+ valid_input INTEGER NOT NULL,
217
+ interval_source TEXT NOT NULL,
218
+ UNIQUE(output_id, sample_key)
219
+ );
220
+ """
221
+ )
222
+ return con
223
+
224
+
225
+ def union_hours(con: sqlite3.Connection, output_id: int) -> float:
226
+ rows = con.execute(
227
+ """
228
+ SELECT station_id, processed_start_us, processed_end_us
229
+ FROM eligibility_intervals
230
+ WHERE output_id=? AND valid_input=1
231
+ ORDER BY station_id, processed_start_us, processed_end_us
232
+ """,
233
+ (output_id,),
234
+ )
235
+ total_us = 0
236
+ current_station = None
237
+ start = end = None
238
+ for station, left, right in rows:
239
+ if station != current_station or start is None or left > end + 1:
240
+ if start is not None:
241
+ total_us += end - start + 1
242
+ current_station = station
243
+ start, end = int(left), int(right)
244
+ else:
245
+ end = max(end, int(right))
246
+ if start is not None:
247
+ total_us += end - start + 1
248
+ return total_us / 3_600_000_000
249
+
250
+
251
+ def build(args: argparse.Namespace) -> None:
252
+ metadata = json.loads(args.metadata.read_text())
253
+ model_names = {int(key): value for key, value in metadata["models"].items()}
254
+ source_by_model = {
255
+ int(item["model_id"]): (ROOT / item["source_file"], int(item["counts"]["phase_picks"]))
256
+ for item in metadata["source_summaries"]
257
+ }
258
+ con = create_database(args.output_db)
259
+ registry_rows = []
260
+ for output_id in sorted(model_names):
261
+ name = model_names[output_id]
262
+ family, checkpoint = OUTPUT_REGISTRY.get(name, (name, "not documented"))
263
+ source, pick_count = source_by_model[output_id]
264
+ con.execute(
265
+ "INSERT INTO outputs VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
266
+ (
267
+ output_id,
268
+ name,
269
+ family,
270
+ checkpoint,
271
+ "not documented",
272
+ "not documented",
273
+ "not documented",
274
+ "P,S",
275
+ release_path(source),
276
+ pick_count,
277
+ ),
278
+ )
279
+ batch = []
280
+ for sample in iter_samples(source):
281
+ batch.append(
282
+ (
283
+ output_id,
284
+ sample["sample_key"],
285
+ sample["station_id"],
286
+ sample["start_us"],
287
+ sample["end_us"],
288
+ 3,
289
+ sample["channel_family"],
290
+ sample["channels"],
291
+ sample["h5_file"],
292
+ sample["day_id"],
293
+ 1,
294
+ sample["interval_source"],
295
+ )
296
+ )
297
+ if len(batch) >= 10_000:
298
+ con.executemany(
299
+ """
300
+ INSERT INTO eligibility_intervals(
301
+ output_id, sample_key, station_id, processed_start_us,
302
+ processed_end_us, phase_mask, channel_family, channels,
303
+ h5_file, day_id, valid_input, interval_source
304
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
305
+ ON CONFLICT(output_id, sample_key) DO UPDATE SET
306
+ processed_start_us=min(processed_start_us, excluded.processed_start_us),
307
+ processed_end_us=max(processed_end_us, excluded.processed_end_us)
308
+ """,
309
+ batch,
310
+ )
311
+ batch.clear()
312
+ if batch:
313
+ con.executemany(
314
+ """
315
+ INSERT INTO eligibility_intervals(
316
+ output_id, sample_key, station_id, processed_start_us,
317
+ processed_end_us, phase_mask, channel_family, channels,
318
+ h5_file, day_id, valid_input, interval_source
319
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
320
+ ON CONFLICT(output_id, sample_key) DO UPDATE SET
321
+ processed_start_us=min(processed_start_us, excluded.processed_start_us),
322
+ processed_end_us=max(processed_end_us, excluded.processed_end_us)
323
+ """,
324
+ batch,
325
+ )
326
+ con.commit()
327
+ stats = con.execute(
328
+ """
329
+ SELECT COUNT(*), COUNT(DISTINCT station_id), MIN(processed_start_us),
330
+ MAX(processed_end_us), GROUP_CONCAT(DISTINCT channel_family)
331
+ FROM eligibility_intervals WHERE output_id=?
332
+ """,
333
+ (output_id,),
334
+ ).fetchone()
335
+ registry_rows.append(
336
+ {
337
+ "output_id": output_id,
338
+ "output_name": name,
339
+ "model_workflow_family": family,
340
+ "checkpoint": checkpoint,
341
+ "training_domain": "not documented",
342
+ "possible_evaluation_overlap": "not documented",
343
+ "threshold": "not documented",
344
+ "phase_classes": "P,S",
345
+ "channel_families": stats[4] or "",
346
+ "processed_intervals": int(stats[0]),
347
+ "processed_station_location_keys": int(stats[1]),
348
+ "processed_station_hours": round(union_hours(con, output_id), 3),
349
+ "source_pick_count": pick_count,
350
+ }
351
+ )
352
+
353
+ con.executescript(
354
+ """
355
+ CREATE INDEX idx_eligibility_station_time
356
+ ON eligibility_intervals(station_id, processed_start_us, processed_end_us);
357
+ CREATE INDEX idx_eligibility_output_station_time
358
+ ON eligibility_intervals(output_id, station_id, processed_start_us, processed_end_us);
359
+ CREATE VIEW output_eligibility AS
360
+ SELECT e.interval_id, o.output_id, o.output_name,
361
+ o.model_workflow_family, e.station_id,
362
+ e.processed_start_us, e.processed_end_us,
363
+ e.phase_mask, e.channel_family, e.channels,
364
+ e.valid_input, e.interval_source, e.h5_file, e.day_id
365
+ FROM eligibility_intervals AS e JOIN outputs AS o USING (output_id);
366
+ """
367
+ )
368
+ quick_check = con.execute("PRAGMA quick_check").fetchone()[0]
369
+ interval_count = con.execute("SELECT COUNT(*) FROM eligibility_intervals").fetchone()[0]
370
+ con.execute("PRAGMA wal_checkpoint(TRUNCATE)")
371
+ con.execute("PRAGMA journal_mode=DELETE")
372
+ con.execute("VACUUM")
373
+ con.close()
374
+
375
+ args.registry.parent.mkdir(parents=True, exist_ok=True)
376
+ with args.registry.open("w", newline="") as stream:
377
+ writer = csv.DictWriter(stream, fieldnames=list(registry_rows[0]), delimiter="\t")
378
+ writer.writeheader()
379
+ writer.writerows(registry_rows)
380
+ summary = {
381
+ "schema": "seismicx-cont-output-eligibility-v1",
382
+ "definition": (
383
+ "An interval is eligible when the source output contains a processed "
384
+ "sample record for the station-location and time. Absence of a pick is "
385
+ "not used to infer eligibility."
386
+ ),
387
+ "outputs": len(registry_rows),
388
+ "eligibility_intervals": int(interval_count),
389
+ "database": release_path(args.output_db),
390
+ "registry": release_path(args.registry),
391
+ "quick_check": quick_check,
392
+ "rows": registry_rows,
393
+ }
394
+ args.summary.parent.mkdir(parents=True, exist_ok=True)
395
+ args.summary.write_text(json.dumps(summary, indent=2, sort_keys=True) + "\n")
396
+ print(json.dumps(summary, indent=2, sort_keys=True))
397
+
398
+
399
+ def parse_args() -> argparse.Namespace:
400
+ parser = argparse.ArgumentParser()
401
+ parser.add_argument("--metadata", type=Path, default=DEFAULT_METADATA)
402
+ parser.add_argument("--output-db", type=Path, default=DEFAULT_DB)
403
+ parser.add_argument("--registry", type=Path, default=DEFAULT_REGISTRY)
404
+ parser.add_argument("--summary", type=Path, default=DEFAULT_SUMMARY)
405
+ return parser.parse_args()
406
+
407
+
408
+ if __name__ == "__main__":
409
+ build(parse_args())
scripts/upload_all_model_phase_catalog.py CHANGED
@@ -1,5 +1,5 @@
1
  #!/usr/bin/env python3
2
- """Upload the compressed all-model phase catalogue to HF and ModelScope."""
3
 
4
  from __future__ import annotations
5
 
@@ -17,18 +17,30 @@ ASSETS = (
17
  "data/label/all_model_phase_picks.sqlite.zst",
18
  "data/label/all_model_phase_picks.metadata.json",
19
  "data/label/README_all_model_phase_picks.md",
 
 
20
  "data/preview/all_model_phase_picks.preview.jsonl",
21
  "data/preview/seismicx_cont_file_index.csv",
 
 
 
22
  "scripts/build_all_model_phase_catalog.py",
 
23
  "scripts/run_all_model_phase_catalog.sh",
24
  "scripts/upload_all_model_phase_catalog.py",
25
  "scripts/upload_restfiles_hf.py",
26
  "scripts/upload_restfiles_ms.py",
 
27
  "scripts/verify_full_dataset.py",
28
  "README.md",
29
  "README.zh.md",
30
  )
31
 
 
 
 
 
 
32
 
33
  def validate_assets() -> list[tuple[Path, str]]:
34
  assets = [(ROOT / rel, rel) for rel in ASSETS]
@@ -58,17 +70,33 @@ def upload_huggingface(repo_id: str, assets: list[tuple[Path, str]]) -> str:
58
  from huggingface_hub import CommitOperationAdd, HfApi
59
 
60
  api = HfApi()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  info = api.create_commit(
62
  repo_id=repo_id,
63
  repo_type="dataset",
64
  operations=[
65
  CommitOperationAdd(path_in_repo=rel, path_or_fileobj=str(path))
66
- for path, rel in assets
67
  ],
68
- commit_message="Add compact all-model phase-candidate catalogue",
69
  commit_description=(
70
- "Add compressed JSONL and SQLite products, machine-readable schema, "
71
- "preview, build scripts, and query documentation."
72
  ),
73
  num_threads=4,
74
  )
@@ -91,8 +119,33 @@ def upload_modelscope(repo_id: str, assets: list[tuple[Path, str]]) -> list[str]
91
  from modelscope.hub.api import HubApi
92
 
93
  api = HubApi()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
  revisions = []
95
- for path, rel in assets:
96
  info = api.upload_file(
97
  path_or_fileobj=str(path),
98
  path_in_repo=rel,
@@ -103,7 +156,7 @@ def upload_modelscope(repo_id: str, assets: list[tuple[Path, str]]) -> list[str]
103
  commit_message=f"Update {rel}",
104
  )
105
  revisions.append(str(getattr(info, "commit_url", info)))
106
- remote: dict[str, int] = {}
107
  page = 1
108
  while True:
109
  batch = api.get_dataset_files(
 
1
  #!/usr/bin/env python3
2
+ """Upload the optional multi-output phase catalogue to HF and ModelScope."""
3
 
4
  from __future__ import annotations
5
 
 
17
  "data/label/all_model_phase_picks.sqlite.zst",
18
  "data/label/all_model_phase_picks.metadata.json",
19
  "data/label/README_all_model_phase_picks.md",
20
+ "data/label/output_eligibility.sqlite",
21
+ "data/label/output_registry.tsv",
22
  "data/preview/all_model_phase_picks.preview.jsonl",
23
  "data/preview/seismicx_cont_file_index.csv",
24
+ "data/validation/multi_output_manual_reference_match.json",
25
+ "data/validation/multi_output_manual_reference_match.tsv",
26
+ "data/validation/output_eligibility_summary.json",
27
  "scripts/build_all_model_phase_catalog.py",
28
+ "scripts/build_output_eligibility.py",
29
  "scripts/run_all_model_phase_catalog.sh",
30
  "scripts/upload_all_model_phase_catalog.py",
31
  "scripts/upload_restfiles_hf.py",
32
  "scripts/upload_restfiles_ms.py",
33
+ "scripts/validate_multi_output_candidates.py",
34
  "scripts/verify_full_dataset.py",
35
  "README.md",
36
  "README.zh.md",
37
  )
38
 
39
+ BULK_IMMUTABLE_ASSETS = {
40
+ "data/label/all_model_phase_picks.jsonl.zst",
41
+ "data/label/all_model_phase_picks.sqlite.zst",
42
+ }
43
+
44
 
45
  def validate_assets() -> list[tuple[Path, str]]:
46
  assets = [(ROOT / rel, rel) for rel in ASSETS]
 
70
  from huggingface_hub import CommitOperationAdd, HfApi
71
 
72
  api = HfApi()
73
+ remote_before = {
74
+ item.path: item.size
75
+ for item in api.get_paths_info(
76
+ repo_id=repo_id,
77
+ repo_type="dataset",
78
+ paths=sorted(BULK_IMMUTABLE_ASSETS),
79
+ )
80
+ }
81
+ upload_assets = [
82
+ (path, rel)
83
+ for path, rel in assets
84
+ if rel not in BULK_IMMUTABLE_ASSETS
85
+ or remote_before.get(rel) != path.stat().st_size
86
+ ]
87
+ skipped = len(assets) - len(upload_assets)
88
+ print(f"Hugging Face upload files: {len(upload_assets)}; unchanged bulk files: {skipped}")
89
  info = api.create_commit(
90
  repo_id=repo_id,
91
  repo_type="dataset",
92
  operations=[
93
  CommitOperationAdd(path_in_repo=rel, path_or_fileobj=str(path))
94
+ for path, rel in upload_assets
95
  ],
96
+ commit_message="Validate multi-output phase-candidate extension",
97
  commit_description=(
98
+ "Add output eligibility and registry files, support-stratified "
99
+ "manual-reference validation, build scripts, and query documentation."
100
  ),
101
  num_threads=4,
102
  )
 
119
  from modelscope.hub.api import HubApi
120
 
121
  api = HubApi()
122
+ remote: dict[str, int] = {}
123
+ page = 1
124
+ while True:
125
+ batch = api.get_dataset_files(
126
+ repo_id,
127
+ revision="master",
128
+ recursive=True,
129
+ page_number=page,
130
+ page_size=100,
131
+ )
132
+ if not isinstance(batch, list):
133
+ raise RuntimeError(f"unexpected ModelScope file-list response: {type(batch)}")
134
+ for item in batch:
135
+ if item.get("Type") == "blob":
136
+ remote[str(item.get("Path"))] = int(item.get("Size") or 0)
137
+ if len(batch) < 100:
138
+ break
139
+ page += 1
140
+ upload_assets = [
141
+ (path, rel)
142
+ for path, rel in assets
143
+ if rel not in BULK_IMMUTABLE_ASSETS or remote.get(rel) != path.stat().st_size
144
+ ]
145
+ skipped = len(assets) - len(upload_assets)
146
+ print(f"ModelScope upload files: {len(upload_assets)}; unchanged bulk files: {skipped}")
147
  revisions = []
148
+ for path, rel in upload_assets:
149
  info = api.upload_file(
150
  path_or_fileobj=str(path),
151
  path_in_repo=rel,
 
156
  commit_message=f"Update {rel}",
157
  )
158
  revisions.append(str(getattr(info, "commit_url", info)))
159
+ remote = {}
160
  page = 1
161
  while True:
162
  batch = api.get_dataset_files(
scripts/upload_restfiles_hf.py CHANGED
@@ -41,7 +41,12 @@ additional_release_paths = {
41
  "data/label/all_model_phase_picks.sqlite.zst",
42
  "data/label/all_model_phase_picks.metadata.json",
43
  "data/label/README_all_model_phase_picks.md",
 
 
44
  "data/preview/all_model_phase_picks.preview.jsonl",
 
 
 
45
  }
46
  # =========================
47
 
 
41
  "data/label/all_model_phase_picks.sqlite.zst",
42
  "data/label/all_model_phase_picks.metadata.json",
43
  "data/label/README_all_model_phase_picks.md",
44
+ "data/label/output_eligibility.sqlite",
45
+ "data/label/output_registry.tsv",
46
  "data/preview/all_model_phase_picks.preview.jsonl",
47
+ "data/validation/multi_output_manual_reference_match.json",
48
+ "data/validation/multi_output_manual_reference_match.tsv",
49
+ "data/validation/output_eligibility_summary.json",
50
  }
51
  # =========================
52
 
scripts/upload_restfiles_ms.py CHANGED
@@ -35,7 +35,12 @@ additional_release_paths = {
35
  "data/label/all_model_phase_picks.sqlite.zst",
36
  "data/label/all_model_phase_picks.metadata.json",
37
  "data/label/README_all_model_phase_picks.md",
 
 
38
  "data/preview/all_model_phase_picks.preview.jsonl",
 
 
 
39
  }
40
  # =========================
41
 
 
35
  "data/label/all_model_phase_picks.sqlite.zst",
36
  "data/label/all_model_phase_picks.metadata.json",
37
  "data/label/README_all_model_phase_picks.md",
38
+ "data/label/output_eligibility.sqlite",
39
+ "data/label/output_registry.tsv",
40
  "data/preview/all_model_phase_picks.preview.jsonl",
41
+ "data/validation/multi_output_manual_reference_match.json",
42
+ "data/validation/multi_output_manual_reference_match.tsv",
43
+ "data/validation/output_eligibility_summary.json",
44
  }
45
  # =========================
46
 
scripts/validate_multi_output_candidates.py ADDED
@@ -0,0 +1,303 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Validate multi-output support strata against C0 manual references.
3
+
4
+ Each support stratum is matched independently with deterministic, time-ordered
5
+ one-to-one station/phase assignment. The objective first maximizes matches
6
+ within the declared tolerance and then minimizes total absolute residual.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import bisect
13
+ import csv
14
+ import io
15
+ import json
16
+ import math
17
+ import sqlite3
18
+ from dataclasses import dataclass
19
+ from pathlib import Path
20
+ from statistics import median
21
+ from typing import Any
22
+
23
+ import orjson
24
+ import zstandard as zstd
25
+
26
+
27
+ ROOT = Path(__file__).resolve().parents[1]
28
+ DEFAULT_CANDIDATES = ROOT / "data/label/all_model_phase_picks.jsonl.zst"
29
+ DEFAULT_REFERENCES = ROOT / "data/label/reference_arrivals.sqlite"
30
+ DEFAULT_JSON = ROOT / "data/validation/multi_output_manual_reference_match.json"
31
+ DEFAULT_TSV = ROOT / "data/validation/multi_output_manual_reference_match.tsv"
32
+
33
+ PERIODS = {
34
+ "2019": (1_561_939_200_000_000, 1_562_544_000_000_000),
35
+ "2021": (1_636_329_600_000_000, 1_636_934_400_000_000),
36
+ }
37
+ STRATA = {
38
+ "support_1": lambda value: value == 1,
39
+ "support_ge_2": lambda value: value >= 2,
40
+ "support_ge_3": lambda value: value >= 3,
41
+ }
42
+
43
+
44
+ @dataclass
45
+ class MatchState:
46
+ count: int
47
+ cost_us: int
48
+ parent: int
49
+ reference_index: int
50
+ candidate_index: int
51
+
52
+
53
+ def match_one_to_one(
54
+ references: list[int], candidates: list[int], tolerance_us: int
55
+ ) -> list[int]:
56
+ """Return signed residuals for a maximum-cardinality minimum-cost match."""
57
+ if not references or not candidates:
58
+ return []
59
+ states = [MatchState(0, 0, -1, -1, -1)]
60
+ fenwick = [0] * (len(candidates) + 1)
61
+
62
+ def better(left_id: int, right_id: int) -> int:
63
+ left = states[left_id]
64
+ right = states[right_id]
65
+ left_key = (left.count, -left.cost_us)
66
+ right_key = (right.count, -right.cost_us)
67
+ if left_key != right_key:
68
+ return left_id if left_key > right_key else right_id
69
+ left_tie = (left.candidate_index, left.reference_index, left_id)
70
+ right_tie = (right.candidate_index, right.reference_index, right_id)
71
+ return left_id if left_tie < right_tie else right_id
72
+
73
+ def query(candidate_index_exclusive: int) -> int:
74
+ best_id = 0
75
+ index = candidate_index_exclusive
76
+ while index > 0:
77
+ best_id = better(best_id, fenwick[index])
78
+ index -= index & -index
79
+ return best_id
80
+
81
+ def update(candidate_index: int, state_id: int) -> None:
82
+ index = candidate_index + 1
83
+ while index < len(fenwick):
84
+ fenwick[index] = better(fenwick[index], state_id)
85
+ index += index & -index
86
+
87
+ for reference_index, reference_time in enumerate(references):
88
+ left = bisect.bisect_left(candidates, reference_time - tolerance_us)
89
+ right = bisect.bisect_right(candidates, reference_time + tolerance_us)
90
+ pending = []
91
+ for candidate_index in range(left, right):
92
+ previous_id = query(candidate_index)
93
+ previous = states[previous_id]
94
+ residual = candidates[candidate_index] - reference_time
95
+ state_id = len(states)
96
+ states.append(
97
+ MatchState(
98
+ previous.count + 1,
99
+ previous.cost_us + abs(residual),
100
+ previous_id,
101
+ reference_index,
102
+ candidate_index,
103
+ )
104
+ )
105
+ pending.append((candidate_index, state_id))
106
+ for candidate_index, state_id in pending:
107
+ update(candidate_index, state_id)
108
+
109
+ residuals = []
110
+ state_id = query(len(candidates))
111
+ while state_id:
112
+ state = states[state_id]
113
+ residuals.append(
114
+ candidates[state.candidate_index] - references[state.reference_index]
115
+ )
116
+ state_id = state.parent
117
+ residuals.reverse()
118
+ return residuals
119
+
120
+
121
+ def load_references(path: Path) -> tuple[dict[tuple[str, str, str], list[int]], dict[tuple[str, str], int]]:
122
+ con = sqlite3.connect(path)
123
+ rows = con.execute(
124
+ """
125
+ SELECT period, station_id, phase, pick_time_epoch
126
+ FROM reference_arrivals
127
+ WHERE c0_point_covered=1 AND manual_primary_reference=1
128
+ ORDER BY period, station_id, phase, pick_time_epoch, arrival_id
129
+ """
130
+ )
131
+ grouped: dict[tuple[str, str, str], list[int]] = {}
132
+ totals: dict[tuple[str, str], int] = {}
133
+ for period, station, phase, epoch in rows:
134
+ grouped.setdefault((str(period), str(station), str(phase)), []).append(
135
+ int(round(float(epoch) * 1_000_000))
136
+ )
137
+ key = (str(period), str(phase))
138
+ totals[key] = totals.get(key, 0) + 1
139
+ con.close()
140
+ return grouped, totals
141
+
142
+
143
+ def period_for_time(time_us: int) -> str | None:
144
+ for period, (left, right) in PERIODS.items():
145
+ if left <= time_us < right:
146
+ return period
147
+ return None
148
+
149
+
150
+ def validate(args: argparse.Namespace) -> None:
151
+ references, reference_totals = load_references(args.references)
152
+ accumulator: dict[tuple[str, str, str], dict[str, Any]] = {}
153
+ for period in PERIODS:
154
+ for phase in ("P", "S"):
155
+ for stratum in STRATA:
156
+ accumulator[(period, phase, stratum)] = {
157
+ "candidate_count": 0,
158
+ "residuals_us": [],
159
+ }
160
+
161
+ def process_group(station: str | None, phase: str | None, values: list[tuple[int, int]]) -> None:
162
+ if station is None or phase is None or not values:
163
+ return
164
+ for period, (left, right) in PERIODS.items():
165
+ period_values = [(time_us, support) for time_us, support in values if left <= time_us < right]
166
+ if not period_values:
167
+ continue
168
+ period_references = references.get((period, station, phase), [])
169
+ for stratum, predicate in STRATA.items():
170
+ candidate_times = [time_us for time_us, support in period_values if predicate(support)]
171
+ target = accumulator[(period, phase, stratum)]
172
+ target["candidate_count"] += len(candidate_times)
173
+ if period_references and candidate_times:
174
+ target["residuals_us"].extend(
175
+ match_one_to_one(period_references, candidate_times, args.tolerance_us)
176
+ )
177
+
178
+ current_station = None
179
+ current_phase = None
180
+ values: list[tuple[int, int]] = []
181
+ record_count = 0
182
+ outside_period_count = 0
183
+ outside_period_examples = []
184
+ with args.candidates.open("rb") as raw:
185
+ decompressor = zstd.ZstdDecompressor()
186
+ with decompressor.stream_reader(raw, read_across_frames=True) as reader:
187
+ stream = io.BufferedReader(reader, buffer_size=16 * 1024 * 1024)
188
+ for line in stream:
189
+ if not line.strip():
190
+ continue
191
+ record = orjson.loads(line)
192
+ station = str(record["s"])
193
+ phase = str(record["p"])
194
+ if current_station is None:
195
+ current_station, current_phase = station, phase
196
+ elif station != current_station or phase != current_phase:
197
+ process_group(current_station, current_phase, values)
198
+ current_station, current_phase = station, phase
199
+ values = []
200
+ values.append((int(record["t"]), int(record["n"])))
201
+ if period_for_time(int(record["t"])) is None:
202
+ outside_period_count += 1
203
+ if len(outside_period_examples) < 10:
204
+ outside_period_examples.append(
205
+ {
206
+ "candidate_id": int(record["id"]),
207
+ "station_id": station,
208
+ "phase": phase,
209
+ "time_us": int(record["t"]),
210
+ "support": int(record["n"]),
211
+ }
212
+ )
213
+ record_count += 1
214
+ process_group(current_station, current_phase, values)
215
+
216
+ rows = []
217
+ for period in PERIODS:
218
+ for phase in ("P", "S"):
219
+ for stratum in STRATA:
220
+ item = accumulator[(period, phase, stratum)]
221
+ residuals = item.pop("residuals_us")
222
+ candidate_count = int(item["candidate_count"])
223
+ matched_count = len(residuals)
224
+ absolute = [abs(value) / 1_000_000 for value in residuals]
225
+ rows.append(
226
+ {
227
+ "period": period,
228
+ "phase": phase,
229
+ "support_stratum": stratum,
230
+ "candidate_count": candidate_count,
231
+ "c0_manual_reference_count": reference_totals.get((period, phase), 0),
232
+ "matched_candidate_count": matched_count,
233
+ "manual_reference_match_fraction": (
234
+ matched_count / candidate_count if candidate_count else None
235
+ ),
236
+ "median_absolute_residual_s": median(absolute) if absolute else None,
237
+ }
238
+ )
239
+
240
+ expected = 49_689_373
241
+ phase_total = sum(
242
+ row["candidate_count"]
243
+ for row in rows
244
+ if row["support_stratum"] == "support_1"
245
+ ) + sum(
246
+ row["candidate_count"]
247
+ for row in rows
248
+ if row["support_stratum"] == "support_ge_2"
249
+ )
250
+ if record_count != expected or phase_total + outside_period_count != expected:
251
+ raise RuntimeError(
252
+ "candidate-count mismatch: "
253
+ f"streamed={record_count}, selected_strata={phase_total}, "
254
+ f"outside={outside_period_count}, expected={expected}"
255
+ )
256
+
257
+ payload = {
258
+ "schema": "seismicx-cont-multi-output-manual-match-v1",
259
+ "candidate_file": str(args.candidates.relative_to(ROOT)),
260
+ "reference_file": str(args.references.relative_to(ROOT)),
261
+ "reference_definition": "C0-covered manual_primary_reference arrivals",
262
+ "matching": {
263
+ "station_location_exact": True,
264
+ "canonical_phase_exact": True,
265
+ "one_to_one": True,
266
+ "objective": "maximize matches, then minimize total absolute residual",
267
+ "tolerance_s": args.tolerance_us / 1_000_000,
268
+ },
269
+ "candidate_records_checked": record_count,
270
+ "selected_period_candidate_records": phase_total,
271
+ "outside_selected_period_count": outside_period_count,
272
+ "outside_selected_period_examples": outside_period_examples,
273
+ "rows": rows,
274
+ "interpretation": (
275
+ "Manual-reference match fraction is a catalogue-agreement diagnostic, "
276
+ "not conventional precision; source annotations are not exhaustive."
277
+ ),
278
+ }
279
+ args.output_json.parent.mkdir(parents=True, exist_ok=True)
280
+ args.output_json.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n")
281
+ with args.output_tsv.open("w", newline="") as stream:
282
+ writer = csv.DictWriter(stream, fieldnames=list(rows[0]), delimiter="\t")
283
+ writer.writeheader()
284
+ writer.writerows(rows)
285
+ print(json.dumps(payload, indent=2, sort_keys=True))
286
+
287
+
288
+ def parse_args() -> argparse.Namespace:
289
+ parser = argparse.ArgumentParser()
290
+ parser.add_argument("--candidates", type=Path, default=DEFAULT_CANDIDATES)
291
+ parser.add_argument("--references", type=Path, default=DEFAULT_REFERENCES)
292
+ parser.add_argument("--tolerance-s", type=float, default=0.5)
293
+ parser.add_argument("--output-json", type=Path, default=DEFAULT_JSON)
294
+ parser.add_argument("--output-tsv", type=Path, default=DEFAULT_TSV)
295
+ args = parser.parse_args()
296
+ if args.tolerance_s <= 0:
297
+ parser.error("--tolerance-s must be positive")
298
+ args.tolerance_us = int(round(args.tolerance_s * 1_000_000))
299
+ return args
300
+
301
+
302
+ if __name__ == "__main__":
303
+ validate(parse_args())
scripts/verify_full_dataset.py CHANGED
@@ -147,6 +147,87 @@ def main() -> None:
147
  if mismatches:
148
  raise RuntimeError("all-model phase-catalogue file-size validation failed")
149
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
150
 
151
  if __name__ == "__main__":
152
  main()
 
147
  if mismatches:
148
  raise RuntimeError("all-model phase-catalogue file-size validation failed")
149
 
150
+ eligibility_db = root / "data" / "label" / "output_eligibility.sqlite"
151
+ registry_path = root / "data" / "label" / "output_registry.tsv"
152
+ agreement_path = (
153
+ root / "data" / "validation" / "multi_output_manual_reference_match.tsv"
154
+ )
155
+ if eligibility_db.is_file() or registry_path.is_file() or agreement_path.is_file():
156
+ required = (eligibility_db, registry_path, agreement_path)
157
+ missing = [str(path.relative_to(root)) for path in required if not path.is_file()]
158
+ if missing:
159
+ raise RuntimeError(
160
+ "incomplete multi-output validation extension: " + ", ".join(missing)
161
+ )
162
+
163
+ output_db = sqlite3.connect(eligibility_db)
164
+ eligibility_check = output_db.execute("PRAGMA quick_check").fetchone()[0]
165
+ n_outputs = output_db.execute("SELECT COUNT(*) FROM outputs").fetchone()[0]
166
+ n_intervals = output_db.execute(
167
+ "SELECT COUNT(*) FROM eligibility_intervals"
168
+ ).fetchone()[0]
169
+ bad_intervals = output_db.execute(
170
+ """
171
+ SELECT COUNT(*) FROM eligibility_intervals
172
+ WHERE processed_end_us < processed_start_us
173
+ OR valid_input NOT IN (0, 1)
174
+ OR phase_mask <= 0
175
+ """
176
+ ).fetchone()[0]
177
+ output_db.close()
178
+
179
+ with registry_path.open(newline="", encoding="utf-8") as handle:
180
+ registry = list(csv.DictReader(handle, delimiter="\t"))
181
+ source_picks = sum(int(row["source_pick_count"]) for row in registry)
182
+
183
+ with agreement_path.open(newline="", encoding="utf-8") as handle:
184
+ agreement = list(csv.DictReader(handle, delimiter="\t"))
185
+ grouped: dict[tuple[str, str], dict[str, float]] = {}
186
+ for row in agreement:
187
+ grouped.setdefault((row["period"], row["phase"]), {})[
188
+ row["support_stratum"]
189
+ ] = float(row["manual_reference_match_fraction"])
190
+ non_monotonic = []
191
+ for key, values in grouped.items():
192
+ ordered = [
193
+ values.get("support_1"),
194
+ values.get("support_ge_2"),
195
+ values.get("support_ge_3"),
196
+ ]
197
+ if any(value is None for value in ordered) or not (
198
+ ordered[0] <= ordered[1] <= ordered[2]
199
+ ):
200
+ non_monotonic.append(key)
201
+
202
+ print("Optional multi-output eligibility and validation extension:")
203
+ print(
204
+ " quick_check={}, outputs={}, intervals={:,}, registry_rows={}, "
205
+ "source_picks={:,}, agreement_rows={}, non_monotonic_groups={}".format(
206
+ eligibility_check,
207
+ n_outputs,
208
+ n_intervals,
209
+ len(registry),
210
+ source_picks,
211
+ len(agreement),
212
+ len(non_monotonic),
213
+ )
214
+ )
215
+ if eligibility_check != "ok" or bad_intervals:
216
+ raise RuntimeError("output-eligibility SQLite integrity validation failed")
217
+ if (n_outputs, n_intervals, len(registry), source_picks, len(agreement)) != (
218
+ 9,
219
+ 169_573,
220
+ 9,
221
+ 124_403_181,
222
+ 12,
223
+ ):
224
+ raise RuntimeError("multi-output extension count validation failed")
225
+ if non_monotonic:
226
+ raise RuntimeError(
227
+ "manual-reference match fractions are not monotonic for "
228
+ + ", ".join(f"{period}/{phase}" for period, phase in non_monotonic)
229
+ )
230
+
231
 
232
  if __name__ == "__main__":
233
  main()