Counter.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import os
  2. import sys
  3. import pandas as pd
  4. from shapely.geometry import Point
  5. import numpy as np
  6. from pathlib import Path
  7. # 添加项目根目录到Python路径
  8. project_root = Path(__file__).parent.parent.parent
  9. sys.path.append(str(project_root))
  10. # 导入数据库服务
  11. from app.services.land_use_service import land_use_service
  12. # 设置要处理的土地类型
  13. land_type = "旱地" # 避免使用str作为变量名,因为它是Python内置函数
  14. # 从数据库获取土地利用数据,替代原来的CSV文件读取
  15. print(f"从数据库获取 '{land_type}' 类型的土地利用数据...")
  16. land_centers_df = land_use_service.get_land_centers_for_processing(land_type)
  17. if land_centers_df is None or land_centers_df.empty:
  18. print(f"数据库中没有找到 '{land_type}' 类型的土地利用数据")
  19. exit(1)
  20. print(f"从数据库获取到 {len(land_centers_df)} 个 '{land_type}' 类型的土地数据")
  21. # 读取采样点数据
  22. xls_file = r"..\Data\Irrigation_water_SamplingPoint.xlsx"
  23. df_xls = pd.read_excel(xls_file)
  24. # 设置系数
  25. A = 711 * 0.524
  26. B = 427 * 0.599
  27. C = 200 * 0.7
  28. # 根据土地类型选择系数
  29. coefficient = 0.0
  30. if land_type == "水浇地":
  31. coefficient = B
  32. elif land_type == "水田":
  33. coefficient = A
  34. else:
  35. coefficient = C
  36. # 存储结果的列表
  37. data_rows = []
  38. # 遍历耕地中心点,使用数据库中的中心点坐标
  39. for index, row in land_centers_df.iterrows():
  40. # 直接使用数据库中已经转换好的WGS84坐标
  41. lon = row['center_lon']
  42. lat = row['center_lat']
  43. # 创建中心点几何对象
  44. center_point = Point(lon, lat)
  45. # 计算到所有采样点的距离
  46. distances = df_xls.apply(
  47. lambda x: center_point.distance(Point(x['经度'], x['纬度'])),
  48. axis=1
  49. )
  50. # 找到最近的采样点
  51. nearest_index = distances.idxmin()
  52. nearest_sample = df_xls.loc[nearest_index]
  53. # 计算Cd值
  54. cd_value = nearest_sample['Cd (ug/L)'] * coefficient
  55. # 添加到结果列表
  56. data_rows.append({
  57. 'DLMC': row['dlmc'], # 使用数据库中的字段名
  58. '中心点经度': lon,
  59. '中心点纬度': lat,
  60. 'Cd (ug/L)': cd_value
  61. })
  62. # 创建DataFrame并选择指定列
  63. csv_data = pd.DataFrame(data_rows)
  64. # 保存结果
  65. output_dir = Path(__file__).parent.parent / "Data"
  66. output_dir.mkdir(exist_ok=True)
  67. csv_file_path = output_dir / f"{land_type}_Cd_DB.csv"
  68. csv_data.to_csv(csv_file_path, index=False, encoding='utf-8-sig')
  69. print(f"CSV文件已保存至: {csv_file_path}")
  70. print(f"总共处理了 {len(csv_data)} 个 {land_type} 面要素")