Spaces:
Runtime error
Runtime error
Commit ·
23eb3ea
1
Parent(s): 7781d84
docs: refactor event handling and streamline data loading in app.py
Browse filesFiles changed (10)
- app.py+409-607
- intensity_map/20240403.png → intensity_map/2021102413113465103_H.pngRenamed
- intensity_map/2022091814441568111_H.pngAdded
- intensity_map/2024040307580972019_H.pngAdded
- intensity_map/2025012100172764007_H.pngAdded
- waveform/20211024.mseedAdded+3
- waveform/20220918.mseedAdded+3
- waveform/20240403.mseed+2-2
- waveform/20250120.mseedAdded+3
- waveform/event.json+45-9
1234567891011121314151617181920212223242526272829303132331 unmodified line3536373839404142434445464748495010 unmodified lines616263646566676869707172737 unmodified lines81828384858687888990912 unmodified lines94959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746821 unmodified lines4904914924934944954969 unmodified lines50650750850951051151251351451551651751851952052120 unmodified lines5425435445455465475485495506 unmodified lines5575585595605615625637 unmodified lines57157257357457557657757857958058158258358423 unmodified lines6086096106116126136146156166176186196206216226236246258 unmodified lines63463563663763863964064142 unmodified lines6846856866876886896906916926936946956962 unmodified lines69970070170270370470570670770813 unmodified lines72272372472572672772872973020 unmodified lines7517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318323 unmodified lines8368378388398408418428438448458468478488494 unmodified lines85485585685785885986015 unmodified lines8768778788798808818828838848858868872 unmodified lines8908918928938948958968978988999009019029039049059069079089099109119122 unmodified lines91591691791891992092192216 unmodified lines9399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689692 unmodified lines97297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410153 unmodified lines101910201021102210231024102510261027102810291030103110322 unmodified lines103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610572 unmodified lines10601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871 unmodified line108910901091109210931094109510961097109810995 unmodified lines11051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113117 unmodified lines114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311 unmodified lines11851186118711881189119011911192119311941 unmodified line11961197119811991200120112024 unmodified lines1207120812091210121112121213121412151216121711 unmodified lines12291230123112321233123412353 unmodified lines12391240124112421243124412457 unmodified lines1253125412551256125712581259126012611262126312642 unmodified lines12671268126912701271127212731274127512761277127812791280128112821283128412852 unmodified lines128812891290129112921293129412952 unmodified lines1298129913001301130213031304130513062 unmodified lines13091310131113121313131413151 unmodified line1317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353import 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 loggerimport plotly.graph_objs as go# 設定 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")elif torch.mps.is_available():device = torch.device("mps")logger.info("使用 Apple MPS")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 資料載入完成")10 unmodified lines# 驗證 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} 找不到")7 unmodified linestarget_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)} 個目標點)")2 unmodified linesexcept Exception as e:logger.error(f"{target_file} 載入失敗: {e}")# 預設地震事件EARTHQUAKE_EVENTS = {"0403花蓮地震 (2024)": "waveform/20240403.mseed",}# ============ 震央資訊管理 ============def load_earthquake_metadata(event_json_path="waveform/event.json"):"""從 JSON 檔案讀取地震事件元資料(震央經緯度、深度等)參數:event_json_path: event.json 的相對或絕對路徑返回:dict: {event_name -> {"epicenter_lat", "epicenter_lon", "depth_km", ...}}若檔案缺失或無效,使用預設座標 (121.57, 23.88) 並記錄警��"""earthquake_metadata = {}try:import jsonwith open(event_json_path, 'r', encoding='utf-8') as f:data = json.load(f)if "events" not in data:logger.warning(f"{event_json_path} 缺少 'events' 鍵,使用預設座標")return {}# 將事件列表轉換為以 event_name 為鍵的字典for event in data["events"]:event_name = event.get("event_name")if event_name:earthquake_metadata[event_name] = {"epicenter_lat": event.get("epicenter_lat", 23.88),"epicenter_lon": event.get("epicenter_lon", 121.57),"depth_km": event.get("depth_km", None),"magnitude": event.get("magnitude", None),}logger.info(f"載入事件: {event_name} | 震央: ({event.get('epicenter_lon', 121.57)}, {event.get('epicenter_lat', 23.88)})")logger.info(f"地震事件元資料載入完成(共 {len(earthquake_metadata)} 個事件)")return earthquake_metadataexcept FileNotFoundError:logger.error(f"事件元資料檔案缺失: {event_json_path}")logger.warning("將使用預設震央座標 (121.57, 23.88)")return {}except Exception as e:logger.error(f"讀取事件元資料時發生錯誤: {e}")logger.warning("將使用預設震央座標 (121.57, 23.88)")return {}def _get_epicenter_coords(event_name):"""從全域 earthquake_metadata 獲取指定事件的震央座標參數:event_name: 事件名稱(EARTHQUAKE_EVENTS 的鍵值)返回:tuple: (epicenter_lat, epicenter_lon)若事件不存在或座標缺失,返回預設座標 (23.88, 121.57)"""if event_name in earthquake_metadata:metadata = earthquake_metadata[event_name]lat = metadata.get("epicenter_lat", 23.88)lon = metadata.get("epicenter_lon", 121.57)return lat, lonelse:logger.warning(f"未找到事件 '{event_name}' 的元資料,使用預設震央座標")return 23.88, 121.57# 載入地震事件元資料earthquake_metadata = load_earthquake_metadata("waveform/event.json")if not earthquake_metadata:logger.warning("無法載入事件元資料,應用將使用預設震央座標")# ============ 模型定義(從 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 / fe21 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])9 unmodified lines# ============ 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):20 unmodified lines# 驗證必要欄位存在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]6 unmodified lines"distance": distance,"latitude": lat,"longitude": lon,"elevation": elev}except Exception as e:logger.warning(f"測站 {station_code} 資訊查詢失敗: {e}")7 unmodified lines# 記錄實際可用的測站數(少於 25 站也允許繼續)actual_count = len(selected_stations)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(st, selected_stations, start_time, duration, vs30_input):"""從 Stream 中提取選定測站的波形資料23 unmodified linessampling_rate = 100 # 100 Hzmin_duration = 30.0 # 最小時間長度 30 秒target_length = 3000 # 30 秒 @ 100 Hz = 3000 samples# 內部計算 end_time(接受 start/duration 參數)end_time = start_time + durationstart_idx = int(start_time * sampling_rate)end_idx = int(end_time * sampling_rate)actual_samples = end_idx - start_idx# 檢查是否需要零填充:長度不足 30 秒時尾段以 0 遮罩補齊needs_padding = duration < min_durationif needs_padding:logger.info(f"時間長度 {duration} 秒 < 30 秒,將以 0 遮罩補齊至 {min_duration} 秒")for station_data in selected_stations:station_code = station_data["station"]8 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:42 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:2 unmodified lineslogger.info(f"成功提取 {len(waveforms)} 個測站的波形")if missing_components_count > 0:logger.info(f"其中 {missing_components_count} 個測站缺少 N 或 E 分量(已以 Z 分量代替)")return waveforms, station_info_list, valid_stations, missing_components_countdef create_input_station_map(selected_stations, epicenter_lat, epicenter_lon):"""創建輸入測站分布地圖:顯示所有測站 + 突顯被選中的 25 個(使用 Plotly)"""13 unmodified linesall_stations_text.append(station_code)# 準備選中測站資料(按距離分組)selected_group1_lat, selected_group1_lon, selected_group1_text = [], [], [] # 前 5 近selected_group2_lat, selected_group2_lon, selected_group2_text = [], [], [] # 6-15 近selected_group3_lat, selected_group3_lon, selected_group3_text = [], [], [] # 16-25 近for i, station_data in enumerate(selected_stations):station_code = station_data["station"]20 unmodified linesfig = go.Figure()# 添加所有測站(灰色小點)fig.add_trace(go.Scattermap(lat=all_stations_lat,lon=all_stations_lon,mode='markers',marker=dict(size=6, color='gray', opacity=0.6),text=all_stations_text,hovertemplate='%{text}<extra></extra>',name=f'所有測站 ({len(all_stations_lat)} 個)',showlegend=True))# 添加選中測站 - 前 5 近(綠色)if selected_group1_lat:fig.add_trace(go.Scattermap(lat=selected_group1_lat,lon=selected_group1_lon,mode='markers',marker=dict(size=12, color='green', opacity=0.8),text=selected_group1_text,hovertemplate='%{text}<extra></extra>',name='前 5 近',showlegend=True))# 添加選中測站 - 6-15 近(藍色)if selected_group2_lat:fig.add_trace(go.Scattermap(lat=selected_group2_lat,lon=selected_group2_lon,mode='markers',marker=dict(size=12, color='blue', opacity=0.8),text=selected_group2_text,hovertemplate='%{text}<extra></extra>',name='6-15 近',showlegend=True))# 添加選中測站 - 16-25 近(橘色)if selected_group3_lat:fig.add_trace(go.Scattermap(lat=selected_group3_lat,lon=selected_group3_lon,mode='markers',marker=dict(size=12, color='orange', opacity=0.8),text=selected_group3_text,hovertemplate='%{text}<extra></extra>',name='16-25 近',showlegend=True))# 添加震央(紅色大點)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})'],hovertemplate='%{text}<extra></extra>',name='震央',showlegend=True))fig.add_trace(go.Scattermap(lat=[epicenter_lat],lon=[epicenter_lon],mode='markers',marker=dict(size=10, color='white'),showlegend=False))# 設置地圖佈局fig.update_layout(map=dict(style="open-street-map",center=dict(lat=epicenter_lat, lon=epicenter_lon),zoom=7),height=500, # 設置固定高度以適應 Gradio 容器margin=dict(l=0, r=0, t=0, b=0),3 unmodified linesy=0.95,xanchor="left",x=0.01,bgcolor="rgba(255, 255, 255, 0.8)"))return figdef plot_waveform(st, selected_stations, start_time, duration):"""繪製選定測站的波形圖(距離-時間圖,可顯示全部 25 個測站)4 unmodified lines- duration: 時間長度(秒)"""# 計算結束時間end_time = start_time + durationfig, ax = plt.subplots(figsize=(14, 10))15 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)2 unmodified linesax2.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 fig16 unmodified linesreturn color_map.get(intensity, "#ffffff")def create_intensity_map(pga_list, target_names, epicenter_lat=None, epicenter_lon=None):"""使用 Plotly 創建互動式震度分布地圖"""# 按震度等級分組資料intensity_groups = {i: {'lat': [], 'lon': [], 'text': [], 'color': get_intensity_color(i)}for i in range(10)}# 添加震度測站標記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)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)# 創建 Plotly 地圖fig = go.Figure()2 unmodified linesintensity_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',marker=dict(size=14,color=group['color'],opacity=0.8),text=group['text'],hovertemplate='%{text}<extra></extra>',name=f'震度 {intensity_labels[intensity_level]}',showlegend=True))else:# 沒有資料的震度等級:添加隱形標記只為了顯示圖例fig.add_trace(go.Scattermap(lat=[None],lon=[None],mode='markers',marker=dict(size=14,color=group['color'],opacity=0.8),name=f'震度 {intensity_labels[intensity_level]}',showlegend=True,hoverinfo='skip'))# 設置地圖佈局fig.update_layout(map=dict(style="open-street-map",center=dict(lat=23.5,lon=121),zoom=7),height=800, # 設置固定高度以適應 Gradio 容器margin=dict(l=0, r=0, t=0, b=0),3 unmodified linesy=0.95,xanchor="left",x=0.01,bgcolor="rgba(255, 255, 255, 0.8)"))return figdef load_observed_intensity_image(event_name):"""從 intensity_map 資料夾載入對應的實際觀測震度圖2 unmodified lines"""import osevent_file = EARTHQUAKE_EVENTS[event_name]event_date = os.path.basename(event_file).replace('.mseed', '')intensity_map_dir = "intensity_map"possible_extensions = ['.png', '.jpg', '.jpeg', '.gif']for ext in possible_extensions:image_path = os.path.join(intensity_map_dir, f"{event_date}{ext}")if os.path.exists(image_path):logger.info(f"載入實際觀測震度圖: {image_path}")return image_pathlogger.warning(f"找不到實際震度圖: {event_date}(將顯示空白占位)")return Nonedef load_and_display_waveform(event_name, start_time, duration):"""載入並顯示波形,讓使用者確認範圍從全域 earthquake_metadata 讀取震央座標2 unmodified lines"""try:# 從全域 earthquake_metadata 讀取震央座標epicenter_lat, epicenter_lon = _get_epicenter_coords(event_name)# 計算結束時間(用於顯示資訊)end_time = start_time + duration# 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, "錯誤:找不到有效的測站資料", gr.update(interactive=False)# 3. 繪製波形(傳入 start_time 和 duration)waveform_plot = plot_waveform(st, selected_stations, start_time, duration)# 4. 創建輸入測站地圖station_map = create_input_station_map(selected_stations, epicenter_lat, epicenter_lon)logger.info("波形載入完成")return station_map, waveform_plot, gr.update(interactive=True)1 unmodified lineexcept Exception as e:logger.error(f"波形載入發生錯誤: {e}")import tracebacktraceback.print_exc()return None, None, gr.update(interactive=False)def predict_intensity(event_name, start_time, duration):"""執行震度預測5 unmodified lines"""try:# 從全域 earthquake_metadata 讀取震央座標epicenter_lat, epicenter_lon = _get_epicenter_coords(event_name)# 計算結束時間(內部處理)end_time = start_time + duration# 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} 秒起,持續 {duration} 秒)...")waveforms, station_info_list, valid_stations, missing_components_count = extract_waveforms_from_stream(st, selected_stations, start_time, duration, vs30_input=600)if len(waveforms) == 0:17 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 個)11 unmodified lines# 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)} 個測站的預測!")1 unmodified linetarget_names = all_target_names# 繪製互動式地圖(固定高度 800)intensity_map = create_intensity_map(pga_list, target_names, epicenter_lat, epicenter_lon)# 載入實際觀測震度圖(filepath;左側以 800 高顯示)observed_intensity_path = load_observed_intensity_image(event_name)4 unmodified linesexcept Exception as e:logger.error(f"預測過程發生錯誤: {e}")import tracebacktraceback.print_exc()return None, Nonedef on_full_workflow(event_name, start_time, duration):"""執行完整的工作流:波形載入 → 測站選擇 → 推論 → 結果展示11 unmodified lines# 步驟 1: 載入波形logger.info(f"[on_full_workflow] 步驟 1/3: 波形載入...")station_map, waveform_plot, _ = load_and_display_waveform(event_name, start_time, duration)if station_map is None:3 unmodified lines# 步驟 2: 執行推論logger.info(f"[on_full_workflow] 步驟 2/3: 模型推論...")observed_img, predicted_map = predict_intensity(event_name, start_time, duration)if predicted_map is None:7 unmodified linesexcept Exception as e:logger.error(f"[on_full_workflow] 完整工作流發生錯誤: {e}")import tracebacktraceback.print_exc()return None, None, f"錯誤: {str(e)}", None, f"錯誤: {str(e)}", None# ============ Gradio 介面 ============with gr.Blocks(title="TTSAM 震度預測系統", fill_height=True) as demo:gr.Markdown("# 🌏 TTSAM 震度預測系統")2 unmodified lines# 左上:使用步驟與狀態顯示with gr.Column(scale=1):gr.Markdown("## 使用步驟")gr.Markdown("""1. 選擇地震事件和時間範圍2. 輸入震央位置和場址參數3. 點擊載入波形確認波形範圍4. 確認無誤後點擊執行預測系統會自動選擇距離震央最近的 25 個測站""")with gr.Column(scale=1):event_dropdown = gr.Dropdown(choices=list(EARTHQUAKE_EVENTS.keys()),value=list(EARTHQUAKE_EVENTS.keys())[0],label="選擇地震事件")# ========== 中層:輸入測站地圖與波形圖 ==========with gr.Row():2 unmodified linesgr.Markdown("## 輸入測站分布")input_station_map = gr.Plot(label="輸入測站地圖")load_waveform_btn = gr.Button("📊 載入波形", variant="secondary", scale=1)predict_btn = gr.Button("🔮 執行預測", variant="primary", scale=1,interactive=False)# 中右:輸入波形with gr.Column(scale=1):2 unmodified lineslabel="地震波形(選定的 25 個測站)",)with gr.Row():start_slider = gr.Slider(0, 300, value=0, step=1, label="開始時間 (秒)")duration_slider = gr.Slider(0, 30, value=30, step=1, label="時間長度 (秒)")# ========== 下層:實際觀測 vs 預測結果 ==========with gr.Row():2 unmodified linesgr.Markdown("## 預測震度分布")predicted_intensity_map = gr.Plot(label="互動式震度地圖")# 右下:實際觀測震度圖with gr.Column(scale=1):gr.Markdown("## 實際觀測震度分布")1 unmodified linelabel="實際觀測震度",type="filepath",height=800,value=load_observed_intensity_image(list(EARTHQUAKE_EVENTS.keys())[0]))# 綁定事件event_dropdown.change(fn=lambda event_name, start_time, duration: (*on_full_workflow(event_name, start_time, duration),),inputs=[event_dropdown, start_slider, duration_slider],outputs=[input_station_map, waveform_plot, predicted_intensity_map, observed_intensity_image])load_waveform_btn.click(fn=load_and_display_waveform,inputs=[event_dropdown, start_slider, duration_slider],outputs=[input_station_map, waveform_plot, predict_btn])predict_btn.click(fn=predict_intensity,inputs=[event_dropdown, start_slider, duration_slider],outputs=[observed_intensity_image, predicted_intensity_map])# 應用啟動時自動執行完整工作流demo.load(fn=lambda event_name, start_time, duration: (*on_full_workflow(event_name, start_time, duration),),inputs=[event_dropdown, start_slider, duration_slider],outputs=[input_station_map, waveform_plot, predicted_intensity_map, observed_intensity_image])demo.launch()1234567891011121314151617181920211 unmodified line2324252627282930313233343536373810 unmodified lines4950515253545556575859606162636465667 unmodified lines7475767778798081828384858687882 unmodified lines91929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015121 unmodified lines1731741751761771789 unmodified lines18818919019119219319419519619720 unmodified lines2182192202212222232242252262272282292306 unmodified lines2372382392402412422437 unmodified lines25125225325425525625725825926026126226326426526626726826927023 unmodified lines2942952962972982993003013023033043053063073083093103113123133148 unmodified lines32332432532632732832933033133233333442 unmodified lines3773783793803813823833843853863873883893903913923932 unmodified lines39639739839940040140240340440540640740813 unmodified lines42242342442542642742842943043143243343443543643743843944044144220 unmodified lines4634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555563 unmodified lines5605615625635645655665675685695705715725734 unmodified lines57857958058158258358415 unmodified lines6006016026036046056066076086096106116126136146156166176186196206212 unmodified lines6246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566572 unmodified lines66066166266366466566666716 unmodified lines6846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367372 unmodified lines7407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777783 unmodified lines7827837847857867877887897907917927937942 unmodified lines7977987998008018028038048058068078088098108118122 unmodified lines8158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528531 unmodified line8558568578588598608618628638648658665 unmodified lines87287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390417 unmodified lines92292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395411 unmodified lines9669679689699709719729739749759769779789799809819821 unmodified line9849859869879889899909919924 unmodified lines99799899910001001100210031004100510061007100811 unmodified lines10201021102210231024102510263 unmodified lines10301031103210331034103510367 unmodified lines104410451046104710481049105010511052105310542 unmodified lines1057105810591060106110621063106410651066106710681069107010711072107310741075107610772 unmodified lines1080108110821083108410851086108710882 unmodified lines1091109210931094109510961097109810992 unmodified lines1102110311041105110611071 unmodified line11091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155import gradio as grimport matplotlib.pyplot as pltimport 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 scipy.signal import detrend, iirfilter, sosfilt, zpk2sosfrom scipy.spatial import cKDTreefrom model import get_full_model# 設定 matplotlib 中文字體支援plt.rcParams["font.sans-serif"] = ["Arial Unicode MS", "DejaVu Sans"]plt.rcParams["axes.unicode_minus"] = False # 解決負號顯示問題tree = 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 資料載入完成")10 unmodified lines# 驗證 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} 找不到")7 unmodified linestarget_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)} 個目標點)")2 unmodified linesexcept Exception as e:logger.error(f"{target_file} 載入失敗: {e}")# ============ 震央資訊管理 ============earthquake_metadata = {}event_json_path="waveform/event.json"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 / fe21 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])9 unmodified 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):20 unmodified lines# 驗證必要欄位存在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]6 unmodified lines"distance": distance,"latitude": lat,"longitude": lon,"elevation": elev,}except Exception as e:logger.warning(f"測站 {station_code} 資訊查詢失敗: {e}")7 unmodified lines# 記錄實際可用的測站數(少於 25 站也允許繼續)actual_count = len(selected_stations)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 中提取選定測站的波形資料23 unmodified linessampling_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_idx# 檢查是否需要零填充:長度不足 30 秒時尾段以 0 遮罩補齊needs_padding = duration < min_durationif needs_padding:logger.info(f"時間長度 {duration} 秒 < 30 秒,將以 0 遮罩補齊至 {min_duration} 秒")for station_data in selected_stations:station_code = station_data["station"]8 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:42 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:2 unmodified lineslogger.info(f"成功提取 {len(waveforms)} 個測站的波形")if missing_components_count > 0:logger.info(f"其中 {missing_components_count} 個測站缺少 N 或 E 分量(已以 Z 分量代替)")return waveforms, station_info_list, valid_stations, missing_components_countdef create_input_station_map(selected_stations, epicenter_lat, epicenter_lon):"""創建輸入測站分布地圖:顯示所有測站 + 突顯被選中的 25 個(使用 Plotly)"""13 unmodified linesall_stations_text.append(station_code)# 準備選中測站資料(按距離分組)selected_group1_lat, selected_group1_lon, selected_group1_text = ([],[],[],) # 前 5 近selected_group2_lat, selected_group2_lon, selected_group2_text = ([],[],[],) # 6-15 近selected_group3_lat, selected_group3_lon, selected_group3_text = ([],[],[],) # 16-25 近for i, station_data in enumerate(selected_stations):station_code = station_data["station"]20 unmodified linesfig = go.Figure()# 添加所有測站(灰色小點)fig.add_trace(go.Scattermap(lat=all_stations_lat,lon=all_stations_lon,mode="markers",marker=dict(size=6, color="gray", opacity=0.6),text=all_stations_text,hovertemplate="%{text}<extra></extra>",name=f"所有測站 ({len(all_stations_lat)} 個)",showlegend=True,))# 添加選中測站 - 前 5 近(綠色)if selected_group1_lat:fig.add_trace(go.Scattermap(lat=selected_group1_lat,lon=selected_group1_lon,mode="markers",marker=dict(size=12, color="green", opacity=0.8),text=selected_group1_text,hovertemplate="%{text}<extra></extra>",name="前 5 近",showlegend=True,))# 添加選中測站 - 6-15 近(藍色)if selected_group2_lat:fig.add_trace(go.Scattermap(lat=selected_group2_lat,lon=selected_group2_lon,mode="markers",marker=dict(size=12, color="blue", opacity=0.8),text=selected_group2_text,hovertemplate="%{text}<extra></extra>",name="6-15 近",showlegend=True,))# 添加選中測站 - 16-25 近(橘色)if selected_group3_lat:fig.add_trace(go.Scattermap(lat=selected_group3_lat,lon=selected_group3_lon,mode="markers",marker=dict(size=12, color="orange", opacity=0.8),text=selected_group3_text,hovertemplate="%{text}<extra></extra>",name="16-25 近",showlegend=True,))# 添加震央(紅色大點)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})"],hovertemplate="%{text}<extra></extra>",name="震央",showlegend=True,))fig.add_trace(go.Scattermap(lat=[epicenter_lat],lon=[epicenter_lon],mode="markers",marker=dict(size=10, color="white"),showlegend=False,))# 設置地圖佈局fig.update_layout(map=dict(style="open-street-map",center=dict(lat=epicenter_lat, lon=epicenter_lon),zoom=7,),height=500, # 設置固定高度以適應 Gradio 容器margin=dict(l=0, r=0, t=0, b=0),3 unmodified linesy=0.95,xanchor="left",x=0.01,bgcolor="rgba(255, 255, 255, 0.8)",),)return figdef plot_waveform(st, selected_stations, first_pick, duration):"""繪製選定測站的波形圖(距離-時間圖,可顯示全部 25 個測站)4 unmodified lines- duration: 時間長度(秒)"""# 計算結束時間end_time = first_pick + durationfig, ax = plt.subplots(figsize=(14, 10))15 unmodified linestimes = tr.times()data = tr.data# 只顯示從資料開始到 30 秒內的波形time_mask = times <= 120.0times = times[time_mask]data = data[time_mask]# 正規化波形振幅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(first_pick, color="blue", linestyle="--", linewidth=2, alpha=0.7, label="初動時間")# 標記選取時間範圍ax.axvline(0,color="red",linestyle="--",linewidth=2,alpha=0.7,label="選取範圍",)ax.axvline(end_time, color="red", linestyle="--", linewidth=2, alpha=0.7)ax.axvspan(0, 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)2 unmodified linesax2.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 fig16 unmodified linesreturn color_map.get(intensity, "#ffffff")def create_intensity_map(pga_list, target_names, epicenter_lat=None, epicenter_lon=None):"""使用 Plotly 創建互動式震度分布地圖"""# 按震度等級分組資料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)# 決定地圖中心(優先使用 epicenter,否則計算平均值)if epicenter_lat is not None and epicenter_lon is not None:map_center_lat = epicenter_latmap_center_lon = epicenter_lonelif all_lats and all_lons:map_center_lat = np.mean(all_lats)map_center_lon = np.mean(all_lons)else:# 如果沒有任何測站資料,使用台灣的中心map_center_lat = 23.5map_center_lon = 121.0logger.warning("無法決定地圖中心,使用台灣預設中心")# 創建 Plotly 地圖fig = go.Figure()2 unmodified linesintensity_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",marker=dict(size=14, color=group["color"], opacity=0.8),text=group["text"],hovertemplate="%{text}<extra></extra>",name=f"震度 {intensity_labels[intensity_level]}",showlegend=True,))else:# 沒有資料的震度等級:添加隱形標記只為了顯示圖例fig.add_trace(go.Scattermap(lat=[None],lon=[None],mode="markers",marker=dict(size=14, color=group["color"], opacity=0.8),name=f"震度 {intensity_labels[intensity_level]}",showlegend=True,hoverinfo="skip",))# 設置地圖佈局fig.update_layout(map=dict(style="open-street-map",center=dict(lat=map_center_lat, lon=map_center_lon),zoom=7,),height=800, # 設置固定高度以適應 Gradio 容器margin=dict(l=0, r=0, t=0, b=0),3 unmodified linesy=0.95,xanchor="left",x=0.01,bgcolor="rgba(255, 255, 255, 0.8)",),)return figdef load_observed_intensity_image(event_name):"""從 intensity_map 資料夾載入對應的實際觀測震度圖2 unmodified lines"""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 Nonedef load_and_display_waveform(event_name, duration):"""載入並顯示波形,讓使用者確認範圍從全域 earthquake_metadata 讀取震央座標2 unmodified lines"""try:# 從全域 earthquake_metadata 讀取震央座標epicenter_lat = earthquake_metadata[event_name]["epicenter_lat"]epicenter_lon = earthquake_metadata[event_name]["epicenter_lon"]mseed_file = earthquake_metadata[event_name]["mseed_file"]first_pick = earthquake_metadata[event_name]["first_pick"]# 計算結束時間(用於顯示資訊)# 1. 載入完整的 mseed 檔案logger.info(f"載入地震事件: {event_name}")st = read(mseed_file)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,"錯誤:找不到有效的測站資料",gr.update(interactive=False),)waveform_plot = plot_waveform(st, selected_stations, first_pick, duration)# 4. 創建輸入測站地圖station_map = create_input_station_map(selected_stations, epicenter_lat, epicenter_lon)logger.info("波形載入完成")return station_map, waveform_plot, gr.update(interactive=True)1 unmodified lineexcept Exception as e:logger.error(f"波形載入發生錯誤: {e}")import tracebacktraceback.print_exc()return None, None, gr.update(interactive=False)def predict_intensity(event_name, duration):"""執行震度預測5 unmodified lines"""try:# 從全域 earthquake_metadata 讀取震央座標epicenter_lat = earthquake_metadata[event_name]["epicenter_lat"]epicenter_lon = earthquake_metadata[event_name]["epicenter_lon"]mseed_file = earthquake_metadata[event_name]["mseed_file"]# 1. 載入完整的 mseed 檔案logger.info(f"載入地震事件: {event_name}")st = read(mseed_file)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"提取波形資料(時間範圍: 初動後 {duration} 秒)...")waveforms, station_info_list, valid_stations, missing_components_count = (extract_waveforms_from_stream(event_name, st, selected_stations, duration, vs30_input=600))if len(waveforms) == 0:17 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 個)11 unmodified lines# 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)} 個測站的預測!")1 unmodified linetarget_names = all_target_names# 繪製互動式地圖(固定高度 800)intensity_map = create_intensity_map(pga_list, target_names, epicenter_lat, epicenter_lon)# 載入實際觀測震度圖(filepath;左側以 800 高顯示)observed_intensity_path = load_observed_intensity_image(event_name)4 unmodified linesexcept Exception as e:logger.error(f"預測過程發生錯誤: {e}")import tracebacktraceback.print_exc()return None, Nonedef on_full_workflow(event_name, duration):"""執行完整的工作流:波形載入 → 測站選擇 → 推論 → 結果展示11 unmodified lines# 步驟 1: 載入波形logger.info(f"[on_full_workflow] 步驟 1/3: 波形載入...")station_map, waveform_plot, _ = load_and_display_waveform(event_name, duration)if station_map is None:3 unmodified lines# 步驟 2: 執行推論logger.info(f"[on_full_workflow] 步驟 2/3: 模型推論...")observed_img, predicted_map = predict_intensity(event_name, duration)if predicted_map is None:7 unmodified linesexcept Exception as e:logger.error(f"[on_full_workflow] 完整工作流發生錯誤: {e}")import tracebacktraceback.print_exc()return None, None, f"錯誤: {str(e)}", None, f"錯誤: {str(e)}", None# ============ Gradio 介面 ============with gr.Blocks(title="TTSAM 震度預測系統", fill_height=True) as demo:gr.Markdown("# 🌏 TTSAM 震度預測系統")2 unmodified lines# 左上:使用步驟與狀態顯示with gr.Column(scale=1):gr.Markdown("## 使用步驟")gr.Markdown("""1. 選擇地震事件和時間範圍2. 輸入震央位置和場址參數3. 點擊載入波形確認波形範圍4. 確認無誤後點擊執行預測系統會自動選擇距離震央最近的 25 個測站""")with gr.Column(scale=1):event_dropdown = gr.Dropdown(choices=list(earthquake_metadata.keys()),value=list(earthquake_metadata.keys())[0],label="選擇地震事件",)# ========== 中層:輸入測站地圖與波形圖 ==========with gr.Row():2 unmodified linesgr.Markdown("## 輸入測站分布")input_station_map = gr.Plot(label="輸入測站地圖")load_waveform_btn = gr.Button("📊 載入波形", variant="secondary", scale=1)predict_btn = gr.Button("🔮 執行預測", variant="primary", scale=1, interactive=False)# 中右:輸入波形with gr.Column(scale=1):2 unmodified lineslabel="地震波形(選定的 25 個測站)",)with gr.Row():duration_slider = gr.Slider(2, 15, value=15, step=1, label="P 波後時間 (秒)")# ========== 下層:實際觀測 vs 預測結果 ==========with gr.Row():2 unmodified linesgr.Markdown("## 預測震度分布")predicted_intensity_map = gr.Plot(label="互動式震度地圖")# 右下:實際觀測震度圖with gr.Column(scale=1):gr.Markdown("## 實際觀測震度分布")1 unmodified linelabel="實際觀測震度",type="filepath",height=800,value=load_observed_intensity_image(list(earthquake_metadata.keys())[0]),)# 綁定事件event_dropdown.change(fn=lambda event_name, duration: (*on_full_workflow(event_name, duration),),inputs=[event_dropdown, duration_slider],outputs=[input_station_map,waveform_plot,predicted_intensity_map,observed_intensity_image,],)load_waveform_btn.click(fn=load_and_display_waveform,inputs=[event_dropdown, duration_slider],outputs=[input_station_map, waveform_plot, predict_btn],)predict_btn.click(fn=predict_intensity,inputs=[event_dropdown, duration_slider],outputs=[observed_intensity_image, predicted_intensity_map],)# 應用啟動時自動執行完整工作流demo.load(fn=lambda event_name, duration: (*on_full_workflow(event_name, duration),),inputs=[event_dropdown, duration_slider],outputs=[input_station_map,waveform_plot,predicted_intensity_map,observed_intensity_image,],)demo.launch()
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:2706992997b8eb30e568c3470e6f1d8c99654b8a4b1a12b33099fe91900cd51asize 37216256123version https://git-lfs.github.com/spec/v1oid sha256:6e8beedc2a60382dd657ca588271db0f6808d45fbd7e4704ff2c09ef76f0e6f0size 22388736
123version https://git-lfs.github.com/spec/v1oid sha256:199bae2e8477f06ea53d085dc3573407a6f8e50b4c798edd999751340d61d4e7size 2035712012345678910111213141516{"events": [{"event_id": "20240403","event_name": "0403花蓮地震 (2024)","epicenter_lat": 23.88,"epicenter_lon": 121.57,"depth_km": 25.0,"magnitude": 7.2,"timestamp": "2024-04-03T07:58:00Z","mseed_file": "waveform/20240403.mseed","intensity_map_file": "intensity_map/20240403.png"}]}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152{"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}]}
app.py+409-607
intensity_map/20240403.png → intensity_map/2021102413113465103_H.pngRenamed

Large File Pointer Details
- SHA256: e522bcc031deb5e7164646db51753e027bc4093fc09e8d0114a39b57e5c2363f
- Pointer size: 131 Bytes
- Size of remote file: 136 kB

Large File Pointer Details
- SHA256: b17fece6647dc8b3c1ecc5ca8fe786638251ac3bc458016f0a90540781046f63
- Pointer size: 131 Bytes
- Size of remote file: 580 kB
intensity_map/2022091814441568111_H.pngAdded

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

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

Large File Pointer Details
- SHA256: 32dc5aa10f81663373c8efd62eac15d4edf7101c9b87e1245f9d420ba745e88c
- Pointer size: 131 Bytes
- Size of remote file: 581 kB
waveform/20211024.mseedAdded+3
waveform/20220918.mseedAdded+3
waveform/20240403.mseed+2-2
waveform/20250120.mseedAdded+3
waveform/event.json+45-9