GdalAlgorithm.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. """
  2. ***************************************************************************
  3. GdalAlgorithm.py
  4. ---------------------
  5. Date : August 2012
  6. Copyright : (C) 2012 by Victor Olaya
  7. Email : volayaf at gmail dot com
  8. ***************************************************************************
  9. * *
  10. * This program is free software; you can redistribute it and/or modify *
  11. * it under the terms of the GNU General Public License as published by *
  12. * the Free Software Foundation; either version 2 of the License, or *
  13. * (at your option) any later version. *
  14. * *
  15. ***************************************************************************
  16. """
  17. __author__ = 'Victor Olaya'
  18. __date__ = 'August 2012'
  19. __copyright__ = '(C) 2012, Victor Olaya'
  20. import os
  21. import re
  22. import numpy as np
  23. from PyQt5.QtGui import QIcon
  24. from osgeo import ogr
  25. from qgis.PyQt.QtCore import QUrl, QCoreApplication
  26. from qgis._core import QgsCoordinateTransformContext, QgsCoordinateReferenceSystem, QgsCoordinateTransform, \
  27. QgsVectorLayer, QgsWkbTypes, QgsFeature, QgsGeometry
  28. from qgis.core import (QgsApplication,
  29. QgsProject,
  30. QgsVectorFileWriter,
  31. QgsProcessingFeatureSourceDefinition,
  32. QgsProcessingAlgorithm,
  33. QgsProcessingContext,
  34. QgsProcessingFeedback,
  35. QgsProviderRegistry,
  36. QgsDataSourceUri)
  37. from processing.algs.gdal.GdalAlgorithmDialog import GdalAlgorithmDialog
  38. from processing.algs.gdal.GdalUtils import GdalUtils
  39. from processing.tools.PostgreSQL.PostgreSQL import PostgreSQL
  40. from processing.tools.GeoServer.Geoserver import Geoserver
  41. from processing.tools.GeoServer.GeoService import GeoService
  42. from processing.tools.QGS.QgsProjectUtils import QgsProjectUtils
  43. from processing.tools.PrintUtils import getLastPrint
  44. from processing.tools.requestUtils import (spotfileUpload, downloadspotfile, deletespotfile)
  45. from processing.tools.FileListPrintUtils import getFileListPrint
  46. from processing.tools.SubprocessUtils import RunSubprocess
  47. import processing.tools.QGS.load
  48. from qgis.PyQt.QtCore import NULL
  49. import siwei_config
  50. pluginPath = os.path.normpath(os.path.join(
  51. os.path.split(os.path.dirname(__file__))[0], os.pardir))
  52. class GdalAlgorithm(QgsProcessingAlgorithm):
  53. def __init__(self):
  54. super().__init__()
  55. # 全局参数修改
  56. self.db_config = siwei_config.CONFIG['db']
  57. self.geoserver_config = siwei_config.CONFIG['geoserver']
  58. self.output_values = {}
  59. self.spatialite_db_path = "D:\\temp\\output.sqlite"
  60. self.pgcoon = {
  61. "host": self.db_config['host'],
  62. "schema": self.db_config['schema'],
  63. "port": self.db_config['port'],
  64. "user": self.db_config['user'],
  65. "password": self.db_config['password'],
  66. "dbname": self.db_config['name']
  67. }
  68. self.geoservercoon = {
  69. "url": self.geoserver_config['url'],
  70. "username": self.geoserver_config['username'],
  71. "password": self.geoserver_config['password'],
  72. "defaultworkspace": self.geoserver_config['default_workspace'],
  73. "cachestart": self.geoserver_config['cachestart'],
  74. "cacheend": self.geoserver_config['cacheend']
  75. }
  76. def icon(self):
  77. return QIcon(os.path.join(pluginPath, 'images', 'dbms', 'tool.png'))
  78. # return QgsApplication.getThemeIcon("/providerGdal.svg")
  79. def tags(self):
  80. return ['ogr', 'gdal', self.commandName()]
  81. def svgIconPath(self):
  82. return os.path.join(pluginPath, 'images', 'dbms', 'tool.png')
  83. # return QgsApplication.iconPath("providerGdal.svg")
  84. def createInstance(self, config={}):
  85. return self.__class__()
  86. def createCustomParametersWidget(self, parent):
  87. return GdalAlgorithmDialog(self, parent=parent)
  88. def getConsoleCommands(self, parameters, context, feedback, executing=True):
  89. return None
  90. def getOgrCompatibleSource(self, parameter_name, parameters, context, feedback, executing):
  91. """
  92. Interprets a parameter as an OGR compatible source and layer name
  93. :param executing:
  94. """
  95. if not executing and parameter_name in parameters and isinstance(parameters[parameter_name],
  96. QgsProcessingFeatureSourceDefinition):
  97. # if not executing, then we throw away all 'selected features only' settings
  98. # since these have no meaning for command line gdal use, and we don't want to force
  99. # an export of selected features only to a temporary file just to show the command!
  100. parameters = {parameter_name: parameters[parameter_name].source}
  101. input_layer = self.parameterAsVectorLayer(parameters, parameter_name, context)
  102. ogr_data_path = None
  103. ogr_layer_name = None
  104. if input_layer is None or input_layer.dataProvider().name() == 'memory':
  105. if executing:
  106. # parameter is not a vector layer - try to convert to a source compatible with OGR
  107. # and extract selection if required
  108. ogr_data_path = self.parameterAsCompatibleSourceLayerPath(parameters, parameter_name, context,
  109. QgsVectorFileWriter.supportedFormatExtensions(),
  110. QgsVectorFileWriter.supportedFormatExtensions()[
  111. 0],
  112. feedback=feedback)
  113. ogr_layer_name = GdalUtils.ogrLayerName(ogr_data_path)
  114. else:
  115. # not executing - don't waste time converting incompatible sources, just return dummy strings
  116. # for the command preview (since the source isn't compatible with OGR, it has no meaning anyway and can't
  117. # be run directly in the command line)
  118. ogr_data_path = 'path_to_data_file'
  119. ogr_layer_name = 'layer_name'
  120. elif input_layer.dataProvider().name() == 'ogr':
  121. if executing and (
  122. isinstance(parameters[parameter_name], QgsProcessingFeatureSourceDefinition) and parameters[
  123. parameter_name].selectedFeaturesOnly) \
  124. or input_layer.subsetString():
  125. # parameter is a vector layer, with OGR data provider
  126. # so extract selection if required
  127. ogr_data_path = self.parameterAsCompatibleSourceLayerPath(parameters, parameter_name, context,
  128. QgsVectorFileWriter.supportedFormatExtensions(),
  129. feedback=feedback)
  130. parts = QgsProviderRegistry.instance().decodeUri('ogr', ogr_data_path)
  131. ogr_data_path = parts['path']
  132. if 'layerName' in parts and parts['layerName']:
  133. ogr_layer_name = parts['layerName']
  134. else:
  135. ogr_layer_name = GdalUtils.ogrLayerName(ogr_data_path)
  136. else:
  137. # either not using the selection, or
  138. # not executing - don't worry about 'selected features only' handling. It has no meaning
  139. # for the command line preview since it has no meaning outside of a QGIS session!
  140. ogr_data_path = GdalUtils.ogrConnectionStringAndFormatFromLayer(input_layer)[0]
  141. ogr_layer_name = GdalUtils.ogrLayerName(input_layer.dataProvider().dataSourceUri())
  142. elif input_layer.dataProvider().name().lower() == 'wfs':
  143. uri = QgsDataSourceUri(input_layer.source())
  144. baseUrl = uri.param('url').split('?')[0]
  145. ogr_data_path = f"WFS:{baseUrl}"
  146. ogr_layer_name = uri.param('typename')
  147. else:
  148. # vector layer, but not OGR - get OGR compatible path
  149. # TODO - handle "selected features only" mode!!
  150. ogr_data_path = GdalUtils.ogrConnectionStringFromLayer(input_layer)
  151. ogr_layer_name = GdalUtils.ogrLayerName(input_layer.dataProvider().dataSourceUri())
  152. return ogr_data_path, ogr_layer_name
  153. def setOutputValue(self, name, value):
  154. self.output_values[name] = value
  155. def processAlgorithm(self, parameters, context, feedback):
  156. print("############进入GdalAlgorithm组件的processAlgorithm################")
  157. # if parameters.get("Metadata_storage") is not None and parameters.get("Metadata_storage") == True:
  158. #
  159. # return;
  160. # TODO wanger GDB入库
  161. if parameters.get("INPUTGDB") is not None:
  162. res = self.gdbimport(parameters, context, feedback, executing=True)
  163. return res
  164. # TODO wanger 拓扑检查
  165. if parameters.get("INPUTVECTOR") is not None:
  166. res = self.topologycheck(parameters, context, feedback, executing=True)
  167. return res
  168. # TODO wanger 生成许可文件
  169. if parameters.get("LICENSEHOST") is not None:
  170. self.generateLicense(parameters)
  171. return {
  172. "许可文件路径": parameters.get("OUTPUT")
  173. }
  174. # TODO wanger 上传图斑文件数据包
  175. if parameters.get("SPOTFILE") is not None:
  176. filepath = parameters.get("SPOTFILE")
  177. print(filepath)
  178. json_obj = spotfileUpload(filepath=filepath)
  179. status = int(json_obj["statuscode"])
  180. if status == 200:
  181. return {
  182. "状态": "上传成功!"
  183. }
  184. else:
  185. return {
  186. "状态": json_obj["message"]
  187. }
  188. # TODO wanger 下载图斑文件数据包
  189. if parameters.get("SPOTFILEDOWNLOAD") is not None:
  190. fileindex = parameters.get("SPOTFILEDOWNLOAD")
  191. print("spotfilelist")
  192. print(self.spotfilelist)
  193. fileparams = self.spotfilelist[fileindex]
  194. print(fileparams)
  195. filestr = downloadspotfile(filename=f'{fileparams["name"]}.{fileparams["filetype"]}',
  196. dir=parameters.get("SPOTFILEOUT"))
  197. return {
  198. "状态": filestr
  199. }
  200. # TODO wanger 删除图斑文件数据包
  201. if parameters.get("SPOTFILEDELETE") is not None:
  202. fileindex = parameters.get("SPOTFILEDELETE")
  203. print("spotfilelist")
  204. print(self.spotfilelist)
  205. fileparams = self.spotfilelist[fileindex]
  206. print(fileparams)
  207. filestr = deletespotfile(id=fileparams["id"])
  208. return {
  209. "状态": "删除成功"
  210. }
  211. # TODO wanger GeoServer服务发布
  212. if parameters.get("Publish_Service") is not None:
  213. zymlbsm = getLastPrint()
  214. if zymlbsm == None or zymlbsm == '':
  215. return {
  216. "Error": "资源目录未选择!"
  217. }
  218. print("zymlbsm====" + zymlbsm)
  219. layer_group_join = ""
  220. if parameters.get("LAYER_GROUP_JOIN") is not None:
  221. layer_group_join = self.groups[parameters.get("LAYER_GROUP_JOIN")]
  222. commands = self.getConsoleCommands(parameters, context, feedback, executing=True)
  223. geoSer = GeoService()
  224. result = None
  225. if parameters.get("INPUTRASTER") != NULL and parameters.get("INPUTRASTER") != "":
  226. # 获取输入栅格图层
  227. raster_layer = self.parameterAsRasterLayer(parameters, self.INPUTRASTER, context)
  228. file = raster_layer.source()
  229. result = geoSer.publishGeoService(parameters, context, feedback, commands, zymlbsm, layer_group_join,
  230. file)
  231. else:
  232. result = geoSer.publishGeoService(parameters, context, feedback, commands, zymlbsm, layer_group_join,
  233. None)
  234. return result
  235. # === 获取gdal命令参数执行并输出log开始 ===
  236. commands = self.getConsoleCommands(parameters, context, feedback, executing=True)
  237. # 增量更新
  238. if parameters.get("ALLOWOVERLAP") is not None and len(commands) == 0:
  239. res = self.updateVector(parameters, context, feedback, executing=True)
  240. return res
  241. # 版本回退
  242. if parameters.get("RESTORETABLE") is not None:
  243. res = self.restoreVector(parameters, context, feedback, executing=True)
  244. return res
  245. command = commands[0]
  246. if command.__contains__(" "):
  247. GdalUtils.runGdal([command], feedback)
  248. commands.remove(command)
  249. GdalUtils.runGdal(commands, feedback)
  250. else:
  251. GdalUtils.runGdal(commands, feedback)
  252. print(commands)
  253. results = {}
  254. for o in self.outputDefinitions():
  255. if o.name() in parameters:
  256. results[o.name()] = parameters[o.name()]
  257. for k, v in self.output_values.items():
  258. results[k] = v
  259. # === 获取gdal命令参数执行并输出log结束 ===
  260. # TODO wanger 元数据入库
  261. if parameters.get("Metadata_storage") is not None and parameters.get("Metadata_storage") == True:
  262. # 所属行政区划
  263. ssxzqh = getLastPrint()
  264. print("ssxzqh====" + ssxzqh)
  265. # 获取附件列表
  266. fileliststr = getFileListPrint()
  267. pgconn = PostgreSQL(schema='base')
  268. ogrLayer = ""
  269. layername = ""
  270. if parameters.get("SOURCE_TYPE") == "vector":
  271. ogrLayer, layername = self.getOgrCompatibleSource(self.INPUT, parameters, context, feedback, None)
  272. elif parameters.get("SOURCE_TYPE") == "raster":
  273. raster_layer = self.parameterAsRasterLayer(parameters, self.INPUT, context)
  274. ogrLayer = raster_layer.source()
  275. print(ogrLayer)
  276. pgconn.metadataStorage(parameters, ssxzqh, fileliststr, self.ywlxs[parameters.get("VECTOR_YWLX")],
  277. self.depts[parameters.get("VECTOR_GLBM")], ogrLayer, layername,
  278. self.zymls[parameters.get("VECTOR_ZYML")])
  279. pgconn.close()
  280. return results
  281. def commandName(self):
  282. parameters = {
  283. param.name(): "1"
  284. for param in self.parameterDefinitions()
  285. }
  286. context = QgsProcessingContext()
  287. feedback = QgsProcessingFeedback()
  288. name = self.getConsoleCommands(parameters, context, feedback, executing=False)[0]
  289. if name.endswith(".py"):
  290. name = name[:-3]
  291. return name
  292. # 将VectorLayer导入到SpatiaLite数据库
  293. def importLayerToSpatiaLite(self, layer, table_name):
  294. # TODO wanger 强制进行坐标系转换 统一入库数据坐标系 增强分析结果准确性
  295. target_crs = QgsCoordinateReferenceSystem("EPSG:4490")
  296. # 创建坐标转换对象
  297. transform_context = QgsProject.instance().transformContext()
  298. transform = QgsCoordinateTransform(layer.crs(), target_crs, transform_context)
  299. # 创建内存图层
  300. geometry_type = layer.wkbType() # 保留原始几何类型
  301. memory_layer = QgsVectorLayer(
  302. f"{QgsWkbTypes.displayString(geometry_type)}", # 指定几何类型
  303. "Transformed Layer",
  304. "memory"
  305. )
  306. # 设置内存图层的 CRS 和属性字段
  307. memory_layer.setCrs(target_crs)
  308. memory_layer.dataProvider().addAttributes(layer.fields()) # 复制字段
  309. memory_layer.updateFields()
  310. # 遍历原图层的所有要素,逐个转换几何并添加到内存图层
  311. features = []
  312. for feature in layer.getFeatures():
  313. new_feature = QgsFeature(feature) # 复制属性
  314. geom = feature.geometry()
  315. if geom: # 检查几何是否有效
  316. geom.transform(transform) # 转换几何坐标
  317. new_feature.setGeometry(geom)
  318. features.append(new_feature)
  319. # 将转换后的要素添加到内存图层
  320. memory_layer.dataProvider().addFeatures(features)
  321. # TODO 构造连接到Spatialite数据库的URI
  322. uri = QgsDataSourceUri()
  323. uri.setDatabase(self.spatialite_db_path)
  324. # TODO 将vectorlayer写入Spatialite 数据库
  325. options = QgsVectorFileWriter.SaveVectorOptions()
  326. options.driverName = "SQLite"
  327. options.layerName = table_name
  328. options.fileEncoding = "UTF-8"
  329. # options.crs = target_crs
  330. options.actionOnExistingFile = QgsVectorFileWriter.CreateOrOverwriteLayer
  331. # TODO 将QgsVectorLayer导入到spatialite并指定表名
  332. result = QgsVectorFileWriter.writeAsVectorFormatV2(memory_layer, self.spatialite_db_path,
  333. QgsProject.instance().transformContext(), options)
  334. return result
  335. # 将VectorLayer导出到文件
  336. def vectorLayerExport(self, layer, path, type):
  337. options = QgsVectorFileWriter.SaveVectorOptions()
  338. options.driverName = type # Output format
  339. # options.includeGeometry = True # Include geometry
  340. context2 = QgsCoordinateTransformContext()
  341. error = QgsVectorFileWriter.writeAsVectorFormatV3(layer, path, context2, options)
  342. if error[0] == QgsVectorFileWriter.NoError:
  343. print(f"Exported {path} successfully!")
  344. else:
  345. print(f"Failed to export to {path}: {error}")
  346. # 将VectorLayer导出到矢量文件
  347. def vectorLayerExportToVector(self, layer, path, type="ESRI Shapefile"):
  348. # TODO 导出矢量文件参数配置
  349. export_options = QgsVectorFileWriter.SaveVectorOptions()
  350. export_options.driverName = type
  351. export_options.fileEncoding = "UTF-8"
  352. result = QgsVectorFileWriter.writeAsVectorFormatV2(layer, path,
  353. QgsCoordinateTransformContext(), export_options)
  354. if result[0] != QgsVectorFileWriter.NoError:
  355. print(f"Failed to export processed layer to SHP file.")
  356. print(result)
  357. # 拓扑检查成功,没有错误项
  358. def topologySuccessWithNone(self):
  359. return {
  360. "状态": "拓扑检查成功",
  361. "结论": "符合"
  362. }
  363. # 拓扑检查成功
  364. def topologySuccess(self, count, reportpath):
  365. return {
  366. "状态": "拓扑检查成功",
  367. "结论": "不符合" if count > 0 else "符合",
  368. "错误项": f"{count}条记录",
  369. "报告输出位置": reportpath
  370. }
  371. def tr(self, string, context=''):
  372. if context == '':
  373. context = self.__class__.__name__
  374. return QCoreApplication.translate(context, string)
  375. def getLayerGeometryType(self, geom_type):
  376. geom_type_str = ""
  377. if geom_type == ogr.wkbPoint:
  378. geom_type_str = "Point"
  379. elif geom_type == ogr.wkbLineString:
  380. geom_type_str = "LineString"
  381. elif geom_type == ogr.wkbPolygon:
  382. geom_type_str = "Polygon"
  383. elif geom_type == ogr.wkbMultiPoint:
  384. geom_type_str = "MultiPoint"
  385. elif geom_type == ogr.wkbMultiLineString:
  386. geom_type_str = "MultiLineString"
  387. elif geom_type == ogr.wkbMultiPolygon:
  388. geom_type_str = "MultiPolygon"
  389. elif geom_type == ogr.wkbGeometryCollection:
  390. geom_type_str = "GeometryCollection"
  391. else:
  392. geom_type_str = None
  393. return geom_type_str