I would like to perform a loop that takes from a given folder a set of rasters and for every raster makes the following operation, that in the specific case is the calculation of the monthly evapotranspiration, that consist in multiplying every raster of monthly average temperature for a given coefficient (that is specified in the two arrays C
and Rg
).
The code doesn't give any error but it doesn't work, because at the end of the loop appears what follow: Invalid layer, Gdal cannot open the dataset
.
Does anyone have any suggestion?
import glob, qgis
import gdal
from qgis.analysis import QgsRasterCalculator, QgsRasterCalculatorEntry
from qgis.core import QgsRasterLayer
C=[0.4, 0.37, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4,0.4]
Rg=[109, 158, 261, 376, 467, 506, 518, 448, 321, 207, 117, 94]
suffix_output=['PET_jan', 'PET_feb', 'PET_mar', 'PET_apr', 'PET_may', 'PET_jun', 'PET_jul', 'PET_aug', 'PET_sep', 'PET_oct', 'PET_nov' ,'PET_dec']
suffix_input=['Tjan', 'Tfeb', 'Tmar', 'Tapr', 'Tmay', 'Tjun', 'Tjul', 'Taug', 'Tsep', 'Toct', 'Tnov', 'Tdec']
outputpath = '/Users/macbook/Desktop/TESI/PROGETTO/'
inputpath = '/Users/macbook/Desktop/TESI/PROGETTO/raster T average/'
list=[0,1,2,3,4,5,6,7,8,9,10,11]
for i in list:
inputrasterfile = QgsRasterLayer(inputpath + suffix_input[i] + ".tif")
entries = []
ras = QgsRasterCalculatorEntry()
ras.ref = 'ras@1'
ras.raster = inputrasterfile
ras.bandNumber = 1
entries.append( ras )
new_path = outputpath + suffix_output[i]+ '.tif'
evapotranspiration = str(C[i]) +'* ras@1 ' + '*(str(Rg[i]) + 50)' + '/(ras@1 + 15)'
Pet = QgsRasterCalculator(evapotranspiration, new_path, 'GTiff', inputrasterfile.extent(), inputrasterfile.width(), inputrasterfile.height(), entries )
Pet.processCalculation()
iface.addRasterLayer(new_path)
Just to understand, why these statement doesn't work? I tried to follow the former suggestion, but the software says that I can't multiply sequence by non-int of type 'str'. I just would like to understand the rule behind this calculation...
evapotranspiration = (str(k[i]) + '* ( 0.46 * ras@1 + 8') * str(p[i]) + '-2)' *str(d[i])
Here I want to write this formula: [k(i)p(i)(0,46*raster+8)-2]*d(i)