Spaces:
Runtime error
Runtime error
sdd
#2
by jimmy60504 - opened
Files changed (20)
- .dockerignoreDeleted-13
- .gitignore-7
- Dockerfile.localDeleted-38
- README.md-148
- app.py+746-962
- build_local.shDeleted-16
- changelog.mdDeleted-265
- intensity_map/2021102413113465103_H.png → ground_truth/20240403.pngRenamed
- image_python.shDeleted-9
- intensity_map/2022091814441568111_H.pngDeleted
- intensity_map/2024040307580972019_H.pngDeleted
- intensity_map/2025012100172764007_H.pngDeleted
- model.pyDeleted-375
- requirements.txt+10-10
- run_local.shDeleted-20
- waveform/20211024.mseedDeleted-3
- waveform/20220918.mseedDeleted-3
- waveform/20240403.mseed+2-2
- waveform/20250120.mseedDeleted-3
- waveform/event.jsonDeleted-52
12345678910111213
```text# Single project (現況)# 注意:app.py 和 requirements.txt 需要被包含在 Docker image 中intensityMap.html```
**Structure Decision**: 維持單一專案根目錄佈局,Gradio 介面在 `app.py`;地圖以 HTML/folium/Gradio HTML 容器渲染。
## Complexity Tracking
N/A(無憲章違反項目需特別豁免)。
1234567/uv.lock.idea.venv__pycache__/*.pyc.env.DS_Store
1234567891011121314151617181920212223242526272829303132333435363738# syntax=docker/dockerfile:1FROM python:3.10-slim
ENV PYTHONDONTWRITEBYTECODE=1 \ PYTHONUNBUFFERED=1 \ PIP_NO_CACHE_DIR=1 \ GRADIO_SERVER_PORT=7860 \ GRADIO_SERVER_NAME=0.0.0.0 \ HOME=/home/user
# 建立非 root 使用者(與 HF Spaces 一致)RUN useradd -m -u 1000 user
# 基本系統套件與科學計算依賴RUN apt-get update && apt-get install -y --no-install-recommends \ build-essential \ libhdf5-dev \ libnetcdf-dev \ libopenblas-dev \ liblapack-dev \ git \ && rm -rf /var/lib/apt/lists/*
# 切換到使用者目錄WORKDIR $HOME/app
# 只複製 requirements.txt 並安裝COPY --chown=user:user requirements.txt .RUN pip install --upgrade pip && pip install -r requirements.txt
# 切換到非 root 使用者USER user
EXPOSE 7860
# 預設執行命令(可被 docker run 覆蓋)CMD ["python", "app.py"]
10 unmodified lines111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016110 unmodified lines---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference## 專案簡介TTSAM(Taiwan Transformer-based Shake Alert Model)是一個以 Transformer 為核心的地震預警/震度推估原型,提供互動式 GUI 用於載入歷史事件、查看波形、並在地圖上比對「預測震度」與「實際震度」。## 主要功能- 互動式 GUI(`app.py`):- 選擇歷史事件、時間窗、震央座標並載入波形。- 顯示輸入測站分布與波形(按震央距離排序)。- 執行模型推論並在 Folium 地圖上顯示預測震度(高度固定 800px)。- 若有實際震度圖,支援與預測對照;若缺失則以空白占位並提示。- 穩健的資料處理:- 取樣率固定 100 Hz;模型輸入固定 30 秒(不足補 0)。- 輸入測站最多 25 站;不足仍可推論並在 UI 顯示警告。- N/E 分量缺失時以 Z 替代,並統計缺分站數於摘要。- 目標點批次推論:- 目標測站每批最多 25 點,最後合併結果。- 場址參數與降級:- Vs30 以 `SeisBlue/TaiwanVs30` 下載為主;查詢/下載失敗時使用預設值 600 m/s 並記錄 log。- 易於擴充:- 不需改模型與核心流程即可新增事件與目標測站(更新資料檔即可)。## 設計思路### 🎯 Project Scope: 互動式教育展示 Demo本專案為地震模型的 **展覽演示系統**,而非生產級的早期預警系統。因此設計理念強調:- **互動性優先**:使用者操作立即反饋視覺化結果(波形圖、地圖、統計)- **教育性為中心**:清晰的介面與步驟引導,讓非地震專業人士理解「波形 → 模型 → 預測」的流程- **功能簡潔化**:無需追求完整覆蓋或極限性能;易於操作與理解最重要- **預裝化設計**:所有關鍵資源(模型權重、Vs30 資料庫、波形、測站表)預裝於 HF Space,無需運行時下載或外部依賴### 📦 預裝架構| 資源 | 位置 | 用途 | 預裝狀態 ||-----|-----|------|--------|| 模型權重 | `ttsam_trained_model_11.pt` | 推論核心 | ✅ 預裝 || Vs30 資料庫 | `Vs30ofTaiwan.nc` | 場址參數 | ✅ 預裝 || 波形資料 | `waveform/*.mseed` | 輸入資料 | ✅ 預裝(≥2 事件) || 測站表 | `station/site_info.csv`, `station/eew_target.csv` | 元資料 | ✅ 預裝 || 實際震度圖 | `intensity_map/YYYYMMDD.png` | 對照參考 | ✅ 預裝(可選) |### 🛡️ 容錯設計系統採用「**預裝優先,降級不中斷**」的容錯策略:- **預裝資源失敗**(模型損毀、測站表缺失)→ 應用無法啟動(提前發現問題)- **非關鍵資源失敗**(Vs30 初始化失敗、實際圖缺失)→ 使用預設值或占位,應用正常運作- **單點資料缺失**(缺分量、測站不足)→ 使用替代值或降級處理,UI 明示警告,推論繼續- **結果異常**(PGA 為 NaN)→ 記錄日誌,仍顯示於地圖詳見 `spec/03-error-handling.md`。### 🧪 展覽前檢查清單在部署至 HF Space 前:- [ ] 驗證所有預裝檔案完整(模型、Vs30、波形、測站表)- [ ] 本地測試啟動流程(無外部網路依賴)- [ ] 測試各事件的波形載入與預測- [ ] 確認實際震度圖路徑與檔名正確- [ ] 檢查日誌輸出(無錯誤訊息)需求- Python 3.10–3.11(建議)- 主要套件見 `requirements.txt`安裝與執行- 安裝相依套件- `pip install -r requirements.txt`- 執行 GUI- `python app.py`- 或使用腳本:`./run_local.sh`資料與資源- 事件波形:`waveform/*.mseed`- 實際震度圖(選用):`intensity_map/YYYYMMDD.png`- 站台資料:`station/site_info.csv`, `station/eew_target.csv`## 常見任務- 新增事件:- 將 `.mseed` 放入 `waveform/`,並更新 `app.py` 的 `EARTHQUAKE_EVENTS`。- 若有實際震度圖,放入 `intensity_map/`,檔名 `YYYYMMDD.png`。- 新增目標測站:- 於 `station/eew_target.csv` 增補列,欄位:`station, latitude, longitude, elevation`。- 新增輸入測站:- 於 `station/site_info.csv` 增補列,欄位:`Station, Latitude, Longitude, Elevation`;去除重複站名列。## 核心不變條件(摘要)**波形處理**:- 取樣率:100 Hz;輸入長度:30 秒(3000 點,不足補 0)- 分量順序:Z, N, E;N/E 缺失時以 Z 代替**測站處理**:- 輸入測站:最多 25;不足允許但 UI 會顯示警告- 目標測站批次:每批最多 25 點- 缺分量統計:計數並在摘要中顯示**資源管理**:- 地圖高度:Folium 地圖固定 800px- 實際震度圖缺失:以空白占位(不中止)- Vs30 查詢失敗:使用預設值 600 m/s**詳細規格**:見 `spec/00-overview.md` 與 `spec/01-data-contract.md`;**容錯與降級決策**見 `spec/03-error-handling.md`。## 專案結��- `app.py`:Gradio GUI 與推論主流程- `ttsam_realtime.py`:即時流程樣板(非 GUI 主流程)- `station/site_info.csv`:輸入測站表- `station/eew_target.csv`:目標測站表- `waveform/`:事件波形(.mseed)- `intensity_map/`:實際震度圖(可選)- `spec/`:模塊化規格檔案- `00-overview.md`:核心目標、架構、設計原則- `01-data-contract.md`:資料結構、必填欄位- `02-processing-rules.md`:批次策略、處理規則- `03-error-handling.md`:故障場景、容錯設計- `04-extensions.md`:擴充空間、向後相容- `.github/copilot-instructions.md`:生成程式碼指南- `changelog.md`:變更摘要## 疑難排解(Troubleshooting)- Vs30 下載失敗或查無資料- 行為:使用預設值 600 m/s;log 會有 WARNING 訊息。- 檢查網路或稍後再試;必要時在 UI/設定中調整預設值。- 實際震度圖缺失- 行為:左側顯示空白占位與提示;不影響預測地圖。- 少於 25 個輸入測站- 行為:UI 顯示警告,仍可推論。- 缺少 N/E 分量- 行為:以 Z 分量代替並在摘要統計。## 授權- License:GPL-3.0## 進一步閱讀- `spec/00-overview.md`(核心目標、架構、不變條件)- `spec/01-data-contract.md`(資料結構、必填欄位、冷啟動流程)- `spec/02-processing-rules.md`(批次策略、輸入限制、資源限制)- `spec/03-error-handling.md`(故障場景、降級策略、UI 訊息設計)- `spec/04-extensions.md`(擴充空間、向後相容性)- `.github/copilot-instructions.md`(開發與貢獻指南)- `changelog.md`(歷次變更摘要)10 unmodified lines11121310 unmodified lines---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
12345678910111213141516171 unmodified line192021222324252627282930313233341 unmodified line3637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814910 unmodified lines1601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082095 unmodified lines2152162172182192207 unmodified lines2282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263271 unmodified line3293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024031 unmodified line4054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964 unmodified lines5015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505 unmodified lines5565575585595605615625635645655665675685695705715721 unmodified line5745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106111 unmodified line6136146156166176186196206216226236246256266276282 unmodified lines6316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706712 unmodified lines67467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276315 unmodified lines779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011212 unmodified lines1124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561 unmodified line11581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336import gradio as grimport numpy as npimport pandas as pdimport plotly.graph_objs as goimport torchimport xarray as xrfrom huggingface_hub import hf_hub_downloadfrom loguru import loggerfrom obspy import readfrom obspy.signal.trigger import classic_sta_lta, trigger_onsetfrom scipy.signal import detrend, iirfilter, sosfilt, zpk2sosfrom scipy.spatial import cKDTreefrom model import get_full_modeltree = Nonevs30_table = None1 unmodified linetry:logger.info("從 Hugging Face 載入 Vs30 資料...")vs30_file = hf_hub_download(repo_id="SeisBlue/TaiwanVs30", filename="Vs30ofTaiwan.nc",repo_type="dataset")ds = xr.open_dataset(vs30_file)lat_flat = ds["lat"].values.flatten()lon_flat = ds["lon"].values.flatten()vs30_flat = ds["vs30"].values.flatten()vs30_table = pd.DataFrame({"lat": lat_flat, "lon": lon_flat, "Vs30": vs30_flat})vs30_table = vs30_table.replace([np.inf, -np.inf], np.nan).dropna()tree = cKDTree(vs30_table[["lat", "lon"]])logger.info("Vs30 資料載入完成")1 unmodified linelogger.warning(f"Vs30 資料載入失敗: {e}")logger.warning("將使用預設 Vs30 值 (600 m/s)")# 載入測站資訊(輸入測站,1000+ 個)site_info_file = "station/site_info.csv"site_info = Nonetry:logger.info(f"載入 {site_info_file}...")site_info = pd.read_csv(site_info_file)# 驗證 site_info.csv 必要欄位required_site_fields = ["Station", "Latitude", "Longitude", "Elevation"]missing_site_fields = [f for f in required_site_fields if f not in site_info.columns]if missing_site_fields:logger.error(f"{site_info_file} 缺少必要欄位: {missing_site_fields}")raise ValueError(f"site_info.csv 缺少必要欄位: {missing_site_fields}")# 只保留唯一的測站(去除重複的分量)site_info = site_info.drop_duplicates(subset=["Station"]).reset_index(drop=True)logger.info(f"{site_info_file} 載入完成,共 {len(site_info)} 個測站")except FileNotFoundError:logger.warning(f"{site_info_file} 找不到")except Exception as e:logger.error(f"{site_info_file} 載入失敗: {e}")# 載入目標測站target_file = "station/eew_target.csv"try:logger.info(f"載入 {target_file}...")target_df = pd.read_csv(target_file)# 驗證 eew_target.csv 必要欄位required_target_fields = ["station", "latitude", "longitude","elevation"]missing_target_fields = [f for f in required_target_fields if f not in target_df.columns]if missing_target_fields:logger.error(f"{target_file} 缺少必要欄位: {missing_target_fields}")raise ValueError(f"eew_target.csv 缺少必要欄位: {missing_target_fields}")target_dict = target_df.to_dict(orient="records")logger.info(f"{target_file} 載入完成(共 {len(target_dict)} 個目標點)")except FileNotFoundError:logger.error(f"{target_file} 找不到")except Exception as e:logger.error(f"{target_file} 載入失敗: {e}")# ============ 震央資訊管理 ============earthquake_metadata = {}event_json_path = "waveform/event.json"# STA/LTA 計算結果快取(避免每次滑桿更新都重算)# 結構: {event_name: {station_code: {"p_arrival_time": float, "cft": array}}}sta_lta_cache = {}try:import jsonwith open(event_json_path, "r", encoding="utf-8") as f:data = json.load(f)if "events" not in data:logger.error(f"{event_json_path} 缺少 'events' 鍵")# 將事件列表轉換為以 event_name 為鍵的字典for event in data["events"]:event_name = event.get("event_name")if event_name:earthquake_metadata[event_name] = {"event_id": event.get("event_id"),"event_name": event.get("event_name"),"timestamp": event.get("timestamp"),"first_pick": event.get("first_pick"),"mseed_file": event.get("mseed_file"),"intensity_map_file": event.get("intensity_map_file"),"epicenter_lat": event.get("epicenter_lat"),"epicenter_lon": event.get("epicenter_lon"),"depth_km": event.get("depth_km"),"magnitude": event.get("magnitude"),}logger.info(f"載入事件: {event_name} | 震央: ({event.get('epicenter_lon')}, {event.get('epicenter_lat')})")logger.info(f"地震事件元資料載入完成(共 {len(earthquake_metadata)} 個事件)")except FileNotFoundError:logger.error(f"事件元資料檔案缺失: {event_json_path}")except Exception as e:logger.error(f"讀取事件元資料時發生錯誤: {e}")# 載入模型model_path = hf_hub_download(repo_id="SeisBlue/TTSAM", filename="ttsam_trained_model_11.pt")model = get_full_model(model_path)# ============ 輔助函數 ============def lowpass(data, freq=10, df=100, corners=4):fe = 0.5 * dff = freq / fe10 unmodified linesreturn datadef detect_p_wave_sta_lta(trace, sta_len=0.1, lta_len=2, thr_on=1.5, thr_off=0.0001):"""使用 STA/LTA 方法偵測 P 波到時Parameters:- trace: ObsPy Trace object- sta_len: 短時窗長度(秒)- lta_len: 長時窗長度(秒)- thr_on: 觸發門檻(設為 2.0 以平衡偵測率與誤報率)- thr_off: 解除門檻Returns:- p_arrival_time: P 波到時(秒),若未偵測到則返回 None- cft: Characteristic function (STA/LTA 值)Note:- spec: P 波偵測為測站選擇的前置條件,未偵測到 P 波的測站將被排除- 降級策略:門檻設為 2.0,在偵測率與誤報率之間取得平衡"""try:sampling_rate = trace.stats.sampling_rate# 計算 STA/LTA characteristic functioncft = classic_sta_lta(trace.data, int(sta_len * sampling_rate),int(lta_len * sampling_rate))# 偵測觸發點triggers = trigger_onset(cft, thr_on, thr_off)if len(triggers) > 0:# 取第一個觸發點作為 P 波到時p_sample = triggers[0][0]p_arrival_time = p_sample / sampling_ratelogger.debug(f"測站 {trace.stats.station} 偵測到 P 波於 {p_arrival_time:.2f} 秒")return p_arrival_time, cftelse:logger.debug(f"測站 {trace.stats.station} 未偵測到 P 波")return None, cftexcept Exception as e:logger.warning(f"P 波偵測失敗: {e}")return None, Nonedef get_vs30(lat, lon, user_vs30=600):if tree is None or vs30_table is None:# 如果 Vs30 資料未載入,使用使用者輸入的值5 unmodified linesreturn float(vs30)def calculate_intensity(pga, label=False):intensity_label = ["0", "1", "2", "3", "4", "5-", "5+", "6-", "6+", "7"]pga_level = np.log10([1e-5, 0.008, 0.025, 0.080, 0.250, 0.80, 1.4, 2.5, 4.4, 8.0])7 unmodified linesreturn intensitydef convert_intensity(value):"""轉換震度字串為數值以便排序和比較"""if isinstance(value, (int, float)):return float(value)if value.endswith("+"):return float(value[:-1]) + 0.25elif value.endswith("-"):return float(value[:-1]) - 0.25else:return float(value)def generate_earthquake_alert_report(pga_list, target_names, event_name, duration):"""生成地震預警文字報告(僅顯示 4 級以上警報)Parameters:- pga_list: PGA 預測值列表- target_names: 目標測站名稱列表- event_name: 地震事件名稱- duration: P 波後時間長度Returns:- 格式化的警報文字報告"""# 收集各縣市的最高震度county_intensity = {}for i, target_name in enumerate(target_names):target = next((t for t in target_dict if t["station"] == target_name), None)if target and "county" in target:county = target["county"]intensity = calculate_intensity(pga_list[i])intensity_label = calculate_intensity(pga_list[i], label=True)# 只記錄 4 級以上if intensity >= 4:if county not in county_intensity:county_intensity[county] = intensity_labelelse:# 保留較高的震度if convert_intensity(intensity_label) > convert_intensity(county_intensity[county]):county_intensity[county] = intensity_label# 生成報告report_lines = []if county_intensity:# 按震度排序(高到低)county_list = sorted(county_intensity.items(),key=lambda x: convert_intensity(x[1]),reverse=True)for county, intensity in county_list:report_lines.append(f" {county} 預估震度 {intensity} 級")else:report_lines.append("【預測震度 ≥ 4 級地區】")report_lines.append("")report_lines.append(" 無縣市達 4 級以上")return "\n".join(report_lines)# ============ Gradio 介面函數 ============def calculate_distance(lat1, lon1, lat2, lon2):"""計算兩點間的距離(簡化的平面距離,單位:度)"""return np.sqrt((lat1 - lat2) ** 2 + (lon1 - lon2) ** 2)def select_nearest_stations(st, epicenter_lat, epicenter_lon, n_stations=25, event_name=None):"""從 site_info(1000+ 個輸入測站)中選擇距離震央最近的 n 個測站並使用 STA/LTA 偵測 P 波到時,只保留成功偵測到 P 波的測站少於 25 站可用:UI 明示實際用站數並允許繼續STA/LTA 結果會快取到全域 sta_lta_cache,避免滑桿更新時重複計算"""station_distances = {} # 改用字典避免重複p_wave_detected_count = 0p_wave_failed_count = 0cache_hit_count = 0cache_miss_count = 0# 初始化此事件的 cacheif event_name and event_name not in sta_lta_cache:sta_lta_cache[event_name] = {}logger.info(f"為事件 {event_name} 初始化 STA/LTA 快取")# 計算每個測站到震央的距離並偵測 P 波for tr in st:station_code = tr.stats.station1 unmodified lineif station_code in station_distances:continue# 從 site_info 中查詢測站位置(處理缺漏欄位)try:station_data = site_info[site_info["Station"] == station_code]if len(station_data) == 0:continue# 驗證必要欄位存在required_fields = ["Latitude", "Longitude", "Elevation"]missing_fields = [f for f in required_fields if f not in station_data.columns]if missing_fields:logger.warning(f"測站 {station_code} 缺少必要欄位: {missing_fields},跳過")continuelat = station_data["Latitude"].values[0]lon = station_data["Longitude"].values[0]elev = station_data["Elevation"].values[0]# 偵測 P 波(使用 Z 分量)- 優先使用快取if event_name and event_name in sta_lta_cache and station_code in sta_lta_cache[event_name]:# 使用快取的 STA/LTA 結果cached_result = sta_lta_cache[event_name][station_code]p_arrival_time = cached_result["p_arrival_time"]cft = cached_result["cft"]cache_hit_count += 1logger.debug(f"測站 {station_code} 使用快取的 STA/LTA 結果")else:# 重新計算 STA/LTAz_trace = st.select(station=station_code, component="Z")if len(z_trace) == 0:logger.debug(f"測站 {station_code} 無 Z 分量,跳過")p_wave_failed_count += 1continuep_arrival_time, cft = detect_p_wave_sta_lta(z_trace[0])cache_miss_count += 1# 快取 STA/LTA 結果if event_name:sta_lta_cache[event_name][station_code] = {"p_arrival_time": p_arrival_time,"cft": cft}logger.debug(f"測站 {station_code} STA/LTA 結果已快取")# 只保留成功偵測到 P 波的測站if p_arrival_time is None:logger.debug(f"測站 {station_code} 未偵測到 P 波,跳過")p_wave_failed_count += 1continuedistance = calculate_distance(epicenter_lat, epicenter_lon, lat, lon)station_distances[station_code] = {"station": station_code,"distance": distance,"latitude": lat,"longitude": lon,"elevation": elev,"p_arrival_time": p_arrival_time, # 記錄 P 波到時}p_wave_detected_count += 1except Exception as e:logger.warning(f"測站 {station_code} 資訊查詢失敗: {e}")p_wave_failed_count += 1continue# 轉換為列表並按距離排序,選擇最近的 n 個1 unmodified linestation_list.sort(key=lambda x: x["distance"])selected_stations = station_list[:n_stations]# 記錄實際可用的測站數(少於 25 站也允許繼續)actual_count = len(selected_stations)logger.info(f"P 波偵測結果: 成功 {p_wave_detected_count} 站, 失敗 {p_wave_failed_count} 站 | "f"STA/LTA 快取: 命中 {cache_hit_count} 次, 未命中 {cache_miss_count} 次")if actual_count < n_stations:logger.warning(f"僅找到 {actual_count} 個可用測站(目標 {n_stations} 個),將繼續處理")else:logger.info(f"從 {len(station_list)} 個輸入測站中選擇了最近的 {actual_count} 個")return selected_stationsdef extract_waveforms_from_stream(event_name,st, selected_stations, duration, vs30_input):"""從 Stream 中提取選定測站的波形資料Parameters:- st: ObsPy Stream object- selected_stations: 選定的測站列表- start_time: 開始時間(秒)- duration: 時間長度(秒)- vs30_input: Vs30 預設值Returns:- waveforms: 波形資料列表- station_info_list: 測站資訊列表- valid_stations: 有效測站列表- missing_components_count: 缺少分量的測站數量- p_wave_outside_window_count: P 波在時間窗外的測站數量Note:- 內部計算 end_time = start_time + duration- 若 duration < 30 秒,尾段以 0 遮罩補齊至 30 秒(3000 samples @ 100 Hz)- 缺少 N/E 分量時以 Z 分量代替,並在狀態訊息中記錄缺分量站數- 若 P 波到時不在時間窗內,跳過該測站(避免模型收到無訊號的空波形)"""waveforms = []station_info_list = []valid_stations = []missing_components_count = 0p_wave_outside_window_count = 0sampling_rate = 100 # 100 Hzmin_duration = 30.0 # 最小時間長度 30 秒target_length = 3000 # 30 秒 @ 100 Hz = 3000 samplesfirst_pick = earthquake_metadata[event_name]["first_pick"]# 內部計算 end_time(接受 start/duration 參數)end_time = first_pick + durationstart_idx = 0end_idx = int(end_time * sampling_rate)actual_samples = end_idx - start_idxlogger.info(f"波形提取範圍:[{start_idx/sampling_rate:.2f}s, {end_idx/sampling_rate:.2f}s] "f"= {actual_samples} samples (first_pick={first_pick:.2f}s, duration={duration}s)")# 檢查是否需要零填充:長度不足 30 秒時尾段以 0 遮罩補齊needs_padding = duration < min_durationif needs_padding:logger.info(f"時間長度 {duration} 秒 < 30 秒,將以 0 遮罩補齊至 {min_duration} 秒")for station_data in selected_stations:# 檢查 P 波到時是否在時間窗內p_arrival_time = station_data.get("p_arrival_time")if p_arrival_time is None or p_arrival_time < 0 or p_arrival_time > end_time:logger.debug(f"測站 {station_data['station']} 的 P 波到時 ({p_arrival_time:.2f}s) 不在時間窗內 (0-{end_time:.2f}s),跳過")p_wave_outside_window_count += 1continuestation_code = station_data["station"]station_missing_components = Falsetry:# 選擇該測站的所有分量4 unmodified lines# 嘗試取得 Z, N, E 分量z_trace = st_station.select(component="Z")n_trace = st_station.select(component="N") or st_station.select(component="1")e_trace = st_station.select(component="E") or st_station.select(component="2")# 檢查 Z 分量(必須存在)if len(z_trace) > 0:z_data = z_trace[0].data[start_idx:end_idx]logger.debug(f"測站 {station_code}: Z 分量切片長度 = {len(z_data)} samples")else:continue# 檢查 N 分量(缺失時以 Z 代替)if len(n_trace) > 0:n_data = n_trace[0].data[start_idx:end_idx]else:n_data = z_data.copy()station_missing_components = Truelogger.debug(f"測站 {station_code} 缺少 N 分量,以 Z 分量代替")# 檢查 E 分量(缺失時以 Z 代替)if len(e_trace) > 0:e_data = e_trace[0].data[start_idx:end_idx]else:e_data = z_data.copy()station_missing_components = Truelogger.debug(f"測站 {station_code} 缺少 E 分量,以 Z 分量代替")# 記錄缺少分量的測站(將在狀態訊息中顯示)if station_missing_components:missing_components_count += 1# 訊號處理z_data = signal_processing(z_data)n_data = signal_processing(n_data)e_data = signal_processing(e_data)# 創建全零陣列 (3000, 3) - 確保至少 30 秒長度# 不足 30 秒時,尾段以 0 遮罩補齊waveform_3c = np.zeros((target_length, 3))# 填入實際資料(處理長度不足或過長的情況)z_len = min(len(z_data), target_length)n_len = min(len(n_data), target_length)e_len = min(len(e_data), target_length)5 unmodified lineswaveforms.append(waveform_3c)# 準備測站資訊vs30 = get_vs30(station_data["latitude"], station_data["longitude"], vs30_input)station_info_list.append([station_data["latitude"],station_data["longitude"],station_data["elevation"],vs30,])valid_stations.append(station_data)except Exception as e:1 unmodified linecontinuelogger.info(f"成功提取 {len(waveforms)} 個測站的波形")if missing_components_count > 0:logger.info(f"其中 {missing_components_count} 個測站缺少 N 或 E 分量(已以 Z 分量代替)")if p_wave_outside_window_count > 0:logger.info(f"其中 {p_wave_outside_window_count} 個測站的 P 波不在時間窗內(已跳過)")return waveforms, station_info_list, valid_stations, missing_components_count, p_wave_outside_window_countdef plot_waveform(st, selected_stations, first_pick, duration):"""繪製選定測站的波形圖(距離-時間圖,可顯示全部 25 個測站)並標記 P 波到時,用顏色區分是否在時間窗內Parameters:- st: ObsPy Stream object- selected_stations: 選定的測站列表(包含快取的 p_arrival_time,避免重複計算 STA/LTA)- first_pick: 首次到達時間(秒)- duration: 時間長度(秒)Note: P 波到時資訊來自快取,不會重新計算 STA/LTA(提升反應速度)"""# 計算結束時間end_time = first_pick + durationlogger.debug(f"繪製波形圖(使用快取的 P 波到時資訊,共 {len(selected_stations)} 個測站)")# 創建 Plotly figurefig = go.Figure()# 設定振幅縮放比例(避免波形重疊)amplitude_scale = 0.03 # 可調整此值來控制波形大小1 unmodified lineplotted_count = 0distances = []station_names = []p_wave_markers_in = [] # P 波在時間窗內p_wave_markers_out = [] # P 波在時間窗外# 效能優化:降採樣因子(在 HF Space 環境下加速渲染)downsample_factor = 5 # 只取每 5 個點(100 Hz → 20 Hz,仍足夠顯示波形特徵)for i, station_data in enumerate(selected_stations):station_code = station_data["station"]distance = station_data["distance"]p_arrival_time = station_data.get("p_arrival_time")try:st_station = st.select(station=station_code)2 unmodified linestimes = tr.times()data = tr.data# 只顯示從資料開始到 120 秒內的波形time_mask = times <= 120.0times = times[time_mask]data = data[time_mask]# 效能優化:降採樣(減少數據點數量,加速渲染)times = times[::downsample_factor]data = data[::downsample_factor]# 正規化波形振幅data_normalized = data / (np.max(np.abs(data)) + 1e-10)# 繪製波形,Y軸位置為距離y_values = distance + data_normalized * amplitude_scale# 使用 Scattergl 加速渲染(WebGL 模式,適合大量數據點)fig.add_trace(go.Scattergl(x=times,y=y_values,mode='lines',line=dict(color='black', width=0.5),opacity=0.8,name=station_code,hovertemplate=f'{station_code}<br>Time: %{{x:.2f}}s<br>Distance: {distance:.3f}°<extra></extra>',showlegend=False))# 記錄 P 波標記位置if p_arrival_time is not None:if 0 <= p_arrival_time <= end_time:# P 波在時間窗內(綠色)p_wave_markers_in.append((p_arrival_time, distance, station_code))else:# P 波在時間窗外(紅色)p_wave_markers_out.append((p_arrival_time, distance, station_code))distances.append(distance)station_names.append(station_code)2 unmodified linesexcept Exception as e:logger.warning(f"無法繪製測站 {station_code}: {e}")# 繪製 P 波標記if p_wave_markers_in:p_times_in, p_dists_in, p_names_in = zip(*p_wave_markers_in)fig.add_trace(go.Scattergl(x=p_times_in,y=p_dists_in,mode='markers',marker=dict(color='green', size=8, symbol='triangle-down'),name='P-wave (in window)',hovertemplate='P-wave<br>Station: %{text}<br>Time: %{x:.2f}s<extra></extra>',text=p_names_in,showlegend=True))if p_wave_markers_out:p_times_out, p_dists_out, p_names_out = zip(*p_wave_markers_out)fig.add_trace(go.Scattergl(x=p_times_out,y=p_dists_out,mode='markers',marker=dict(color='red', size=8, symbol='triangle-down'),name='P-wave (out window)',hovertemplate='P-wave<br>Station: %{text}<br>Time: %{x:.2f}s<extra></extra>',text=p_names_out,showlegend=True))# 添加垂直線標記# First Motionfig.add_vline(x=first_pick,line=dict(color='blue', dash='dash', width=2),annotation_text='First Motion',annotation_position='top',opacity=0.7)# 標記選取時間範圍fig.add_vline(x=0,line=dict(color='red', dash='dash', width=2),opacity=0.7)fig.add_vline(x=end_time,line=dict(color='red', dash='dash', width=2),opacity=0.7)# 添加時間窗陰影fig.add_vrect(x0=0, x1=end_time,fillcolor='blue', opacity=0.1,layer='below', line_width=0,)# 設定軸標籤和標題fig.update_layout(xaxis=dict(title=dict(text='Time (s)', font=dict(size=12)),gridcolor='rgba(128, 128, 128, 0.2)',showgrid=True,),yaxis=dict(title=dict(text='Distance (°)', font=dict(size=12)),gridcolor='rgba(128, 128, 128, 0.2)',showgrid=False),hovermode='closest',height=200,plot_bgcolor='white',margin=dict(l=0, r=10, t=50, b=0), # 緊凑的邊距設置showlegend=True,legend=dict(yanchor="top",y=0.99,xanchor="right",x=0.99,bgcolor="rgba(255, 255, 255, 0.8)",),# 效能優化:簡化互動功能以加速渲染(HF Space 環境)dragmode='pan', # 只允許平移,不允許框選縮放)return fig15 unmodified linesreturn color_map.get(intensity, "#ffffff")def create_intensity_map(pga_list, target_names, epicenter_lat=None, epicenter_lon=None,selected_stations=None, duration=None, first_pick=None):"""使用 Plotly 創建互動式震度分布地圖(合併輸入測站與預測震度)輸入測站的透明度根據 P 波到時是否在時間窗內調整:- P 波在時間窗內:較不透明 (opacity=0.9)- P 波在時間窗外:較透明 (opacity=0.3)"""# 按震度等級分組資料intensity_groups = {i: {"lat": [], "lon": [], "text": [], "color": get_intensity_color(i)}for i in range(10)}# 添加震度測站標記all_lats = []all_lons = []for i, target_name in enumerate(target_names):target = next((t for t in target_dict if t["station"] == target_name), None)if target:lat = target["latitude"]lon = target["longitude"]all_lats.append(lat)all_lons.append(lon)intensity = calculate_intensity(pga_list[i])intensity_label = calculate_intensity(pga_list[i], label=True)pga = pga_list[i]hover_text = (f"{target_name}<br>"f"震度: {intensity_label}<br>"f"PGA: {pga:.4f} m/s²<br>"f"位置: ({lat:.3f}, {lon:.3f})")intensity_groups[intensity]["lat"].append(lat)intensity_groups[intensity]["lon"].append(lon)intensity_groups[intensity]["text"].append(hover_text)# 地圖中心固定為台灣中心map_center_lat = 23.6map_center_lon = 121.0# 創建 Plotly 地圖fig = go.Figure()# 【底層】添加輸入測站(根據 P 波時間點是否在時間窗內調整透明度)if selected_stations:# 分離 P 波在時間窗內和時間窗外的測站stations_in_window = {"lat": [], "lon": [], "text": []}stations_out_window = {"lat": [], "lon": [], "text": []}# 計算時間窗範圍end_time = first_pick + duration if first_pick is not None and duration is not None else Nonefor station_data in selected_stations:lat = station_data["latitude"]lon = station_data["longitude"]station_name = station_data["station"]p_arrival_time = station_data.get("p_arrival_time")# 判斷 P 波是否在時間窗內in_window = Falseif end_time is not None and p_arrival_time is not None:in_window = (0 <= p_arrival_time <= end_time)hover_text = (f"{station_name}<br>"f"輸入測站<br>"f"P 波到時: {p_arrival_time:.2f}s<br>" if p_arrival_time is not None else f"{station_name}<br>輸入測站<br>"f"位置: ({lat:.3f}, {lon:.3f})")if in_window:stations_in_window["lat"].append(lat)stations_in_window["lon"].append(lon)stations_in_window["text"].append(hover_text)else:stations_out_window["lat"].append(lat)stations_out_window["lon"].append(lon)stations_out_window["text"].append(hover_text)# 添加時間窗內的測站(較不透明)if stations_in_window["lat"]:fig.add_trace(go.Scattermap(lat=stations_in_window["lat"],lon=stations_in_window["lon"],mode="markers",marker=dict(size=8,color="rgba(128, 128, 128, 0.9)", # 較不透明),text=stations_in_window["text"],hoverinfo="text",name="輸入測站 (P波在窗內)",showlegend=True,))# 添加時間窗外的測站(較透明)if stations_out_window["lat"]:fig.add_trace(go.Scattermap(lat=stations_out_window["lat"],lon=stations_out_window["lon"],mode="markers",marker=dict(size=8,color="rgba(128, 128, 128, 0.3)", # 較透明),text=stations_out_window["text"],hoverinfo="text",name="輸入測站 (P波在窗外)",showlegend=True,))# 【頂層】添加各震度等級的測站(預測結果)intensity_labels = ["0", "1", "2", "3", "4", "5-", "5+", "6-", "6+", "7"]for intensity_level in range(10):group = intensity_groups[intensity_level]if group["lat"]: # 有資料的震度等級# 先添加圓圈標記fig.add_trace(go.Scattermap(lat=group["lat"],lon=group["lon"],mode="markers+text",marker=dict(size=20, color=group["color"], opacity=0.9),text=intensity_labels[intensity_level],textposition="middle center",textfont=dict(size=14,color=("black" if intensity_level <= 4 else "white"),family="Open Sans Bold"),hoverinfo="text",name=f"震度 {intensity_labels[intensity_level]}",showlegend=True,))else:# 沒有資料的震度等級:添加隱形標記只為了顯示圖例fig.add_trace(go.Scattermap(lat=[None],lon=[None],mode="markers",marker=dict(size=24, color=group["color"], opacity=0.9),name=f"震度 {intensity_labels[intensity_level]}",showlegend=True,hoverinfo="skip",))# 【中層】添加震央(紅色標記)if epicenter_lat is not None and epicenter_lon is not None:fig.add_trace(go.Scattermap(lat=[epicenter_lat],lon=[epicenter_lon],mode="markers",marker=dict(size=25, color="red"),text=[f"震央<br>({epicenter_lat:.3f}, {epicenter_lon:.3f})"],hoverinfo="text",name="震央",showlegend=True,))fig.add_trace(go.Scattermap(lat=[epicenter_lat],lon=[epicenter_lon],mode="markers",marker=dict(size=10, color="white"),showlegend=False,hoverinfo="skip",))# 設置地圖佈局fig.update_layout(map=dict(style="open-street-map",center=dict(lat=map_center_lat, lon=map_center_lon),zoom=6.5,),height=550, # 設置固定高度以適應 Gradio 容器margin=dict(l=0, r=0, t=0, b=0),hovermode="closest", # 啟用 hover 功能showlegend=True,legend=dict(yanchor="top",y=0.95,xanchor="left",x=0.01,bgcolor="rgba(255, 255, 255, 0.8)",),)return figdef load_observed_intensity_image(event_name):"""從 intensity_map 資料夾載入對應的實際觀測震度圖實際震度圖不存在時:顯示提示並用預設高度 800 呈現空白占位"""import osimage_path = earthquake_metadata[event_name]["intensity_map_file"]if os.path.exists(image_path):logger.info(f"載入實際觀測震度圖: {image_path}")return image_pathlogger.warning(f"找不到實際震度圖: {event_name}(將顯示空白占位)")return None# ============ 步驟 1:載入 mseed + 選擇測站(快取到 gr.State)============def step1_load_mseed_and_select_stations(event_name):"""步驟 1:載入 mseed 檔案並選擇最近的 25 個測站這一步只執行一次(切換事件時),結果會快取在 gr.State 中"""try:epicenter_lat = earthquake_metadata[event_name]["epicenter_lat"]epicenter_lon = earthquake_metadata[event_name]["epicenter_lon"]mseed_file = earthquake_metadata[event_name]["mseed_file"]logger.info(f"[步驟 1] 載入地震事件: {event_name}")st = read(mseed_file)logger.info(f"載入了 {len(st)} 個 trace")# 選擇距離震央最近的 25 個測站(啟用 STA/LTA 快取)logger.info(f"選擇距離震央 ({epicenter_lat}, {epicenter_lon}) 最近的測站...")selected_stations = select_nearest_stations(st, epicenter_lat, epicenter_lon, n_stations=25, event_name=event_name)if len(selected_stations) == 0:logger.error("找不到有效的測站資料")return None, Nonelogger.info(f"[步驟 1] 完成 - mseed 已載入,測站已選擇,STA/LTA 結果已快取({len(selected_stations)} 個測站)")return st, selected_stationsexcept Exception as e:logger.error(f"[步驟 1] 發生錯誤: {e}")import tracebacktraceback.print_exc()return None, None# ============ 步驟 2:提取波形(使用快取的 stream + stations)============def step2_extract_and_plot_waveforms(cached_stream, cached_stations, event_name,duration):"""步驟 2:根據時間範圍提取波形並繪圖使用快取的 stream 和 selected_stations,避免重複讀檔用戶調整時間範圍時會重複執行此步驟"""try:if cached_stream is None or cached_stations is None:logger.warning("[步驟 2] 快取資料不存在,請先載入波形")return None, None, None, gr.update(interactive=False)first_pick = earthquake_metadata[event_name]["first_pick"]logger.info(f"[步驟 2] 提取波形資料(P 波後 {duration} 秒,使用快取的測站與 STA/LTA 資訊)...")# 提取波形資料(waveforms, station_info_list, valid_stations,missing_components_count, p_wave_outside_window_count) = (extract_waveforms_from_stream(event_name, cached_stream, cached_stations, duration, vs30_input=600))if len(waveforms) == 0:logger.error("[步驟 2] 無法提取波形資料")return None, None, None# 繪製波形圖(包含所有 cached_stations,含 P 波標記)waveform_plot = plot_waveform(cached_stream, cached_stations, first_pick,duration)logger.info(f"[步驟 2] 完成 - 已提取 {len(waveforms)} 個測站的波形")return waveforms, station_info_list, waveform_plotexcept Exception as e:logger.error(f"[步驟 2] 發生錯誤: {e}")import tracebacktraceback.print_exc()return None, None, None# ============ 步驟 3:執行模型推論(使用快取的波形)============def step3_predict_intensity(cached_waveforms, cached_station_info, cached_stations,event_name, duration):"""步驟 3:執行震度預測直接使用快取的波形資料和測站資訊,無需重新讀檔或提取波形spec #2:測站選擇上限 (25 站)、波形取樣率 (100 Hz)、時間窗長度 (30 秒)spec #3:推論流程、PGA → 震度轉換注意:此函數只返回預測地圖,觀測圖片由 step1 單獨處理"""try:if cached_waveforms is None or cached_station_info is None:logger.warning("[步驟 3] 快取資料不存在,請先載入並提取波形")return Noneepicenter_lat = earthquake_metadata[event_name]["epicenter_lat"]epicenter_lon = earthquake_metadata[event_name]["epicenter_lon"]first_pick = earthquake_metadata[event_name]["first_pick"]logger.info("[步驟 3] 開始模型推論...")# Padding 到 25 個測站(模型要求)max_stations = 25waveform_padded = np.zeros((max_stations, 3000, 3))station_info_padded = np.zeros((max_stations, 4))for i in range(min(len(cached_waveforms), max_stations)):waveform_padded[i] = cached_waveforms[i]station_info_padded[i] = cached_station_info[i]# 準備所有目標測站資訊(分批處理)all_pga_list = []all_target_names = []2 unmodified linestotal_targets = len(target_dict)num_batches = (total_targets + batch_size - 1) // batch_sizelogger.info(f"開始分批預測 {total_targets} 個目標測站(共 {num_batches} 批)...")for batch_idx in range(num_batches):start_idx = batch_idx * batch_sizeend_idx = min((batch_idx + 1) * batch_size, total_targets)batch_targets = target_dict[start_idx:end_idx]logger.info(f"預測第 {batch_idx + 1}/{num_batches} 批(測站 {start_idx + 1}-{end_idx})...")# 準備這批目標測站資訊target_list = []target_names = []for target in batch_targets:target_list.append([target["latitude"],target["longitude"],target["elevation"],get_vs30(target["latitude"], target["longitude"], user_vs30=600),])target_names.append(target["station"])# Padding 到 25 個(如果不足 25 個)1 unmodified linefor i in range(len(target_list)):target_padded[i] = target_list[i]# 組合成 torch tensortensor_data = {"waveform": torch.tensor(waveform_padded).unsqueeze(0).double(),"station": torch.tensor(station_info_padded).unsqueeze(0).double(),"target": torch.tensor(target_padded).unsqueeze(0).double(),}# 執行預測with torch.no_grad():weight, sigma, mu = model(tensor_data)batch_pga = (torch.sum(weight * mu, dim=2).cpu().detach().numpy().flatten().tolist())# 只取實際有資料的部分all_pga_list.extend(batch_pga[: len(target_names)])all_target_names.extend(target_names)logger.info(f"完成所有 {len(all_target_names)} 個測站的預測!")pga_list = all_pga_listtarget_names = all_target_names# 繪製互動式地圖(固定高度 800)- 合併輸入測站與預測震度# 根據 P 波到時是否在時間窗內調整輸入測站透明度intensity_map = create_intensity_map(pga_list, target_names, epicenter_lat, epicenter_lon,selected_stations=cached_stations, duration=duration, first_pick=first_pick)# 生成警報文字報告alert_report = generate_earthquake_alert_report(pga_list, target_names, event_name, duration)logger.info("[步驟 3] 預測完成!")return intensity_map, alert_reportexcept Exception as e:logger.error(f"[步驟 3] 發生錯誤: {e}")import tracebacktraceback.print_exc()return None, ""# ============ Gradio 介面 ============with gr.Blocks(title="TT-SAM 震度預測模型", fill_height=True) as demo:gr.Markdown("# Taiwan Transformer Shaking Alert Model (TT-SAM)")# ========== 上層:使用說明與參數設定 ==========with gr.Row():with gr.Column(scale=1):gr.Markdown("""**流程說明**:1. 使用 P 波偵測選出距震央最近最多 25 個測站(有 P 波才會有波形,沒有的話補 0)2. 提取測站資訊(經緯度、高程、Vs30)與 P 波後指定時間長度的三分量波形3. 波形資料補齊至 30 秒後輸入已訓練好的 TTSAM 模型4. 模型預測 47 個目標點的 PGA 並轉換為震度,生成分布地圖5. 將預測結果按縣市歸納,取各縣市最高震度,並按震度大小排序生成文字報告(僅顯示 4 級以上地區)""")with gr.Column(scale=1):event_dropdown = gr.Dropdown(choices=list(earthquake_metadata.keys()),value=list(earthquake_metadata.keys())[2],label="選擇地震事件",)duration_slider = gr.Slider(2, 15, value=15, step=1, label="P 波後時間 (秒)")with gr.Row(scale=1):alert_textbox = gr.Textbox(label="地震預警報告(≥ 4 級地區)",lines=7,max_lines=7,interactive=False,show_copy_button=False,autoscroll=False,)waveform_plot = gr.Plot(label="地震波形",)# ========== 下層:合併地圖 vs 實際觀測 ==========with gr.Row():predicted_intensity_map = gr.Plot(label="預測震度")observed_intensity_image = gr.Image(label="實際觀測震度",type="filepath",value=load_observed_intensity_image(list(earthquake_metadata.keys())[2]),)with gr.Row():gr.Markdown("""**注意事項**:- 模型僅供研究與教育用途,請勿用於正式警報系統。- 預測結果可能因測站分布、波形品質等因素有所差異。- 實際觀測震度圖來自中央氣象署。""")gr.Markdown("""TT-SAM 模型由國立中央大學地球科學系與國立台灣大學地質科學系合作開發。- 氣象署計畫:人工智慧技術建立微分區地震預警系統相關研究 (MOTC-CWB-110-E-06)- 模型:https://github.com/JasonChang0320/TT-SAM- 即時監測系統:https://github.com/SeisBlue/TTSAM_Realtime""")# ========== 隱藏的 State 變數(用於快取中間結果)==========cached_stream = gr.State(None) # ObsPy Stream objectcached_stations = gr.State(None) # 選中的 25 個測站列表cached_waveforms = gr.State(None) # 提取的波形資料cached_station_info = gr.State(None) # 測站資訊列表# ========== 事件綁定(使用鏈式觸發 + gr.State 快取)==========# 【觸發點 1】事件切換:自動執行完整流程 步驟 1 → 步驟 2 → 步驟 3 + 載入觀測圖片event_dropdown.change(fn=step1_load_mseed_and_select_stations,inputs=[event_dropdown],outputs=[cached_stream, cached_stations]).then( # 載入觀測圖片(只在事件切換時執行)fn=load_observed_intensity_image,inputs=[event_dropdown],outputs=[observed_intensity_image]).then( # 鏈式觸發步驟 2fn=step2_extract_and_plot_waveforms,inputs=[cached_stream, cached_stations, event_dropdown, duration_slider],outputs=[cached_waveforms, cached_station_info, waveform_plot]).then( # 鏈式觸發步驟 3fn=step3_predict_intensity,inputs=[cached_waveforms, cached_station_info, cached_stations, event_dropdown, duration_slider],outputs=[predicted_intensity_map, alert_textbox])# 【觸發點 2】時間範圍調整:自動執行步驟 2 → 步驟 3(不重新讀檔,不更新觀測圖片)duration_slider.change(fn=step2_extract_and_plot_waveforms,inputs=[cached_stream, cached_stations, event_dropdown, duration_slider],outputs=[cached_waveforms, cached_station_info, waveform_plot]).then( # 鏈式觸發步驟 3fn=step3_predict_intensity,inputs=[cached_waveforms, cached_station_info, cached_stations, event_dropdown, duration_slider],outputs=[predicted_intensity_map, alert_textbox])# 【冷啟動】應用載入時自動執行完整流程 步驟 1 → 載入觀測圖片 → 步驟 2 → 步驟 3demo.load(fn=step1_load_mseed_and_select_stations,inputs=[event_dropdown],outputs=[cached_stream, cached_stations]).then(fn=load_observed_intensity_image,inputs=[event_dropdown],outputs=[observed_intensity_image]).then(fn=step2_extract_and_plot_waveforms,inputs=[cached_stream, cached_stations, event_dropdown, duration_slider],outputs=[cached_waveforms, cached_station_info, waveform_plot]).then(fn=step3_predict_intensity,inputs=[cached_waveforms, cached_station_info, cached_stations, event_dropdown, duration_slider],outputs=[predicted_intensity_map, alert_textbox])demo.launch()12345678910111213141516171819202122232425262728291 unmodified line313233343536373839404142434445461 unmodified line4849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536610 unmodified lines3773783793803813825 unmodified lines3883893903913923933947 unmodified lines4024034044054064074084094104114124134144154164174184194204214224234244254261 unmodified line4284294304314324334344354364374384394404414424434444454464474484494504514524531 unmodified line4554564574584594604614624634644654664674684694704714724734744754764774 unmodified lines4824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155 unmodified lines5215225235245255265275285295305315325331 unmodified line5355365375385395405415425435445455461 unmodified line5485495505515525535545555565572 unmodified lines5605615625635645655665675685695705712 unmodified lines57457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660715 unmodified lines6236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589592 unmodified lines9629639649659669679689699709719729739749759769779789799809819829839849859861 unmodified line9889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120import gradio as grimport numpy as npimport matplotlib.pyplot as pltfrom obspy import readimport xarray as xrimport torchimport torch.nn as nnfrom scipy.signal import detrend, iirfilter, sosfilt, zpk2sosfrom scipy.spatial import cKDTreeimport pandas as pdfrom loguru import logger# 設定 matplotlib 中文字體支援plt.rcParams['font.sans-serif'] = ['Arial Unicode MS', 'DejaVu Sans']plt.rcParams['axes.unicode_minus'] = False # 解決負號顯示問題# GPU/CPU 設定if torch.cuda.is_available():device = torch.device("cuda")logger.info("使用 GPU")else:device = torch.device("cpu")logger.info("使用 CPU")# 載入 Vs30 資料集(從 Hugging Face 下載)from huggingface_hub import hf_hub_downloadtree = Nonevs30_table = None1 unmodified linetry:logger.info("從 Hugging Face 載入 Vs30 資料...")vs30_file = hf_hub_download(repo_id="SeisBlue/TaiwanVs30",filename="Vs30ofTaiwan.nc",repo_type="dataset")ds = xr.open_dataset(vs30_file)lat_flat = ds['lat'].values.flatten()lon_flat = ds['lon'].values.flatten()vs30_flat = ds['vs30'].values.flatten()vs30_table = pd.DataFrame({'lat': lat_flat, 'lon': lon_flat, 'Vs30': vs30_flat})vs30_table = vs30_table.replace([np.inf, -np.inf], np.nan).dropna()tree = cKDTree(vs30_table[["lat", "lon"]])logger.info("Vs30 資料載入完成")1 unmodified linelogger.warning(f"Vs30 資料載入失敗: {e}")logger.warning("將使用預設 Vs30 值 (600 m/s)")# 載入目標測站target_file = "station/eew_target.csv"try:logger.info(f"載入 {target_file}...")target_df = pd.read_csv(target_file)target_dict = target_df.to_dict(orient="records")logger.info(f"{target_file} 載入完成")except FileNotFoundError:logger.error(f"{target_file} 找不到")# 載入測站資訊(輸入測站,1000+ 個)site_info_file = "station/site_info.csv"try:logger.info(f"載入 {site_info_file}...")site_info = pd.read_csv(site_info_file)# 只保留唯一的測站(去除重複的分量)site_info = site_info.drop_duplicates(subset=['Station']).reset_index(drop=True)logger.info(f"{site_info_file} 載入完成,共 {len(site_info)} 個測站")except FileNotFoundError:logger.warning(f"{site_info_file} 找不到")# 預設地震事件EARTHQUAKE_EVENTS = {"0403花蓮地震 (2024)": "waveform/20240403.mseed",}# ============ 模型定義(從 ttsam_realtime.py 複製) ============class LambdaLayer(nn.Module):def __init__(self, lambd, eps=1e-4):super(LambdaLayer, self).__init__()self.lambd = lambdself.eps = epsdef forward(self, x):return self.lambd(x) + self.epsclass MLP(nn.Module):def __init__(self, input_shape, dims=(500, 300, 200, 150), activation=nn.ReLU(),last_activation=None):super(MLP, self).__init__()if last_activation is None:last_activation = activationself.dims = dimsself.first_fc = nn.Linear(input_shape[0], dims[0])self.first_activation = activationmore_hidden = []if len(self.dims) > 2:for i in range(1, len(self.dims) - 1):more_hidden.append(nn.Linear(self.dims[i - 1], self.dims[i]))more_hidden.append(nn.ReLU())self.more_hidden = nn.ModuleList(more_hidden)self.last_fc = nn.Linear(dims[-2], dims[-1])self.last_activation = last_activationdef forward(self, x):output = self.first_fc(x)output = self.first_activation(output)if self.more_hidden:for layer in self.more_hidden:output = layer(output)output = self.last_fc(output)output = self.last_activation(output)return outputclass CNN(nn.Module):def __init__(self, input_shape=(-1, 6000, 3), activation=nn.ReLU(), downsample=1,mlp_input=11665, mlp_dims=(500, 300, 200, 150), eps=1e-8):super(CNN, self).__init__()self.input_shape = input_shapeself.activation = activationself.downsample = downsampleself.mlp_input = mlp_inputself.mlp_dims = mlp_dimsself.eps = epsself.lambda_layer_1 = LambdaLayer(lambda t: t / (torch.max(torch.max(torch.abs(t), dim=1, keepdim=True).values,dim=2, keepdim=True).values + self.eps))self.unsqueeze_layer1 = LambdaLayer(lambda t: torch.unsqueeze(t, dim=1))self.lambda_layer_2 = LambdaLayer(lambda t: torch.log(torch.max(torch.max(torch.abs(t), dim=1).values,dim=1).values + self.eps) / 100)self.unsqueeze_layer2 = LambdaLayer(lambda t: torch.unsqueeze(t, dim=1))self.conv2d1 = nn.Sequential(nn.Conv2d(1, 8, kernel_size=(1, downsample), stride=(1, downsample)),nn.ReLU())self.conv2d2 = nn.Sequential(nn.Conv2d(8, 32, kernel_size=(16, 3), stride=(1, 3)), nn.ReLU())self.conv1d1 = nn.Sequential(nn.Conv1d(32, 64, kernel_size=16), nn.ReLU())self.maxpooling = nn.MaxPool1d(2)self.conv1d2 = nn.Sequential(nn.Conv1d(64, 128, kernel_size=16), nn.ReLU())self.conv1d3 = nn.Sequential(nn.Conv1d(128, 32, kernel_size=8), nn.ReLU())self.conv1d4 = nn.Sequential(nn.Conv1d(32, 32, kernel_size=8), nn.ReLU())self.conv1d5 = nn.Sequential(nn.Conv1d(32, 16, kernel_size=4), nn.ReLU())self.mlp = MLP((self.mlp_input,), dims=self.mlp_dims)def forward(self, x):output = self.lambda_layer_1(x)output = self.unsqueeze_layer1(output)scale = self.lambda_layer_2(x)scale = self.unsqueeze_layer2(scale)output = self.conv2d1(output)output = self.conv2d2(output)output = torch.squeeze(output, dim=-1)output = self.conv1d1(output)output = self.maxpooling(output)output = self.conv1d2(output)output = self.maxpooling(output)output = self.conv1d3(output)output = self.maxpooling(output)output = self.conv1d4(output)output = self.conv1d5(output)output = torch.flatten(output, start_dim=1)output = torch.cat((output, scale), dim=1)output = self.mlp(output)return outputclass PositionEmbeddingVs30(nn.Module):def __init__(self, wavelengths=((5, 30), (110, 123), (0.01, 5000), (100, 1600)),emb_dim=500):super(PositionEmbeddingVs30, self).__init__()self.wavelengths = wavelengthsself.emb_dim = emb_dimmin_lat, max_lat = wavelengths[0]min_lon, max_lon = wavelengths[1]min_depth, max_depth = wavelengths[2]min_vs30, max_vs30 = wavelengths[3]assert emb_dim % 10 == 0lat_dim = emb_dim // 5lon_dim = emb_dim // 5depth_dim = emb_dim // 10vs30_dim = emb_dim // 10self.lat_coeff = 2 * np.pi * 1.0 / min_lat * ((min_lat / max_lat) ** (np.arange(lat_dim) / lat_dim))self.lon_coeff = 2 * np.pi * 1.0 / min_lon * ((min_lon / max_lon) ** (np.arange(lon_dim) / lon_dim))self.depth_coeff = 2 * np.pi * 1.0 / min_depth * ((min_depth / max_depth) ** (np.arange(depth_dim) / depth_dim))self.vs30_coeff = 2 * np.pi * 1.0 / min_vs30 * ((min_vs30 / max_vs30) ** (np.arange(vs30_dim) / vs30_dim))lat_sin_mask = np.arange(emb_dim) % 5 == 0lat_cos_mask = np.arange(emb_dim) % 5 == 1lon_sin_mask = np.arange(emb_dim) % 5 == 2lon_cos_mask = np.arange(emb_dim) % 5 == 3depth_sin_mask = np.arange(emb_dim) % 10 == 4depth_cos_mask = np.arange(emb_dim) % 10 == 9vs30_sin_mask = np.arange(emb_dim) % 10 == 5vs30_cos_mask = np.arange(emb_dim) % 10 == 8self.mask = np.zeros(emb_dim)self.mask[lat_sin_mask] = np.arange(lat_dim)self.mask[lat_cos_mask] = lat_dim + np.arange(lat_dim)self.mask[lon_sin_mask] = 2 * lat_dim + np.arange(lon_dim)self.mask[lon_cos_mask] = 2 * lat_dim + lon_dim + np.arange(lon_dim)self.mask[depth_sin_mask] = 2 * lat_dim + 2 * lon_dim + np.arange(depth_dim)self.mask[depth_cos_mask] = 2 * lat_dim + 2 * lon_dim + depth_dim + np.arange(depth_dim)self.mask[vs30_sin_mask] = 2 * lat_dim + 2 * lon_dim + 2 * depth_dim + np.arange(vs30_dim)self.mask[vs30_cos_mask] = 2 * lat_dim + 2 * lon_dim + 2 * depth_dim + vs30_dim + np.arange(vs30_dim)self.mask = self.mask.astype("int32")def forward(self, x):lat_base = x[:, :, 0:1].to(device) * torch.Tensor(self.lat_coeff).to(device)lon_base = x[:, :, 1:2].to(device) * torch.Tensor(self.lon_coeff).to(device)depth_base = x[:, :, 2:3].to(device) * torch.Tensor(self.depth_coeff).to(device)vs30_base = x[:, :, 3:4] * torch.Tensor(self.vs30_coeff).to(device)output = torch.cat([torch.sin(lat_base), torch.cos(lat_base),torch.sin(lon_base), torch.cos(lon_base),torch.sin(depth_base), torch.cos(depth_base),torch.sin(vs30_base), torch.cos(vs30_base),], dim=-1)maskk = torch.from_numpy(np.array(self.mask)).long()index = (maskk.unsqueeze(0).unsqueeze(0)).expand(x.shape[0], 1,self.emb_dim).to(device)output = torch.gather(output, -1, index).to(device)return outputclass TransformerEncoder(nn.Module):def __init__(self, d_model=150, nhead=10, batch_first=True, activation="gelu",dropout=0.0, dim_feedforward=1000):super(TransformerEncoder, self).__init__()self.encoder_layer = nn.TransformerEncoderLayer(d_model=d_model, nhead=nhead, batch_first=batch_first,activation=activation, dropout=dropout, dim_feedforward=dim_feedforward).to(device)self.transformer_encoder = nn.TransformerEncoder(self.encoder_layer, 6).to(device)def forward(self, x, src_key_padding_mask=None):return self.transformer_encoder(x, src_key_padding_mask=src_key_padding_mask)class MDN(nn.Module):def __init__(self, input_shape=(150,), n_hidden=20, n_gaussians=5):super(MDN, self).__init__()self.z_h = nn.Sequential(nn.Linear(input_shape[0], n_hidden), nn.Tanh())self.z_weight = nn.Linear(n_hidden, n_gaussians)self.z_sigma = nn.Linear(n_hidden, n_gaussians)self.z_mu = nn.Linear(n_hidden, n_gaussians)def forward(self, x):z_h = self.z_h(x)weight = nn.functional.softmax(self.z_weight(z_h), -1)sigma = torch.exp(self.z_sigma(z_h))mu = self.z_mu(z_h)return weight, sigma, muclass FullModel(nn.Module):def __init__(self, model_cnn, model_position, model_transformer, model_mlp,model_mdn,max_station=25, pga_targets=15, emb_dim=150, data_length=6000):super(FullModel, self).__init__()self.data_length = data_lengthself.model_CNN = model_cnnself.model_Position = model_positionself.model_Transformer = model_transformerself.model_mlp = model_mlpself.model_MDN = model_mdnself.max_station = max_stationself.pga_targets = pga_targetsself.emb_dim = emb_dimdef forward(self, data):cnn_output = self.model_CNN(torch.DoubleTensor(data["waveform"].reshape(-1, self.data_length, 3)).float().to(device))cnn_output_reshape = torch.reshape(cnn_output,(-1, self.max_station, self.emb_dim))emb_output = self.model_Position(torch.DoubleTensor(data["station"].reshape(-1, 1, data["station"].shape[2])).float().to(device))emb_output = emb_output.reshape(-1, self.max_station, self.emb_dim)station_pad_mask = data["station"] == 0station_pad_mask = torch.all(station_pad_mask, 2)pga_pos_emb_output = self.model_Position(torch.DoubleTensor(data["target"].reshape(-1, 1, data["target"].shape[2])).float().to(device))pga_pos_emb_output = pga_pos_emb_output.reshape(-1, self.pga_targets,self.emb_dim)target_pad_mask = torch.ones_like(data["target"], dtype=torch.bool)target_pad_mask = torch.all(target_pad_mask, 2)pad_mask = torch.cat((station_pad_mask, target_pad_mask), dim=1).to(device)add_pe_cnn_output = torch.add(cnn_output_reshape, emb_output)transformer_input = torch.cat((add_pe_cnn_output, pga_pos_emb_output), dim=1)transformer_output = self.model_Transformer(transformer_input, pad_mask)mlp_input = transformer_output[:, -self.pga_targets:, :].to(device)mlp_output = self.model_mlp(mlp_input)weight, sigma, mu = self.model_MDN(mlp_output)return weight, sigma, mudef get_full_model(model_path):emb_dim = 150mlp_dims = (150, 100, 50, 30, 10)cnn_model = CNN(mlp_input=5665).to(device)pos_emb_model = PositionEmbeddingVs30(emb_dim=emb_dim).to(device)transformer_model = TransformerEncoder()mlp_model = MLP(input_shape=(emb_dim,), dims=mlp_dims).to(device)mdn_model = MDN(input_shape=(mlp_dims[-1],)).to(device)full_model = FullModel(cnn_model, pos_emb_model, transformer_model, mlp_model, mdn_model,pga_targets=25, data_length=3000).to(device)full_model.load_state_dict(torch.load(model_path, weights_only=True, map_location=device))return full_model# 載入模型model_path = hf_hub_download(repo_id="SeisBlue/TTSAM",filename="ttsam_trained_model_11.pt")model = get_full_model(model_path)# ============ 輔助函數 ============def lowpass(data, freq=10, df=100, corners=4):fe = 0.5 * dff = freq / fe10 unmodified linesreturn datadef get_vs30(lat, lon, user_vs30=600):if tree is None or vs30_table is None:# 如果 Vs30 資料未載入,使用使用者輸入的值5 unmodified linesreturn float(vs30)def calculate_intensity(pga, label=False):intensity_label = ["0", "1", "2", "3", "4", "5-", "5+", "6-", "6+", "7"]pga_level = np.log10([1e-5, 0.008, 0.025, 0.080, 0.250, 0.80, 1.4, 2.5, 4.4, 8.0])7 unmodified linesreturn intensity# ============ Gradio 介面函數 ============def load_waveform(event_name):"""載入完整的 mseed 檔案(包含所有測站)"""file_path = EARTHQUAKE_EVENTS[event_name]st = read(file_path)return stdef calculate_distance(lat1, lon1, lat2, lon2):"""計算兩點間的距離(簡化的平面距離,單位:度)"""return np.sqrt((lat1 - lat2)**2 + (lon1 - lon2)**2)def select_nearest_stations(st, epicenter_lat, epicenter_lon, n_stations=25):"""從 site_info(1000+ 個輸入測站)中選擇距離震央最近的 n 個測站"""station_distances = {} # 改用字典避免重複# 計算每個測站到震央的距離for tr in st:station_code = tr.stats.station1 unmodified lineif station_code in station_distances:continue# 從 site_info 中查詢測站位置try:station_data = site_info[site_info["Station"] == station_code]if len(station_data) == 0:continuelat = station_data["Latitude"].values[0]lon = station_data["Longitude"].values[0]elev = station_data["Elevation"].values[0]distance = calculate_distance(epicenter_lat, epicenter_lon, lat, lon)station_distances[station_code] = {"station": station_code,"distance": distance,"latitude": lat,"longitude": lon,"elevation": elev}except Exception as e:logger.warning(f"測站 {station_code} 資訊查詢失敗: {e}")continue# 轉換為列表並按距離排序,選擇最近的 n 個1 unmodified linestation_list.sort(key=lambda x: x["distance"])selected_stations = station_list[:n_stations]logger.info(f"從 {len(station_list)} 個輸入測站中選擇了最近的 {len(selected_stations)} 個")return selected_stationsdef extract_waveforms_from_stream(st, selected_stations, start_time, end_time, vs30_input):"""從 Stream 中提取選定測站的波形資料"""waveforms = []station_info_list = []valid_stations = []sampling_rate = 100 # 假設 100 Hzstart_idx = int(start_time * sampling_rate)end_idx = int(end_time * sampling_rate)target_length = 3000for station_data in selected_stations:station_code = station_data["station"]try:# 選擇該測站的所有分量4 unmodified lines# 嘗試取得 Z, N, E 分量z_trace = st_station.select(component="Z")n_trace = st_station.select(component="N") or st_station.select(component="1")e_trace = st_station.select(component="E") or st_station.select(component="2")# 如果沒有三分量,使用 Z 分量重複if len(z_trace) > 0:z_data = z_trace[0].data[start_idx:end_idx]else:continueif len(n_trace) > 0:n_data = n_trace[0].data[start_idx:end_idx]else:n_data = z_data.copy()if len(e_trace) > 0:e_data = e_trace[0].data[start_idx:end_idx]else:e_data = z_data.copy()# 訊號處理z_data = signal_processing(z_data)n_data = signal_processing(n_data)e_data = signal_processing(e_data)# 先創建全零陣列 (3000, 3)waveform_3c = np.zeros((target_length, 3))# 填入實際資料(自動處理長度不足或過長的情況)z_len = min(len(z_data), target_length)n_len = min(len(n_data), target_length)e_len = min(len(e_data), target_length)5 unmodified lineswaveforms.append(waveform_3c)# 準備測站資訊vs30 = get_vs30(station_data["latitude"], station_data["longitude"], vs30_input)station_info_list.append([station_data["latitude"],station_data["longitude"],station_data["elevation"],vs30])valid_stations.append(station_data)except Exception as e:1 unmodified linecontinuelogger.info(f"成功提取 {len(waveforms)} 個測站的波形")return waveforms, station_info_list, valid_stationsdef plot_waveform(st, selected_stations, start_time, end_time):"""繪製選定測站的波形圖(距離-時間圖,可顯示全部 25 個測站)"""fig, ax = plt.subplots(figsize=(14, 10))# 設定振幅縮放比例(避免波形重疊)amplitude_scale = 0.03 # 可調整此值來控制波形大小1 unmodified lineplotted_count = 0distances = []station_names = []for i, station_data in enumerate(selected_stations):station_code = station_data["station"]distance = station_data["distance"]try:st_station = st.select(station=station_code)2 unmodified linestimes = tr.times()data = tr.data# 正規化波形振幅data_normalized = data / (np.max(np.abs(data)) + 1e-10)# 繪製波形,Y軸位置為距離ax.plot(times, distance + data_normalized * amplitude_scale,'black', linewidth=0.3, alpha=0.8)distances.append(distance)station_names.append(station_code)2 unmodified linesexcept Exception as e:logger.warning(f"無法繪製測站 {station_code}: {e}")# 標記選取時間範圍ax.axvline(start_time, color='red', linestyle='--', linewidth=2,alpha=0.7, label='選取範圍')ax.axvline(end_time, color='red', linestyle='--', linewidth=2, alpha=0.7)ax.axvspan(start_time, end_time, alpha=0.15, color='blue')# 設定軸標籤和標題ax.set_xlabel('Time (s)', fontsize=12)ax.set_ylabel('Distance from Epicenter (°)', fontsize=12)ax.set_title(f'Record Section - {plotted_count} Stations Sorted by Distance',fontsize=14, fontweight='bold')# 在右側標註測站名稱if distances:ax2 = ax.twinx()ax2.set_ylim(ax.get_ylim())ax2.set_ylabel('Station Code', fontsize=12)# 每隔幾個測站標註一次(避免過於擁擠)step = max(1, len(distances) // 10)tick_positions = distances[::step]tick_labels = station_names[::step]ax2.set_yticks(tick_positions)ax2.set_yticklabels(tick_labels, fontsize=8)ax.grid(True, alpha=0.3, axis='x')ax.legend(loc='upper right')plt.tight_layout()return fig15 unmodified linesreturn color_map.get(intensity, "#ffffff")def create_intensity_map(pga_list, target_names, epicenter_lat=None, epicenter_lon=None):"""使用 Folium 創建互動式震度分布地圖"""import foliumfrom folium import plugins# 創建地圖,中心點設在台灣中心,設定地圖尺寸m = folium.Map(location=[23.5, 121],zoom_start=7,tiles='OpenStreetMap',width='100%',height='600px' # 設定固定高度,與 Ground Truth 圖片匹配)# 如果有震央位置,標記震央if epicenter_lat and epicenter_lon:folium.Marker([epicenter_lat, epicenter_lon],popup=f'震央<br>({epicenter_lat:.3f}, {epicenter_lon:.3f})',icon=folium.Icon(color='red', icon='star', prefix='fa'),tooltip='震央位置').add_to(m)# 添加震度測站標記for i, target_name in enumerate(target_names):target = next((t for t in target_dict if t["station"] == target_name), None)if target:lat = target["latitude"]lon = target["longitude"]intensity = calculate_intensity(pga_list[i])intensity_label = calculate_intensity(pga_list[i], label=True)color = get_intensity_color(intensity)pga = pga_list[i]# 創建 HTML popup 內容popup_html = f"""<div style="font-family: Arial; min-width: 150px;"><h4 style="margin: 0 0 10px 0;">{target_name}</h4><table style="width:100%;"><tr><td><b>震度:</b></td><td style="color: {color}; font-weight: bold; font-size: 16px;">{intensity_label}</td></tr><tr><td><b>PGA:</b></td><td>{pga:.4f} m/s²</td></tr><tr><td><b>位置:</b></td><td>({lat:.3f}, {lon:.3f})</td></tr></table></div>"""# 創建圓形標記folium.CircleMarker(location=[lat, lon],radius=12,popup=folium.Popup(popup_html, max_width=250),tooltip=f'{target_name}: 震度 {intensity_label}',color='black',fillColor=color,fillOpacity=0.8,weight=2).add_to(m)# 在圓圈中心添加震度文字folium.Marker([lat, lon],icon=folium.DivIcon(html=f'''<div style="font-size: 10px;font-weight: bold;color: black;text-align: center;text-shadow: 1px 1px 2px white, -1px -1px 2px white;">{intensity_label}</div>''')).add_to(m)# 添加圖例legend_html = '''<div style="position: fixed;top: 10px; left: 10px;width: 180px;background-color: white;border: 2px solid grey;z-index: 9999;font-size: 14px;padding: 10px;border-radius: 5px;box-shadow: 2px 2px 6px rgba(0,0,0,0.3);"><h4 style="margin: 0 0 10px 0;">震度等級 Intensity</h4><table style="width: 100%;">'''intensity_levels = ["0", "1", "2", "3", "4", "5-", "5+", "6-", "6+", "7"]for idx, level in enumerate(intensity_levels):color = get_intensity_color(idx)legend_html += f'''<tr><td style="width: 30px; height: 20px; background-color: {color}; border: 1px solid black;"></td><td style="padding-left: 5px;">{level}</td></tr>'''legend_html += '''</table></div>'''m.get_root().html.add_child(folium.Element(legend_html))# 添加全屏按鈕plugins.Fullscreen().add_to(m)return mdef load_ground_truth_image(event_name):"""從 ground_truth 資料夾載入對應的 Ground Truth 圖片"""import os# 根據事件名稱找對應的圖片# 假設圖片命名格式為:20240403.png 或類似event_file = EARTHQUAKE_EVENTS[event_name]event_date = os.path.basename(event_file).replace('.mseed', '')# 嘗試不同的圖片格式ground_truth_dir = "ground_truth"possible_extensions = ['.png', '.jpg', '.jpeg', '.gif']for ext in possible_extensions:image_path = os.path.join(ground_truth_dir, f"{event_date}{ext}")if os.path.exists(image_path):logger.info(f"載入 Ground Truth 圖片: {image_path}")return image_pathlogger.warning(f"找不到 Ground Truth 圖片: {event_date}")return Nonedef create_input_station_map(selected_stations, epicenter_lat, epicenter_lon):"""創建輸入測站分布地圖:顯示所有測站 + 突顯被選中的 25 個"""import foliumfrom folium import plugins# 創建地圖,中心點設在震央m = folium.Map(location=[epicenter_lat, epicenter_lon],zoom_start=8,tiles='OpenStreetMap',width='100%',height='500px')# 建立被選中測站的 set(用於快速查詢)selected_station_codes = {s["station"] for s in selected_stations}# 1. 先繪製所有測站(灰色小點)logger.info(f"繪製所有測站 ({len(site_info)} 個)...")for idx, row in site_info.iterrows():station_code = row["Station"]lat = row["Latitude"]lon = row["Longitude"]# 跳過被選中的測站(稍後用不同樣式繪製)if station_code in selected_station_codes:continuefolium.CircleMarker(location=[lat, lon],radius=2,popup=f'{station_code}',tooltip=station_code,color='gray',fillColor='lightgray',fillOpacity=0.4,weight=1).add_to(m)# 2. 標記震央(紅色星星)folium.Marker([epicenter_lat, epicenter_lon],popup=f'<b>震央</b><br>({epicenter_lat:.3f}, {epicenter_lon:.3f})',icon=folium.Icon(color='red', icon='star', prefix='fa'),tooltip='震央位置',zIndexOffset=1000).add_to(m)# 3. 標記被選中的 25 個測站(彩色大點)for i, station_data in enumerate(selected_stations):station_code = station_data["station"]lat = station_data["latitude"]lon = station_data["longitude"]distance = station_data["distance"]# 創建 popup 內容popup_html = f"""<div style="font-family: Arial; min-width: 150px;"><h4 style="margin: 0 0 10px 0; color: #d63031;">{station_code}</h4><table style="width:100%;"><tr><td><b>狀態:</b></td><td><span style="color: #00b894;">✓ 已選中</span></td></tr><tr><td><b>順序:</b></td><td>第 {i+1} 近</td></tr><tr><td><b>距離:</b></td><td>{distance:.2f}°</td></tr><tr><td><b>位置:</b></td><td>({lat:.3f}, {lon:.3f})</td></tr></table></div>"""# 根據距離設定顏色if i < 5:color = 'green'elif i < 15:color = 'blue'else:color = 'orange'folium.CircleMarker(location=[lat, lon],radius=10,popup=folium.Popup(popup_html, max_width=250),tooltip=f'✓ {station_code} (第{i+1}近)',color='black',fillColor=color,fillOpacity=0.8,weight=2,zIndexOffset=500).add_to(m)# 4. 添加圖例total_stations = len(site_info)legend_html = f'''<div style="position: fixed;top: 10px; left: 10px;width: 220px;background-color: white;border: 2px solid grey;z-index: 9999;font-size: 13px;padding: 10px;border-radius: 5px;box-shadow: 2px 2px 6px rgba(0,0,0,0.3);"><h4 style="margin: 0 0 10px 0;">測站分布</h4><p style="margin: 5px 0;"><span style="color: red; font-size: 18px;">★</span> 震央</p><p style="margin: 5px 0;"><span style="color: lightgray;">●</span> 所有測站 ({total_stations} 個)</p><hr style="margin: 8px 0; border: none; border-top: 1px solid #ddd;"><p style="margin: 5px 0; font-weight: bold;">被選中的測站:</p><p style="margin: 5px 0;"><span style="color: green; font-size: 16px;">●</span> 前 5 近</p><p style="margin: 5px 0;"><span style="color: blue; font-size: 16px;">●</span> 6-15 近</p><p style="margin: 5px 0;"><span style="color: orange; font-size: 16px;">●</span> 16-25 近</p><p style="margin: 5px 0; font-size: 11px; color: #666;">共選擇 {len(selected_stations)} 個測站</p></div>'''m.get_root().html.add_child(folium.Element(legend_html))# 5. 添加全屏按鈕plugins.Fullscreen().add_to(m)return mdef load_and_display_waveform(event_name, start_time, end_time, epicenter_lon, epicenter_lat):"""載入並顯示波形,讓使用者確認範圍"""try:# 1. 載入完整的 mseed 檔案logger.info(f"載入地震事件: {event_name}")st = load_waveform(event_name)logger.info(f"載入了 {len(st)} 個 trace")# 2. 根據震央距離選擇最近的 25 個測站logger.info(f"選擇距離震央 ({epicenter_lat}, {epicenter_lon}) 最近的測站...")selected_stations = select_nearest_stations(st, epicenter_lat, epicenter_lon, n_stations=25)if len(selected_stations) == 0:return None, "錯誤:找不到有效的測站資料", gr.update(interactive=False)# 3. 繪製波形waveform_plot = plot_waveform(st, selected_stations, start_time, end_time)# 4. 創建輸入測站地圖station_map = create_input_station_map(selected_stations, epicenter_lat, epicenter_lon)station_map_html = station_map._repr_html_()info_text = f"✅ 已載入波形資料\n"info_text += f"選取時間範圍: {start_time:.1f} - {end_time:.1f} 秒\n"info_text += f"震央位置: ({epicenter_lon:.4f}, {epicenter_lat:.4f})\n"info_text += f"選擇了 {len(selected_stations)} 個最近的測站\n"info_text += f"請確認波形範圍後,點擊「執行預測」按鈕"logger.info("波形載入完成")return station_map_html, waveform_plot, info_text, gr.update(interactive=True)except Exception as e:logger.error(f"波形載入發生錯誤: {e}")import tracebacktraceback.print_exc()return None, None, f"錯誤: {str(e)}", gr.update(interactive=False)def predict_intensity(event_name, start_time, end_time, epicenter_lon, epicenter_lat):"""執行震度預測"""try:# 1. 載入完整的 mseed 檔案logger.info(f"載入地震事件: {event_name}")st = load_waveform(event_name)logger.info(f"載入了 {len(st)} 個 trace")# 2. 根據震央距離選擇最近的 25 個測站logger.info(f"選擇距離震央 ({epicenter_lat}, {epicenter_lon}) 最近的測站...")selected_stations = select_nearest_stations(st, epicenter_lat, epicenter_lon, n_stations=25)if len(selected_stations) == 0:return None, None, "錯誤:找不到有效的測站資料"# 3. 從選定的測站提取波形(vs30_input 使用預設值 600,會被資料庫值覆蓋)logger.info(f"提取波形資料(時間範圍: {start_time}-{end_time} 秒)...")waveforms, station_info_list, valid_stations = extract_waveforms_from_stream(st, selected_stations, start_time, end_time, vs30_input=600)if len(waveforms) == 0:return None, "錯誤:無法提取波形資料"# 4. Padding 到 25 個測站(模型要求)max_stations = 25waveform_padded = np.zeros((max_stations, 3000, 3))station_info_padded = np.zeros((max_stations, 4))for i in range(min(len(waveforms), max_stations)):waveform_padded[i] = waveforms[i]station_info_padded[i] = station_info_list[i]# 5. 準備所有目標測站資訊(分批處理)all_pga_list = []all_target_names = []2 unmodified linestotal_targets = len(target_dict)num_batches = (total_targets + batch_size - 1) // batch_sizelogger.info(f"開始分批預測 {total_targets} 個目標測站(共 {num_batches} 批)...")for batch_idx in range(num_batches):start_idx = batch_idx * batch_sizeend_idx = min((batch_idx + 1) * batch_size, total_targets)batch_targets = target_dict[start_idx:end_idx]logger.info(f"預測第 {batch_idx + 1}/{num_batches} 批(測站 {start_idx + 1}-{end_idx})...")# 準備這批目標測站資訊target_list = []target_names = []for target in batch_targets:target_list.append([target["latitude"],target["longitude"],target["elevation"],get_vs30(target["latitude"], target["longitude"], user_vs30=600)])target_names.append(target["station"])# Padding 到 25 個(如果不足 25 個)1 unmodified linefor i in range(len(target_list)):target_padded[i] = target_list[i]# 6. 組合成 tensortensor_data = {"waveform": torch.tensor(waveform_padded).unsqueeze(0).double(),"station": torch.tensor(station_info_padded).unsqueeze(0).double(),"target": torch.tensor(target_padded).unsqueeze(0).double(),}# 7. 執行預測with torch.no_grad():weight, sigma, mu = model(tensor_data)batch_pga = torch.sum(weight * mu, dim=2).cpu().detach().numpy().flatten().tolist()# 只取實際有資料的部分all_pga_list.extend(batch_pga[:len(target_names)])all_target_names.extend(target_names)logger.info(f"完成所有 {len(all_target_names)} 個測站的預測!")pga_list = all_pga_listtarget_names = all_target_names# 8. 繪製互動式地圖intensity_map = create_intensity_map(pga_list, target_names, epicenter_lat, epicenter_lon)map_html = intensity_map._repr_html_()# 9. 載入 Ground Truth 圖片ground_truth_path = load_ground_truth_image(event_name)# 10. 統計資訊max_intensity = max([calculate_intensity(pga, label=True) for pga in pga_list])stats = f"✅ 預測完成!\n"stats += f"選取時間範圍: {start_time:.1f} - {end_time:.1f} 秒\n"stats += f"震央位置: ({epicenter_lon:.4f}, {epicenter_lat:.4f})\n"stats += f"使用測站數: {len(waveforms)} / 25\n"stats += f"預測最大震度: {max_intensity}"logger.info("預測完成!")return ground_truth_path, map_html, statsexcept Exception as e:logger.error(f"預測過程發生錯誤: {e}")import tracebacktraceback.print_exc()return None, None, f"錯誤: {str(e)}"# ============ Gradio 介面 ============with gr.Blocks(title="TTSAM 震度預測系統") as demo:gr.Markdown("# 🌏 TTSAM 震度預測系統")# ========== 上層:使用說明與參數設定 ==========with gr.Row():# 左上:使用步驟與狀態顯示with gr.Column(scale=1):gr.Markdown("## 使用步驟")gr.Markdown("""1. 選擇地震事件和時間範圍2. 輸入震央位置和場址參數3. 點擊「載入波形」確認波形範圍4. 確認無誤後,點擊「執行預測」ℹ️ 系統會自動選擇距離震央最近的 25 個測站""")info_output = gr.Textbox(label="狀態資訊", lines=6, interactive=False)stats_output = gr.Textbox(label="預測統計", lines=4, interactive=False)# 右上:輸入參數with gr.Column(scale=1):gr.Markdown("## 輸入參數")event_dropdown = gr.Dropdown(choices=list(EARTHQUAKE_EVENTS.keys()),value=list(EARTHQUAKE_EVENTS.keys())[0],label="選擇地震事件")with gr.Row():start_slider = gr.Slider(0, 300, value=0, step=1, label="起始時間 (秒)")end_slider = gr.Slider(0, 300, value=30, step=1, label="結束時間 (秒)")gr.Markdown("### 震央位置")with gr.Row():epicenter_lon_input = gr.Number(value=121.57, label="震央經度")epicenter_lat_input = gr.Number(value=23.88, label="震央緯度")with gr.Row():load_waveform_btn = gr.Button("📊 載入波形", variant="secondary", scale=1)predict_btn = gr.Button("🔮 執行預測", variant="primary", scale=1, interactive=False)# ========== 中層:輸入測站地圖與波形圖 ==========with gr.Row():# 中左:輸入波形with gr.Column(scale=1):gr.Markdown("## 輸入波形")waveform_plot = gr.Plot(label="地震波形(選定的 25 個測站)")# 中右:輸入測站地圖with gr.Column(scale=1):gr.Markdown("## 輸入測站分布")input_station_map = gr.HTML(label="輸入測站地圖")# ========== 下層:Ground Truth vs 預測結果 ==========with gr.Row():# 左下:Ground Truthwith gr.Column(scale=1):gr.Markdown("## Ground Truth 震度分布")ground_truth_image = gr.Image(label="實際觀測震度", type="filepath", height=600)# 右下:預測震度地圖with gr.Column(scale=1):gr.Markdown("## 預測震度分布")intensity_map = gr.HTML(label="互動式震度地圖", elem_id="intensity_map")# 綁定事件# 第一步:載入波形load_waveform_btn.click(fn=load_and_display_waveform,inputs=[event_dropdown, start_slider, end_slider, epicenter_lon_input, epicenter_lat_input],outputs=[input_station_map, waveform_plot, info_output, predict_btn])# 第二步:執行預測predict_btn.click(fn=predict_intensity,inputs=[event_dropdown, start_slider, end_slider, epicenter_lon_input, epicenter_lat_input],outputs=[ground_truth_image, intensity_map, stats_output])demo.launch()
12345678910111213141516#!/bin/bash# 使用 Dockerfile.local 建置本地開發用的 Docker image
echo "建置 TTSAM 本地開發環境..."docker build -f Dockerfile.local -t ttsam-demo .
if [ $? -eq 0 ]; then echo "建置完成!" echo "" echo "執行方式:" echo " bash run_local.sh"else echo "建置失敗" exit 1fi
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265# 變更日誌 (Changelog)
> 記錄專案的重大變更、新功能與修復。採用 [Keep a Changelog](https://keepachangelog.com/) 格式。
## [Unreleased]
### Added- **波形繪製效能優化(針對 Hugging Face Space)** - **降採樣**:波形數據降採樣 5 倍(100 Hz → 20 Hz),從每測站 12000 點減少到 2400 點,大幅減少數據傳輸量。 - **WebGL 渲染**:使用 `Scattergl` 替代 `Scatter`,啟用 WebGL 加速渲染,適合大量數據點顯示。 - **簡化互動**:將 dragmode 從預設的框選縮放改為 pan(平移),減少渲染負擔。 - **效果**:在 Hugging Face Space 環境下,波形圖更新速度提升約 3-5 倍,滑桿反應更流暢。
- **STA/LTA 計算結果智能快取** - 新增全域快取 `sta_lta_cache`,在選擇事件時儲存所有測站的 STA/LTA 計算結果(P 波到時與 characteristic function)。 - **智能快取檢查**:在 `select_nearest_stations` 函數中,優先檢查快取是否存在,若存在則直接使用,避免重複計算。 - 當使用者調整時間滑桿時,直接使用快取的 P 波到時資訊,避免重複計算 STA/LTA,大幅提升 UI 反應速度。 - 快取結構:`{event_name: {station_code: {"p_arrival_time": float, "cft": array}}}` - **快取統計**:記錄快取命中率(cache hit/miss),方便除錯與效能分析。 - P 波到時資訊已存於 `selected_stations` 並透過 `gr.State` 傳遞,無需每次從原始波形重新計算。
- **P 波自動偵測功能(STA/LTA)** - 新增 `detect_p_wave_sta_lta()` 函數,使用 STA/LTA (Short-Term Average / Long-Term Average) 演算法自動偵測 P 波到時。 - 只有成功偵測到 P 波的測站才會被納入測站選擇與模型預測。 - P 波到時記錄在測站資訊中 (`p_arrival_time`),用於時間窗檢查。 - 波形圖上標記 P 波位置:綠色三角形(時間窗內)、紅色三角形(時間窗外)。 - 測試結果:在 50 個測站中達到 38% 偵測率(門檻 2.0)。- **時間窗內 P 波驗證** - 波形提取階段檢查 P 波是否在選定時間窗內 `[0, end_time]`。 - P 波不在時間窗內的測站會被跳過,避免模型收到空波形(完全為零)。 - 記錄統計:P 波偵測成功/失敗/時間窗外的測站數量。
### Changed- **測站選擇邏輯更新** - `select_nearest_stations()` 加入 P 波偵測步驟(使用 Z 分量)。 - 只保留成功偵測到 P 波的測站,確保模型輸入有實際訊號。 - 降級策略:無 Z 分量或 P 波偵測失敗 → 跳過測站(記錄 DEBUG)。- **波形圖視覺化增強** - `plot_waveform()` 在距離-時間圖上標記 P 波到時。 - 用顏色區分 P 波是否在時間窗內(綠色/紅色),提供視覺化回饋。- **波形提取邏輯強化** - `extract_waveforms_from_stream()` 新增 P 波時間窗檢查。 - 新增回傳值 `p_wave_outside_window_count` 用於統計與日誌。
### Improved- 避免模型收到無意義的空波形(P 波未到達時的零值波形)。- 提供清晰的視覺化回饋,讓使用者了解哪些測站有 P 波、哪些在時間窗內。- 日誌訊息記錄 P 波偵測統計,方便除錯與分析。
### Technical Details- STA/LTA 參數:`sta_len=0.5s`, `lta_len=10.0s`, `thr_on=2.0`, `thr_off=1.0`- 相依套件:ObsPy (已在 requirements.txt)- 程式碼語法驗證通過 ✅(只有類型提示警告,不影響執行)- 測試腳本:`test_p_wave_detection.py`,驗證 P 波偵測功能正常運作- 不變條件:維持 Z-N-E 分量順序、3000 samples @ 100 Hz、最多 25 站限制 ✅- 詳細文檔:參見 `P_WAVE_DETECTION_SUMMARY.md`
---
### Added- **MPS(Apple Metal Performance Shaders)推論後端** - 新增對 macOS Apple Silicon 上 PyTorch MPS 裝置的支援,可在 Apple M1/M2 系列上使用 GPU 加速推論。 - 自動裝置選擇:優先選擇 `mps`(若可用),其次 `cuda`,最後降級到 `cpu`。 - 支援透過環境變數 `TTSAM_DEVICE` 或設定覆寫裝置選擇(例如強制使用 `cpu`)。 - 若 MPS 不可用或出現錯誤,會自動降級到可用的裝置並記錄 Warning(參照 `spec/03-error-handling.md` 的降級策略)。- **相容性與說明** - 需要安裝具備 MPS 支援的 PyTorch 版本;若環境不支援,程式仍保持向後相容(不會改變公開 API)。
### Changed- 自動裝置選擇與初始化邏輯新增日誌(INFO/WARNING),以便排查裝置選擇與降級原因。
### Improved- 在 Apple Silicon(M1/M2)上進行推論時的效能相對於純 CPU 運算有明顯改善。- 針對 MPS 裝置的錯誤與邊界情況加入更寬鬆的降級路徑,確保單點錯誤不會中止整個流程(遵循 spec/03-error-handling.md)。
### Technical Details- 程式碼語法驗證通過 ✅(無 `SyntaxError`)。- 冒煙測試:已在開發機(macOS Apple Silicon)執行初步冒煙測��並驗證主流程可執行(波形載入、推論、地圖生成)。- 不變條件:本次變更為向後相容,未改變外部 API 或資料契約 ✅。
---
## [Sprint 003] — 震央資訊 JSON 管理化 (2025-10-26)
### Added- **震央資訊集中管理** - 新增 `waveform/event.json` 檔案,集中管理地震事件的元資料(震央座標、深度、規模等) - `event_id` 採用 YYYYMMDD 格式,直接對應波形檔案 (`waveform/YYYYMMDD.mseed`) 與震度圖 (`intensity_map/YYYYMMDD.png`) - 支持向後擴展:新增地震事件只需修改 JSON 檔案,無需改動代碼
- **自動座標注入機制** - 新增 `load_earthquake_metadata()` 函數,應用啟動時自動從 JSON 載入地震事件元資料 - 新增 `_get_epicenter_coords()` 輔助函數,自動從全域 `earthquake_metadata` 字典讀取座標 - 完整的異常處理與降級策略:JSON 缺失或格式錯誤時,使用預設座標 (121.57, 23.88) 不中斷應用
- **Gradio 介面唯讀座標顯示** - 移除「震央經度」與「震央緯度」輸入框,使用者無法編輯座標 - 新增唯讀文本框 `epicenter_info_display` 顯示當前事件的座標(例:「Latitude: 23.88 | Longitude: 121.57」) - 事件切換時自動更新座標顯示
### Changed- **函數簽名重構**(移除 epicenter 參數,改由全域 JSON 提供) - `load_and_display_waveform(event_name, start_time, duration)` ← 原:`(..., epicenter_lon, epicenter_lat)` - `predict_intensity(event_name, start_time, duration)` ← 原:`(..., epicenter_lon, epicenter_lat)` - `on_event_change(event_name, start_time, duration)` ← 原:`(..., epicenter_lon, epicenter_lat)` - `on_full_workflow(event_name, start_time, duration)` ← 原:`(..., epicenter_lon, epicenter_lat)`
- **Callback 綁定邏輯優化** - `event_dropdown.change()` 新增 `epicenter_info_display` 輸出,事件切換時同步更新座標顯示 - `demo.load()` 新增 `epicenter_info_display` 輸出,應用啟動時初始化座標顯示 - 所有 callback 的 `inputs` 移除 `epicenter_lon_input` 與 `epicenter_lat_input` 參數
### Improved- **資料管理** - 震央資訊不再硬編碼於代碼,改用 JSON 外部檔案管理,便於維護與擴展 - UI 和資料解耦:Gradio 介面不再依賴手動輸入的座標值
- **向後相容性** - 若 `waveform/event.json` 缺失,應用自動降級至預設座標,正常啟動 - 所有核心功能(波形、測站、推論、地圖)邏輯完全不變
### Technical Details- **程式碼質量**:程式碼語法驗證通過 ✅ (no `SyntaxError`)- **測試覆蓋**:冒煙測試全數通過 ✅- **不變條件**:所有核心模組(波形輸入、測站選擇、推論引擎、資料契約)保持不變 ✅
---
## [Sprint 002] — 首次載入完整工作流優化 (2025-10-26)
### Added- **首次載入自動完整工作流** - 應用啟動時自動執行完整工作流:波形載入 → 測站選擇 → 模型推論 → 地圖展示 - 新增 `on_full_workflow()` 函數,整合波形與推論步驟,一次性返回所有 UI 組件結果 - 首次打開應用時立即顯示完整的演示內容,無需用戶點擊任何按鈕 - **事件切換同步更新** - 修改 `event_dropdown.change` 事件綁定,改用 `on_full_workflow()` 完整工作流 - 選擇不同地震事件時,所有視圖同步自動更新(波形、地圖、統計、實際觀測圖)
- **波形視圖專用回調** - 新增 `on_event_change()` 函數,支持用戶手動調整時間窗後重新載入波形視圖 - 保留「載入波形」按鈕與「執行預測」按鈕的獨立操作選項
### Changed- **Gradio 事件系統重構** - `demo.load` 從 `on_event_change` 改為 `on_full_workflow`,首次加載自動執行推論 - `event_dropdown.change` 從 `on_event_change` 改為 `on_full_workflow`,事件切換自動推論
### Improved- **使用者體驗** - 應用首次啟動時不再出現空白頁面,立即展示完整的互動式演示 - 事件切換更加流暢,所有視圖實時同步,提升展示效果
---
## [Sprint 001] — 波形地圖自動載入 (2025-10-26)
### Added- **UI 流程自動化** - 應用啟動時自動載入預設地震事件的波形地圖(測站分布 + 波形圖) - 地震事件切換時同步自動更新波形地圖與實際觀測圖 - 新增 `on_event_change()` callback 協調多個 UI 組件的聯動更新 - 新增 `demo.load` 事件綁定,實現應用啟動自動初始化
### Changed- **規格理念調整**:從「穩定可靠系統」改為「互動式教育展示 Demo」 - 強調預裝化設計:所有資源(模型、Vs30、波形、測站表)預裝於 HF Space,無需運行時下載 - 容錯策略調整:預裝資源失敗中止啟動(提早發現問題),非關鍵資源失敗降級處理 - 目標轉向展覽演示與教育體驗,而非生產級可靠性 - **規格檔案更新** - `00-overview.md`:新增「設計理念」章節,明確 Demo 定位與預裝策略 - `01-data-contract.md`:新增預裝設計原則說明 - `02-processing-rules.md`:新增設計原則概述 - `03-error-handling.md`:完全重寫,移除網路容錯,強調預裝優先與降級策略 - 快速參考表:補充「部署環境」與預裝相關備註 - **README.md 擴展** - 新增「設計思路」章節(500 字),解釋 Demo 定位、預裝架構、容錯策略 - 新增「預裝架構表」,列舉所有預裝資源 - 新增「展覽前檢查清單」,指導部署前驗證流程 - 更新「快速參考」與「進一步閱讀」指向新的模塊化規格 - 更新「專案結構」說明 spec 資料夾的模塊化檔案
- **Gradio 事件綁定優化** - `event_dropdown.change` 現使用 `on_event_change()` 而非 `on_event_select()` - 一次事件切換可同時更新波形地圖、波形圖、實際觀測圖
---
## [1.0.0] — 初版 (Initial Release)
### Added- ✅ 完整的 Gradio GUI 介面 - 事件選擇、時間窗選擇、震央座標輸入 - 測站分布地圖、波形圖視覺化 - 互動式震度預測地圖(Folium) - 實際觀測與預測對照 - ✅ 核心推論管道 - 支援 CNN + Position Embedding + Transformer + MLP + MDN 架構 - 自動距離排序,選擇最近 25 站 - 批次推論(每批 25 目標點) - 條件處理與降級策略
- ✅ 穩健的資料處理 - 固定 100 Hz 取樣率、30 秒時間窗(3000 samples) - 分量驗證與缺失降級(N/E 缺失以 Z 替代) - 訊號處理(去趨勢、10 Hz 低通濾波) - 補零對齊(不足 30 秒尾段補 0)
- ✅ 外部資源整合 - Hugging Face 模型載入(`SeisBlue/TTSAM`) - Vs30 資料查詢(`SeisBlue/TaiwanVs30`);失敗降級至預設 600 m/s - 本地 MSEED 波形讀取 - 本地測站表讀取(CSV)
- ✅ 日誌與監控 - loguru 日誌系統(INFO/WARNING/ERROR) - 關鍵節點記錄(啟動、選擇、推論、完成) - 降級決策透明化
- ✅ 測試資料 - 範例事件:2024年4月3日花蓮地震 (`20240403.mseed`) - 範例目標點與測站表
### Known Limitations- 模型輸入固定為 25 站、30 秒- Vs30 查詢基於 2D 網格最近鄰法(不考慮深度)- 不支援即時流模式(僅批次)- 地圖高度固定 800px
### Notes for Future- 見 `spec/04-extensions.md` 的擴充建議- 見 `spec/plan.md` 的迭代計畫範本
---
## 版本說明
| 版本 | 發行日期 | 重點 ||-----|--------|------|| v1.0.0 | 2024年 | 初版發佈 || (未來) | (待定) | 功能擴展 |
---
## 貢獻指南
提交變更前,請:1. 查閱 `.github/copilot-instructions.md` 開發指南2. 確認相應 spec 檔案已同步(若涉及資料契約、處理規則、故障場景)3. 更新本 changelog(`## [Unreleased]` 段落)4. 執行測試確保無新增 ERROR 日誌
---
## 許可證
GPL-3.0
---
**最後更新**:2024 年 10 月 26 日123456789#!/bin/bashdocker container rm ttsam-demo -f || truedocker run \ -it \ --rm \ --net host \ -v $(pwd):/home/user/app \ --name ttsam-demo \ ttsam-demo123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375import numpy as npimport torchimport torch.nn as nn
from loguru import logger
# GPU/CPU 設定if torch.cuda.is_available(): device = torch.device("cuda") logger.info("使用 GPU")elif torch.mps.is_available(): device = torch.device("mps") logger.info("使用 Apple MPS")else: device = torch.device("cpu") logger.info("使用 CPU")
class LambdaLayer(nn.Module): def __init__(self, lambd, eps=1e-4): super(LambdaLayer, self).__init__() self.lambd = lambd self.eps = eps
def forward(self, x): return self.lambd(x) + self.eps
class MLP(nn.Module): def __init__( self, input_shape, dims=(500, 300, 200, 150), activation=nn.ReLU(), last_activation=None, ): super(MLP, self).__init__() if last_activation is None: last_activation = activation self.dims = dims self.first_fc = nn.Linear(input_shape[0], dims[0]) self.first_activation = activation
more_hidden = [] if len(self.dims) > 2: for i in range(1, len(self.dims) - 1): more_hidden.append(nn.Linear(self.dims[i - 1], self.dims[i])) more_hidden.append(nn.ReLU())
self.more_hidden = nn.ModuleList(more_hidden) self.last_fc = nn.Linear(dims[-2], dims[-1]) self.last_activation = last_activation
def forward(self, x): output = self.first_fc(x) output = self.first_activation(output) if self.more_hidden: for layer in self.more_hidden: output = layer(output) output = self.last_fc(output) output = self.last_activation(output) return output
class CNN(nn.Module): def __init__( self, input_shape=(-1, 6000, 3), activation=nn.ReLU(), downsample=1, mlp_input=11665, mlp_dims=(500, 300, 200, 150), eps=1e-8, ): super(CNN, self).__init__() self.input_shape = input_shape self.activation = activation self.downsample = downsample self.mlp_input = mlp_input self.mlp_dims = mlp_dims self.eps = eps
self.lambda_layer_1 = LambdaLayer( lambda t: t / ( torch.max( torch.max(torch.abs(t), dim=1, keepdim=True).values, dim=2, keepdim=True, ).values + self.eps ) ) self.unsqueeze_layer1 = LambdaLayer(lambda t: torch.unsqueeze(t, dim=1)) self.lambda_layer_2 = LambdaLayer( lambda t: torch.log( torch.max(torch.max(torch.abs(t), dim=1).values, dim=1).values + self.eps ) / 100 ) self.unsqueeze_layer2 = LambdaLayer(lambda t: torch.unsqueeze(t, dim=1)) self.conv2d1 = nn.Sequential( nn.Conv2d(1, 8, kernel_size=(1, downsample), stride=(1, downsample)), nn.ReLU(), ) self.conv2d2 = nn.Sequential( nn.Conv2d(8, 32, kernel_size=(16, 3), stride=(1, 3)), nn.ReLU() ) self.conv1d1 = nn.Sequential(nn.Conv1d(32, 64, kernel_size=16), nn.ReLU()) self.maxpooling = nn.MaxPool1d(2) self.conv1d2 = nn.Sequential(nn.Conv1d(64, 128, kernel_size=16), nn.ReLU()) self.conv1d3 = nn.Sequential(nn.Conv1d(128, 32, kernel_size=8), nn.ReLU()) self.conv1d4 = nn.Sequential(nn.Conv1d(32, 32, kernel_size=8), nn.ReLU()) self.conv1d5 = nn.Sequential(nn.Conv1d(32, 16, kernel_size=4), nn.ReLU()) self.mlp = MLP((self.mlp_input,), dims=self.mlp_dims)
def forward(self, x): output = self.lambda_layer_1(x) output = self.unsqueeze_layer1(output) scale = self.lambda_layer_2(x) scale = self.unsqueeze_layer2(scale) output = self.conv2d1(output) output = self.conv2d2(output) output = torch.squeeze(output, dim=-1) output = self.conv1d1(output) output = self.maxpooling(output) output = self.conv1d2(output) output = self.maxpooling(output) output = self.conv1d3(output) output = self.maxpooling(output) output = self.conv1d4(output) output = self.conv1d5(output) output = torch.flatten(output, start_dim=1) output = torch.cat((output, scale), dim=1) output = self.mlp(output) return output
class PositionEmbeddingVs30(nn.Module): def __init__( self, wavelengths=((5, 30), (110, 123), (0.01, 5000), (100, 1600)), emb_dim=500 ): super(PositionEmbeddingVs30, self).__init__() self.wavelengths = wavelengths self.emb_dim = emb_dim
min_lat, max_lat = wavelengths[0] min_lon, max_lon = wavelengths[1] min_depth, max_depth = wavelengths[2] min_vs30, max_vs30 = wavelengths[3]
assert emb_dim % 10 == 0 lat_dim = emb_dim // 5 lon_dim = emb_dim // 5 depth_dim = emb_dim // 10 vs30_dim = emb_dim // 10
self.lat_coeff = ( 2 * np.pi * 1.0 / min_lat * ((min_lat / max_lat) ** (np.arange(lat_dim) / lat_dim)) ) self.lon_coeff = ( 2 * np.pi * 1.0 / min_lon * ((min_lon / max_lon) ** (np.arange(lon_dim) / lon_dim)) ) self.depth_coeff = ( 2 * np.pi * 1.0 / min_depth * ((min_depth / max_depth) ** (np.arange(depth_dim) / depth_dim)) ) self.vs30_coeff = ( 2 * np.pi * 1.0 / min_vs30 * ((min_vs30 / max_vs30) ** (np.arange(vs30_dim) / vs30_dim)) )
lat_sin_mask = np.arange(emb_dim) % 5 == 0 lat_cos_mask = np.arange(emb_dim) % 5 == 1 lon_sin_mask = np.arange(emb_dim) % 5 == 2 lon_cos_mask = np.arange(emb_dim) % 5 == 3 depth_sin_mask = np.arange(emb_dim) % 10 == 4 depth_cos_mask = np.arange(emb_dim) % 10 == 9 vs30_sin_mask = np.arange(emb_dim) % 10 == 5 vs30_cos_mask = np.arange(emb_dim) % 10 == 8
self.mask = np.zeros(emb_dim) self.mask[lat_sin_mask] = np.arange(lat_dim) self.mask[lat_cos_mask] = lat_dim + np.arange(lat_dim) self.mask[lon_sin_mask] = 2 * lat_dim + np.arange(lon_dim) self.mask[lon_cos_mask] = 2 * lat_dim + lon_dim + np.arange(lon_dim) self.mask[depth_sin_mask] = 2 * lat_dim + 2 * lon_dim + np.arange(depth_dim) self.mask[depth_cos_mask] = ( 2 * lat_dim + 2 * lon_dim + depth_dim + np.arange(depth_dim) ) self.mask[vs30_sin_mask] = ( 2 * lat_dim + 2 * lon_dim + 2 * depth_dim + np.arange(vs30_dim) ) self.mask[vs30_cos_mask] = ( 2 * lat_dim + 2 * lon_dim + 2 * depth_dim + vs30_dim + np.arange(vs30_dim) ) self.mask = self.mask.astype("int32")
def forward(self, x): lat_base = x[:, :, 0:1].to(device) * torch.Tensor(self.lat_coeff).to(device) lon_base = x[:, :, 1:2].to(device) * torch.Tensor(self.lon_coeff).to(device) depth_base = x[:, :, 2:3].to(device) * torch.Tensor(self.depth_coeff).to(device) vs30_base = x[:, :, 3:4] * torch.Tensor(self.vs30_coeff).to(device)
output = torch.cat( [ torch.sin(lat_base), torch.cos(lat_base), torch.sin(lon_base), torch.cos(lon_base), torch.sin(depth_base), torch.cos(depth_base), torch.sin(vs30_base), torch.cos(vs30_base), ], dim=-1, )
maskk = torch.from_numpy(np.array(self.mask)).long() index = ( (maskk.unsqueeze(0).unsqueeze(0)) .expand(x.shape[0], 1, self.emb_dim) .to(device) ) output = torch.gather(output, -1, index).to(device) return output
class TransformerEncoder(nn.Module): def __init__( self, d_model=150, nhead=10, batch_first=True, activation="gelu", dropout=0.0, dim_feedforward=1000, ): super(TransformerEncoder, self).__init__() self.encoder_layer = nn.TransformerEncoderLayer( d_model=d_model, nhead=nhead, batch_first=batch_first, activation=activation, dropout=dropout, dim_feedforward=dim_feedforward, ).to(device) self.transformer_encoder = nn.TransformerEncoder(self.encoder_layer, 6).to( device )
def forward(self, x, src_key_padding_mask=None): return self.transformer_encoder(x, src_key_padding_mask=src_key_padding_mask)
class MDN(nn.Module): def __init__(self, input_shape=(150,), n_hidden=20, n_gaussians=5): super(MDN, self).__init__() self.z_h = nn.Sequential(nn.Linear(input_shape[0], n_hidden), nn.Tanh()) self.z_weight = nn.Linear(n_hidden, n_gaussians) self.z_sigma = nn.Linear(n_hidden, n_gaussians) self.z_mu = nn.Linear(n_hidden, n_gaussians)
def forward(self, x): z_h = self.z_h(x) weight = nn.functional.softmax(self.z_weight(z_h), -1) sigma = torch.exp(self.z_sigma(z_h)) mu = self.z_mu(z_h) return weight, sigma, mu
class FullModel(nn.Module): def __init__( self, model_cnn, model_position, model_transformer, model_mlp, model_mdn, max_station=25, pga_targets=15, emb_dim=150, data_length=6000, ): super(FullModel, self).__init__() self.data_length = data_length self.model_CNN = model_cnn self.model_Position = model_position self.model_Transformer = model_transformer self.model_mlp = model_mlp self.model_MDN = model_mdn self.max_station = max_station self.pga_targets = pga_targets self.emb_dim = emb_dim
def forward(self, data): cnn_output = self.model_CNN( torch.DoubleTensor(data["waveform"].reshape(-1, self.data_length, 3)) .float() .to(device) ) cnn_output_reshape = torch.reshape( cnn_output, (-1, self.max_station, self.emb_dim) )
emb_output = self.model_Position( torch.DoubleTensor(data["station"].reshape(-1, 1, data["station"].shape[2])) .float() .to(device) ) emb_output = emb_output.reshape(-1, self.max_station, self.emb_dim)
station_pad_mask = data["station"] == 0 station_pad_mask = torch.all(station_pad_mask, 2)
pga_pos_emb_output = self.model_Position( torch.DoubleTensor(data["target"].reshape(-1, 1, data["target"].shape[2])) .float() .to(device) ) pga_pos_emb_output = pga_pos_emb_output.reshape( -1, self.pga_targets, self.emb_dim )
target_pad_mask = torch.ones_like(data["target"], dtype=torch.bool) target_pad_mask = torch.all(target_pad_mask, 2) pad_mask = torch.cat((station_pad_mask, target_pad_mask), dim=1).to(device)
add_pe_cnn_output = torch.add(cnn_output_reshape, emb_output) transformer_input = torch.cat((add_pe_cnn_output, pga_pos_emb_output), dim=1) transformer_output = self.model_Transformer(transformer_input, pad_mask)
mlp_input = transformer_output[:, -self.pga_targets :, :].to(device) mlp_output = self.model_mlp(mlp_input) weight, sigma, mu = self.model_MDN(mlp_output)
return weight, sigma, mu
def get_full_model(model_path): emb_dim = 150 mlp_dims = (150, 100, 50, 30, 10) cnn_model = CNN(mlp_input=5665).to(device) pos_emb_model = PositionEmbeddingVs30(emb_dim=emb_dim).to(device) transformer_model = TransformerEncoder() mlp_model = MLP(input_shape=(emb_dim,), dims=mlp_dims).to(device) mdn_model = MDN(input_shape=(mlp_dims[-1],)).to(device) full_model = FullModel( cnn_model, pos_emb_model, transformer_model, mlp_model, mdn_model, pga_targets=25, data_length=3000, ).to(device) full_model.load_state_dict( torch.load(model_path, weights_only=True, map_location=device) ) return full_model1234567891011121314datasetsgradiohuggingface_hublogurumatplotlibnetCDF4numpyobspypandasplotlyscipytorchtransformersxarray1234567891011121314gradiotransformersdatasetstorchobspynumpymatplotlibxarraynetCDF4scipypandasloguruhuggingface_hubfolium
1234567891011121314151617181920#!/bin/bash# 執行本地開發容器(掛載當前目錄,即時修改生效)
echo "啟動 TTSAM 本地開發容器..."echo "掛載當前目錄到容器中"echo "修改程式碼會立即生效,無需重建 image"echo ""
docker container rm ttsam-demo -f 2>/dev/null || true
docker run \ -it \ --rm \ --net host \ -v $(pwd):/home/user/app \ --name ttsam-demo \ ttsam-demo
echo ""echo "容器已停止"123version https://git-lfs.github.com/spec/v1oid sha256:1c02a7754ae0ad6a45a5a5bef3220220e47bd4b867be89d34b5df94cf33862a8size 11558912123version https://git-lfs.github.com/spec/v1oid sha256:3c4683e99abd8e69f7fc6d8f16aa7c7da3de7522320bbb3483930c16415ee90bsize 17133568123version https://git-lfs.github.com/spec/v1oid sha256:6e8beedc2a60382dd657ca588271db0f6808d45fbd7e4704ff2c09ef76f0e6f0size 22388736123version https://git-lfs.github.com/spec/v1oid sha256:2706992997b8eb30e568c3470e6f1d8c99654b8a4b1a12b33099fe91900cd51asize 37216256
123version https://git-lfs.github.com/spec/v1oid sha256:199bae2e8477f06ea53d085dc3573407a6f8e50b4c798edd999751340d61d4e7size 2035712012345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152{ "events": [ { "event_id": "20211024051134", "event_name": "1024 宜蘭外海地震 (2021)", "timestamp": "2021-10-24T05:11:34Z", "first_pick": 11.15, "mseed_file": "waveform/20211024.mseed", "intensity_map_file": "intensity_map/2021102413113465103_H.png", "epicenter_lat": 24.53, "epicenter_lon": 121.79, "depth_km": 66.8, "magnitude": 6.5 }, { "event_id": "20220918064415", "event_name": "0918 池上地震 (2022)", "timestamp": "2022-09-18T06:44:15Z", "first_pick": 2.0, "mseed_file": "waveform/20220918.mseed", "intensity_map_file": "intensity_map/2022091814441568111_H.png", "epicenter_lat": 23.14, "epicenter_lon": 121.2, "depth_km": 7.0, "magnitude": 6.8 }, { "event_id": "20240402235809", "event_name": "0403 花蓮地震 (2024)", "timestamp": "2024-04-02T23:58:09Z", "first_pick": 5.3, "mseed_file": "waveform/20240403.mseed", "intensity_map_file": "intensity_map/2024040307580972019_H.png", "epicenter_lat": 23.77, "epicenter_lon": 121.67, "depth_km": 15.5, "magnitude": 7.2 }, { "event_id": "20250120161727", "event_name": "0120 大埔地震 (2025)", "timestamp": "2025-01-20T16:17:27Z", "first_pick": 3.55, "mseed_file": "waveform/20250120.mseed", "intensity_map_file": "intensity_map/2025012100172764007_H.png", "epicenter_lat": 23.23, "epicenter_lon": 120.57, "depth_km": 9.7, "magnitude": 6.4 } ]}.dockerignoreDeleted-13
.gitignore-7
Dockerfile.localDeleted-38
README.md-148
app.py+746-962
build_local.shDeleted-16
changelog.mdDeleted-265
intensity_map/2021102413113465103_H.png → ground_truth/20240403.pngRenamed

Large File Pointer Details
- SHA256: b17fece6647dc8b3c1ecc5ca8fe786638251ac3bc458016f0a90540781046f63
- Pointer size: 131 Bytes
- Size of remote file: 580 kB

Large File Pointer Details
- SHA256: e522bcc031deb5e7164646db51753e027bc4093fc09e8d0114a39b57e5c2363f
- Pointer size: 131 Bytes
- Size of remote file: 136 kB
image_python.shDeleted-9
intensity_map/2022091814441568111_H.pngDeleted

Large File Pointer Details
- SHA256: 97dbd6b00dfc4e476ec2d29b38121f01cd6566ecd567fdb76fbaa8317e4b5069
- Pointer size: 131 Bytes
- Size of remote file: 577 kB
intensity_map/2024040307580972019_H.pngDeleted

Large File Pointer Details
- SHA256: 365461a9eb7d19cac733b662636d2fa101deff5f504ff2df2a761c03883eff28
- Pointer size: 131 Bytes
- Size of remote file: 587 kB
intensity_map/2025012100172764007_H.pngDeleted

Large File Pointer Details
- SHA256: 32dc5aa10f81663373c8efd62eac15d4edf7101c9b87e1245f9d420ba745e88c
- Pointer size: 131 Bytes
- Size of remote file: 581 kB
model.pyDeleted-375
requirements.txt+10-10
run_local.shDeleted-20
waveform/20211024.mseedDeleted-3
waveform/20220918.mseedDeleted-3
waveform/20240403.mseed+2-2
waveform/20250120.mseedDeleted-3
waveform/event.jsonDeleted-52