jimmy60504 commited on
Commit
ba6a003
·
1 Parent(s): ea06d35

refactor select_nearest_stations to use a dictionary for station distances to avoid duplicates

Browse files
Files changed (1) hide show
  1. app.py +12 -7
app.py CHANGED
@@ -418,12 +418,16 @@ def calculate_distance(lat1, lon1, lat2, lon2):
418
 
419
  def select_nearest_stations(st, epicenter_lat, epicenter_lon, n_stations=25):
420
  """從 site_info(1000+ 個輸入測站)中選擇距離震央最近的 n 個測站"""
421
- station_distances = []
422
 
423
  # 計算每個測站到震央的距離
424
  for tr in st:
425
  station_code = tr.stats.station
426
 
 
 
 
 
427
  # 從 site_info 中查詢測站位置
428
  try:
429
  station_data = site_info[site_info["Station"] == station_code]
@@ -435,22 +439,23 @@ def select_nearest_stations(st, epicenter_lat, epicenter_lon, n_stations=25):
435
  elev = station_data["Elevation"].values[0]
436
 
437
  distance = calculate_distance(epicenter_lat, epicenter_lon, lat, lon)
438
- station_distances.append({
439
  "station": station_code,
440
  "distance": distance,
441
  "latitude": lat,
442
  "longitude": lon,
443
  "elevation": elev
444
- })
445
  except Exception as e:
446
  logger.warning(f"測站 {station_code} 資訊查詢失敗: {e}")
447
  continue
448
 
449
- # 按距離排序並選擇最近的 n 個
450
- station_distances.sort(key=lambda x: x["distance"])
451
- selected_stations = station_distances[:n_stations]
 
452
 
453
- logger.info(f"從 {len(station_distances)} 個輸入測站中選擇了最近的 {len(selected_stations)} 個")
454
  return selected_stations
455
 
456
 
 
418
 
419
  def select_nearest_stations(st, epicenter_lat, epicenter_lon, n_stations=25):
420
  """從 site_info(1000+ 個輸入測站)中選擇距離震央最近的 n 個測站"""
421
+ station_distances = {} # 改用字典避免重複
422
 
423
  # 計算每個測站到震央的距離
424
  for tr in st:
425
  station_code = tr.stats.station
426
 
427
+ # 如果這個測站已經處理過,跳過(避免重複計算不同分量)
428
+ if station_code in station_distances:
429
+ continue
430
+
431
  # 從 site_info 中查詢測站位置
432
  try:
433
  station_data = site_info[site_info["Station"] == station_code]
 
439
  elev = station_data["Elevation"].values[0]
440
 
441
  distance = calculate_distance(epicenter_lat, epicenter_lon, lat, lon)
442
+ station_distances[station_code] = {
443
  "station": station_code,
444
  "distance": distance,
445
  "latitude": lat,
446
  "longitude": lon,
447
  "elevation": elev
448
+ }
449
  except Exception as e:
450
  logger.warning(f"測站 {station_code} 資訊查詢失敗: {e}")
451
  continue
452
 
453
+ # 轉換為列表並按距離排序,選擇最近的 n 個
454
+ station_list = list(station_distances.values())
455
+ station_list.sort(key=lambda x: x["distance"])
456
+ selected_stations = station_list[:n_stations]
457
 
458
+ logger.info(f"從 {len(station_list)} 個輸入測站中選擇了最近的 {len(selected_stations)} 個")
459
  return selected_stations
460
 
461