mtl_gis_oo/scrub_layer_class.py

66 lines
2.0 KiB
Python
Raw Normal View History

2024-03-15 16:43:27 -04:00
from qgis.core import QgsApplication, QgsField, QgsProject, \
QgsProcessingFeedback, QgsVectorLayer, QgsVectorDataProvider, \
QgsExpressionContext, QgsExpressionContextUtils
2024-03-15 12:08:52 -04:00
from qgis.analysis import QgsNativeAlgorithms
2024-03-15 16:43:27 -04:00
import processing
2024-03-15 11:26:23 -04:00
class ScrubLayer:
2024-03-15 12:08:52 -04:00
def __init__(self, qgis_path, layer_path, layer_name):
# Set the path to QGIS installation
QgsApplication.setPrefixPath(qgis_path, True)
# Initialize QGIS application
qgs = QgsApplication([], False)
qgs.initQgis()
2024-03-15 11:26:23 -04:00
self.layer_path = layer_path
self.layer_name = layer_name
2024-03-15 12:08:52 -04:00
self.layer = self.load_layer()
2024-03-15 11:26:23 -04:00
2024-03-15 12:08:52 -04:00
def load_layer(self):
the_layer = QgsVectorLayer(self.layer_path, self.layer_name, 'ogr')
2024-03-15 11:26:23 -04:00
if not the_layer.isValid():
2024-03-15 12:08:52 -04:00
raise ValueError(f'Failed to load layer {self.layer_name} from {self.layer_path}')
2024-03-15 11:26:23 -04:00
else:
2024-03-15 12:08:52 -04:00
QgsProject.instance().addMapLayer(the_layer)
return the_layer
def fix_geometries(self, fixed_layer):
QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms())
fix_geometries_params = {
'INPUT': self.layer,
'METHOD': 0,
'OUTPUT': fixed_layer
}
processing.run("native:fixgeometries", fix_geometries_params)
2024-03-15 16:43:27 -04:00
def create_spatial_index(self):
QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms())
create_spatial_index_params = {
'INPUT': self.layer,
2024-03-15 16:43:27 -04:00
'OUTPUT': 'Output'
}
processing.run("native:createspatialindex", create_spatial_index_params)
print(f'Creating spatial index for {self.layer_name} is completed.')
def clip_layer(self, overlay_layer, clipped_layer):
QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms())
clip_layer_params = {
'INPUT': self.layer_path,
'OVERLAY': overlay_layer,
'FILTER_EXPRESSION': '',
'FILTER_EXTENT': None,
'OUTPUT': clipped_layer
}
processing.run("native:clip", clip_layer_params)
print(f'Clipping of {self.layer_name} is completed.')
2024-03-15 16:43:27 -04:00
2024-03-15 12:08:52 -04:00
@staticmethod
def cleanup():
QgsApplication.exitQgis()
2024-03-15 11:26:23 -04:00
2024-03-15 12:08:52 -04:00