Python looping over fits datacube to fit spectra - python

I have a fits datacube in Python where I need to fit the spectra of each pixel in the cube. My code for fitting just one spectrum works great, but for some reason I can't figure out how to translate that into fitting each pixel (100 pixels total for a 10by10).
ngc2617 = fits.open('NGC2617.fits')[1]
cube2617 = SpectralCube.read(ngc2617)
data2617 = ngc2617.data
nz,ny,nx = np.shape(data2617)
obs_2617 = cube2617.spectral_axis
z_2617 = 0.014326 #simbad
rest_2617 = np.asarray(obs_2617 / (1+z_2617))
flux_2617 = data2617[:,172,142]
flux_2617[np.isnan(flux_2617)]=0
halpha_chans = np.asarray(np.where((rest_2617 > 6365) & (rest_2617 < 6715)))
halphawaves = np.asarray(rest_2617[halpha_chans]).T
halphaflux = np.asarray(flux_2617[halpha_chans]).T
cont_chans = np.asarray(np.where((rest_2617 > 5500) & (rest_2617 < 5510)))
cont_2617 = np.asarray(flux_2617[cont_chans]).T
x_halpha = halphawaves.flatten()
y_halpha = halphaflux.flatten()
c = 2.998 * 10**5 #km/s
plt.figure(figsize=[10,8])
plt.subplot(2,1,1)
plt.plot(x_halpha,y_halpha, '--', label = 'data')
def Gauss(x, A, x0, fwhm):
sigma = (fwhm * x0) / (2.355 * c)
return A * np.exp(-(x - x0) ** 2 / (2 * sigma ** 2))
def func(x, A0, A1, x0, fwhm, fwhm1, cont):
param1 = cont
param2 = Gauss(x, A0, x0 - 14.75, fwhm) + Gauss(x, A1, x0, fwhm) + Gauss(x, A0*3, x0 + 20.66, fwhm) + Gauss(x, A1, x0, fwhm1)
return param1 + param2
cont_init = np.average(cont_2617)
A0_init = np.max(y_halpha[0:150])-cont_init
A1_init = np.max(y_halpha)-cont_init
x0_init = x_halpha[np.where(y_halpha==np.max(y_halpha))][0]
fwhm_init = (x_halpha[np.where(y_halpha==np.max(y_halpha))][0] - x_halpha[np.where((np.min(abs(np.max(y_halpha)/2 - y_halpha))))][0])*2
fwhm1_init = (x_halpha[np.where(y_halpha==np.max(y_halpha))][0] - x_halpha[np.where((np.min(abs(np.max(y_halpha)/2 - y_halpha[0:150]))))][0])*2
parameters, covariance = curve_fit(func, x_halpha, y_halpha, p0=[A0_init, A1_init, x0_init, fwhm_init, fwhm1_init, cont_init])
fit_y = func(x_halpha, *parameters)
fit1_NII = Gauss(x_halpha, A0_init, parameters[2]-14.75, parameters[3]) + parameters[5]
fit2_NII = Gauss(x_halpha, A0_init, parameters[2]+20.66, parameters[3]) + parameters[5]
fit_Halph = Gauss(x_halpha, A1_init, parameters[2], parameters[3]) + parameters[5]
plt.plot(x_halpha, fit_y, '-', label='full fit')
plt.plot(x_halpha, fit1_NII, '-', label='NII 6549.86 fit')
plt.plot(x_halpha, fit2_NII, '-', label='NII 6585.27 fit')
plt.plot(x_halpha, fit_Halph, '-', label='H\u03B1 fit')
plt.title('NGC2617 H\u03B1 & NII Spectra of Central Point with Gaussian Fit', fontsize = 15)
plt.xlabel('wavelength [$\AA$]', fontsize = 12)
plt.ylabel(r'flux [10$^{-20}$ $erg * s^{-1}$ * $cm^{-2}$ * $\AA^{-1}$]', fontsize = 12)
plt.grid(True)
plt.legend()
plt.subplot(2,1,2)
plt.plot(np.linspace(0,0,6800), color = 'r', label = '0 point')
plt.scatter(x_halpha, y_halpha-fit_y, marker = 'o', label='residuals')
plt.xlim(halphawaves[0],halphawaves[-1])
plt.xlabel('wavelength [$\AA$]', fontsize = 12)
plt.ylabel('residuals', fontsize = 12)
plt.grid(True)
plt.legend()
plt.tight_layout()
plt.show()
this is my code for the single spectrum...can anyone help me create a loop that will do this but for a full cube? Thanks!

