I am trying to add an isdigit() to the program so that I can verify what the user enters is valid. This is what I have so far. But when I run it an enter a character, say "f". It crashes and gives me the error which will be posted below the code. Any ideas?
def mirrorHorizontal(source):
userMirrorPoint = requestString("Enter a mirror point from 0 to halfway through the pitcure.") #asks user for an input
while (int(userMirrorPoint) < 0 or int(userMirrorPoint) > (int(getHeight(source) - 1)//2)) or not(userMirrorPoint.isdigit()):
userMirrorPoint = requestString("Enter a mirror point from 0 to halfway through the pitcure.")
height = getHeight(source)
mirrorPoint = int(userMirrorPoint)
for x in range(0, getWidth(source)):
for y in range(0, mirrorPoint):
topPixel = getPixel(source, x, y)
bottomPixel = getPixel(source, x, height-y-1)
color = getColor(topPixel)
setColor(bottomPixel, color)
The error was: f
Inappropriate argument value (of correct type).
An error occurred attempting to pass an argument to a function.
Please check line 182 of /Volumes/FLASHDRIVE2/College/Spring 16'/Programs - CPS 201/PA5Sikorski.py
isdigit() itself behaves itself in the 2.7.0 jython version I have locally
>>> '1'.isdigit()
True
>>> ''.isdigit()
False
>>> 'A'.isdigit()
False
>>> 'A2'.isdigit()
False
>>> '2'.isdigit()
True
>>> '22321'.isdigit()
True
Try breaking your big expression up, as typecasting to integers will throw errors for non-numeric strings. This is true across Python versions.
>>> int('b')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'b'
>>> int('2')
2
You probably want to be careful about the order of the parts of that long expression (this or that or ...). Breaking it up would also make it more readable.
Related
I am trying to do feature selection using feature forward method.
Tried previously answered questions but didn't get any proper solution. My code is as follows:
def forward_selection_rf(data, target, number_of_features=14):
# adapt number of features to select: if requested number
# is greater than features availabe, go for 75% of the
# features instead
if number_of_features > len(data.columns):
print("SFS: Wanted " + str(number_of_features) + " from " + str(len(data.columns)) + " featurs. Sanifying to 75%")
number_of_features = 0.75
# Sequential Forward Selection(sfs)
sfs1 = sfs(RandomForestClassifier(
n_estimators=70,
criterion='gini',
max_depth=15,
min_samples_split=2,
min_samples_leaf=1,
min_weight_fraction_leaf=0.0,
max_features='auto',
max_leaf_nodes=None,
min_impurity_decrease=0.0,
min_impurity_split=None,
bootstrap=True,
oob_score=False,
n_jobs=-1,
random_state=0,
verbose=0,
warm_start=False,
class_weight='balanced'
),
n_features_to_select=14,
direction='forward',
scoring = 'roc_auc',
cv = 5,
n_jobs = 3)
sfs1.fit(data, target)
return sfs1
compiler gives runtime error as follows:
forward_selection_rf(X, y, number_of_features=14)
Traceback (most recent call last):
File "C:\Users\drash\AppData\Local\Temp\ipykernel_37980\1091017691.py", line 1, in <module>
forward_selection_rf(X, y, number_of_features=14)
File "C:\Users\drash\OneDrive\Desktop\Howto Health\untitled3.py", line 102, in forward_selection_rf
TypeError: __init__() got an unexpected keyword argument 'n_features_to_select'
I'm still not very familiar with numba and my problem is that I have the piece of code bellow that I use for randomize the edges of graphs.
This code is simply used to swap some edges in a connectivity matrix given the number of desired swaps and a seed for the random number generator.
My problem is that when I try to use it with numba to speed it up I did not menage to run it. The error it returns is also pasted bellow.
#nb.jit(nopython=True)
def _randomize_adjacency_wei(A, n_swaps, seed):
np.random.seed(seed)
# Number of nodes
n_nodes = A.shape[0]
# Copy the adj. matrix
Arnd = A.copy()
# Choose edges that will be swaped
edges = np.random.choice(n_nodes, size=(4, n_swaps), replace=True).T
#itr = range(n_swaps)
#for it in tqdm(itr) if verbose else itr:
it = 0
for it in range(n_swaps):
i,j,k,l = edges[it,:]
if len(np.unique([i,j,k,l]))<4:
continue
else:
# Old values of weigths
w_ij,w_il,w_kj,w_kl=Arnd[i,j],Arnd[i,l],Arnd[k,j],Arnd[k,l]
# Swaping edges
Arnd[i,j]=Arnd[j,i]=w_il
Arnd[k,l]=Arnd[l,k]=w_kj
Arnd[i,l]=Arnd[l,i]=w_ij
Arnd[k,j]=Arnd[j,k]=w_kl
return Arnd
TypingError: Failed in nopython mode pipeline (step: nopython frontend)
No implementation of function Function(<function unique at 0x7f1a1c03b0d0>) found for signature:
>>> unique(list(int64)<iv=None>)
There are 2 candidate implementations:
- Of which 2 did not match due to:
Overload in function 'np_unique': File: numba/np/arrayobj.py: Line 1915.
With argument(s): '(list(int64)<iv=None>)':
Rejected as the implementation raised a specific error:
TypingError: Failed in nopython mode pipeline (step: nopython frontend)
Unknown attribute 'ravel' of type list(int64)<iv=None>
File "../../../home/vinicius/anaconda3/lib/python3.8/site-packages/numba/np/arrayobj.py", line 1918:
def np_unique_impl(a):
b = np.sort(a.ravel())
^
During: typing of get attribute at /home/vinicius/anaconda3/lib/python3.8/site-packages/numba/np/arrayobj.py (1918)
File "../../../home/vinicius/anaconda3/lib/python3.8/site-packages/numba/np/arrayobj.py", line 1918:
def np_unique_impl(a):
b = np.sort(a.ravel())
^
raised from /home/vinicius/anaconda3/lib/python3.8/site-packages/numba/core/typeinfer.py:1071
During: resolving callee type: Function(<function unique at 0x7f1a1c03b0d0>)
During: typing of call at <ipython-input-165-90ffd30fe0e8> (19)
File "<ipython-input-165-90ffd30fe0e8>", line 19:
def _randomize_adjacency_wei(A, n_swaps, seed):
<source elided>
i,j,k,l = edges[it,:]
if len(np.unique([i,j,k,l]))<4:
^
Thanks in advance,
Vinicius
According to the comments, you are passing a list to np.unique() but this is not supported by Numba.
Modifying the code this way:
i, j, k, l = e = edges[it, :]
if len(np.unique(e)) < 4:
...
The following example doesn't produce any errors:
>>> A = np.random.randint(0, 5, (8,8))
>>> r = _randomize_adjacency_wei(A, 4, 33)
I have question about the data type of the result returned by Sympy Poly.all_coeffs(). I have started to use Sympy just recently.
My Sympy transfer function is following:
Then I run this code:
n,d = fraction(Gs)
num = Poly(n,s)
den = Poly(d,s)
num_c = num.all_coeffs()
den_c = den.all_coeffs()
I get:
Then I run this code:
from scipy import signal
#nu = [5000000.0]
#de = [4.99, 509000.0]
nu = num_c
de = den_c
sys = signal.lti(nu, de)
w,mag,phase = signal.bode(sys)
plt.plot(w/(2*np.pi), mag)
and the result is:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-131-fb960684259c> in <module>
4 nu = num_c
5 de = den_c
----> 6 sys = signal.lti(nu, de)
But if I use those commented line 'nu' and 'de' straight python lists instead, the program works. So what is wrong here?
Why did you just show a bit the error? Why not the full message, maybe even the full traceback!
In [60]: sys = signal.lti(num_c, den_c)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-60-21f71ecd8884> in <module>
----> 1 sys = signal.lti(num_c, den_c)
/usr/local/lib/python3.6/dist-packages/scipy/signal/ltisys.py in __init__(self, *system, **kwargs)
590 self._den = None
591
--> 592 self.num, self.den = normalize(*system)
593
594 def __repr__(self):
/usr/local/lib/python3.6/dist-packages/scipy/signal/filter_design.py in normalize(b, a)
1609 leading_zeros = 0
1610 for col in num.T:
-> 1611 if np.allclose(col, 0, atol=1e-14):
1612 leading_zeros += 1
1613 else:
<__array_function__ internals> in allclose(*args, **kwargs)
/usr/local/lib/python3.6/dist-packages/numpy/core/numeric.py in allclose(a, b, rtol, atol, equal_nan)
2169
2170 """
-> 2171 res = all(isclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan))
2172 return bool(res)
2173
<__array_function__ internals> in isclose(*args, **kwargs)
/usr/local/lib/python3.6/dist-packages/numpy/core/numeric.py in isclose(a, b, rtol, atol, equal_nan)
2267 y = array(y, dtype=dt, copy=False, subok=True)
2268
-> 2269 xfin = isfinite(x)
2270 yfin = isfinite(y)
2271 if all(xfin) and all(yfin):
TypeError: ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
Now look at the elements of the num_c list (same for den_c):
In [55]: num_c[0]
Out[55]: 500000.000000000
In [56]: type(_)
Out[56]: sympy.core.numbers.Float
The scipy code is doing numpy testing on the inputs. So it's first turned the lists into arrays:
In [61]: np.array(num_c)
Out[61]: array([500000.000000000], dtype=object)
This array contains sympy object(s). It can't cast that to numpy float with 'safe'. But an explicit astype uses unsafe as the default:
In [63]: np.array(num_c).astype(float)
Out[63]: array([500000.])
So lets convert both lists into valid numpy float arrays:
In [64]: sys = signal.lti(np.array(num_c).astype(float), np.array(den_c).astype(float))
In [65]: sys
Out[65]:
TransferFunctionContinuous(
array([100200.4008016]),
array([1.00000000e+00, 1.02004008e+05]),
dt: None
)
Conversion in a list comprehension also works:
sys = signal.lti([float(i) for i in num_c],[float(i) for i in den_c])
You likely need to conver sympy objects to floats / lists of floats.
I would like to know the right way to read float fields using Quickfix (python). I was getting a string then casting to float.
For instance:
>>> m = fix.Message()
>>> m.setField(fix.BidPx(1.12))
>>> m.getField(fix.BidPx()).getString()
'1.12'
>>> float(m.getField(fix.BidPx()).getString())
1.12
The way above works fine for floats with less then 15 digits of precision. But I got the following error for float numbers with more the 15 digits of precision:
>>> m = fix.Message()
>>> m.setField(fix.BidPx(1.123456789123456))
>>> m.getField(fix.BidPx()).getString()
'\x00\xe1}\xf5\x82U\x00\x0078912346'
>>> float(m.getField(fix.BidPx()).getString())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float:
I am not sure if that sample works, may be you should explain how you import "fix".
Any way, this sample works with python 3.7 and quickfix 1.15.1
>>> import quickfix as fix
>>> m = fix.Message()
>>> m.setField(fix.BidPx(1.123456789123456789123456789))
>>> m.getField(fix.BidPx().getField())
'1.12345678912346'
>>>
if you need more precision in the float number, you can do
>>> m.setField(fix.StringField(fix.BidPx().getField(),"1.123456789123456789123456789"))
>>> m.getField(fix.BidPx().getField())
'1.123456789123456789123456789'
>>>
I hope I've helped
When I use sympy to get the square root of 8, the output is ugly:
2*2**(1/2)
import sympy
In [2]: sympy.sqrt(8)
Out[2]: 2*2**(1/2)
Is there any way to make sympy print output in proper mathematical notation (i.e. using the proper symbol for square root) ?
UPDATE:
when I follow the suggestions from #pqnet:
from sympy import *
x, y, z = symbols('x y z')
init_printing()
init_session()
I get following error:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-23-21d886bf3e54> in <module>()
2 x, y, z = symbols('x y z')
3 init_printing()
----> 4 init_session()
/usr/lib/python2.7/dist-packages/sympy/interactive/session.pyc in init_session(ipython, pretty_print, order, use_unicode, quiet, argv)
154 # and False means don't add the line to IPython's history.
155 ip.runsource = lambda src, symbol='exec': ip.run_cell(src, False)
--> 156 mainloop = ip.mainloop
157 else:
158 mainloop = ip.interact
AttributeError: 'ZMQInteractiveShell' object has no attribute 'mainloop'
In an ipython notebook you can enable Sympy's graphical math typesetting with the init_printing function:
import sympy
sympy.init_printing(use_latex='mathjax')
After that, sympy will intercept the output of each cell and format it using math fonts and symbols. Try:
sympy.sqrt(8)
See also:
Printing section in the Sympy Tutorial.
The simplest way to do it is this:
sympy.pprint(sympy.sqrt(8))
For me (using rxvt-unicode and ipython) it gives
___
2⋅╲╱ 2