-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplot_white_noise_1d.py
228 lines (201 loc) · 7.88 KB
/
plot_white_noise_1d.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
#!/usr/bin/env python
"""
plot_white_noise_1d.py
=========================
Plot examples of fitting white noise in 1D, using stored results created by the script
fitting_white_noise_1d.py
"""
import os
import pickle
import numpy as np
import matplotlib.pyplot as plt
# Ready output folder
if not os.path.isdir(os.path.join(".", "plots")):
os.mkdir(os.path.join(".", "plots"))
# Load detailed ("all") results from pickled file object for sinusoid fits
with open("wns1d.1e3.all.pickle", "rb") as fin:
rall = pickle.load(fin)
# Pull out results
yall = rall["yall"]
yfit = rall["yfit"]
rcf = rall["rcf"]
ncf = rall["ncf"]
# Single examples of fitting in 1D
# ================================
#
# Define unit interval
x = np.linspace(-.5, .5, num=yall.shape[-1], endpoint=False)
print("Sum of Square Errors (SSE) results for basic y, fit and residuals examples")
print("--------------------------------------------------------------------------")
# Loop through orders to show in the example figures - something low -> intermediate -> high
for m, fig_str in zip((1, 21, 41), ("fig1", "fig2", "fig3")):
print("m = "+str(m))
fig = plt.figure(figsize=(6, 4))
plt.grid()
plt.plot(x, yall[m, 0, :], label=r"$Y \sim N(0, 1)$")
plt.plot(x, yfit[m, 0, :], label=r"Best-fitting curve for $M="+str(m)+"$")
plt.ylim(-3, 3)
plt.xlabel(r"$x$")
plt.ylabel(r"$y$")
plt.legend(loc=2)
plt.tight_layout()
plt.savefig(os.path.join(".", "plots", fig_str+"a.pdf"))
plt.close(fig)
fig = plt.figure(figsize=(6, 4))
print("SSE of y (no fit applied) = "+str(np.sum(yall[m, 0, :]**2)))
plt.grid()
#plt.plot(x, yall[m, 0, :], label=r"White noise $\sim N(0, 1)$")
plt.plot(
x, yall[m, 0, :] - yfit[m, 0, :], "r--",
label=r"Residual from best-fitting curve for $M="+str(m)+"$")
plt.ylim(-3, 3)
plt.xlabel(r"$x$")
plt.ylabel(r"$y$")
plt.legend(loc=2)
plt.tight_layout()
plt.savefig(os.path.join(".", "plots", fig_str+"b.pdf"))
plt.clf()
print("SSE of fit (M="+str(m)+") residuals = "+str(np.sum((yall[m, 0, :] - yfit[m, 0, :])**2)))
plt.close(fig)
# Residual correlation functions for single 1D examples
# =====================================================
#
# Loop through orders to show the rcf examples
mmax = 1 + ncf.shape[-1]//2
fig, axes = plt.subplots(3, 1, sharex=True)
# Loop through 3 examples
for i, m in enumerate((1, 21, 41)):
axes[i].plot(rcf[m, 0, :mmax], label=r"$M="+str(m)+"$")
axes[i].set_yticks(np.arange(-0.5, 1.5, 0.5))
axes[i].set_ylim(-1, 1.1)
axes[i].grid()
if i == 0: # Add a top axis with delta x units (rather than delta i)
ax2 = axes[i].twiny()
ax2.set_xlabel(r'$|\Delta x|$')
ax2.set_xlim(tuple(.01 * np.asarray(axes[i].get_xlim())))
elif i == 1:
axes[i].set_ylabel("Residual autocorrelation")
axes[i].legend(loc=1)
# Add x label to final subplot
axes[-1].set_xlabel(r"Lag $|l|$")
# Remove horizontal space between axes
plt.tight_layout()
fig.subplots_adjust(hspace=0)
# Save and close
fig.savefig(os.path.join(".", "plots", "fig4.pdf"))
plt.close(fig)
# Plot mean of all residual autocorrelations for the full sinusoidal runs
# =======================================================================
#
# Load results from pickled file object
with open("wns1d.1e5.pickle", "rb") as fin:
rse5 = pickle.load(fin)
# Build the plot output
fig, ax = plt.subplots()
rcf_plt = rse5["m_rcf"][:(mmax - 1), :mmax]
# Seismic has good contrast
im = ax.pcolor(rcf_plt, vmin=-1, vmax=+1, cmap="seismic")
fig.colorbar(im)
# Shift ticks to be at 0.5, 1.5, etc
ax.xaxis.set(ticks=np.arange(0.5, mmax, 10), ticklabels=np.arange(0, mmax, 10))
ax.yaxis.set(
ticks=list(np.arange(0.5, mmax-1, 10))+[49.5], ticklabels=list(np.arange(0, mmax-1, 10))+[49])
ax.set_xlabel(r"Lag $|l|$", size="large")
ax.set_ylabel(r"Overfitting order $M$", size="large")
ax.set_title("Averaged residual autocorrelation")
fig.savefig(os.path.join(".", "plots", "fig5.pdf"))
plt.close(fig)
# Plot mean of all power spectra for the full sinusoidal runs
# ===========================================================
#
ps_plt = np.abs(np.fft.fft(rse5["m_rcf"]))[:(mmax - 1), :mmax]
pss_plt = (ps_plt.T / ps_plt.max(axis=1)).T
# Build the plot output
fig, ax = plt.subplots()
# Seismic has good contrast
im = ax.pcolor(pss_plt, vmin=-1, vmax=+1, cmap="seismic")
fig.colorbar(im)
# Shift ticks to be at 0.5, 1.5, etc
ax.xaxis.set(ticks=np.arange(0.5, mmax, 10), ticklabels=np.arange(0, mmax, 10))
ax.yaxis.set(
ticks=list(np.arange(0.5, mmax-1, 10))+[49.5], ticklabels=list(np.arange(0, mmax-1, 10))+[49])
ax.set_xlabel(r"$|k|$", size="large")
ax.set_ylabel(r"Overfitting order $M$", size="large")
ax.set_title("Averaged residual power spectral signature")
fig.savefig(os.path.join(".", "plots", "fig6.pdf"))
plt.close(fig)
# Plot mean of all residual autocorrelations for the full chebyshev runs
# ======================================================================
#
# Load results from pickled file object
with open("wnc1d.1e5.pickle", "rb") as fin:
rce5 = pickle.load(fin)
# Build the plot output
fig, ax = plt.subplots(figsize=(6, 6))
rcf_plt = rce5["m_rcf"][:, :mmax]
# Seismic has good contrast
im = ax.pcolor(rcf_plt, vmin=-1, vmax=+1, cmap="seismic")
fig.colorbar(im)
# Shift ticks to be at 0.5, 1.5, etc
ax.xaxis.set(ticks=np.arange(0.5, mmax, 10), ticklabels=np.arange(0, mmax, 10))
ax.yaxis.set(
ticks=list(np.arange(0.5, rcf_plt.shape[0], 10)),
ticklabels=list(np.arange(0, rcf_plt.shape[0], 10)))
ax.set_xlabel(r"Lag $|l|$", size="large")
ax.set_ylabel(r"Overfitting order $M$", size="large")
ax.set_title("Averaged residual autocorrelation")
fig.savefig(os.path.join(".", "plots", "fig7.pdf"))
plt.close(fig)
# Plot mean of all power spectra for the full chebyshev runs
# ==========================================================
#
ps_plt = np.abs(np.fft.fft(rce5["m_rcf"]))[:, :mmax]
pss_plt = (ps_plt.T / ps_plt.max(axis=1)).T
# Build the plot output
fig, ax = plt.subplots(figsize=(6, 6))
# Seismic has good contrast
im = ax.pcolor(pss_plt, vmin=-1, vmax=+1, cmap="seismic")
fig.colorbar(im)
# Shift ticks to be at 0.5, 1.5, etc
ax.xaxis.set(ticks=np.arange(0.5, mmax, 10), ticklabels=np.arange(0, mmax, 10))
ax.yaxis.set(
ticks=list(np.arange(0.5, pss_plt.shape[0], 10)),
ticklabels=list(np.arange(0, pss_plt.shape[0], 10)))
ax.set_xlabel(r"$|k|$", size="large")
ax.set_ylabel(r"Overfitting order $M$", size="large")
ax.set_title("Averaged residual power spectral signature")
fig.savefig(os.path.join(".", "plots", "fig8.pdf"))
plt.close(fig)
# Plots of 1 - \sum \ln(pk)
# =========================
#
fig = plt.figure(figsize=(5, 4))
plt.grid()
plt.plot(1 + np.asarray(rse5["med_lrcps"][:-1]), "b-", label="Fourier Series Model")
plt.plot(1 + np.asarray(rse5["lqt_lrcps"][:-1]), "b--")
plt.plot(1 + np.asarray(rse5["uqt_lrcps"][:-1]), "b--")
plt.axhline(1 + np.mean(rse5["med_lncps"]), ls="-", color="k")
plt.axhline(1 + np.mean(rse5["lqt_lncps"]), ls="--", color="k")
plt.axhline(1 + np.mean(rse5["uqt_lncps"]), ls="--", color="k")
plt.ylim((0, 37.5))
plt.xlabel(r"Overfitting order $M$")
plt.ylabel(r"$1 - \frac{1}{N} \sum_{k=0}^{N-1} \ln{\left[ \tilde{\rho}_{rr}(k) \right]}$")
plt.legend()
plt.tight_layout()
fig.savefig(os.path.join(".", "plots", "fig9.pdf"))
plt.close(fig)
fig = plt.figure(figsize=(5, 4))
plt.grid()
plt.plot(1 + np.asarray(rce5["med_lrcps"]), "r-", label="Chebyshev Series Model")
plt.plot(1 + np.asarray(rce5["lqt_lrcps"]), "r--")
plt.plot(1 + np.asarray(rce5["uqt_lrcps"]), "r--")
plt.axhline(1 + np.mean(rce5["med_lncps"]), ls="-", color="k")
plt.axhline(1 + np.mean(rce5["lqt_lncps"]), ls="--", color="k")
plt.axhline(1 + np.mean(rce5["uqt_lncps"]), ls="--", color="k")
plt.ylim((0, 37.5))
plt.xlabel(r"Overfitting order $M$")
plt.ylabel(r"$1 - \frac{1}{N} \sum_{k=0}^{N-1} \ln{\left[ \tilde{\rho}_{rr}(k) \right]}$")
plt.legend()
plt.tight_layout()
fig.savefig(os.path.join(".", "plots", "fig10.pdf"))
plt.close(fig)