Python Code unable to execute in Windows - python

My python code was running successfully in Ubuntu 14.04; but when I went to run in Windows Platform, it throws me into error.
The Code:
import pymc
with open("days1.txt") as f:
dataset = map(float, f)
a = pymc.Uniform('a', lower=0, upper=1500000, value=70, doc='Weibull alpha parameter')
b = pymc.Uniform('b', lower=0, upper=1500000, value=70, doc='Weibull beta parameter')
like = pymc.Weibull('like', alpha=a, beta=b, value=dataset, observed=True)
if __name__=='__main__':
import pylab
M = pymc.MCMC([a,b,like])
M.sample(10000,5000,2)
pymc.Matplot.plot(a)
pymc.Matplot.plot(b)
M.summary()
M.write_csv("parameters1.csv")
The error:
C:\Python35-32>python.exe "E:\TCS\Desktop\EarlyWarning\JLR\Data\EJ327000AB\Scrip
ts\Screen 7\Check Python - 1\weibullEstimationOutData - 1.py"
Traceback (most recent call last):
File "C:\Python35-32\lib\site-packages\pymc\PyMCObjects.py", line 742, in __in
it__
self._value = np.array(value, dtype=dtype)
TypeError: float() argument must be a string or a number, not 'map'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "E:\TCS\Desktop\EarlyWarning\JLR\Data\EJ327000AB\Scripts\Screen 7\Check P
ython - 1\weibullEstimationOutData - 1.py", line 8, in <module>
like = pymc.Weibull('like', alpha=a, beta=b, value=dataset, observed=True)
AttributeError: 'TypeError' object has no attribute 'message'
Kindly Help. Thanks in Advance

You are using Python 2 with Ubuntu, but Python 3 with Windows. Install Python 2 for Windows, or port your code to Python 3
import pylab
import pymc
with open("days1.txt") as f:
dataset = list(map(float, f))
a = pymc.Uniform('a', lower=0, upper=1500000, value=70, doc='Weibull alpha parameter')
b = pymc.Uniform('b', lower=0, upper=1500000, value=70, doc='Weibull beta parameter')
like = pymc.Weibull('like', alpha=a, beta=b, value=dataset, observed=True)
if __name__=='__main__':
M = pymc.MCMC([a,b,like])
M.sample(10000,5000,2)
pymc.Matplot.plot(a)
pymc.Matplot.plot(b)
M.summary()
M.write_csv("parameters1.csv")

Related

why is 'log' object not callable?