Related

Ploting a point for each step i

I'm doing a free fall caluculations (really simple) and would like to plot each instance of height of the objects - that is the height of the object to be displayed as it 'falls' down. I tried running it throught a for loop, but i just get the end result plotted. What would i need to do to dislplay the object as it falls, for each individual - not just the end result.
Here is my code:
#Input parameters
y1 = 490 #starting position
y2 = 0 #ground
g = -9.81 #gravity
VY = 0 #starting speed
import math
import numpy as np
import matplotlib.pyplot as plt
sqrt_part = math.sqrt(VY**2-2*g*(y1-y2))
t1 = - VY - sqrt_part/g
t2 = - VY + sqrt_part/g
if t1 > 0:
t = t1
else:
t = t2
print('t = ' + str(t) + ' ' + 's')
t_space = np.linspace(0,t,50)
y_t = y1 + VY * t_space + 0.5 * g * t_space**2
v_t = abs(y_t[1:] - y_t[0:-1])/abs(t_space[0:-1] - t_space[1:])
plt.plot(t_space, y_t, 'go')
plt.plot(t_space[1:], v_t, 'r--')
for i in range(np.size(t_space)):
plt.plot(t_space[i], y_t[i], 'go')
The for loop displays the same as the plot above it, but i would like it to update and show the 'ro' as it moves thorught time. How would i do that?
On the left is what i get, on the right is what i want
enter image description here
Please, take a look at matplotlib animation api.
#Input parameters
y1 = 490 #starting position
y2 = 0 #ground
g = -9.81 #gravity
VY = 0 #starting speed
import math
import numpy as np
import matplotlib.pyplot as plt
sqrt_part = math.sqrt(VY**2-2*g*(y1-y2))
t1 = - VY - sqrt_part/g
t2 = - VY + sqrt_part/g
if t1 > 0:
t = t1
else:
t = t2
print('t = ' + str(t) + ' ' + 's')
t_space = np.linspace(0,t,50)
y_t = y1 + VY * t_space + 0.5 * g * t_space**2
v_t = np.abs((np.roll(y_t, -1) - y_t) / (np.roll(t_space, -1) - t_space))
v_t = np.roll(v_t, 1)
v_t[0] = 0
from matplotlib.animation import FuncAnimation
fig, ax = plt.subplots()
# create two empty lines
ln_y, = plt.plot([], [], 'go', label="y")
ln_v, = plt.plot([], [], 'r--', label="v")
def init():
ax.set_xlim(0, max(t_space))
ax.set_ylim(0, max(y_t))
ax.set_xlabel("t")
ax.legend()
return ln_y, ln_v
def update(i):
# i represents the index of the slice to use at the current frame
ln_y.set_data(t_space[:i], y_t[:i])
ln_v.set_data(t_space[:i], v_t[:i])
return ln_y, ln_v,
ani = FuncAnimation(fig, update, frames=range(len(v_t)),
init_func=init, blit=False, repeat=False)
plt.show()

ValueError: setting an array element with a sequence rectifying error

