calling Python module from VBA/xlwings - python

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)

Related

python gdal not processing grib file properly on CENTOS linux

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)

Py2app not functioning as desired to create an app for mac

I'm very new to working on MacOS, but I need to make an app that Mac users can utilize. It's supposed to be a simple plug-and-play app, that is to say that I want to make sure that all they need to do is download the Mac executable file and then they can use the app freely. My app currently seems to be working perfectly fine, that is at least while I'm running the program using the PyCharm IDE, which is also where I compiled my code. This app works through the IDE on the original machine, as well as any other device that I can install the IDE and the other required packages (wand). However, when creating an app through py2app and running it, I get the following error:
avery#averys-MacBook-Air-2 Patents %
./dist/PatDrawDemo.app/Contents/MacOS/PatDrawDemo
Exception in Tkinter callback
Traceback (most recent call last):
File
"/usr/local/opt/python#3.9/Frameworks/Python.framework/Versions/3.9/lib/python3.9/tkinter/init.py",
line 1892, in call
return self.func(*args)
File "/Users/avery/Documents/Patents/PatDrawDemo.py", line
165, in get_input
fig_one(txt, int(ct))
File "/Users/avery/Documents/Patents/PatDrawDemo.py", line
105, in fig_one
fig1.save(filename='PatDrawFig1.png')
File
"/usr/local/opt/python#3.9/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/wand/image.py",
line 9892, in save
self.raise_exception()
File
"/usr/local/opt/python#3.9/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/wand/resource.py",
line 222, in raise_exception
raise e
wand.exceptions.CoderError: WriteBlob Failed `PatDrawFig1.png' #
error/png.c/MagickPNGErrorHandler/1713
I imagine that the error I'm getting is due to the path to which it's supposed to save to is invalid or unreachable or something of the sort, but then again I honestly don't know what the problem is. Any help would be greatly appreciated. If there's anything that is needed in addition to what I've posted, please let me know. Below is just a snippet of the code where 'PatDrawFig1.png' is saving.
def fig_one(full_text, ct):
target_width = 375
y_offset = 0
y_padding = 5
x_padding = 7
with Image(width=2000, height=5000, pseudo='xc:white') as fig1:
for match in find_matches(text=full_text):
with Drawing() as ctx:
ctx.font_size = 20
ctx.text_alignment = 'center'
words = match.split(" ")
word_count = len(words)
while True:
temp_text = rebuild_text(words, word_count, str(ct))
metrics = ctx.get_font_metrics(fig1, temp_text, multiline=True)
if metrics.text_width > target_width:
word_count -= 1
else:
text = temp_text
target_height = int(metrics.text_height + 1)
break
ctx.push()
ctx.fill_color = 'white'
ctx.stroke_width = 3
ctx.stroke_color = 'black'
ctx.rectangle(2, y_offset + y_padding, width=2*x_padding+target_width,
height=2*y_padding+target_height)
ctx.pop()
ctx.text(x_padding+3 + (target_width // 2), 10 + 4*y_padding+y_offset, text)
ctx(fig1)
y_offset += target_height + 4*y_padding - 2
ct += 2
fig1.trim()
fig1.save(filename='PatDrawFig1.png')
open_image('PatDrawFig1.png')
exit()
Also let me know if there's any other sort of clarification needed.

Cannot generate subsets of feature class with arcpy (ArcGIS library in Python 2.7)

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])))

Passing a Python variable to R using rpy2

I have basic R script that performs a GLM on a MySQL dataset. This runs fine using Rscript in bash. However I would like to call it within a python script so I can add it to a loop, I can create the sql statement but I can't seem to pass it to R using rpy2;
for word in words:
sql_scores = "select a.article_id, response, score from scores as a join profile as b on a.article_id = b.article_id where response in (1,0) and keyword = '%s';" % (word[0])
robjects.r("library(RMySQL)")
robjects.r("mydb = dbConnect(MySQL(), user='me', password='xxxx', host='aws.host', dbname='mydb')")
robjects.r("results = fetch(dbSendQuery(mydb, '%s'))") % (sql_scores)
robjects.r("model <- glm(response ~ score , data=results, family=binomial)")
robjects.r("summary(model)")
If I print sql_scores I can run this fine directly in MySQL. However Python produces this error;
Loading required package: DBI
Traceback (most recent call last):
File "keyword_searcher.py", line 30, in <module>
robjects.r("results = fetch(dbSendQuery(mydb, '%s'))") % (sql_scores)
File "/usr/local/lib/python2.7/dist-packages/rpy2/robjects/__init__.py", line 268, in __call__
p = rinterface.parse(string)
ValueError: Error while parsing the string.
I can't figure out the proper syntax for:
robjects.r("results = fetch(dbSendQuery(mydb, %s))") % (sql_scores)
Use double quotes around the "%s" and single quotes around the robjects.r string:
robjects.r('results = fetch(dbSendQuery(mydb, "%s"))') % (sql_scores)
or use the format() method:
robjects.r('fetch(dbSendQuery(mydb, {0}))'.format(sql_scores))
You can access variables in the R environment with robjects.globalenv['varname'].
So an alternative way is:
robjects.globalenv['sql_scores'] = sql_scores
robjects.r("results = fetch(dbSendQuery(mydb, sql_scores))")

Interpolating R objects into R code strings

I am using rpy2 to run some R commands. Dont ask why. It's necessary at this moment. So here's a part of the code.
import pandas.rpy.common as com
from rpy2.robjects import r
#Load emotionsCART decision tree. Successful.
r_dataframe = com.convert_to_r_dataframe(data)
print type(r_dataframe)
(<class 'rpy2.robjects.vectors.DataFrame'>)
r('pred = predict(emotionsCART, newdata = %s)') %(r_dataframe)
Here what I want to do is pass this r_dataframe into the calculation. I'm using the decision tree that I'd loaded earlier to predict the values. But the last line gives me an error. It says
Traceback (most recent call last):
File "<pyshell#38>", line 1, in <module>
r('pred = predict(emotionsCART, newdata = %s)') %(r_dataframe)
File "C:\Python27\lib\site-packages\rpy2\robjects\__init__.py", line 245, in __call__
p = rinterface.parse(string)
ValueError: Error while parsing the string.
Ideas why this is happening?
I think that:
r('pred = predict(emotionsCART, newdata = %s)') %(r_dataframe)
SHould be:
r('pred = predict(emotionsCART, newdata = %s)' % (r_dataframe) )
The %(r_dataframe) was associated with the r() part, while it should be associated with the '' (string).
But it is hard to check without a reproducible example.

Categories