x = Symbol ("x")
f = log(x)
dif1 = diff(f,x)
dif2 = diff(dif1,x)
dif3 = diff(dif2,x)
dif4 = diff(dif3,x)
dif5 = diff(dif4,x)
def D11(a,h):
return (f.evalf(subs={x:a+h})-f.evalf(subs={x:a}))/h + (h/2)*dif2.evalf(subs={x:a+h/2})
def D12(a,h):
return ((f.evalf(subs={x:(a+h)}) - f(a-h)))/(2*h) - h**2/6*dif3.evalf(subs={x:(a)})
def D13(a,h):
return (f.evalf(subs={x:(a-2*h)})- 8*f.evalf(subs={x:(a-h)}) + 8*f.evalf(a+h) - f(a+2*h))/(12*h) - h**4/30*ftuletis5(a)
def D22(a,h):
return (f.evalf(subs={x:(a+h)}) - 2*f.evalf(subs={x:(a)}) + f.evalf(subs={x:(a-h)}))/h**2 - h**2/12*(dif4.evalf(subs={x:(a)}))
vigaD11 = []
vigaD12 = []
vigaD13 = []
vigaD22 = []
h=[]
for i in range(20):
h+=h+[(10**(-i))]
vigaD11+= vigaD11 + [(D11(2,h[i])-(dif1.evalf(subs={x:2})))]
vigaD12+= vigaD12+[(D12(2,h[i])-(dif1.evalf(subs={x:2})))]
vigaD13+= vigaD13 + [(D13(2,h[i])-(dif1.evalf(subs={x:2})))]
vigaD22+= vigaD22 [(D22(2,h[i])-(dif2.evalf(subs={x:2})))]
I get an error message saying that log object is not callable. Currently I'm using the math package and Sympy package to get the program to do what I want.
The error message I get:
Traceback (most recent call last):
File "C:\Users\arman\Desktop\Numbrilised meetodid\praktikum12\praktikum12.py", line 64, in <module>
vigaD12+= vigaD12+[(D12(2,h[i])-(dif1.evalf(subs={x:2})))]
File "C:\Users\arman\Desktop\Numbrilised meetodid\praktikum12\praktikum12.py", line 37, in D12
return ((f.evalf(subs={x:(a+h)}) - f(a-h)))/(2*h) - h**2/6*dif3.evalf(subs={x:(a)})
TypeError: 'log' object is not callable
It still does not work when I specifically call out the sympy version of log. Please help.
You could try f = math.log(x) or whichever log function you want to use. Maybe python just doesn't find the right function to call.
In an isympy session with * import ofsympyandxsymbol,log` a sympy object
In [1]: log
Out[1]: log
In [2]: x
Out[2]: x
In [3]: f = log(x)
In [4]: f(23)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-4-a73e6f7d2549> in <module>
----> 1 f(23)
TypeError: 'log' object is not callable
You can't call log again; it's already been "called". You can evaluate it at specific number with:
In [13]: f.evalf(subs={x:1.23})
Out[13]: 0.207014169384326
You do that once in the problem expression, but not the second time. Why not?
f.evalf(subs={x:(a+h)}) - f(a-h)

How to resolve ValueError in python?

I am running one code in python2.7.9 so code is working fine but the same code i am running in python2.7.5 it is giving me value error.
Can you please help to to resolve this?
code:
import os
import sys
table = sys.argv[1] #CALL_KEY
column_nm = sys.argv[2] #ID
file_loc = '/medaff/eureka/RawLayer/AMPIL/'
lkp_file_path ='/medaff/eureka/AMPIL_INCREMENT/'
tgt_file_path ='/medaff/eureka/AMPIL_UNMATCHED/'
def get_col_index(file,col):
header=open(file).readline().strip()
header_list = header.split('|')
return str(header_list.index(col)+1)
src_file_nm = file_loc+table+'/'+table+'.txt'
lkp_file = lkp_file_path+table+'/'+table+'.txt'
trgt_file_nm = tgt_file_path+table+'/'+table+'_Unmatched.txt'
print(lkp_file)
rm_str = 'rm -f '+trgt_file_nm
print(rm_str)
matcher_str = 'awk -F \'|\' \'NR==FNR && NR>1{id[toupper($' + get_col_index(lkp_file,column_nm) + ')]; next} !(toupper(' + get_col_index(src_file_nm,column_nm) + ') in id)\' '+lkp_file+' '+src_file_nm+'|tail -n +2 >> '+trgt_file_nm
os.system(matcher_str)
error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in get_col_index
ValueError: 'ID' is not in list

Error: module 'MSGARCH' has no attribute 'predict'

I am using the package rpy2 to use R language in Python environment. I am using the MSGARCH package which is only on R. The package is clearly suppose to come with the attribute predict.
https://rdrr.io/cran/MSGARCH/man/predict.html
I don't understand why I have this error. Do you have an idea please?
the full error message is :
Traceback (most recent call last):
File "markov.py", line 165, in <module>
pred = ms.predict(object = fitMCMC, newdata = None, nahead = '30L')
AttributeError: module 'MSGARCH' has no attribute 'predict'
The code is:
ms = importr('MSGARCH')
from rpy2.robjects import r, pandas2ri, numpy2ri, vectors
pandas2ri.activate()
numpy2ri.activate()
base = importr('base')
stats = importr('stats')
pred = ms.predict(object = fitMCMC, newdata = None, nahead = '30L')

Determine Error/Exception Type Python

I am using the win32Com module to write data to an excel sheet on a Windows 7 machine with Python 3.5. While it is running I get thrown an error. I tried making a "try/except" block but the error type I attempted is apparently not an actual error type. Here is my code :
import win32com.client as win32
import sqlite3
def writeWords(storage):
excel = win32.gencache.EnsureDispatch('Excel.Application')
excel.Visible = True
wb = excel.Workbooks.Add()
ws = wb.Worksheets('Sheet1')
i = 0
storLen = len(storage)
while i < storLen:
varX = storage[i]
lenVar = len(varX)
q = 0
while q < lenVar:
tarf = str(storage[i][q].encode('ascii', errors='ignore')).lstrip("b\'").rstrip("\'")
try :
ws.Cells(q+1,i+1).Value = (tarf)
except pywintypes.com_error:
print("Error")
q +=1
q += 1
i += 1
The traceback I get is this :
Traceback (most recent call last):
File "C:\Users\LewTo002\Google Drive\Todd's Stuff\python\mailWords\current\mailWords2.py", line 65, in writeWords
ws.Cells(q+1,i+1).Value = (tarf)
File "C:\Users\LewTo002\AppData\Local\Programs\Python\Python35\lib\site-packages\win32com\client\__init__.py", line 474, in __setattr__
self._oleobj_.Invoke(*(args + (value,) + defArgs))
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2146777998), None)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\LewTo002\AppData\Local\Programs\Python\Python35\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 326, in RunScript
exec(codeObject, __main__.__dict__)
File "C:\Users\LewTo002\Google Drive\Todd's Stuff\python\mailWords\current\mailWords2.py", line 100, in <module>
writeWords(storage)
File "C:\Users\LewTo002\Google Drive\Todd's Stuff\python\mailWords\current\mailWords2.py", line 66, in writeWords
except pywintypes.com_error:
NameError: name 'pywintypes' is not defined
I am used to seeing things like here ( https://docs.python.org/2/library/exceptions.html#exception-hierarchy ) and have been basing my method of writing the try/except off of here ( https://docs.python.org/3/tutorial/errors.html )
My question is how do I determine the error type that I am trying to catch based on the top portion of the traceback?
You need to add an import, more specifically
from pywintypes import com_error
then use the following
except com_error as e:
By importing "pywintypes" my error try/except functions properly.

Why is python pocketsphinx giving TypeError?

I am using the Python pocket sphinx tutorial, according to
https://metakermit.com/2011/python-speech-recognition-helloworld/
(complete code here):
import sys,os
def decodeSpeech(hmmd,lmdir,dictp,wavfile):
"""
Decodes a speech file
"""
try:
import pocketsphinx as ps
import sphinxbase
except:
print """Pocket sphinx and sphixbase is not installed
in your system. Please install it with package manager.
"""
speechRec = ps.Decoder(hmm = hmmd, lm = lmdir, dict = dictp)
wavFile = file(wavfile,'rb')
wavFile.seek(44)
speechRec.decode_raw(wavFile)
result = speechRec.get_hyp()
return result[0]
if __name__ == "__main__":
hmdir = "/usr/share/pocketsphinx/model/hmm/en_US/"
lmd = "/usr/share/pocketsphinx/model/lm/en_US/hub4.5000.DMP"
dictd = "/usr/share/pocketsphinx/model/lm/en_US/cmu07a.dic"
wavfile = sys.argv[1]
recognised = decodeSpeech(hmdir,lmd,dictd,wavfile)
print "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"
print recognised
print "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"
and when I run it I get the following error message:
Traceback (most recent call last):
File "hello.py", line 30, in <module>
recognised = decodeSpeech(hmdir,lmd,dictd,wavfile)
File "hello.py", line 17, in decodeSpeech
speechRec = ps.Decoder(hmm = hmmd, lm = lmdir, dict = dictp)
TypeError: __init__() got an unexpected keyword argument 'hmm'
Could you help me?
Looking at the pocketsphinx code on GitHub, in decoder_test.py we have an example of how to pass options to Decoder.
So it looks like your tutorial is for an old version and you actually want:
config = ps.Decoder.default_config()
config.set_string('-hmm', hmmd)
config.set_string('-lm', lmdir)
config.set_string('-dict', dictp)
speechRec = ps.Decoder(config)

Categories

Resources