-
Notifications
You must be signed in to change notification settings - Fork 0
/
arearatio.py
272 lines (249 loc) · 11.3 KB
/
arearatio.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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
# -*- coding: utf-8 -*-
"""
/***************************************************************************
AreaRatio
A QGIS plugin
Area ratio of polygons within an other polygon (different layers)
use it for example to calculate building footprints areas percent to
the parcel area
Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
-------------------
begin : 2020-11-26
git sha : $Format:%H$
copyright : (C) 2020 by Zoltan Siki
email : siki1958@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. *
* *
***************************************************************************/
"""
from qgis.PyQt.QtCore import QSettings, QTranslator, QCoreApplication, QPoint
from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtWidgets import QAction, QMessageBox
from qgis.gui import QgsMapTool
from qgis.core import QgsPoint, QgsProject, QgsSpatialIndex, \
QgsFeatureRequest, QgsGeometry, QgsProcessingFeatureSourceDefinition
from qgis import processing
import configparser
# Initialize Qt resources from file resources.py
from .resources import *
from .arearatio_dialog import AreaRatioDialog
import os.path
DEFAULT_CONFIG = "L:/xxii/arearatio.cfg"
class AreaRatio:
"""QGIS Plugin to calculate area ratio among polygons"""
def __init__(self, iface):
"""Constructor.
:param iface: An interface instance that will be passed to this class
which provides the hook by which you can manipulate the QGIS
application at run time.
:type iface: QgsInterface
"""
# Save reference to the QGIS interface
self.iface = iface
# initialize plugin directory
self.plugin_dir = os.path.dirname(__file__)
# initialize locale
locale = QSettings().value('locale/userLocale')
if not locale:
locale = QSettings().value('locale/globalLocale')
if not locale:
locale = "en"
locale = locale[0:2]
locale_path = os.path.join(self.plugin_dir, 'i18n', '{}.qm'.format(locale))
if os.path.exists(locale_path):
self.translator = QTranslator()
self.translator.load(locale_path)
QCoreApplication.installTranslator(self.translator)
self.dlg = AreaRatioDialog(self)
if os.path.exists(DEFAULT_CONFIG):
parcel, buildings = self.config(DEFAULT_CONFIG)
else:
parcel, buildings = self.config(os.path.join(
self.plugin_dir, 'default.cfg'))
self.parcel = parcel
self.buildings = buildings
# noinspection PyMethodMayBeStatic
def tr(self, message):
"""Get the translation for a string using Qt translation API.
We implement this ourselves since we do not inherit QObject.
:param message: String for translation.
:type message: str, QString
:returns: Translated version of message.
:rtype: QString
"""
# noinspection PyTypeChecker,PyArgumentList,PyCallByClass
return QCoreApplication.translate('AreaRatio', message)
def config(self, path):
""" load default configuration (layers) """
parcel = 'TELEK'
buildings = ["Lakóépület", "Középület", "Gazdasági épület",
"Melléképület", "Üdülőépület", "Toronyépület",
"Üzemi épület", "Vegyes rendeltetésű épület"]
parser = configparser.ConfigParser()
if not os.path.exists(path):
QMessageBox.warning(None, self.tr("Missing file"),
self.tr("Config file not found: {}").format(path))
return parcel, buildings
try:
parser.read(path)
except:
QMessageBox.warning(None, self.tr("Error in file"),
self.tr("Config file is not valid: {}").format(path))
return parcel, buildings
for section in parser.sections():
if section == "layers":
parcel = parser[section].get('parcel', parcel)
w = parser[section].get('buildings')
if len(w) > 0:
buildings = [name.strip() for name in w.split(',')]
return parcel, buildings
def initGui(self):
"""Create the menu entries and toolbar icons inside the QGIS GUI."""
icon_path = ':/plugins/arearatio/icon.png'
self.action = QAction(QIcon(icon_path),
self.tr(u'Area Ratio'),
self.iface.mainWindow())
self.action.setCheckable(True)
self.action.triggered.connect(self.run)
self.iface.addToolBarIcon(self.action)
self.iface.addPluginToMenu(u'Area Ratio', self.action)
self.tool = PointTool(self.iface.mapCanvas(), self.action, self)
# dialog
icon_path = ':/plugins/arearatio/icon1.png'
self.action1 = QAction(QIcon(icon_path),
self.tr(u'Area Ratio Dialog'),
self.iface.mainWindow())
self.action1.triggered.connect(self.dia)
self.iface.addToolBarIcon(self.action1)
self.iface.addPluginToMenu(u'Area Ratio', self.action1)
def unload(self):
"""Removes the plugin menu item and icon from QGIS GUI."""
self.iface.removePluginMenu(u'Area Ratio', self.action)
self.iface.removePluginMenu(u'Area Ratio', self.action1)
self.iface.removeToolBarIcon(self.action)
self.iface.removeToolBarIcon(self.action1)
def run(self):
""" Activate map tool """
self.iface.mapCanvas().setMapTool(self.tool)
def dia(self):
"""Show layer selection dialog"""
self.dlg.show()
result = self.dlg.exec_()
if result:
index = self.dlg.parcelLayerComboBox.currentIndex()
self.parcel = self.dlg.parcelLayerComboBox.itemText(index)
#self.tool.poly_layer_name = self.dlg.parcelLayerComboBox.currentText()
#self.tool.in_poly_layers = [name.strip() for name
# in self.dlg.buildingsComboBox.currentText().split(',')]
self.buildings = self.dlg.buildingsComboBox.checkedItems()
# force index creation
self.tool.index = None
class PointTool(QgsMapTool):
""" Map tool to query area in a polygon from other layers
:param canvas: map canvas
:param action: action to tool
"""
def __init__(self, canvas, action, main):
QgsMapTool.__init__(self, canvas)
self.canvas = canvas
self.action = action
self.index = None
#self.poly_layer = None
#self.poly_path = None
#self.poly_layer_name = parcel # large polygons
# smaller polygons
#self.in_poly_layers = buildings
self.main = main
def activate(self):
""" activate is called when the button is clicked """
super().activate()
def deactivate(self):
""" deactivate called when another tool button is clicked """
super().deactivate()
self.deactivated.emit()
self.action.setChecked(False) # set tool state to unchecked
def canvasPressEvent(self, event):
""" handle click event on the canvas when tool is active """
x = event.pos().x()
y = event.pos().y()
pos = self.toMapCoordinates(QPoint(x, y))
# search for parcel layer
poly_layers = QgsProject.instance().mapLayersByName(self.main.parcel)
if len(poly_layers) == 0:
QMessageBox.warning(None, self.tr("Area ratio"),
self.tr("{} layer not found".format(self.main.parcel)))
return
poly_layer = poly_layers[0]
# remove | layer: 0 tag from the end TODO not always good!
poly_path = poly_layer.dataProvider().dataSourceUri().split('|')[0]
# build index for polygon layer
if self.index is None:
self.index = QgsSpatialIndex()
for feat in poly_layer.getFeatures():
self.index.insertFeature(feat)
in_poly_layers = self.main.buildings
# find polygons which MBR cover point
fids = self.index.nearestNeighbor(pos)
request = QgsFeatureRequest()
request.setFilterFids(fids)
features = poly_layer.getFeatures(request)
p_geom = QgsGeometry.fromPointXY(pos)
f = None
for feat in features:
if feat.geometry().intersects(p_geom):
f = feat
break
else:
# No poly found
QMessageBox.warning(None, self.tr("Area ratio"),
self.tr("Feature not found on layer {} ".format(self.main.parcel)))
return
# remove previous selection
poly_layer.removeSelection()
# select polygon clicked
poly_layer.select(f.id())
area1 = f.geometry().area() # parcel area
area2 = 0 # sum area for in_poly_layers
msg = self.main.parcel + ": {:.1f}\n".format(area1)
# go through building layers
for name in in_poly_layers:
layers = QgsProject.instance().mapLayersByName(name)
if len(layers) == 0:
QMessageBox.warning(None, self.tr("Area ratio"),
self.tr("{} layer not found".format(name)))
continue
layer = layers[0]
# remove | layer: 0 tag from the end
layer_path = layer.dataProvider().dataSourceUri().split('|')[0]
# select intersecting building
try:
processing.run("native:selectbylocation",
{'INPUT': layer_path,
'INTERSECT': QgsProcessingFeatureSourceDefinition(poly_path, True),
'METHOD': 0, 'PREDICATE': [0]})
except:
QMessageBox.warning(None, self.tr("Area ratio"),
self.tr("Please enable Processing plugin and try again"))
return
features = layer.selectedFeatures()
n = 0
area3 = 0 # sum area for actual layer
for feat in features:
# accept intersecting buildings if an internal point is in the parcel
p = feat.geometry().pointOnSurface()
if p.intersects(f.geometry()):
warea = feat.geometry().area()
n += 1
area3 += warea # total area in this layer
area2 += warea # total area in all layers
if n > 0:
msg = msg + "\n{:d} {}: {:.1f}".format(n, name, area3)
layer.removeSelection()
msg = msg + "\n\n{:.1f} %".format(area2 / area1 * 100.0)
QMessageBox.information(None, self.tr("Area ratio"), msg)