__init__.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. from common.BigDataCenterAPI import *
  4. from models import *
  5. from sqlalchemy import text
  6. from sqlalchemy import func
  7. from shapely.geometry import Polygon, MultiPolygon
  8. from shapely.ops import unary_union
  9. import json
  10. def convert_to_polygon(points):
  11. # 将点的列表转换为POLYGON格式的字符串
  12. polygon_str = "POLYGON(("
  13. for point in points:
  14. # 假设点的顺序是经度(x),纬度(y)
  15. polygon_str += f"{point['y']} {point['x']}, "
  16. # 移除最后一个逗号和空格,然后添加闭合点和结束括号
  17. polygon_str = polygon_str.rstrip(", ") + f", {points[0]['y']} {points[0]['x']}))"
  18. return polygon_str
  19. def get_town_list2(location_list:list,db):
  20. # resutl = []
  21. if len(location_list) ==0:
  22. return []
  23. query = []
  24. for location in location_list:
  25. if isinstance(location,dict):
  26. pass
  27. else:
  28. return []
  29. location = convert_to_polygon(location) #,geometry
  30. query.append(f"ST_Intersects(geometry,ST_PolygonFromText( '{location}', 4326 ))")
  31. query=' or '.join(query)
  32. sql = text(f"""SELECT DISTINCT `name`,properties,pac FROM tp_geojson_data_zj WHERE {query}""")
  33. # print(sql)
  34. resutl=db.execute(sql).all()
  35. return resutl
  36. def get_village_list(location_list:list,db,pac=''):
  37. if len(location_list) ==0:
  38. return []
  39. resutl = []
  40. query = []
  41. for location in location_list:
  42. if isinstance(location,dict):
  43. pass
  44. else:
  45. return []
  46. location = convert_to_polygon(location) #geometry,
  47. query.append(f"ST_Intersects(geometry,ST_PolygonFromText( '{location}', 4326 ))")
  48. query=' or '.join(query)
  49. sql = text(f"""SELECT DISTINCT `name`,properties,pac,populationSize,GDP FROM (select * from tp_geojson_data_cj_sq {pac})A WHERE {query} """)
  50. # print(sql)
  51. resutl=db.execute(sql).all()
  52. return resutl
  53. def get_town_list(locations,):
  54. # 初始化一个空的MultiPolygon来容纳所有多边形
  55. multi_polygon = MultiPolygon()
  56. # 遍历每个位置,创建多边形并添加到multi_polygon中
  57. for location in locations:
  58. # 将边界列表转换为Polygon
  59. polygon = Polygon([(item['x'], item['y']) for item in location])
  60. multi_polygon = multi_polygon.union(polygon)
  61. # 将GeoJSON数据转换为字典
  62. with open('/home/python3/zj_geojson.json', 'r', encoding='utf-8') as file:
  63. geojson = json.load(file)
  64. # 假设GeoJSON数据是一个FeatureCollection
  65. features = geojson.get('features', [])
  66. # 初始化一个空列表来存储结果
  67. intersected_names_and_pacs = []
  68. # 遍历GeoJSON中的每个Feature,计算交集
  69. for feature in features:
  70. geom = feature['geometry']
  71. if 'coordinates' in geom:
  72. # 将GeoJSON Polygon转换为shapely Polygon
  73. if geom['type'] == 'Polygon':
  74. polygon = Polygon(geom['coordinates'][0])
  75. intersection = polygon.intersection(multi_polygon)
  76. elif geom['type'] == 'MultiPolygon':
  77. multi_polygon_feature = MultiPolygon([Polygon(coords[0]) for coords in geom['coordinates']])
  78. intersection = multi_polygon_feature.intersection(multi_polygon)
  79. else:
  80. continue # 跳过非Polygon和非MultiPolygon类型的几何对象
  81. if not intersection.is_empty:
  82. properties = feature['properties']
  83. intersected_names_and_pacs.append({
  84. "townName": properties.get('NAME', ''),
  85. "code": properties.get('PAC', ''),
  86. "populationSize": 0, # 假设值,需要从数据中获取
  87. "areaSize": round(intersection.area, 2), # 交集区域的面积
  88. "GDP": 0 # 假设值,需要从数据中获取
  89. })
  90. return intersected_names_and_pacs, len(intersected_names_and_pacs)
  91. def get_bqw_yj_quyu_data(area_code,db):
  92. sql = text(
  93. """SELECT ifnull(populationSize,0) as populationSize,
  94. ifnull(populationSize_unit,'') as populationSize_unit,
  95. ifnull(areaSize,0) as areaSize,
  96. ifnull(areaSize_unit,'')as areaSize_unit,ifnull(GDP,0) as GDP,ifnull(GDP_unit,'') as GDP_unit FROM sharedb.`bqw_yj_quyu_data` where `area_code`like :code order by area_code,year desc """).bindparams(
  97. code=f'%{area_code}%')
  98. # 执行查询
  99. result = db.execute(sql).fetchone()
  100. # 处理结果
  101. if result:
  102. return dict(result)
  103. else:
  104. return {"populationSize":0,"populationSize_unit":"","areaSize":0,"areaSize_unit":"","GDP":0,"GDP_unit":""}
  105. def get_town_village_list(locations,db):
  106. # 初始化一个空的MultiPolygon来容纳所有多边形
  107. intersected_towns = get_town_list2(locations,db)
  108. # 初始化一个空列表来存储结果
  109. intersected_names_and_pacs = []
  110. town_count = len(intersected_towns)
  111. village_count = 0
  112. populationSize = 0
  113. areaSize = 0
  114. GDP = 0
  115. for town in intersected_towns:
  116. # town_count+=1
  117. town_pac = town.pac
  118. properties = json.loads(town.properties)
  119. quyu_data = get_bqw_yj_quyu_data(town.pac,db)
  120. town_data = {
  121. "townName": town.name,
  122. "code": town.pac,
  123. "populationSize": f"{quyu_data['populationSize']}{quyu_data['populationSize_unit']}",
  124. "areaSize": f"{quyu_data['areaSize']}{quyu_data['areaSize_unit']}",
  125. "GDP": f"{quyu_data['GDP']}{quyu_data['GDP_unit']}" # 假设值,需要从数据中获取
  126. }
  127. populationSize += quyu_data['populationSize']
  128. areaSize += quyu_data['areaSize']
  129. GDP += quyu_data['GDP']
  130. # intersected_villages = db.query(TpCjSqGeoJSONData).filter(
  131. # func.ST_Intersects(TpCjSqGeoJSONData.geometry, multi_polygon) == True
  132. # ).filter(TpCjSqGeoJSONData.pac.like(f'{town_pac}%')).all()
  133. intersected_villages = get_village_list(locations,db,pac=f""" where pac like '{town_pac}%'""")
  134. intersected_villages_names_and_pacs = []
  135. for village in intersected_villages:
  136. quyu_data = get_bqw_yj_quyu_data(village.pac, db)
  137. # town_data['populationSize']+=village.populationSize
  138. # town_data['GDP']+=village.GDP
  139. # properties = json.loads(village.properties)
  140. village_data = {
  141. "villageName": village.name,
  142. "code": village.pac,
  143. "populationSize": f"{quyu_data['populationSize']}{quyu_data['populationSize_unit']}",#village.populationSize, # 假设值,需要从数据中获取
  144. "areaSize": f"{quyu_data['areaSize']}{quyu_data['areaSize_unit']}",#properties['GEO_AREA'], # 交集区域的面积 0,#
  145. "GDP": f"{quyu_data['GDP']}{quyu_data['GDP_unit']}"#village.GDP # 假设值,需要从数据中获取
  146. }
  147. intersected_villages_names_and_pacs.append(village_data)
  148. villageCount= len(intersected_villages_names_and_pacs)
  149. if villageCount>0:
  150. town_data['children']=intersected_villages_names_and_pacs
  151. town_data['villageCount'] =villageCount
  152. village_count += villageCount
  153. intersected_names_and_pacs.append(town_data)
  154. return intersected_names_and_pacs, town_count,village_count,populationSize,areaSize,GDP
  155. # import geopandas as gpd
  156. # from shapely.geometry import Polygon
  157. #
  158. #
  159. #
  160. # def get_town_list(locations):
  161. # # 读取GeoJSON文件为GeoDataFrame
  162. # gdf = gpd.read_file('zj_geojson.json')
  163. # gdf = gdf.set_crs("EPSG:4326", allow_override=True)
  164. #
  165. # # 初始化一个空的GeoDataFrame来容纳所有多边形
  166. # multi_polygon_gdf = gpd.GeoDataFrame(crs=gdf.crs)
  167. #
  168. # # 遍历每个位置,创建多边形并添加到multi_polygon_gdf中
  169. # for location in locations:
  170. # # 将边界列表转换为Polygon
  171. # polygon = Polygon([(item['x'], item['y']) for item in location])
  172. # # 将多边形添加到multi_polygon_gdf中
  173. # multi_polygon_gdf = multi_polygon_gdf.append(gpd.GeoDataFrame([1], geometry=[polygon], crs=gdf.crs))
  174. #
  175. # # 使用overlay函数来找出相交的区域
  176. # intersected = gpd.overlay(gdf, multi_polygon_gdf, how='intersection')
  177. #
  178. # # 获取相交区域的名称和PAC
  179. # intersected_names_and_pacs = [{"name": row['NAME'], "pac": row['PAC'],"populationSize":0,"areaSize":0,"GDP":0} for index, row in intersected.iterrows() if 'NAME' in row and 'PAC' in row]
  180. #
  181. # return intersected_names_and_pacs,len(intersected_names_and_pacs)
  182. def count_town_village(location_list:list,db):
  183. town_count = 0
  184. town_list = []
  185. village_count = 0
  186. village_list = []
  187. result = []
  188. url = 'https://19.15.75.180:8581/GatewayMsg/http/api/proxy/invoke'
  189. service_code= 'YZT1685418808667'
  190. service_info = db.query(OneShareApiEntity).filter(OneShareApiEntity.servercode == service_code).first()
  191. signTime = str(GetTime() // 1000)
  192. nonce = GetNonce(5)
  193. sign = GetSign(signTime, nonce, service_info.passtoken)
  194. headers = {
  195. # 'Content-Type': 'application/json',
  196. 'x-tif-signature': sign,
  197. 'x-tif-timestamp': signTime,
  198. 'x-tif-nonce': nonce,
  199. 'x-tif-paasid': service_info.passid,
  200. 'x-tif-serviceId': service_code
  201. }
  202. response = requests.post(url=url, headers=headers, json=location_list, verify=False)
  203. if response.status_code==200:
  204. data_list = response.json()['data']
  205. for data in data_list:
  206. township = data['townshipCode']
  207. if township not in town_list:
  208. town_count+=1
  209. town_list.append(township)
  210. # result.append({'township':data['township'],"townshipCode":data['townshipCode'],"villages":[]})
  211. result.append({'township':data['township'],"townshipCode":data['townshipCode'],"village":'-',"villageCode":'-',"populationSize":0,"areaSize":0,"GDP":0})
  212. village = data['villageCode']
  213. if village not in village_list:
  214. village_count+=1
  215. village_list.append(village)
  216. # for town in result:
  217. # if town['townshipCode']==data['townshipCode']:
  218. # town["villages"].append({'village': data['village'], "villageCode": data['villageCode']})
  219. result.append({'township':data['township'],"townshipCode":data['townshipCode'],'village': data['village'], "villageCode": data['villageCode'],"populationSize":0,"areaSize":0,"GDP":0})
  220. return result,town_count,village_count
  221. def count_emergency_expert(location_list:list,db):
  222. if isinstance(location_list, dict):
  223. pass
  224. else:
  225. return []
  226. location = convert_to_polygon(location_list)
  227. sql = text(f"""SELECT * FROM emergency_expert WHERE ST_Contains(ST_PolygonFromText( '{location}', 4326 ),ST_PointFromText(CONCAT('POINT(', latitude, ' ', longitude, ')'), 4326))""")
  228. return len(db.execute(sql).all())
  229. def count_emergency_management(location_list: list, db):
  230. if isinstance(location_list, dict):
  231. pass
  232. else:
  233. return []
  234. location = convert_to_polygon(location_list)
  235. sql = text(f"""SELECT DISTINCT management_unit FROM `rescue_materia` WHERE ST_Contains(ST_PolygonFromText( '{location}', 4326 ),ST_PointFromText(CONCAT('POINT(', latitude, ' ', longitude, ')'), 4326))""")
  236. return len(db.execute(sql).all())
  237. def get_hospital_list(location_list:list,db):
  238. resutl = []
  239. for location in location_list:
  240. if isinstance(location,dict):
  241. pass
  242. else:
  243. return []
  244. location = convert_to_polygon(location)
  245. sql = text(f"""SELECT hospital_name as `name`,longitude,latitude,6 AS `dataType` FROM mid_hospital WHERE ST_Contains(ST_PolygonFromText( '{location}', 4326 ),ST_PointFromText(CONCAT('POINT(', latitude, ' ', longitude, ')'), 4326))""")
  246. resutl+=db.execute(sql).all()
  247. return resutl
  248. def get_emergency_shelter_list(location_list:list,db):
  249. resutl = []
  250. for location in location_list:
  251. if isinstance(location,dict):
  252. pass
  253. else:
  254. return []
  255. location = convert_to_polygon(location)
  256. sql = text(f"""SELECT shelter_name as `name`,lng as longitude,lat as latitude,3 AS `dataType` FROM mid_emergency_shelter WHERE ST_Contains(ST_PolygonFromText( '{location}', 4326 ),ST_PointFromText(CONCAT('POINT(', lat, ' ', lng, ')'), 4326))""")
  257. resutl+=db.execute(sql).all()
  258. return resutl
  259. def get_waterlogged_roads_list(location_list:list,db):
  260. resutl = []
  261. for location in location_list:
  262. if isinstance(location,dict):
  263. pass
  264. else:
  265. return []
  266. location = convert_to_polygon(location)
  267. sql = text(f"""SELECT flood_name as `name`,lng as longitude,lat as latitude,4 AS `dataType` FROM mid_waterlogged_roads WHERE ST_Contains(ST_PolygonFromText( '{location}', 4326 ),ST_PointFromText(CONCAT('POINT(', lat, ' ', lng, ')'), 4326))""")
  268. resutl+=db.execute(sql).all()
  269. return resutl
  270. def get_point_list(location_list:list,db):
  271. resutl = []
  272. for location in location_list:
  273. if isinstance(location,dict):
  274. pass
  275. else:
  276. return []
  277. location = convert_to_polygon(location)
  278. sql = text(f"""SELECT `id` ,`name`, longitude, latitude, `dataType` FROM point_data WHERE ST_Contains(ST_PolygonFromText( '{location}', 4326 ),ST_PointFromText(CONCAT('POINT(', latitude, ' ', longitude, ')'), 4326))""")
  279. resutl+=db.execute(sql).all()
  280. return resutl