I am trying to execute the following code but it is giving me an error
File "/home/utente/Desktop/python/untitled3.py", line 29, in <module>
bits = randn(Nbits,1) > 0
TypeError: 'module' object is not callable
import numpy as np
#import pandas as pd
import matplotlib.pyplot as plt
#import matplotlib.lines as lines
import random as randn
from numpy import r_
from numpy import sin
from numpy import pi
fs = 44100 # sampling rate
baud = 300 # symbol rate
Nbits = 10 # number of bits
Ns = fs/baud
N = Nbits * Ns
f0 = 1800
# bits = randn(Nbits,1) > 0
np.random.seed(seed=1)
bits = randn(Nbits,1) > 0
M = np.tile(bits,(1,Ns))
t = r_[0.0:N]/fs
OOK = M.ravel()*sin(2*pi*f0*t)
fig = plt.figure(figsize = (16,4))
plt(t,OOK)
If you are trying to call the randn method, it is part of the random module.
Since you imported the random module as randn, the call should be randn.randn(Nbits, 1).
I would suggest usind randn directly from the numpy module, as np.random.randn(Nbits, 1)
Let's read the error. 'module' object is not callable in the code bits = randn(Nbits,1) > 0.
There is only one function call there, which is randn(). However, you imported it as import random as randn. This only gives an alias to the module 'random'. What you need to do is use a function from the module, like random.randint() (after importing the module 'random', without an alias).
From your code, I assume you are looking for numpy.random.randn. In that case, add this line to your import statements.
from numpy.random import randn
You're creating a namespace collision by importing the random module as randn which is the method you wish to call from that module. So you need to remove that assignment and reference the np.random.randn module explicitly (or add a from np.random import randn).
import numpy as np
#import pandas as pd
import matplotlib.pyplot as plt
#import matplotlib.lines as lines
import random as randn <- REMOVE THIS LINE
from numpy import r_
from numpy import sin
from numpy import pi
fs = 44100 # sampling rate
baud = 300 # symbol rate
Nbits = 10 # number of bits
Ns = fs/baud
N = Nbits * Ns
f0 = 1800
# bits = randn(Nbits,1) > 0
np.random.seed(seed=1)
bits = randn(Nbits,1) > 0 <- CHANGE THIS TO bits = np.random.randn(Nbits,1) > 0
M = np.tile(bits,(1,Ns))
t = r_[0.0:N]/fs
OOK = M.ravel()*sin(2*pi*f0*t)
fig = plt.figure(figsize = (16,4))
plt(t,OOK)
Related
I want to change the color of the line but I have no idea how I should code.
import numpy as np
from sympy import *
import sympy as sp
t=sp.symbols('t')
y=sp.Function('y')
overdamped = Eq(10*y(t).diff(t,2)+100*y(t).diff(t,1)+90*y(t),0)
psol1=dsolve(overdamped,ics={y(0):0.16, y(t).diff(t).subs(t,0):0})
underdamped = Eq(10*y(t).diff(t,2)+10*y(t).diff(t,1)+90*y(t),0)
psol3=dsolve(underdamped,ics={y(0):0.16, y(t).diff(t).subs(t,0):0})
plot(psol1.rhs, psol3.rhs, (t,0,10))
This is the work I've done. The plot works well but I want the two lines to be in differnt colors. I'll be very thankful if you help me out.
import numpy as np
from sympy import *
import sympy as sp
t=sp.symbols('t')
y=sp.Function('y')
overdamped = Eq(10*y(t).diff(t,2)+100*y(t).diff(t,1)+90*y(t),0)
psol1=dsolve(overdamped,ics={y(0):0.16, y(t).diff(t).subs(t,0):0})
underdamped = Eq(10*y(t).diff(t,2)+10*y(t).diff(t,1)+90*y(t),0)
psol3=dsolve(underdamped,ics={y(0):0.16, y(t).diff(t).subs(t,0):0})
p = plot(psol1.rhs, psol3.rhs, (t,0,10))
p[0].line_color = 'g'
p[1].line_color = 'r'
p.show()
I have:
import librosa
from scipy import signal
import scipy.io.wavfile as sf
samples, sample_rate = sf.read(args.file)
nperseg = int(sample_rate * 0.001 * 20)
frequencies, times, spectrogram = signal.spectrogram(samples,
sample_rate,
nperseg=nperseg,
window=signal.hann(nperseg))
audio_signal = librosa.griffinlim(spectrogram)
print(audio_signal, audio_signal.shape)
sf.write('test.wav', audio_signal, sample_rate)
However, this produces a (near) empty sound file.
As #DrSpill mentioned, scipy.io.wav.read and scipy.io.wav.write orders were wrong and also the import from librosa was not correct. This should do it:
import librosa
import numpy as np
import scipy.signal
import scipy.io.wavfile
# read file
file = "temp/processed_file.wav"
fs, sig = scipy.io.wavfile.read(file)
nperseg = int(fs * 0.001 * 20)
# process
frequencies, times, spectrogram = scipy.signal.spectrogram(sig,
fs,
nperseg=nperseg,
window=scipy.signal.hann(nperseg))
audio_signal = librosa.core.spectrum.griffinlim(spectrogram)
print(audio_signal, audio_signal.shape)
# write output
scipy.io.wavfile.write('test.wav', fs, np.array(audio_signal, dtype=np.int16))
Remark:
The resulting file had an accelerated tempo when I heard it, I think this is due to your processing but with some tweaking it should work.
A good alternative, would be to only use librosa, like this:
import librosa
import numpy as np
# read file
file = "temp/processed_file.wav"
sig, fs = librosa.core.load(file, sr=8000)
# process
abs_spectrogram = np.abs(librosa.core.spectrum.stft(sig))
audio_signal = librosa.core.spectrum.griffinlim(abs_spectrogram)
print(audio_signal, audio_signal.shape)
# write output
librosa.output.write_wav('test2.wav', audio_signal, fs)
librosa.output was removed. It is no longer providing its deprecated output module. Instead try soundfile.write:
import numpy as np
import soundfile as sf
sf.write('stereo_file.wav', np.random.randn(10, 2), 44100, 'PCM_24')
#Per your code you could try:
sf.write('test.wav', audio_signal, sample_rate, 'PCM_24')
I am trying to plot a graph using matplotlib.pyplot in Python but getting an error:
int() argument must be a string, a bytes-like object or a number, not
'list'
in the second-to-last line.
Here is the code:
import numpy as np
import random
import matplotlib.pyplot as plt
#constants
mUn0 = 1350
Vcat = 18000000
n = 2 * pow(10,16)
e = 1.6 * pow(10,-19)
#variable
E = 1000
d = []
f = []
for i in range(1,E):
j = log(n*e*mUn0) + log(i) - 0.5 * log(1+pow((mUn0*i/Vcat),2))
f.append(j)
d.append(log(i))
plt.xlabel('E')
plt.ylabel('V')
plt.subplot(2,1,2)
plt.subplot(f,d,'bo')
plt.show()
Thank you
pyplot.subplot() requires subplot(nrows, ncols, plot_number), all three options are integers.
Matplotlib is trying to cast your f and d lists to integer type and failing.
Just a couple of small issues. You have to use plt.plot() to plot, and you can't just use log, you need np.log() or to import the math module and then use math.log(). I noted the lines I changed with #FIXED
import numpy as np
import random
import matplotlib.pyplot as plt
#constants
mUn0 = 1350
Vcat = 18000000
n = 2 * pow(10,16)
e = 1.6 * pow(10,-19)
#variable
E = 1000
d = []
f = []
for i in range(1,E):
j = np.log(n*e*mUn0) + np.log(i) - 0.5 * np.log(1+pow((mUn0*i/Vcat),2)) #FIXED
f.append(j)
d.append(np.log(i)) #FIXED
plt.xlabel('E')
plt.ylabel('V')
plt.subplot(2,1,2) #not needed, but maybe a holdover from full code
plt.plot(f,d,'bo') #FIXED
plt.show()
That takes care of the syntax errors. Using a subplot works with one plot but you don't need it, so I don't know what type of logic error that is (do you want two plots?)
I want to draw a function which has periodic condition.
My code is as following.
import numpy as np
import matplotlib.pyplot as plt
from numpy import *
import itertools
from itertools import *
r = np.linspace(-1, 1, 1000)
f(r) = np.exp(-pow(r,2)/5)
In this situation, the period of f(r) equals 2. I want to plot (r,f(r)) in the range -inf < r < 1.
With using itertools.repeat, how can I plot that figure?
f(r) = np.exp(-pow(r,2)/5) isn't valid python. Just try print np.exp(-pow(r, 2)/5). Or def f(r): return np.exp(-pow(r, 2)/5)
from numpy import * does nothing for below it.
from itertools import * does nothing below for below it.
Imports are in the form of:
import blah
blah.blah_function()
or
from blah import blah_function
blah_function()
or (don't do this... ever... please)
from blah import *
blah_function()
also
float('inf'), -float('inf'), and float('-inf') are all valid in python.
When I call random.sample(arr,length) an error returns random_sample() takes at most 1 positional argument (2 given).I've tried importing numpy under a different name, which doesn't fix the problem.Any thoughts? Thanks
import numpy.random
import random
import numpy as np
from numpy import *
points = [[1,1],[1.5,2],[3,4],[5,7],[3.5,5],[4.5,5], [3.5,4]]
def cluster(X,center):
clusters = {}
for x in X:
z= min([(i[0], np.linalg.norm(x-center[i[0]])) for i in enumerate(center)], key=lambda t:t[1])
try:
clusters[z].append(x)
except KeyError:
clusters[z]=[x]
return clusters
def update(oldcenter,clusters):
d=[]
r=[]
newcenter=[]
for k in clusters:
if k[0]==0:
d.append(clusters[(k[0],k[1])])
else:
r.append(clusters[(k[0],k[1])])
c=np.mean(d, axis=0)
u=np.mean(r,axis=0)
newcenter.append(c)
newcenter.append(u)
return newcenter
def shouldStop(oldcenter,center, iterations):
MAX_ITERATIONS=0
if iterations > MAX_ITERATIONS: return True
u=np.array_equal(center,oldcenter)
return u
def init_board(N):
X = np.array([(random.uniform(1,4), random.uniform(1, 4)) for i in range(4)])
return X
def kmeans(X,k):
clusters={}
iterations = 0
oldcenter=([[],[]])
center = random.sample(X,k)
while not shouldStop(oldcenter, center, iterations):
# Save old centroids for convergence test. Book keeping.
oldcenter=center
iterations += 1
clusters=cluster(X,center)
center=update(oldcenter,clusters)
return (center,clusters)
X=init_board(4)
(center,clusters)=kmeans(X,2)
print "center:",center
#print "clusters:", clusters
When you use from numpy import * you import all items that are in the numpy namespace into your scripts namespace. When you do this any functions/variables/etc that have the same name will be overwritten by the items from the numpy namespace.
numpy has a subpackage called numpy.random which then overwrote your random import as the code below shows:
import random
# Here random is the Python stdlib random package.
from numpy import *
# As numpy has a random package, numpy.random,
# random is now the numpy.random package as it has been overwritten.
In this case you should instead use import numpy as np which will allow you to access both:
import random
# random now contains the stdlib random package
import numpy as np
# np.random now contains the numpy.random package
Your points is List type, so you should convert it to an array
points = np.asarray(point)
Also, you should use import random