def nonuniform_poly_interpolation(a,b,p,n,x,f,produce_fig):
xhat = np.zeros(p+1)
for j in range(p+1):
xhat[j] = b - a + a * np.cos(np.pi * (((2*j)+1)/(2*(p+1))))
lagrange_matrix = lagrange_poly(p,xhat,n,x,1e-10)
nu_interpolant = np.empty(n)
for i in range(p+1):
nu_interpolant[i] = nu_interpolant[i] + (f(xhat[i]) * lagrange_matrix[i]);
fig = plt.figure()
plt.plot(x,f(x), label = "f(x)")
plt.plot(x,nu_interpolant, label = "Pp(x)")
plt.legend(loc = "upper left")
plt.xlabel("x")
plt.ylabel("Pp(x)")
plt.title("Nonuniform Polynomial Interpolation")
plt.show()
if produce_fig == True:
fig = fig
else:
fig = None
return nu_interpolant, fig
Not sure what "ValueError: setting an array element with a sequence" means and how I could fix this code? It is sensing an error on line 127 (for i in range(p+1):
nu_interpolant[i] = nu_interpolant[i] + (f(xhat[i]) * lagrange_matrix[i]);

AttributeError: 'list' object has no attribute 'ndim'

I am trying to make a 3d plot using frames and an array. In this code you can see that I have a system of equations that needs to be solved in order to get the "Z" value for my points. Each time through the for loop, I call in 2 values that are needed to solve the system and those 2 values are ultimately my "X" and "Y" values. Upon solving the system I pull one of the values and use it to find my "Z" value.
Running the code gives me
AttributeError: 'list' object has no attribute 'ndim'
on line
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap = 'plasma')
What is the fix for this problem?
from pylab import *
from random import *
from mpl_toolkits import mplot3d
import pandas as pd
from scipy.optimize import fsolve
mdoth = 0.004916
Tinfhin = 334.75
cph = 1008
nsh = .598
hh= 86.68
Ash = .02
n=127
alpha = .00041427
rho = .002129
k=3.041
Le = .0025
Ae = .000001
re = rho * Le/Ae
Ke = k * Ae/Le
nsc = .674
hc = 87.68
Asc = .016
Tinfcin = 295.75
rL = re
mdotc = .004542
cpc = 1007
dframe = pd.read_csv("file name here")
plot(dframe['Sec'], dframe['TC (C)'], 'b-')
#annotate(xy=[818,72.25], s=&apos;First Entry&apos;)
xlabel('Time (s)')
ylabel('Temperature (C)')
title("Exhaust")
show()
plot(dframe['Sec'], dframe['Amb (C)'], 'r-')
xlabel('Time (s)')
ylabel('Temperature (C)')
title("Ambient")
show()
plot(dframe['Sec'], dframe['TC (C)'], 'b-', label = "Exhaust")
plot(dframe['Sec'], dframe['Amb (C)'], 'r-', label = "Ambient")
xlabel('Time (s)')
ylabel('Temperature (C)')
legend()
show()
Tinfhin = dframe['TC (C)']
Tinfcin = dframe['Amb (C)']
X, Y = meshgrid(Tinfhin,Tinfcin)
powerArray = []
for index, row in dframe.iterrows():
Tinfhin = row['TC (C)']
Tinfcin = row['Amb (C)']
def function(z):
II = z[0]
Qc = z[1]
Qh = z[2]
Tc = z[3]
Th = z[4]
Tinfcout = z[5]
Tinfhout = z[6]
F = np.empty((7))
F[0] = mdoth * cph * (Tinfhin - Tinfhout) - Qh
F[1] = nsh * hh * Ash * ((Tinfhin + Tinfhout)/2 - Th) - Qh
F[2] = n * (alpha * II * Th - 1/2 * (II**2) * re + (Ke * (Th-Tc))) - Qh
F[3] = n * (alpha * II * Tc + 1/2 * (II**2) * re + (Ke * (Th-Tc))) - Qc
F[4] = nsc * hc * Asc * (Tc - (Tinfcin + Tinfcout)/2) - Qc
F[5] = mdotc * cpc * (Tinfcin - Tinfcout) - Qc
F[6] = (alpha * (Th - Tc))/(rL/n + re) - II
return F
guess = np.array([1,1,1,1,1,1,1])
z = fsolve(function, guess)
power = n * z[0]**2 * rL
powerArray.append(power)
Z = powerArray
ax = axes(projection='3d')
ax.set_xlabel("TC")
ax.set_ylabel("Ambient")
ax.set_zlabel("Voltage")
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap = 'plasma')
ax.view_init(0, 180)

Use recursion to avoid writing nested loop number equal to the number of layers?

