Brickwall Frequency Splitter Python - python-3.x

Hey guys so I am trying to make a Brickwall Frequency Splitter in python 3.+, by this I mean that say I have an audio file, I want to split the audio file into 6 different bands, Sub, Lows, Low-Mids, Mids, High-Mids, Highs. However, I don't want to use a butter filter instead I want a filter that cuts any other frequencies below and above the desired range lets say I want from 200Hz to 400Hz I want a clean cut of them frequencies.
Thanks,
elliott
Currently my code looks like this I have a filter going on but it is like a sweep and doesn't really work for me:
import numpy as np
import sounddevice as sd
import os
import soundfile as sf
import matplotlib.pyplot as plt
sampling_rate = 44100
duration_in_seconds = 30
highpass = False
amplitude = 0.3
duration_in_samples = int(duration_in_seconds *
sampling_rate)
folder_number = 1
folder_number_str = str(folder_number)
folder_type = 'short/'
cut_type = '/30CUT/'
audio_file_dir = os.listdir('for_analysis/' + folder_type + folder_number_str + cut_type)[0]
audio_dir = 'for_analysis/' + folder_type + folder_number_str + cut_type
print(audio_dir)
print(audio_file_dir)
length = len(audio_dir)
file_format = audio_dir[length - 3:]
full_path = audio_dir + audio_file_dir
print(full_path)
data, fs = sf.read(full_path)
print(data.shape, fs)
plt.plot(data)
input_signal = data
cutoff_frequency = np.geomspace(50, 50, input_signal.shape[0])
allpass_output = np.zeros_like(input_signal)
dn_1 = 0
for n in range(input_signal.shape[0]):
break_frequency = cutoff_frequency[n]
tan = np.tan(np.pi * break_frequency / sampling_rate)
a1 = (tan - 1) / (tan + 1)
allpass_output[n] = a1 * input_signal[n] + dn_1
dn_1 = input_signal[n] - a1 * allpass_output[n]
if highpass:
allpass_output *= -1
filter_output = input_signal + allpass_output
filter_output *= 0.5
filter_output *= amplitude
sd.play(filter_output, sampling_rate)
sd.wait()
Unfortutantly, I have searched around the internet to be left with no result. If you have any documentation I could read to help me with this that would be great, or better any code you could show to aid.
Here is my desired result

Related

A more efficient way of comparing two images in a python

I have a task where i need to specify the upper left coordinate of the smaller image in the larger image.
I implemented this code, however it is too slow since I have a time limit of 20 seconds, and in some datasets I have 3000 images. How can this be implemented more effectively? I can use numpy, scipy and all packages from the standard python library.
import numpy as np
from PIL import Image
map_image_path = input()
map_image = Image.open(map_image_path)
map_ar = np.asarray(map_image)
map_ar_y, map_ar_x = map_ar.shape[:2]
i = int(input())
dimensions = input()
patches=list()
for k in range(i):
patch_image_path = input()
patches.append(Image.open(patch_image_path))
for j in range(i):
patch_ar = np.asarray(patches[j])
patch_ar_y, patch_ar_x = patch_ar.shape[:2]
stop_x = map_ar_x - patch_ar_x + 1
stop_y = map_ar_y - patch_ar_y + 1
for x in range(0, stop_x):
for y in range(0, stop_y):
x2 = x + patch_ar_x
y2 = y + patch_ar_y
picture = map_ar[y:y2, x:x2]
if np.array_equal(picture, patch_ar):
print(str(x) + "," + str(y))

Simaltaneous trignometric equation in python

My task is to simulate a 3 DOF robotic arm system in python. The aim is to trace out a 3D Gaussian surface. Input data is coordinates of the end effector gained using 3D Gaussian equation. The code is supposed to solve a system of the trigonometric equation to find out angles theta1, theta2 & theta3. I used "solve([eqn1,eqn2,eqn3],theta1,theta2,theta3)" to solve for the system of equation. Python is taking a too long time to respond.
I tried solving using fsolve, but the results were incomparable to the solution from MATLAB. Btw, I got a very good simulation in MATLAB using "solve".
I am using Python 3.7.3 through spyder under Anaconda 2019.03 environment in Windows 10.
Generating data set (Gaussian surface) : P matrix
a = 8
x0 = 0
y0 = 0
sigmax = 3
sigmay = 3
P_x = np.arange(7,-8,-1)
P_y = np.arange(7,-8,-1)
xx , yy = np.meshgrid(P_x,P_y)
s_x,s_y = np.subtract(xx,x0),np.subtract(yy,y0)
sq_x,sq_y = np.square(s_x),np.square(s_y)
X,Y = np.divide(sq_x,2*(sigmax**2)),np.divide(sq_y,2*(sigmay**2))
E = np.exp(-X-Y)
zz = np.multiply(E,a)
xx,yy,zz = xx.flatten(),yy.flatten(),zz.flatten()
P = np.vstack([yy,xx,zz]).T
import numpy as np
from sympy import *
from sympy import Symbol, solve, Eq
for j in range(len(P)):
theta1 = Symbol('theta1',real = True)
theta2 = Symbol('theta2',real = True)
theta3 = Symbol('theta3',real = True)
x,y,z = P[j,0],P[j,1],P[j,2]
eq1 = Eq(R1*cos(theta1) + R2*cos(theta1)*cos(theta2) +
R3*cos(theta1)*cos(theta3) - x)
eq2 = Eq(R1*sin(theta1) + R2*cos(theta2)*sin(theta1) +
R3*cos(theta3)*sin(theta1) - y)
eq3 = Eq(R2*sin(theta2) + R3*sin(theta3) -z )
solve([eq1,eq2,eq3],theta1,theta2,theta3)
solution[j,0] = degrees(theta1)
solution[j,1] = degrees(theta3)
solution[j,2] = degrees(theta2)
Expected result: Solution matrix with values of theta1, theta2 & theta3.
Python takes too much time to respond.

