import os import sys import pandas as pd from shapely.geometry import Point import numpy as np from pathlib import Path # 添加项目根目录到Python路径 project_root = Path(__file__).parent.parent.parent sys.path.append(str(project_root)) # 导入数据库服务 from app.services.land_use_service import land_use_service # 设置要处理的土地类型 land_type = "旱地" # 避免使用str作为变量名,因为它是Python内置函数 # 从数据库获取土地利用数据,替代原来的CSV文件读取 print(f"从数据库获取 '{land_type}' 类型的土地利用数据...") land_centers_df = land_use_service.get_land_centers_for_processing(land_type) if land_centers_df is None or land_centers_df.empty: print(f"数据库中没有找到 '{land_type}' 类型的土地利用数据") exit(1) print(f"从数据库获取到 {len(land_centers_df)} 个 '{land_type}' 类型的土地数据") # 读取采样点数据 xls_file = r"..\Data\Irrigation_water_SamplingPoint.xlsx" df_xls = pd.read_excel(xls_file) # 设置系数 A = 711 * 0.524 B = 427 * 0.599 C = 200 * 0.7 # 根据土地类型选择系数 coefficient = 0.0 if land_type == "水浇地": coefficient = B elif land_type == "水田": coefficient = A else: coefficient = C # 存储结果的列表 data_rows = [] # 遍历耕地中心点,使用数据库中的中心点坐标 for index, row in land_centers_df.iterrows(): # 直接使用数据库中已经转换好的WGS84坐标 lon = row['center_lon'] lat = row['center_lat'] # 创建中心点几何对象 center_point = Point(lon, lat) # 计算到所有采样点的距离 distances = df_xls.apply( lambda x: center_point.distance(Point(x['经度'], x['纬度'])), axis=1 ) # 找到最近的采样点 nearest_index = distances.idxmin() nearest_sample = df_xls.loc[nearest_index] # 计算Cd值 cd_value = nearest_sample['Cd (ug/L)'] * coefficient # 添加到结果列表 data_rows.append({ 'DLMC': row['dlmc'], # 使用数据库中的字段名 '中心点经度': lon, '中心点纬度': lat, 'Cd (ug/L)': cd_value }) # 创建DataFrame并选择指定列 csv_data = pd.DataFrame(data_rows) # 保存结果 output_dir = Path(__file__).parent.parent / "Data" output_dir.mkdir(exist_ok=True) csv_file_path = output_dir / f"{land_type}_Cd_DB.csv" csv_data.to_csv(csv_file_path, index=False, encoding='utf-8-sig') print(f"CSV文件已保存至: {csv_file_path}") print(f"总共处理了 {len(csv_data)} 个 {land_type} 面要素")