-
Notifications
You must be signed in to change notification settings - Fork 0
/
line_grid_algorithm.py
215 lines (166 loc) · 9.24 KB
/
line_grid_algorithm.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
# -*- coding: utf-8 -*-
"""
/***************************************************************************
illini_drainage_tools
A QGIS plugin
Performs Specific Draiange Related Tasks and Analysis on a Site
Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
-------------------
begin : 2022-03-15
copyright : (C) 2022 by FALASY Anamelechi
email : fvw.services@gmail.com
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
"""
__author__ = 'FALASY Anamelechi'
__date__ = '2022-03-15'
__copyright__ = '(C) 2022 by FALASY Anamelechi'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
import processing
import os, math
import inspect
import time
import qgis.utils
import numpy as np
from qgis.gui import *
from PyQt5 import QtWidgets
from collections import Counter
from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtCore import QCoreApplication, QVariant
from qgis.core import QgsProcessing
from qgis.core import QgsProcessingAlgorithm
from qgis.core import QgsProcessingMultiStepFeedback
from qgis.core import QgsProcessingParameterExtent
from qgis.core import QgsProcessingParameterRasterLayer
from qgis.core import QgsProcessingParameterFeatureSource
from qgis.core import QgsProcessingParameterFeatureSink
from qgis.core import QgsProcessingParameterBoolean
from qgis.core import QgsProcessingParameterVectorLayer
from qgis.core import QgsProcessingParameterNumber
from qgis.core import QgsProcessingParameterPoint
from qgis.core import QgsProcessingParameterField
from qgis.core import QgsProcessingParameterCrs
from qgis.core import QgsCoordinateReferenceSystem
from qgis.core import QgsFeatureSink
from qgis.core import QgsFeatureRequest
from qgis.core import QgsVectorLayer
from qgis.core import QgsLineSymbol
from qgis.core import QgsProperty
from qgis.core import QgsProcessingLayerPostProcessorInterface
from qgis.core import QgsProcessingParameterVectorDestination
from qgis.core import (edit,QgsField, QgsFeature, QgsPointXY, QgsWkbTypes, QgsGeometry, QgsFields)
class LineGridAlgorithm(QgsProcessingAlgorithm):
ROTATION_KEY = 'ROTATION_KEY'
USE_ASS_KEY = 'USE_ASS_KEY'
def tr(self, string):
return QCoreApplication.translate('Processing', string)
def createInstance(self):
return LineGridAlgorithm()
def name(self):
return 'd. Tile Layout Grids'
def displayName(self):
return self.tr(self.name())
def group(self):
return self.tr(self.groupId())
def groupId(self):
return ''
def icon(self):
cmd_folder = os.path.split(inspect.getfile(inspect.currentframe()))[0]
icon = QIcon(os.path.join(os.path.join(cmd_folder, 'logo.png')))
return icon
def shortHelpString(self):
return self.tr( """This tool creates a merged vector layers (both linear and perpendicular) of grids covering a given extent of a Field.
Workflow:
1. From the layers Panel, left-click on the Field Boundary Layer to highlight it and then on the map Canvas "Zoom Out" a liitle bit
2. From the Grid Extent options, choose the "Use Map Canvas Extent" to define the spatial extent for the grid lines
3. Specify the grid cell dimensions. The Default values can be left so if desired
4. Save the output files (optional)
5. Click on \"Run\"
The script will give out two outputs.
Note: To have the full benefits of this tool, ensure the input Field Boundary Layer is at least twice the size of tile layout area.
The help link in the Graphical User Interface (GUI) provides more information about the plugin.
""")
def helpUrl(self):
return "https://publish.illinois.edu/illinoisdrainageguide/files/2022/06/PublicAccess.pdf"
def initAlgorithm(self, config=None):
self.addParameter(QgsProcessingParameterExtent('Extent', 'Grid Extent', defaultValue=None))
self.addParameter(QgsProcessingParameterCrs('CRS', 'Coordinate Reference System', defaultValue='EPSG:3435'))
self.addParameter(QgsProcessingParameterVectorDestination('LinearGrid', 'Linear Grids', type=QgsProcessing.TypeVectorAnyGeometry, createByDefault=True, defaultValue=None))
self.addParameter(QgsProcessingParameterVectorDestination('PerpendicularGrid', 'Perpendicular Grids', type=QgsProcessing.TypeVectorAnyGeometry, createByDefault=True, defaultValue=None))
self.addParameter(QgsProcessingParameterNumber('GridWidth', 'Horizontal Spacing', type=QgsProcessingParameterNumber.Double, minValue=0.000001, defaultValue=100))
self.addParameter(QgsProcessingParameterNumber('GridHeight', 'Vertical Spacing', type=QgsProcessingParameterNumber.Double, minValue=0.000001, defaultValue=100))
self.addParameter(QgsProcessingParameterNumber('RotateGrid', 'Rotation Angle', type=QgsProcessingParameterNumber.Double, minValue=1.0,maxValue=180.0, defaultValue=45.0))
self.addParameter(QgsProcessingParameterPoint('GridAnchor', 'Indicate Grid Center', defaultValue=None))
def processAlgorithm(self, parameters, context, model_feedback):
# Use a multistep feedback, so that individual child algorithm progress reports are adjusted for the
# overall progress through the model
feedback = QgsProcessingMultiStepFeedback(2, model_feedback)
results = {}
outputs = {}
# Create the Original Parent Grid [Straight]
grid_params = {
'TYPE': 1,
'EXTENT': parameters['Extent'],
'HSPACING': parameters['GridWidth'],
'VSPACING': parameters['GridHeight'],
'HOVERLAY': 0,
'VOVERLAY': 0,
'CRS': parameters['CRS'],
'OUTPUT': parameters['LinearGrid']
}
feedback.setCurrentStep(1)
if feedback.isCanceled():
return {}
outputs['CreateGrid'] = processing.run("native:creategrid", grid_params, context=context, feedback=feedback, is_child_algorithm=True)#1
results['CreateGrid'] = outputs['CreateGrid']['OUTPUT']
# Rotate the Original Parent Grid [Perpendicular]
rotate_params = {
'INPUT': results['CreateGrid'],
'ANGLE': parameters['RotateGrid'],
'ANCHOR': parameters['GridAnchor'],
'OUTPUT': parameters['PerpendicularGrid']
}
feedback.setCurrentStep(2)
if feedback.isCanceled():
return {}
outputs['RotateFeatures'] = processing.run('native:rotatefeatures', rotate_params, context=context, feedback=feedback, is_child_algorithm=True) #2
results['RotateFeatures'] = outputs['RotateFeatures']['OUTPUT']
if context.willLoadLayerOnCompletion(results['CreateGrid']):
context.layerToLoadOnCompletionDetails(results['CreateGrid']).setPostProcessor(GridPostProcessor.create())
if context.willLoadLayerOnCompletion(results['RotateFeatures']):
context.layerToLoadOnCompletionDetails(results['RotateFeatures']).setPostProcessor(LinePostProcessor.create())
return results
class GridPostProcessor(QgsProcessingLayerPostProcessorInterface):
instance = None
def postProcessLayer(self, layer, context, feedback):
if not isinstance(layer, QgsVectorLayer):
return
renderer = layer.renderer().clone()
symbol = QgsLineSymbol.createSimple({'line_color': '191,191,191,255', 'line_width': '0.20', 'line_style': 'dash'})
renderer.setSymbol(symbol)
layer.setRenderer(renderer)
@staticmethod
def create() -> 'GridPostProcessor':
GridPostProcessor.instance = GridPostProcessor()
return GridPostProcessor.instance
class LinePostProcessor(QgsProcessingLayerPostProcessorInterface):
instance = None
def postProcessLayer(self, layer, context, feedback):
if not isinstance(layer, QgsVectorLayer):
return
renderer = layer.renderer().clone()
symbol = QgsLineSymbol.createSimple({'line_color': '191,191,191,255', 'line_width': '0.20', 'line_style': 'dash'})
renderer.setSymbol(symbol)
layer.setRenderer(renderer)
@staticmethod
def create() -> 'LinePostProcessor':
LinePostProcessor.instance = LinePostProcessor()
return LinePostProcessor.instance