Errors when trying to solve large system of PDEs

I have a system of 18 linear (i'm assuming) PDEs. Howe ever they are very awkwardly shaped PDEs. Every time I try to use FiPy to solve the system of coupled PDEs I get an error. I have fixed most of them on my own but I can't seem to get past this one.
First you will need a list of equations that will be added later in the program:
import time
from fipy import Variable, FaceVariable, CellVariable, Grid1D, Grid2D, ExplicitDiffusionTerm, TransientTerm, DiffusionTerm, Viewer,PowerLawConvectionTerm, ImplicitSourceTerm
from fipy.tools import numerix
import math
import numpy as np
import sympy as sp
Temperature = 500.0 #Temperature in Celsius
Temp_K = Temperature + 273.15 #Temperature in Kelvin
Ea = [342,7,42,45,34] #Activation energy in order from the list excel/word file
#Frequency factor ko (Initial k)
k_0 =[5.9 * (10**15), 1.3 * (10**13), 1.0 * (10**12), 5.0 * (10**11), 1.2 * (10**13)]
fk1 = [math.exp((-1.0 * x)/(R*Temp_K)) for x in Ea] #Determines k value at given temperature value (exp(-Ea/R*T))
final_k = [fk1*k_0 for fk1,k_0 in zip(fk1,k_0)] #Multiplys by the inital k value to determine the k value at the given temperature (ko * exp(-Ea/R*T))
final_kcm = [x for x in final_k]
def rhs(eq):
eq_list = [-1.0*final_kcm[0]*EDC - final_kcm[1]*EDC*R1 - final_kcm[2]*EDC*R2 - final_kcm[3]*EDC*R4 - final_kcm[4]*EDC*R5 - final_kcm[5]*EDC*R6,
final_kcm[2]*EDC*R2 - final_kcm[8]*EC*R1 + final_kcm[13]*VCM*R2,
final_kcm[1]*EDC*R1 + final_kcm[6]*R2*R1 + final_kcm[7]*R1*R3 + final_kcm[8]*R1*EC + final_kcm[9]*R1*C11 + final_kcm[10]*R1*C112 + final_kcm[12]*R1*VCM + 2.0*final_kcm[20]*R1*C2H2,
2.0*final_kcm[20]*R2*C2H2,
final_kcm[15]*R5*VCM,
return eq_list[eq]
Here is the rest of the program I use to generate the system of PDEs.
EDC = CellVariable(mesh=mesh, hasOld=True, value=10)
EC = CellVariable(mesh=mesh, hasOld=True, value=0)
HCl = CellVariable(mesh=mesh, hasOld=True, value=0)
Coke = CellVariable(mesh=mesh, hasOld=True, value=0)
CP = CellVariable(mesh=mesh, hasOld=True, value=0)
EDC.constrain(10, mesh.facesLeft)
EC.constrain(0., mesh.facesLeft)
HCl.constrain(0., mesh.facesLeft)
Coke.constrain(0., mesh.facesLeft)
CP.constrain(0., mesh.facesLeft)
nsp =18
u_x = [[ [0,]*nsp for n in range(nsp) ]]
for z in range(nsp):
u_x[0][z][z] = 1.0
eq0 = TransientTerm(var = EDC) == PowerLawConvectionTerm(coeff = u_x, var = EDC) + ImplicitSourceTerm(rhs(0),var = EDC)
eq1 = TransientTerm(var = EC) == PowerLawConvectionTerm(coeff = u_x, var = EC) + ImplicitSourceTerm(rhs(1),var = (EC))
eq2 = TransientTerm(var = HCl) == PowerLawConvectionTerm(coeff = u_x, var = HCl) + ImplicitSourceTerm(rhs(2),var = (HCl))
eq3 = TransientTerm(var = Coke) == PowerLawConvectionTerm(coeff = u_x, var = Coke) + ImplicitSourceTerm(rhs(3),var = (Coke))
eq4 = TransientTerm(var = CP) == PowerLawConvectionTerm(coeff = u_x, var = CP) + ImplicitSourceTerm(rhs(4),var = (CP))
eqn = eq0 & eq1 & eq2 & eq3 & eq4
if __name__ == '__main__':
viewer = Viewer(vars = (EDC,EC,HCl,Coke,CP))
viewer.plot()
for t in range(1):
EDC.updateOld()
EC.updateOld()
HCl.updateOld()
Coke.updateOld()
CP.updateOld()
eqn.solve(dt=1.e-3)
Sorry for the long code but I can't really show it any other way. Anyway this is the error it returns :
File
"C:\Users\tjcze\Anaconda3\lib\site-packages\fipy\matrices\scipyMatrix.py",
line 218, in addAt
assert(len(id1) == len(id2) == len(vector))
AssertionError
What should I do to get this system to work correctly?
The error is because of whatever you're trying to do with u_x. u_x should be a rank-1 FaceVariable.
Its shape should be #dims x #faces (or #dims x 1); it should not be (#eqns x #eqns).
Setting u_x = [1.] gets rid of the AssertionError.
You will then get a series of warnings:
UserWarning: sweep() or solve() are likely to produce erroneous results when `var` does not contain floats.
Fix this by initializing all of your CellVariables with floats, e.g.,
EDC = CellVariable(mesh=mesh, hasOld=True, value=10.)
instead of
EDC = CellVariable(mesh=mesh, hasOld=True, value=10)
With those changes, the code runs. It doesn't do anything interesting, but that's hardly surprising, as it's way too complicated at this stage. 18 equations only obfuscates things. I strongly recommend you troubleshoot this problem with <= 2 equations.
At this point, your equations aren't coupled at all (eq0 only implicitly depends on EDC, eq1 only on EC, etc.). This isn't wrong, but not terribly useful. Certainly no point in the eq = eq0 & eq1 & ... syntax. EDC is the only variable with a chance of evolving, and it's constant, so it won't evolve, either.
In future, please provide examples that actually run (up to the point of the error, anyway).

Python / Spyder - Contourf() animation questions. Speed and Colorbar.

I am new to python and recently was able to generate a contourf animation. I know how to generate a colorbar, however I'm unsure as to how to implement a colorbar into the animation.
Also, is there a way to speed up the animation process?
My data is taken from an oscilloscope in a plane of measurement. Each location in the plane of measurement is stored as a file, where the file name is the location of measurement.
Below is my code.
from pylab import *
import matplotlib.animation as animation
# import pylab won't import animation
dr = 4;
dz = 4;
rStart = -72;
rEnd = 72;
zStart = -20;
zEnd = -236;
datatype = dtype('>d')
rspace = arange(rStart,rEnd+dr,dr)
zspace = arange(zStart,zEnd-dz,-dz)
tspace = 1000000 # number of samples
directory = 'D:\OscopeData\\'
data = zeros([len(zspace),len(rspace),tspace], dtype=datatype)
for j in range(0,len(zspace)):
for i in range(0,len(rspace)):
r = 'R' + str(rStart + dr(i))
z = 'Z' + str(zStart - dz(j))
datafile = directory + r + z + 'Ch1.dat'
data[j][i] = fromfile(datafile, dtype = datatype)
fig,ax = subplots()
textsize = 30
def animate(t):
ax.clear
ax.contourf(data[:,:,t],50)
title('Plot Title', fontsize = textsize + 6)
xlabel('R axis', fontsize = textsize)
ylabel('Z axis', fontsize = textsize)
anim = animation.FuncAnimation(fig, animate,50,blit=False)

Thermodynamic analysis using linear interpolation

I am trying to find the values of temperatures between 2250 K to 2300 K and have written a basic equation that uses linear interpolation to define the enthalpies between these temperatures. I am not exactly sure how to do this.
This is the equation:
T1_e = 868739/(0.9*h1_co2 + 0.1*h1_co + 2*h1_h2o + 0.05*h1_o2 + 7.52*h1_n2)
T2_e = 868739/(0.9*h2_co2 + 0.1*h2_co + 2*h2_h2o + 0.05*h2_o2 + 7.52*h2_n2)
The values of h1_co2, h1_co, h2_co2, h2_co and so forth are constants for the respective temperatures of K.
T1_e represents the temperature at 2250 K.
T2_e represents the temperature at 2300 K.
I imagine your answer would something like this
import numpy as np
import matplotlib.pyplot as plt
# define your constants
h1_co2 = 7
h1_co = 12
h2_co2 = 6
h2_co = .5
# etc...
def T1_e(h1_co2, h1_co, h1_h2o, h1_o2, h1_n2):
t1_e = 868739/(0.9*h1_co2 + 0.1*h1_co + 2*h1_h2o + 0.05*h1_o2 + 7.52*h1_n2)
return t1_e
def T2_e(h2_co2, h2_co, h2_h2o, h2_o2, h2_n2):
t2_e = 868739/(0.9*h2_co2 + 0.1*h2_co + 2*h2_h2o + 0.05*h2_o2 + 7.52*h2_n2)
return t2_e
temp = [2250, 2300]
e1 = T1_e(h1_co2, h1_co, h1_h2o, h1_o2, h1_n2)
e2 = T2_e(h2_co2, h2_co, h2_h2o, h2_o2, h2_n2)
e = [e1, e2]
p = np.polyfit(temp, e, 1)
x = np.linspace(2250, 2300, 100)
plt.plot(x, np.poly1d(x))
plt.show()

Resources