TinInterpolation.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. """
  2. ***************************************************************************
  3. TinInterpolation.py
  4. ---------------------
  5. Date : October 2016
  6. Copyright : (C) 2016 by Alexander Bruy
  7. Email : alexander dot bruy 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__ = 'Alexander Bruy'
  18. __date__ = 'October 2016'
  19. __copyright__ = '(C) 2016, Alexander Bruy'
  20. import os
  21. import math
  22. from qgis.PyQt.QtGui import QIcon
  23. from qgis.core import (QgsProcessingUtils,
  24. QgsProcessing,
  25. QgsProcessingParameterEnum,
  26. QgsProcessingParameterNumber,
  27. QgsProcessingParameterExtent,
  28. QgsProcessingParameterDefinition,
  29. QgsProcessingParameterRasterDestination,
  30. QgsWkbTypes,
  31. QgsProcessingParameterFeatureSink,
  32. QgsProcessingException,
  33. QgsCoordinateReferenceSystem)
  34. from qgis.analysis import (QgsInterpolator,
  35. QgsTinInterpolator,
  36. QgsGridFileWriter)
  37. from processing.algs.qgis.QgisAlgorithm import QgisAlgorithm
  38. from processing.algs.qgis.ui.InterpolationWidgets import ParameterInterpolationData, ParameterPixelSize
  39. pluginPath = os.path.split(os.path.split(os.path.dirname(__file__))[0])[0]
  40. class TinInterpolation(QgisAlgorithm):
  41. INTERPOLATION_DATA = 'INTERPOLATION_DATA'
  42. METHOD = 'METHOD'
  43. PIXEL_SIZE = 'PIXEL_SIZE'
  44. COLUMNS = 'COLUMNS'
  45. ROWS = 'ROWS'
  46. EXTENT = 'EXTENT'
  47. OUTPUT = 'OUTPUT'
  48. TRIANGULATION = 'TRIANGULATION'
  49. def icon(self):
  50. return QIcon(os.path.join(pluginPath, 'images', 'interpolation.png'))
  51. def group(self):
  52. return self.tr('Interpolation')
  53. def groupId(self):
  54. return 'interpolation'
  55. def __init__(self):
  56. super().__init__()
  57. def initAlgorithm(self, config=None):
  58. self.METHODS = [self.tr('Linear'),
  59. self.tr('Clough-Toucher (cubic)')
  60. ]
  61. self.addParameter(ParameterInterpolationData(self.INTERPOLATION_DATA,
  62. self.tr('Input layer(s)')))
  63. self.addParameter(QgsProcessingParameterEnum(self.METHOD,
  64. self.tr('Interpolation method'),
  65. options=self.METHODS,
  66. defaultValue=0))
  67. self.addParameter(QgsProcessingParameterExtent(self.EXTENT,
  68. self.tr('Extent'),
  69. optional=False))
  70. pixel_size_param = ParameterPixelSize(self.PIXEL_SIZE,
  71. self.tr('Output raster size'),
  72. layersData=self.INTERPOLATION_DATA,
  73. extent=self.EXTENT,
  74. minValue=0.0,
  75. default=0.1)
  76. self.addParameter(pixel_size_param)
  77. cols_param = QgsProcessingParameterNumber(self.COLUMNS,
  78. self.tr('Number of columns'),
  79. optional=True,
  80. minValue=0, maxValue=10000000)
  81. cols_param.setFlags(cols_param.flags() | QgsProcessingParameterDefinition.FlagHidden)
  82. self.addParameter(cols_param)
  83. rows_param = QgsProcessingParameterNumber(self.ROWS,
  84. self.tr('Number of rows'),
  85. optional=True,
  86. minValue=0, maxValue=10000000)
  87. rows_param.setFlags(rows_param.flags() | QgsProcessingParameterDefinition.FlagHidden)
  88. self.addParameter(rows_param)
  89. self.addParameter(QgsProcessingParameterRasterDestination(self.OUTPUT,
  90. self.tr('Interpolated')))
  91. triangulation_file_param = QgsProcessingParameterFeatureSink(self.TRIANGULATION,
  92. self.tr('Triangulation'),
  93. type=QgsProcessing.TypeVectorLine,
  94. optional=True)
  95. triangulation_file_param.setCreateByDefault(False)
  96. self.addParameter(triangulation_file_param)
  97. def name(self):
  98. return 'tininterpolation'
  99. def displayName(self):
  100. return self.tr('TIN interpolation')
  101. def processAlgorithm(self, parameters, context, feedback):
  102. interpolationData = ParameterInterpolationData.parseValue(parameters[self.INTERPOLATION_DATA])
  103. method = self.parameterAsEnum(parameters, self.METHOD, context)
  104. bbox = self.parameterAsExtent(parameters, self.EXTENT, context)
  105. pixel_size = self.parameterAsDouble(parameters, self.PIXEL_SIZE, context)
  106. output = self.parameterAsOutputLayer(parameters, self.OUTPUT, context)
  107. columns = self.parameterAsInt(parameters, self.COLUMNS, context)
  108. rows = self.parameterAsInt(parameters, self.ROWS, context)
  109. if columns == 0:
  110. columns = max(math.ceil(bbox.width() / pixel_size), 1)
  111. if rows == 0:
  112. rows = max(math.ceil(bbox.height() / pixel_size), 1)
  113. if interpolationData is None:
  114. raise QgsProcessingException(
  115. self.tr('You need to specify at least one input layer.'))
  116. layerData = []
  117. layers = []
  118. crs = QgsCoordinateReferenceSystem()
  119. for i, row in enumerate(interpolationData.split('::|::')):
  120. v = row.split('::~::')
  121. data = QgsInterpolator.LayerData()
  122. # need to keep a reference until interpolation is complete
  123. layer = QgsProcessingUtils.variantToSource(v[0], context)
  124. data.source = layer
  125. data.transformContext = context.transformContext()
  126. layers.append(layer)
  127. if not crs.isValid():
  128. crs = layer.sourceCrs()
  129. data.valueSource = int(v[1])
  130. data.interpolationAttribute = int(v[2])
  131. if data.valueSource == QgsInterpolator.ValueAttribute and data.interpolationAttribute == -1:
  132. raise QgsProcessingException(self.tr(
  133. 'Layer {} is set to use a value attribute, but no attribute was set').format(i + 1))
  134. if v[3] == '0':
  135. data.sourceType = QgsInterpolator.SourcePoints
  136. elif v[3] == '1':
  137. data.sourceType = QgsInterpolator.SourceStructureLines
  138. else:
  139. data.sourceType = QgsInterpolator.SourceBreakLines
  140. layerData.append(data)
  141. if method == 0:
  142. interpolationMethod = QgsTinInterpolator.Linear
  143. else:
  144. interpolationMethod = QgsTinInterpolator.CloughTocher
  145. (triangulation_sink, triangulation_dest_id) = self.parameterAsSink(parameters, self.TRIANGULATION, context,
  146. QgsTinInterpolator.triangulationFields(), QgsWkbTypes.LineString, crs)
  147. interpolator = QgsTinInterpolator(layerData, interpolationMethod, feedback)
  148. if triangulation_sink is not None:
  149. interpolator.setTriangulationSink(triangulation_sink)
  150. writer = QgsGridFileWriter(interpolator,
  151. output,
  152. bbox,
  153. columns,
  154. rows)
  155. writer.writeFile(feedback)
  156. return {self.OUTPUT: output, self.TRIANGULATION: triangulation_dest_id}