I am trying to use python gdal to process a grib2 file into a geotiff file based on the following example:
https://geoexamples.com/d3-raster-tools-docs/code_samples/vardah.html
based on this I have the following code:
import gdal
import osr
ds = gdal.Open(r"/home/test/gfs.t12z.sfluxgrbf000.grib2",1)
gph = ds.GetRasterBand(84).ReadAsArray()
press = ds.GetRasterBand(54).ReadAsArray() / 100
temp = ds.GetRasterBand(52).ReadAsArray()
u = ds.GetRasterBand(50).ReadAsArray()
v = ds.GetRasterBand(51).ReadAsArray()
corr_press = press * (1 - (0.0065*gph/(0.0065*gph + temp + 273.15)))**-5.257
driver = gdal.GetDriverByName('GTiff')
outRaster = driver.Create("/home/test/vardah2.tiff", ds.RasterXSize, ds.RasterYSize, 4, gdal.GDT_Float32)
outRaster.SetGeoTransform(ds.GetGeoTransform())
outband = outRaster.GetRasterBand(1)
outband.WriteArray(corr_press)
outband.SetMetadata({'name': 'press'})
outRasterSRS = osr.SpatialReference()
outRasterSRS.ImportFromEPSG(4326)
outRaster.SetProjection(outRasterSRS.ExportToWkt())
outband.FlushCache()
I am attempting to do this on centos 7 and when I run the program I get the following error:
ERROR 6: The GRIB driver does not support update access to existing datasets.
Traceback (most recent call last):
File "ficky.py", line 4, in <module>
gph = ds.GetRasterBand(84).ReadAsArray()
AttributeError: 'NoneType' object has no attribute 'GetRasterBand'
How do I resolve this error to get a successful run of this script on a centos interface?
Change
ds = gdal.Open(r"/home/test/gfs.t12z.sfluxgrbf000.grib2",1)
to
ds = gdal.Open("/home/test/gfs.t12z.sfluxgrbf000.grib2")
or even better
ds = gdal.Open("/home/test/gfs.t12z.sfluxgrbf000.grib2", GA_ReadOnly)
Related
I'm having a hard time here on processing GIS data in Python, using library ArcPy.
I've been trying to generate independent features from a feature class based on a field of the attribute table which is a unique code representing productive forest units, but I can't get it done.
I've already done this in other situations, but this time I don't know what I am missing.
Here is the code and the error I get:
# coding utf-8
import arcpy
arcpy.env.overwriteOutput = True
ws = r'D:\Projeto_VANT\SIG\proc_parc.gdb'
arcpy.env.workspace = ws
talhoes = r'copy_talhoes'
estados = ('SP', 'MG')
florestas = ('PROPRIA', 'PARCERIA')
arcpy.MakeFeatureLayer_management(talhoes,
'talhoes_layer',
""" "ESTADO" IN {} AND "FLORESTA" IN {} """.format(estados, florestas),
ws)
arcpy.FeatureClassToFeatureClass_conversion(in_features = 'talhoes_layer',
out_path = ws,
out_name = 'talhoes1')
talhoes1 = r'talhoes1'
arcpy.AddField_management(talhoes1, 'CONCAT_T', 'TEXT')
arcpy.CalculateField_management(talhoes1, 'CONCAT_T', """ [ESTADO] & "_" & [CODIGO] & "_" & [TALHAO] """, 'VB')
with arcpy.da.SearchCursor(talhoes1, ['CONCAT_T', 'AREA']) as tal_cursor:
for x in tal_cursor:
print(x[0] + " " + str(x[1])) # This print is just to check if the cursor works and it does!
arcpy.MakeFeatureLayer_management(x,
'teste',
""" CONCAT_T = '{}' """.format(str(x[0]))) # Apparently the problem is here!
arcpy.CopyFeatures_management('teste',
'Layer{}'.format(x[0]))
Here is the error:
Traceback (most recent call last):
File "D:/ArcPy_Classes/Scripts/sampling_sig.py", line 32, in <module>
""" CONCAT_T = '{}' """.format(str(x[0])))
File "C:\Program Files (x86)\ArcGIS\Desktop10.5\ArcPy\arcpy\management.py", line 6965, in MakeFeatureLayer
raise e
RuntimeError: Object: Error in executing tool
I think the issue is with your In feature. you will want your in feature to be talhoes1 since x is the cursor object and not a feature.
arcpy.MakeFeatureLayer_management(talhoes1,'teste',""" CONCAT_T =
'{}'""".format(str(x[0])))
I am very new to GDAL library (trying it as of today actually) and I have a hard time figuring out what I'm doing wrong here. I am trying to execute the 'proximity' function from GDAL, but keep getting the ''str' object is not callable' error message.
Can anyone indicate me what I'm doing wrong.
import os
from osgeo import gdal, osr
gdal_proximity = "C:\\anaconda3\\envs\\geo_py37\\Scripts\\gdal_proximity.py"
proximityInput = gdal.Open(folderPath + os.sep + "proximity_input.tif")
outputTemplate = gdal.Open(folderPath + os.sep + "output_template.tif")
######## Raster properties based on 'outputTemplate' ################
projection = outputTemplate.GetProjection()
ncols = outputTemplate.RasterXSize
nrows = outputTemplate.RasterYSize
bandCount = outputTemplate.RasterCount
upx, xres, xskew, upy, yskew, yres = outputTemplate.GetGeoTransform()
#####################################################################
driver = gdal.GetDriverByName('Gtiff')
proximityOutput = driver.Create(folderPath + os.sep + "proximity_output.tif", ncols, nrows, bandCount, gdal.GDT_Float32)
proximityOutput.SetGeoTransform([upx, xres, xskew, upy, yskew, yres])
proximityOutputPrj = distanceRaster.SetProjection(projection)
gdal_proximity (proximityInput, proximityOutputPrj)
Traceback:
Traceback (most recent call last):
File "C:/Users/antoi/.PyCharmCE2019.3/config/scratches/Radial_Linear_Mean.py", line 22, in <module>
gdal_proximity(proximityInput, proximityOutputPrj)
TypeError: 'str' object is not callable
in your third line of code you set (overwrite) gdal_proximity to be the following string
gdal_proximity = "C:\\anaconda3\\envs\\geo_py37\\Scripts\\gdal_proximity.py"
You then try to call it as a function.
gdal_proximity (proximityInput, proximityOutputPrj)
which triggers your error because its not a function, its a string, so is not callable as a function.
I'm working on an excel/xlwings tool to practice my mental math, using old python scripts I used to run off a command line. When trying to run my VBA macro, I get the following error:
Traceback (most recent call last):
File "<string>", line 1, in <module>
ModuleNotFoundError: No module named 'Training_factoring'
I'll offer something of a checklist to give this request some context:
I'm using Anaconda3 and the spyder IDE
My PYTHONPATH is C:\Users\benms\Anaconda3, and my Interpreter path
is C:\Users\benms\Anaconda3\python.exe
My excel file is located in the same directory as my python module
I have imported the xlwings bas file
My RunPython call does follow the syntax guidelines from the docs, and my python module has the xw.Book.caller() piece per the docs
Here are my code samples:
VBA macro
Sub PracticeStart()
Dim i As Integer
Dim Response As Long
Do While True
RunPython ("import Training_factoring; Training_factoring.DistributionTwoDigit()")
Response = InputBox("Answer? ")
ActiveWorkbook.Worksheets("practice").Range(i + 2, 1).Value = Response
i = i + 2
Loop
End Sub
Python module
def DistributionTwoDigit():
wb = xw.Book.caller()
x = random.randrange(10, 99, 1)
y = random.randrange(10, 99, 1)
i = 0
i =+ 2
wb.sheets[0].range("A1").value = "Distribution (Two-Digit)"
wb.sheets[0].range(i+1,1).value = '{}*{}'.format(x, y)
RunAnswer()
wb.sheets[0].range(i+3,1).value = (x*y)
wb.sheets[0].range(i+4,1).value = '-------------------------------'
x = random.randrange(10, 90, 1)
y = random.randrange(10, 90, 1)
I'm unable to run this code. When I run this it gives me an error which, from what I understand it means that it is unable to import cvxopt.base module.
If there is anyone who has encountered this error or knows the solution to this problem, please reach out.
I'm sharing the code & trace of Python interface below:
The Code:
#!/usr/bin/env python
import numpy as np
from numpy import linalg
from cvxopt import solvers
def Twin_plane_1(R,S,C1,Epsi1,regulz1):
StS = np.dot(S.T,S)
# for regularization we add identity matrix with wt. before inversion
StS = StS + regulz1*(np.identity(StS.shape[0]))
StSRt = linalg.solve(StS,R.T)
RtStSRt = np.dot(R,StSRt)
RtStSRt = (RtStSRt+(RtStSRt.T))/2
m2 = R.shape[0]
e2 = -np.ones((m2,1))
solvers.options['show_progress'] = False
vlb = np.zeros((m2,1))
vub = C1*(np.ones((m2,1)))
# x<=vub
# x>=vlb -> -x<=-vlb
# cdx<=vcd
cd = np.vstack((np.identity(m2),-np.identity(m2)))
vcd = np.vstack((vub,-vlb))
alpha = solvers.qp(matrix(RtStSRt,tc='d'),matrix(e2,tc='d'),matrix(cd,tc='d'),matrix(vcd,tc='d'))#,matrix(0.0,(1,m1)),matrix(0.0))#,None,matrix(x0))
alphasol = np.array(alpha['x'])
z = -np.dot(StSRt,alphasol)
w1 = z[:len(z)-1]
b1 = z[len(z)-1]
return [w1,b1]
The Trace:
Traceback (most recent call last): File
"C:\Users\sau\Downloads\Twin-SVM-master\Twin-SVM-master\TwinPlane1.py",
line 6, in
from cvxopt import solvers File "C:\Python35\lib\site-packages\cvxopt__init__.py", line 50, in
import cvxopt.base ImportError: DLL load failed: The specified module could not be found.
I was having the same issue...try this:
import os
os.environ['PATH'] += r';C:\\Users\\user\\AppData\\Local\\Continuum\\anaconda3\\Library\\mingw-
w64\\bin'
I'm having trouble combining audio and video into one file. The Python code looks like this;
filmPipe = gst.Pipeline("filmPipe")
filmSrc = gst.element_factory_make("multifilesrc", "filmSrc")
filmSrc.set_property("location", "pictures/%d.png")
filmFilt1 = gst.element_factory_make("capsfilter", "filmFilt1")
filmCap1 = gst.Caps("image/png,framerate=5/1,pixel-aspect-ratio=1/1")
filmFilt1.set_property("caps", filmCap1)
filmPngDec = gst.element_factory_make("pngdec", "filmPngDec")
filmff = gst.element_factory_make("ffmpegcolorspace", "filmff")
filmFilt2 = gst.element_factory_make("capsfilter", "filmFilt2")
filmCap2 = gst.Caps("video/x-raw-yuv")
filmFilt2.set_property("caps", filmCap2)
filmTheora = gst.element_factory_make("xvidenc", "filmTheora")
filmQue = gst.element_factory_make("queue", "filmQue")
filmOggmux = gst.element_factory_make("ffmux_mp4", "filmOggmux")
filmFilesink = gst.element_factory_make("filesink", "filmFilesink")
filmFilesink.set_property("location", self.movPath)
musicSrc = gst.element_factory_make("filesrc", "musicSrc")
musicSrc.set_property("location", self.musicPath)
musicDec = gst.element_factory_make("ffdec_mp3", "musicDec")
musicEnc = gst.element_factory_make("lame", "musicEnc")
musicQue = gst.element_factory_make("queue", "musicQue")
filmPipe.add(filmSrc, filmFilt1, filmPngDec, filmff, filmFilt2, filmTheora, filmQue, filmOggmux, filmFilesink)
filmPipe.add(musicSrc, musicDec, musicEnc, musicQue)
gst.element_link_many(filmSrc, filmFilt1, filmPngDec, filmff, filmFilt2, filmTheora, filmQue, filmOggmux, filmFilesink)
gst.element_link_many(musicSrc, musicDec, musicEnc, musicQue, filmOggmux, filmFilesink)
filmPipe.set_state(gst.STATE_PLAYING)
This returns the following error:
Traceback (most recent call last):
File "app.py", line 100, in movGen
gst.element_link_many(musicSrc, musicDec, musicEnc, musicQue, filmOggmux, filmFilesink)
gst.LinkError: failed to link filmOggmux with filmFilesink
Does anybody know where I'm going wrong, or how to fix this?
You are linking 2 times filmOggmux to filmFilesink: this is not allowed, only one link is possible.
Try removing filmFilesink in the second gst.element_link_many().