1

I have created a script which reads a JSON file and based on the attributes creates a grid and assigns values to the grid. This JSON file may change. I wanted to create an infinite loop to run the script every 0.5s and recreate the layer.

When I use while loop, QGIS crashes. I tried to use Qtime but no success. I want to make the process run in the background so while it is refreshing I can make an analysis.

Here is my code:

import time
import sched
import json
import numpy as np
import math


class grid_geometries():
    def __init__(self, points_array,polygon_array):
        self.points_array = points_array
        self.polygon_array = polygon_array

def grid_generator(latitude , longitude , cell_size , nrows, ncols):
    points_array_size = (nrows +1 ,ncols+1,2)                    #point array size
    points_array= np.zeros(points_array_size, dtype=float)        #point array creation
    polygon_array_size = (nrows,ncols,4,2)                       #vector array size
    polygon_array= np.full(polygon_array_size,0, dtype=float)    #vector array creation

    ### START :   Creating points with coordinates
    i=0
    while i < nrows +1 :
        j=0
        while j < ncols + 1:
            points_array[i][j][0]= latitude + cell_size*(j*math.cos(rotation)- i * math.sin(rotation))
            points_array[i][j][1]= longitude + cell_size*(i*math.cos(rotation)+ j * math.sin(rotation))
            j = j+1
        i = i+1

    ### END :    Creating points with coordinates

    ### START :  Creating Vector's List

    i=0
    while i < nrows:
        j=0
        while j < ncols:
            polygon_array[i][j][0]=points_array[i+1][j+1]
            polygon_array[i][j][1]=points_array[i+1][j]
            polygon_array[i][j][2]=points_array[i][j]
            polygon_array[i][j][3]=points_array[i][j+1]
            j = j+1
        i = i+1
    # End :  Creating Vector's List
    return grid_geometries(points_array , polygon_array)

def _Layer_Creator_(vectorLyr,grid_coordinates,grid_data):

    i=0
    while i < nrows:
        j=0
        while j < ncols:
            poly = QgsGeometry.fromPolygonXY([[
                QgsPointXY(grid_coordinates.polygon_array[i][j][0][0], grid_coordinates.polygon_array[i][j][0][1]),
                QgsPointXY(grid_coordinates.polygon_array[i][j][1][0], grid_coordinates.polygon_array[i][j][1][1]),
                QgsPointXY(grid_coordinates.polygon_array[i][j][2][0], grid_coordinates.polygon_array[i][j][2][1]),
                QgsPointXY(grid_coordinates.polygon_array[i][j][3][0], grid_coordinates.polygon_array[i][j][3][1]),
                QgsPointXY(grid_coordinates.polygon_array[i][j][0][0], grid_coordinates.polygon_array[i][j][0][1])
                ]])
            f=QgsFeature(vectorLyr.fields())
            f.setAttributes([((i)*ncols)+j+1,float(grid_data[i][j])])
            f.setGeometry(poly)
            vpr.addFeatures([f])
            j = j+1
        i = i+1

    QgsProject.instance().addMapLayer(vectorLyr)
    return vectorLyr

#  CLASS AND FUNCTION  ---  END  ####



path = r'C:\Users\firoozb1.AALTO\OneDrive - Aalto University\Aalto\City Scope Project\json_Example.json'
# Removing Previous Layer

try:
    QgsProject.instance().removeMapLayer(vectorLyr)
except:
    print("no layer to remove")



start = time.time()
### Reading JSON FILE
with open(path) as json_file:
    data = json.load(json_file)

grid = data['grid']
nrows = data['header']['spatial']['nrows']
ncols = data['header']['spatial']['ncols']
cell_size = data['header']['spatial']['cellSize']
rotation =math.radians(data['header']['spatial']['rotation'])
longitude = data['header']['spatial']['longitude']
latitude = data['header']['spatial']['latitude']


value_sensor = data['grid']                                             ### Sensor value is for tracking changes for both study and triggering the grid update
### GRID COORDINATES CREATION

grid_coordinates = grid_generator(latitude , longitude , cell_size , nrows, ncols)


grid_size = (nrows,ncols)
grid_data = np.zeros(grid_size)




# INSERTING THE VALUES


i = ncols
while i > 0:
    j = 0    
    while j < nrows:
        grid_data[abs(i-ncols)][j] = grid[j + abs(i-ncols)*(ncols)]
        j=j+1
    i = i-1

# CREATING COORDINATES FOR GRID




Counter = Counter +1
vectorLyr = QgsVectorLayer('Polygon?crs:epsg=4326&field=ID:integer(3)&field=value:double','test' + str(Counter),"memory")
vpr = vectorLyr.dataProvider()



# Creating Grid and adding data

vectorLyr = _Layer_Creator_(vectorLyr,grid_coordinates,grid_data)
vectorLyr = iface.activeLayer()

# Applying Style ###

vectorLyr.loadNamedStyle(r'C:\Users\firoozb1.AALTO\OneDrive - Aalto University\Aalto\City Scope Project\Style.qml')
vectorLyr.triggerRepaint()

### refreshing the view

vectorLyr.updateExtents()
qgis.utils.iface.mapCanvas().refresh()
vectorLyr.triggerRepaint()
end = time. time()


### timer
print(end - start)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.