Setting an array element with a sequence python - python

import math
import pylab
from matplotlib.pylab import *
import numpy as np
import scipy.fftpack
from scipy.io.wavfile import read
w = read('c:/users/ggg.wav')
a=np.array(w[1])
l=len(a)
#from __future__ import division
#b=(l/w[0])
b=(float(l)/w[0])
c=b*1000
d=int(c/40)
print d
print l/d
e=l/d
for i in range(0,d):
k[9]=np.array(a[(i*e)+1:((i+1)*e)])
print k
this is a python code to frame an audio signal. But when i executed this code,i got an error "ValueError: setting an array element with a sequence.". How can i avoid this error?

There is another problem with your code I can at least help you with:
You can't assign k[9] without k being undefined. E.g:
>>> k[9] = 'test'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'k' is not defined
'k' needs to be defined as an array and needs to get the 'proper' index. You can't assign the index on it straight after.
See the following examples:
>>> k[9]='test'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
and
>>> k = [None]*10
>>> k[9]='test'
>>> k
[None, None, None, None, None, None, None, None, None, 'test']

This works fine with a sample .wav
w = read('ggg.wav')
a = w[1] # already an array
l=len(a)
b=(float(l)/w[0])
c=b*1000
d=int(c/40)
e=l/d
k = a[:e*d].reshape(d,e)
print k.shape
print k
print ''
k = [[] for i in range(d)] # initialize python list
for i in range(0,d):
k[i] = a[(i*e)+1:((i+1)*e)]
for i in k:
print i
# or
k = np.zeros((d,e-1),dtype='int') # initialize np.array
for i in range(d):
k[i,:] = a[(i*e)+1:((i+1)*e)]
print k
w[1] is already an np.array. I think what you want to break a into blocks e long. To do that, I truncated a and reshaped it, producing my k. Your indexing misses a[0], a[e], etc.

Related

ValueError: The truth value of an array

I work on a Python 3.11 program and I have this error:
Traceback (most recent call last):
File "\Égalisation\Python Version\Wiener Filter\main.py", line 14, in <module>
symb = [random.choice(A) for _ in range(nbsymb)]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "\Égalisation\Python Version\Wiener Filter\main.py", line 14, in <listcomp>
symb = [random.choice(A) for _ in range(nbsymb)]
^^^^^^^^^^^^^^^^
File "\Programs\Python\Python311\Lib\random.py", line 369, in choice
if not seq:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
When I run this simple code:
import numpy as np
import random
nbsymb = 8
M = 16
A = np.arange(-np.sqrt(M)+1, np.sqrt(M), 2)
symb = [random.choice(A) for _ in range(8)]
Sounds like this is due to a regression in Python 3.11 which was later fixed. Upgrade to Python >=3.11.2
Numpy has its own random stuff, perhaps you should use that instead: https://numpy.org/doc/stable/reference/random/
If for some reason you can't upgrade, choose random elements from a list instead of a numpy array:
A = list(np.arange(-np.sqrt(M)+1, np.sqrt(M), 2))
symb = [random.choice(A) for _ in range(nbsymb)]

Fix a method to convert list of integers to NumPy matrix

I want to create random integers and convert them in binary format via NumPy matrix. I wrote the following code:
def toBinary(C):
l = []
for x in C:
b = [int(i) for i in bin(x)[2:]]
l = np.vstack((l, np.array(b)))
return l
list_vectors = [random.randint(0, 2 ** 64) for _ in range(2)]
print(toBinary(list_vectors))
But I still don't know how to solve this error:
Traceback (most recent call last):
File "test.py", line 31, in <module>
print(toBinary(list_vectors))
File "test.py", line 27, in toBinary
l = np.vstack((l, np.array(b)))
File "/anaconda3/lib/python3.6/site-packages/numpy/core/shape_base.py", line 234, in vstack
return _nx.concatenate([atleast_2d(_m) for _m in tup], 0)
ValueError: all the input array dimensions except for the concatenation axis must match exactly
Any suggestion is highly appreciated.
The issue here is that the conversion to binary does not always return a binary number of same length.
If the first integer in C is, let's say 3, it'll give '0b11'. Stack this in the array, then try to convert 17. Oops, you're trying to concatenate '11' and '1001' together, it won't work.
What I did here then, is forcing the converted binary number length to 10 using the format() function (Convert to binary and keep leading zeros in Python).
import numpy as np
import numpy.random as random
def toBinary(C):
binaries_length = 10
bin_format = f'#0{binaries_length+2}b'
array_rows = len(C)
l = np.empty((array_rows, binaries_length))
for i, x in enumerate(C):
l[i,:] = np.array([int(i) for i in format(x, bin_format)[2:]])
return l
list_vectors = [random.randint(0, 2 * 64) for _ in range(10)]
print(toBinary(list_vectors))
Also, the returned array is pre-allocated, since you now perfectly know what size it will be :
binaries_length = 10
bin_format = f'#0{10+2}b'
array_rows = len(C)
l = np.empty((array_rows, binaries_length))
By the way, the call random.randint(0, 2 ** 64) also triggers an exception because 2 ** 64 is insanely too high so I changed it to 2*64 here.
To go further, you can find the optimal binary length by finding the maximum of C.
Try this, it will return a list instead of array, so make the necessary adjustments if you like:
def toBinary(C):
l = []
for x in C:
b = [i for i in bin(x)[2:]]
a="".join(b)
a=int(a)
l.append(a)
return l

Datatype definition - TypeError