This excellent answer to Return a list of all objects vertically stacked above a given object? started me on tree traversal, now I need to start building a complex control panel using wxPython.
I'm learning about sizers but for this abstracted script I've used matplotlib to generate what the panel will look like.
The part I need help with is only the bit near the end with the comments First layer, Second layer and Third layer. What I need is to use recursion so that I don't have to have the correct number of nested loops equal to the number of layers.
Once I get better at wxPython I'll use the same recursion to build the real control panel.
Each heavy black rectangle will ultimately be a cluster of wxPython widgets, and each thing red rectangle will be the enclosing sizer.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.lines as lines
class DG():
def __init__(self, name):
self.dgs = []
self.name = str(name)
def add_dg(self, name):
dg = DG(name=name)
self.dgs.append(dg)
return dg
def __repr__(self):
return ('{self.name}'.format(self=self))
def find_trees(self):
# https://stackoverflow.com/questions/60339232/return-a-list-of-all-objects-vertically-stacked-above-a-given-object
# https://en.wikipedia.org/wiki/Tree_traversal
self.trees = []
def __fill_dg_trees(dg_trees, dg, path):
for th in dg.dgs:
__fill_dg_trees(dg_trees, th, path + [dg])
if not dg.dgs:
self.trees.append(path + [dg])
__fill_dg_trees(self.trees, self, [])
self.n_trees = len(self.trees)
class Sub():
def __init__(self, name):
self.width = 1.0
self.x0 = 0.0
self.name = name
self.dgs = []
def add_dg(self, name):
dg = DG(name=name)
self.dgs.append(dg)
return dg
def find_trees(self):
# https://stackoverflow.com/questions/60339232/return-a-list-of-all-objects-vertically-stacked-above-a-given-object
# https://en.wikipedia.org/wiki/Tree_traversal
self.trees = []
def __fill_dg_trees(dg_trees, dg, path):
for th in dg.dgs:
__fill_dg_trees(dg_trees, th, path + [dg])
if not dg.dgs:
self.trees.append(path + [dg])
__fill_dg_trees(self.trees, self, [])
self.n_trees = len(self.trees)
def __repr__(self):
return ('{self.name}'.format(self=self))
# -----------
# | C | D |
# -----------------------------
# | B | F | G | H |
# -----------------------------
# | A | E |
# -----------------------------
# | Substrate |
# -----------------------------
sub = Sub(name='My Substrate')
A = sub.add_dg(name='A')
B = A.add_dg(name='B')
C = B.add_dg(name='C')
D = B.add_dg(name='D')
E = sub.add_dg('E')
F = E.add_dg('F')
G = E.add_dg('G')
H = E.add_dg('H')
sub.find_trees()
sub.goodies = set(sum(sub.trees, [])).difference(set([sub]))
for thing in sub.goodies:
thing.find_trees()
sub.tree_height = max([len(tree) for tree in sub.trees]) - 1
sub.n_trees = len(sub.trees)
sub.n_goodies = len(sub.goodies)
print('sub.tree_height: ', sub.tree_height)
print('sub.n_trees: ', sub.n_trees)
print('sub.n_goodies: ', sub.n_goodies)
print('sub.goodies: ', sub.goodies)
for i, tree in enumerate(sub.trees):
print(i, tree)
def squareit(thing, nh, dh, dd, hw, hh):
x0 = thing.x0
linez, texts = [], []
print('called thing: ', thing)
print('thing.width, thing.n_trees: ', thing.width, thing.n_trees)
for i, dg in enumerate(thing.dgs):
print('i, dg: ', i, dg)
print('dg.n_trees: ', dg.n_trees)
dg.width = float(dg.n_trees) * thing.width / thing.n_trees
dg.x0 = x0
print('dg.width: ', dg.width)
x1, x2 = x0+dd, x0 + dg.width - dd
y1, y2 = nh*dh + dd, ((nh+1)*dh) - dd
xx = np.array([x1, x2, x2, x1, x1])
yy = np.array([y1, y1, y2, y2, y1])
outline = lines.Line2D(xx, yy, lw=1., color='r', alpha=1.0,
transform=fig.transFigure, figure=fig) # https://stackoverflow.com/a/5022412/3904031
xt, yt = x0+1.5*dd, ((nh+0.5)*dh)-dd
texts.append((xt, yt, dg.name))
x1, x2 = x0 + 0.5*dg.width - hw, x0 + 0.5*dg.width + hw
y1, y2 = ((nh+0.5)*dh) - hh, ((nh+0.5)*dh) + hh
xx = np.array([x1, x2, x2, x1, x1])
yy = np.array([y1, y1, y2, y2, y1])
control_pannel_line = lines.Line2D(xx, yy, lw=3., color='k', alpha=1.0,
transform=fig.transFigure, figure=fig) # https://stackoverflow.com/a/5022412/3904031
linez += [outline, control_pannel_line]
x0 += dg.width
return linez, texts
if True:
fig = plt.figure()
x0 = 0.
dd = 0.01
dh = 0.2
hw, hh = 0.05, 0.075
# linez, texts = [], []
# draw the substrate first
nh = 0
x1, x2 = x0+dd, x0 + sub.width - dd
y1, y2 = nh*dh + dd, ((nh+1)*dh) - dd
xx = np.array([x1, x2, x2, x1, x1])
yy = np.array([y1, y1, y2, y2, y1])
outline = lines.Line2D(xx, yy, lw=1., color='r', alpha=1.0,
transform=fig.transFigure, figure=fig)
xt, yt = x0+1.5*dd, ((nh+0.5)*dh)-dd
texts = [(xt, yt, sub.name)]
x1, x2 = x0 + 0.5*sub.width - hw, x0 + 0.5*sub.width + hw
y1, y2 = ((nh+0.5)*dh) - hh, ((nh+0.5)*dh) + hh
xx = np.array([x1, x2, x2, x1, x1])
yy = np.array([y1, y1, y2, y2, y1])
control_pannel_line = lines.Line2D(xx, yy, lw=3., color='k', alpha=1.0,
transform=fig.transFigure, figure=fig)
linez = [outline, control_pannel_line]
# now iterate through the whole thing
# first layer:
a, b = squareit(sub, nh=1, dh=dh, dd=dd, hw=hw, hh=hh)
linez += a
texts += b
# second layer:
for dg in sub.dgs:
a, b = squareit(dg, nh=2, dh=dh, dd=dd, hw=hw, hh=hh)
linez += a
texts += b
# third layer:
for dgg in dg.dgs:
a, b = squareit(dgg, nh=3, dh=dh, dd=dd, hw=hw, hh=hh)
linez += a
texts += b
fig.lines.extend(linez) # https://matplotlib.org/3.1.0/gallery/pyplots/fig_x.html
for (x, y, text) in texts:
fig.text(x, y, text, fontsize=14)
plt.show()
I use dfs and only use one class Sub (since I think Sub and DG is redundant).
Here is the code:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.lines as lines
class Sub():
def __init__(self, name):
self.width = 1.0
self.x0 = 0.0
self.name = name
self.dgs = []
def add_dg(self, name):
dg = Sub(name=name)
self.dgs.append(dg)
return dg
def find_trees(self):
# https://stackoverflow.com/questions/60339232/return-a-list-of-all-objects-vertically-stacked-above-a-given-object
# https://en.wikipedia.org/wiki/Tree_traversal
self.trees = []
def __fill_dg_trees(dg_trees, dg, path):
for th in dg.dgs:
__fill_dg_trees(dg_trees, th, path + [dg])
if not dg.dgs:
self.trees.append(path + [dg])
__fill_dg_trees(self.trees, self, [])
self.n_trees = len(self.trees)
def __repr__(self):
return ('{self.name}'.format(self=self))
# -----------
# | C | D |
# -----------------------------
# | B | F | G | H |
# -----------------------------
# | A | E |
# -----------------------------
# | Substrate |
# -----------------------------
sub = Sub(name='My Substrate')
A = sub.add_dg(name='A')
B = A.add_dg(name='B')
C = B.add_dg(name='C')
D = B.add_dg(name='D')
E = sub.add_dg('E')
F = E.add_dg('F')
G = E.add_dg('G')
H = E.add_dg('H')
sub.find_trees()
sub.goodies = set(sum(sub.trees, [])).difference(set([sub]))
for thing in sub.goodies:
thing.find_trees()
sub.tree_height = max([len(tree) for tree in sub.trees]) - 1
sub.n_trees = len(sub.trees)
sub.n_goodies = len(sub.goodies)
print('sub.tree_height: ', sub.tree_height)
print('sub.n_trees: ', sub.n_trees)
print('sub.n_goodies: ', sub.n_goodies)
print('sub.goodies: ', sub.goodies)
for i, tree in enumerate(sub.trees):
print(i, tree)
def squareit(thing, nh, dh, dd, hw, hh):
x0 = thing.x0
linez, texts = [], []
print('called thing: ', thing)
print('thing.width, thing.n_trees: ', thing.width, thing.n_trees)
for i, dg in enumerate(thing.dgs):
print('i, dg: ', i, dg)
print('dg.n_trees: ', dg.n_trees)
dg.width = float(dg.n_trees) * thing.width / thing.n_trees
dg.x0 = x0
print('dg.width: ', dg.width)
x1, x2 = x0+dd, x0 + dg.width - dd
y1, y2 = nh*dh + dd, ((nh+1)*dh) - dd
xx = np.array([x1, x2, x2, x1, x1])
yy = np.array([y1, y1, y2, y2, y1])
outline = lines.Line2D(xx, yy, lw=1., color='r', alpha=1.0,
transform=fig.transFigure, figure=fig) # https://stackoverflow.com/a/5022412/3904031
xt, yt = x0+1.5*dd, ((nh+0.5)*dh)-dd
texts.append((xt, yt, dg.name))
x1, x2 = x0 + 0.5*dg.width - hw, x0 + 0.5*dg.width + hw
y1, y2 = ((nh+0.5)*dh) - hh, ((nh+0.5)*dh) + hh
xx = np.array([x1, x2, x2, x1, x1])
yy = np.array([y1, y1, y2, y2, y1])
control_pannel_line = lines.Line2D(xx, yy, lw=3., color='k', alpha=1.0,
transform=fig.transFigure, figure=fig) # https://stackoverflow.com/a/5022412/3904031
linez += [outline, control_pannel_line]
x0 += dg.width
return linez, texts
if True:
fig = plt.figure()
x0 = 0.
dd = 0.01
dh = 0.2
hw, hh = 0.05, 0.075
# linez, texts = [], []
# draw the substrate first
nh = 0
x1, x2 = x0+dd, x0 + sub.width - dd
y1, y2 = nh*dh + dd, ((nh+1)*dh) - dd
xx = np.array([x1, x2, x2, x1, x1])
yy = np.array([y1, y1, y2, y2, y1])
outline = lines.Line2D(xx, yy, lw=1., color='r', alpha=1.0,
transform=fig.transFigure, figure=fig)
xt, yt = x0+1.5*dd, ((nh+0.5)*dh)-dd
texts = [(xt, yt, sub.name)]
x1, x2 = x0 + 0.5*sub.width - hw, x0 + 0.5*sub.width + hw
y1, y2 = ((nh+0.5)*dh) - hh, ((nh+0.5)*dh) + hh
xx = np.array([x1, x2, x2, x1, x1])
yy = np.array([y1, y1, y2, y2, y1])
control_pannel_line = lines.Line2D(xx, yy, lw=3., color='k', alpha=1.0,
transform=fig.transFigure, figure=fig)
linez = [outline, control_pannel_line]
# Using DFS:
def dfs(node, nh, linez, texts):
a, b = squareit(node, nh=nh, dh=dh, dd=dd, hw=hw, hh=hh)
linez += a
texts += b
for child in node.dgs:
dfs(child, nh+1, linez, texts)
dfs(sub, nh=1, linez=linez, texts=texts)
fig.lines.extend(linez) # https://matplotlib.org/3.1.0/gallery/pyplots/fig_x.html
for (x, y, text) in texts:
fig.text(x, y, text, fontsize=14)
plt.show()
Notice the part with comment # Using DFS.
I have tried it on my jupyter and seems to output the same thing as your code. Hope this help!

