FindProjection.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. """
  2. ***************************************************************************
  3. FindProjection.py
  4. -----------------
  5. Date : February 2017
  6. Copyright : (C) 2017 by Nyall Dawson
  7. Email : nyall dot dawson 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__ = 'Nyall Dawson'
  18. __date__ = 'February 2017'
  19. __copyright__ = '(C) 2017, Nyall Dawson'
  20. import os
  21. from qgis.core import (QgsGeometry,
  22. QgsFeature,
  23. QgsFeatureSink,
  24. QgsField,
  25. QgsFields,
  26. QgsCoordinateReferenceSystem,
  27. QgsCoordinateTransform,
  28. QgsCoordinateTransformContext,
  29. QgsWkbTypes,
  30. QgsProcessingException,
  31. QgsProcessingParameterFeatureSource,
  32. QgsProcessingParameterExtent,
  33. QgsProcessingParameterCrs,
  34. QgsProcessingParameterFeatureSink,
  35. QgsProcessingParameterDefinition)
  36. from qgis.PyQt.QtCore import QVariant
  37. from processing.algs.qgis.QgisAlgorithm import QgisAlgorithm
  38. pluginPath = os.path.split(os.path.split(os.path.dirname(__file__))[0])[0]
  39. class FindProjection(QgisAlgorithm):
  40. INPUT = 'INPUT'
  41. TARGET_AREA = 'TARGET_AREA'
  42. TARGET_AREA_CRS = 'TARGET_AREA_CRS'
  43. OUTPUT = 'OUTPUT'
  44. def tags(self):
  45. return self.tr('crs,srs,coordinate,reference,system,guess,estimate,finder,determine').split(',')
  46. def group(self):
  47. return self.tr('Vector general')
  48. def groupId(self):
  49. return 'vectorgeneral'
  50. def __init__(self):
  51. super().__init__()
  52. def initAlgorithm(self, config=None):
  53. self.addParameter(QgsProcessingParameterFeatureSource(self.INPUT,
  54. self.tr('Input layer')))
  55. extent_parameter = QgsProcessingParameterExtent(self.TARGET_AREA,
  56. self.tr('Target area for layer'))
  57. self.addParameter(extent_parameter)
  58. # deprecated
  59. crs_param = QgsProcessingParameterCrs(self.TARGET_AREA_CRS, 'Target area CRS', optional=True)
  60. crs_param.setFlags(crs_param.flags() | QgsProcessingParameterDefinition.FlagHidden)
  61. self.addParameter(crs_param)
  62. self.addParameter(QgsProcessingParameterFeatureSink(self.OUTPUT,
  63. self.tr('CRS candidates')))
  64. def name(self):
  65. return 'findprojection'
  66. def displayName(self):
  67. return self.tr('Find projection')
  68. def processAlgorithm(self, parameters, context, feedback):
  69. source = self.parameterAsSource(parameters, self.INPUT, context)
  70. if source is None:
  71. raise QgsProcessingException(self.invalidSourceError(parameters, self.INPUT))
  72. extent = self.parameterAsExtent(parameters, self.TARGET_AREA, context)
  73. target_crs = self.parameterAsExtentCrs(parameters, self.TARGET_AREA, context)
  74. if self.TARGET_AREA_CRS in parameters:
  75. c = self.parameterAsCrs(parameters, self.TARGET_AREA_CRS, context)
  76. if c.isValid():
  77. target_crs = c
  78. target_geom = QgsGeometry.fromRect(extent)
  79. fields = QgsFields()
  80. fields.append(QgsField('auth_id', QVariant.String, '', 20))
  81. (sink, dest_id) = self.parameterAsSink(parameters, self.OUTPUT, context,
  82. fields, QgsWkbTypes.NoGeometry, QgsCoordinateReferenceSystem())
  83. if sink is None:
  84. raise QgsProcessingException(self.invalidSinkError(parameters, self.OUTPUT))
  85. # make intersection tests nice and fast
  86. engine = QgsGeometry.createGeometryEngine(target_geom.constGet())
  87. engine.prepareGeometry()
  88. layer_bounds = QgsGeometry.fromRect(source.sourceExtent())
  89. crses_to_check = QgsCoordinateReferenceSystem.validSrsIds()
  90. total = 100.0 / len(crses_to_check)
  91. found_results = 0
  92. transform_context = QgsCoordinateTransformContext()
  93. for current, srs_id in enumerate(crses_to_check):
  94. if feedback.isCanceled():
  95. break
  96. candidate_crs = QgsCoordinateReferenceSystem.fromSrsId(srs_id)
  97. if not candidate_crs.isValid():
  98. continue
  99. transform_candidate = QgsCoordinateTransform(candidate_crs, target_crs, transform_context)
  100. transform_candidate.setBallparkTransformsAreAppropriate(True)
  101. transform_candidate.disableFallbackOperationHandler(True)
  102. transformed_bounds = QgsGeometry(layer_bounds)
  103. try:
  104. if transformed_bounds.transform(transform_candidate) != 0:
  105. continue
  106. except:
  107. continue
  108. try:
  109. if engine.intersects(transformed_bounds.constGet()):
  110. feedback.pushInfo(self.tr('Found candidate CRS: {}').format(candidate_crs.authid()))
  111. f = QgsFeature(fields)
  112. f.setAttributes([candidate_crs.authid()])
  113. sink.addFeature(f, QgsFeatureSink.FastInsert)
  114. found_results += 1
  115. except:
  116. continue
  117. feedback.setProgress(int(current * total))
  118. if found_results == 0:
  119. feedback.reportError(self.tr('No matching projections found'))
  120. return {self.OUTPUT: dest_id}