import cmath
import math
import random
import time
P = []
V = []
Vin = []
def Compute_wn_win(n,V,Vin):
for i in range (0,n):
V.append(complex(math.cos(2*math.pi*i/n),math.sin(2*math.pi*i/n)))
Vin.append(1/(complex(math.cos(2*math.pi*i/n),math.sin(2*math.pi*i/n))))
Compute_wn_win(8,V,Vin)
for i in range(0,8):
random_number = random.uniform(-1.0,1.0)
P.append(random_number)
def FFT(P,V,n):
if(n==1):
return P[0]
else:
Peven = []
Podd = []
for i in range(0,n/2):
Peven.append(P[2*i])
Podd.append(P[(2*i)+1])
Vsquared = []
for i in range(0,n/2):
Vsquared.append(V[i]*V[i])
Sole = FFT(Peven,Vsquared,n/2)
Solo = FFT(Podd,Vsquared,n/2)
Sol = [0 for x in range(0,n)]
for i in range(0,n/2):
Sol[i] = Sole[i]+V[i]*Solo[i]
Sol[i+n/2] = Sole[i]-V[i]*Solo[i]
return Sol
Sol = FFT(P,V,8)
I am new to Python. I have the following code. However I get the following error for lines Sole = FFT(Peven,Vsquared,n/2) and Sol[i] = Sole[i]+V[i]*Solo[i]. However, I have defined, Sole, Solo and Sol as list data type so I don't understand why it mentions that float datatype does not have an attribute getitem
Exact Error is
Traceback (most recent call last):
File "/Users/globetrekker/Documents/CS5050/Assignment7/Test_py.py", line 40, in <module>
Sol = FFT(P,V,8)
File "/Users/globetrekker/Documents/CS5050/Assignment7/Test_py.py", line 33, in FFT
Sole = FFT(Peven,Vsquared,n//2)
File "/Users/globetrekker/Documents/CS5050/Assignment7/Test_py.py", line 33, in FFT
Sole = FFT(Peven,Vsquared,n//2)
File "/Users/globetrekker/Documents/CS5050/Assignment7/Test_py.py", line 37, in FFT
Sol[i] = Sole[i]+V[i]*Solo[i]
TypeError: 'float' object has no attribute '__getitem__'
Sole and Solo are the return values from recursive calls to FFT(), but FFT()'s base case (when n == 1) returns a float, not a list, so the step above the base case will fail by trying to index a float. Presumably, you want to change return P[0] in the base case to return [P[0]].
This is introducing a float:
for i in range(0,n/2):
Checkout: I keep getting this error for my simple python program: "TypeError: 'float' object cannot be interpreted as an integer"

IndexError: tuple index out of range, error when trying to integrate the fucntion

I am trying to calculate a value of function f_integ, which is a result of integration of function f from 0 to x_v.
f = lambda x : x + 1
def f_integ(x_array):
int_result = np.zeros_like(x_array)
indexes = np.shape(x_array)[0]
for ind in range(indexes):
x_v = x_array[ind]
int_result[ind] = integ.quad(f, 0.0, x_v)[0]
return int_result
C = f_integ(1)
print "C", C
When I run this, I get the following error:
Traceback (most recent call last):
File "untitled.py", line 117, in <module>
C = f_integ(1)
File "scr1.py", line 110, in f_integ
indexes = np.shape(x_array)[0]
IndexError: tuple index out of range
I know that quad() returns a tuple, but I can not figure out how to put a number as an argument in the result of integration. I'm new to Python, please help.
Call the function like this:
C = f_integ(np.array([1]))
print "C", C
Currently you are passing a number to f_integ(), not an array. When it encounters np.shape(x_array)[0], the shape of a number is just (), so it cannot return anything at index 0 for an empty tuple.

Searching for floats in web-page, then creating a graph using these floats

the errorI'm trying to write a code which will scan a web-page, find needed data, pack it as a list of floats and depict a graph using these floats. Consider the following code:
import matplotlib.pyplot as pyplot
from urllib.request import *
import re
import struct
x = []
temp = []
y = []
data = urlopen('http://www.banki.ru/products/currency/usd/').read()
temp = re.findall(b'<td>(\d\d,\d+)</td>', data) #searching for specific floats. Without 'b'' I get error.
del temp[-1] #deleting the last element b/c it is invalid for my task
for num in range(0,len(y)): #data for Y-axis
x.append(num)
for i in temp: #Trying to 'unpack' byte-objects into dloats and then use them to create a graph
num = struct.unpack('f',i)
y.append(float(num[0]))
pyplot.plot(y,x)
pyplot.show()
And I get the following error:
Traceback (most recent call last):
File "C:/Users/*/PycharmProjects/untitled/test.py", line 19, in <module>
num = struct.unpack('f',i)
struct.error: unpack requires a bytes object of length 4
I understand the error. The questions is, how to transform a list with byte-objects to floats?
---------------UPDATE---------------------
got this done.
import matplotlib.pyplot as pyplot
from urllib.request import *
import re
import struct
x = []
temp = []
y = []
data = urlopen('http://www.banki.ru/products/currency/usd/').read()
temp = re.findall(b'<td>(\d\d,\d+)</td>', data)
del temp[-1]
for item in range(len(temp)):
tm = temp[item].decode('utf8')
tmn = tm.replace(',','.')
y.append(float(tmn))
for num in range(0,len(y)):
x.append(num)
pyplot.plot(x,y)
pyplot.show()

Categories