Python - find where the plot crosses the axhline on python plot

I am doing some analysis on some simple data, and I am trying to plot auto-correlation and partial auto-correlation. Using these plots, I am trying to find the P and Q value to plot in my ARIMA model.
I can see on the graphs, but I am wondering if I can explicitly find, for each graph, where the plot crosses the axhline?
plt.subplot(122)
plt.plot(lag_pacf)
plt.axhline(y=0, linestyle = '--', color = 'grey')
plt.axhline(y=-1.96/np.sqrt(len(log_moving_average_difference)),linestyle = '--',color = 'red')
plt.axhline(y=1.96/np.sqrt(len(log_moving_average_difference)),linestyle = '--', color = 'green')
plt.title('Partial Autocorelation Function')
So in the above code, can I find, and show, where the lag_pacf plot crosses the axhlines that I have predetermined?
Thanks
You'll need to calculate the intersections between the line segments of lag_pacf and y's:
from matplotlib import pyplot as plt
import numpy as np
lag_pacf = np.random.randint(-10,10,30)
log_moving_average_difference = [i for i in range(30)]
#plt.subplot(122)
plt.plot(lag_pacf)
plt.axhline(y=0, linestyle = '--', color = 'grey')
plt.axhline(y=-1.96/np.sqrt(len(log_moving_average_difference)),linestyle = '--',color = 'red')
plt.axhline(y=1.96/np.sqrt(len(log_moving_average_difference)),linestyle = '--', color = 'green')
plt.title('Partial Autocorelation Function')
plt.xlim(0,30)
plt.ylim(-10,10)
plt.show()
def line_intersection(line1, line2):
xdiff = (line1[0][0] - line1[1][0], line2[0][0] - line2[1][0])
ydiff = (line1[0][1] - line1[1][1], line2[0][1] - line2[1][1]) #Typo was here
def det(a, b):
return a[0] * b[1] - a[1] * b[0]
div = det(xdiff, ydiff)
if div == 0:
return None
d = (det(*line1), det(*line2))
x = det(d, xdiff) / div
y = det(d, ydiff) / div
return x, y
def near(a, b, rtol=1e-5, atol=1e-8):
return abs(a - b) < (atol + rtol * abs(b))
def crosses(line1, line2):
"""
Return True if line segment line1 intersects line segment line2 and
line1 and line2 are not parallel.
"""
(x1,y1), (x2,y2) = line1
(u1,v1), (u2,v2) = line2
(a,b), (c,d) = (x2-x1, u1-u2), (y2-y1, v1-v2)
e, f = u1-x1, v1-y1
denom = float(a*d - b*c)
if near(denom, 0):
# parallel
return False
else:
t = (e*d - b*f)/denom
s = (a*f - e*c)/denom
# When 0<=t<=1 and 0<=s<=1 the point of intersection occurs within the
# line segments
return 0<=t<=1 and 0<=s<=1
plt.plot(lag_pacf)
plt.axhline(y=0, linestyle = '--', color = 'grey')
plt.axhline(y=-1.96/np.sqrt(len(log_moving_average_difference)),linestyle = '--',color = 'red')
plt.axhline(y=1.96/np.sqrt(len(log_moving_average_difference)),linestyle = '--', color = 'green')
plt.title('Partial Autocorelation Function')
yys = [0,-1.96/np.sqrt(len(log_moving_average_difference)),1.96/np.sqrt(len(log_moving_average_difference))]
xx, yy = [],[]
xo,yo = [k for k in range(30)],lag_pacf
d = 20
for i in range(1,len(lag_pacf)):
for k in yys:
p1 = np.array([xo[i-1],yo[i-1]],dtype='float')
p2 = np.array([xo[i],yo[i]],dtype='float')
k1 = np.array([xo[i-1],k],dtype='float')
k2 = np.array([xo[i],k],dtype='float')
if crosses((p2,p1),(k1,k2)):
seg = line_intersection((p2,p1),(k1,k2))
if seg is not None:
xx.append(seg[0])
yy.append(seg[1]-d)
plt.scatter(seg[0],seg[1],c='red')
plt.xlim(0,30)
plt.ylim(-10,10)
plt.show()
, for this completely randomized example:
I obtained this:

Categories