def plot_fft2(samp_t, ROWLIST, SETTINGS): from scipy import signal from scipy.ndimage.filters import maximum_filter from scipy.ndimage.morphology import generate_binary_structure, binary_erosion, iterate_structure xcm, vcm, fi_rows, R, t, imap, rmap = slicer(SETTINGS) RUNS, ini, end, rows, Name = SETTINGS mag = lambda F: (F * cj(F)).real T, Npr, rows = fi_rows.shape for ROW in ROWLIST: fig, ax = plt.subplots(1, 1) print(ROW) matrix = fi_rows[:, :, ROW].T Fmatrix = np.fft.fftshift(mag(np.fft.fftn(matrix))) # Fmatrix = mag( np.fft.fftn(matrix) ) shape = Fmatrix.shape F = Fmatrix.flatten() F[np.argmax(F)] = 0 newmax = F[np.argmax(F)] Fmatrix = F.reshape(shape) thresh = Fmatrix > 0.5 * newmax samp_e = 1. # vecinos t_freq = np.fft.fftshift(np.fft.fftfreq(len(t), d=1. / samp_t)) e_freq = np.fft.fftshift(np.fft.fftfreq(Npr, d=1. / samp_e)) # print(e_freq) defreq = e_freq[1] - e_freq[0] dtfreq = t_freq[1] - t_freq[0] logF = np.log(Fmatrix) filt = logF > np.max(logF) * .7 # print( logF.shape, filt.shape ) # # Peak finder # neighborhood = np.zeros((5,5)); neighborhood[2,2]=1 # neighborhood = neighborhood.astype(bool) # local_max = maximum_filter(Fmatrix, footprint=neighborhood)==Fmatrix # background = (Fmatrix <= np.max(Fmatrix)*.9) # eroded_background = binary_erosion(background, structure=neighborhood, iterations=1, border_value=1) # detected_peaks = local_max ^ eroded_background # peaks_index = np.transpose( np.nonzero( detected_peaks ) ) # for ipeak in peaks_index: # espacial = "i={0}, k={1:f} 1/vec, la={2:f} vec".format(ipeak[0],e_freq[ipeak[0]],1/e_freq[ipeak[0]]) # temporal = "i={0}, f={1:f} 1/, T={2:f} corrida".format(ipeak[1],t_freq[ipeak[1]],1/t_freq[ipeak[1]]) # print( espacial ) # print( temporal ) # ax.imshow( np.log( Fmatrix*thresh +1 ) ,aspect='auto', extent=[ t_freq[0], t_freq[-1], e_freq[0]+defreq, e_freq[-1]+defreq ] ) ax.imshow(logF * filt, aspect='auto', extent=[ t_freq[0], t_freq[-1], e_freq[0] + defreq, e_freq[-1] + defreq ]) ax.axhline(0, c='r') ax.axvline(0, c='r') # plt.show() return fig, ax
def angle_dist(ROWLIST): X, V, fi_rows, R, t, imap, rmap = slicer(SETTINGS) RUNS, ini, end, rows, Name = loadargs(sys.argv[2:]) r2 = (R * cj(R)).real Rang = np.angle(R) #+ np.pi print(Rang.min(), Rang.max()) print(fi_rows.min(), fi_rows.max()) Tsize, Npr, rows = fi_rows.shape DAT = [RUNS, ini, end, rows, Name, Tsize, Npr] ed2cen = lambda ed: .5 * (ed[1:] + ed[:-1]) def bound(A): for i in range(len(A)): if A[i] > np.pi: A[i] = -A[i] + 2 * np.pi return A def bound2(A): for i in range(len(A)): if A[i] < 0: A[i] = A[i] + 2 * np.pi return A def bound3(A): for i in range(len(A)): if A[i] > np.pi * .5: A[i] = A[i] - np.pi return A fi_rel = np.empty_like(fi_rows) for c in range(Npr): fi_rel[:, c, :] = fi_rows[:, c, :] - Rang fig, ax = plt.subplots(1, 1) for ROW in ROWLIST: fi_rel_flat = fi_rel[:, :, ROW].flatten() fi_rel_flat_bound = bound(fi_rel_flat) # fi_rel_flat_bound = fi_rel_flat # ax.plot( t, np.angle(R[:,ROW]), 'k' ) H, ed = np.histogram(abs(fi_rel_flat_bound), bins=100, density=True) bins = ed2cen(ed) ax.plot(bins, H, 'o-') plt.show()
def r2_stat(SETTINGS): xcm, vcm, fi_rows, R, t, imap, rmap = slicer(SETTINGS) RUNS, ini, end, rows, Name = SETTINGS r2 = (R * cj(R)).real mean = np.mean(r2, axis=0) std = np.std(r2, axis=0) print(" ".join(["ROW", "MEAN", "STD"])) for i in range(len(mean)): # text = "{0}\t{1:.3f}\t{2:.3f}".format( i, mean[i], std[i]) text = "{0} {1:.3f} {2:.3f}".format(i, mean[i], std[i]) print(text) print("-" * len(text)) print("\t".join(["<MEAN>", "<STD>/sqrt(size)"])) print("{0:.3f}\t{1:.3f}".format(np.mean(mean), np.mean(std) / len(std)**.5))
def stripes_ROW(ROWLIST, SETTINGS): xcm, vcm, fi_rows, R, t, imap, rmap = slicer(SETTINGS) RUNS, ini, end, rows, Name = SETTINGS r2 = R * cj(R) T, Npr, rows = fi_rows.shape DAT = [RUNS, ini, end, rows, Name, T, Npr] for ROW in ROWLIST: matrix = fi_rows[:, :, ROW].T # (osc, time) labeled, n_obj = find_stripes(matrix) pendientes = [] tiempos = [] # Taking means centers = np.empty((labeled.shape[0], n_obj)) centers[:, :] = np.nan for obj in range(1, n_obj + 1): # objects start at 1 filt = labeled == obj obj_i = np.where(filt) length = len(set(np.transpose(obj_i)[:, 0])) if length > int(Npr * .6): # stripe-length % of system for fila in range(centers.shape[0]): centers[fila, obj - 1] = np.mean(t[filt[fila, :]]) center_obj = centers[:, obj - 1] nanfilt = ~np.isnan(center_obj) if any(nanfilt): cent = center_obj[nanfilt] vec = (np.arange(0, Npr) + .5)[nanfilt] P = np.polyfit(vec, cent, 1) pendientes.append(P[0]) tiempos.append(np.mean(cent)) block_name = "block_" + str(ROW) + "_" + Name np.savez(block_name, pendientes=pendientes, tiempos=tiempos, DAT=DAT, centers=centers, r2=r2)
def plot_r2(SETTINGS, ROWLIST): xcm, vcm, fi_rows, R, t, imap, rmap = slicer(SETTINGS) RUNS, ini, end, rows, Name = SETTINGS fig, axROWS = plt.subplots(len(ROWLIST), 1) cmap = plt.cm.tab10(range(len(ROWLIST))) r2 = R * cj(R) if type(axROWS) == np.ndarray: for i, ROW in enumerate(ROWLIST): axROWS[i].plot(t, r2[:, ROW].real, color=cmap[i]) axROWS[int(len(axROWS) * .5)].set_ylabel( r'$\left\Vert R\right\Vert^{2}$', fontsize=13) axROWS[-1].set_xlabel(r'$Nº\;Corrida\;[10^6 \Delta t]$', fontsize=13) else: for ROW in ROWLIST: axROWS.plot(t, r2[:, ROW].real) axROWS.set_ylabel(r'$\left\Vert R\right\Vert^{2}$', fontsize=13) axROWS.set_xlabel(r'$Nº\;Corrida\;[10^6 \Delta t]$', fontsize=13) # ax.plot(t,r2[:,0].real) print(np.mean(r2.real, axis=0)) return fig, axROWS
def plot_polar(ROWLIST, SETTINGS): X, V, fi_rows, R, t, imap, rmap = slicer(SETTINGS) RUNS, ini, end, rows, Name = SETTINGS r2 = (R * cj(R)).real Tsize, Npr, rows = fi_rows.shape DAT = [RUNS, ini, end, rows, Name, Tsize, Npr] # fig_R, ax_R = plt.subplots(1,1,figsize=fsize) cm2in = lambda w, h: (w / 2.54, h / 2.54) fig, ax = plt.subplots(2, 3, subplot_kw=dict(polar=True)) rowi = np.asarray([[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2]]) p = 1.8 fig.set_size_inches(cm2in(p * 12, p * 8), forward=True) def bound2(A): if A < 0: A += 2 * np.pi return A T = 0000 for ROW in ROWLIST: for c in range(Npr): i, j = rowi[ROW] # fi_rel = bound2( fi_rows[T,c,ROW]-np.angle(R[T,ROW]) ) fi_rel = fi_rows[T, c, ROW] - (np.angle(R[T, ROW])) ax[i, j].scatter(0, np.absolute(R[T, ROW]), 50, color='xkcd:red') ax[i, j].scatter(fi_rel, 1, 30, color='xkcd:blue') # ax_R.plot(t,np.absolute(R),zorder=-1) # ax_R.set_xlabel(r'$Corrida \: [10^6 \: \Delta t ] $') # fig_R.tight_layout() fig.tight_layout() plt.show() # ax.plot(fi[0,:],r_0[0,:]) return [fig, fig_R], [ax, ax_R]
#!/usr/bin/env python3 import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np from numpy import conjugate as cj import sys, argparse, pickle padlength = lambda size: int(2**np.ceil(np.log2(size))-size) Mag = lambda f: (f*cj(f)).real cm2in = lambda w,h: (w/2.54,h/2.54) get_par = lambda d: "{0:.2f}".format(float(d.split('=')[1].strip('$'))) def plot_par(sim,par,ROWS): par = int(par) datos = np.load('corr_err_rows_'+sim+'.npz') corr, cerr, labels = datos['CORR'],datos['CERR'],datos['labels'] ch=np.linspace(0,10,11); N=ch.shape[0] if sim == 'mec' : sim_label = r'$\rho ='; sim_unit = r'\;1/\sigma$' if sim == 'ela' : sim_label = r'$ k ='; sim_unit = r'\;\epsilon/\sigma^2$' fig, ax = plt.subplots(1,1) # colormap = plt.cm.nipy_spectral #I suggest to use nipy_spectral, Set1,Paired # ax.set_color_cycle([colormap(i) for i in np.linspace(0., 0.95,4 )]) for ROW in ROWS: # for d, label in enumerate( labels ): # label = labels[n] # corr = C_ce[n,:,0] # err = C_ce[n,:,1] ax.errorbar(ch[1:], corr[par,ROW,1:], yerr=cerr[par,ROW,1:], fmt='-o', ms=3, capsize=5, lw=1.,
def corr(ROWLIST, SETTINGS): xcm, vcm, fi_rows, R, t, imap, rmap = slicer(SETTINGS) RUNS, ini, end, rows, Name = SETTINGS r2 = (R * cj(R)).real mag = lambda F: (F * cj(F)).real T, Npr, rows = fi_rows.shape def rot(v, j): # posiciona el indice j primero, preservando orden ciclico v2 = np.copy(v) n = len(v) i = int(n / 2 + 1 + j) if i > n - 1: i = int(i - n) v2[:n - i] = v[i:] v2[n - i:] = v[:i] return v2 def plegado(A, j): # Pliega la matriz de correlacion sobre la col j # A[i, j+1] -> (A[i,j+1] + A[i,j-1])/2 col = (A.shape[0], 1) flip = np.copy(A[:, :j]) for i in range(j): flip[:, i] = A[:, j - 1 - i] if A.shape[1] % 2 == 0: B = np.concatenate( ((A[:, j].reshape(col)), ((A[:, j + 1:-1] + flip) * .5), (A[:, -1].reshape(col))), axis=1) else: B = np.concatenate( ((A[:, j].reshape(col)), ((A[:, j + 1:] + flip) * .5)), axis=1) return B def CrossCorr(ROW): # fi = fi_rows[:,:,ROW] # time, chain c = xcm[:, :, ROW] # time, chain C = 0 * np.empty((Npr, Npr)) for i in range(Npr): sig_i = np.std(c[:, i]) c_i = c[:, i] - np.mean(c[:, i]) for j in range(i + 1): sig_j = np.std(c[:, j]) c_j = c[:, j] - np.mean(c[:, j]) C[i, j] = np.mean(c_i * c_j) / (sig_i * sig_j) C[j, i] = C[i, j] C_cent = np.empty((Npr, Npr)) for ch in range(Npr): C_cent[ch, :] = rot(C[ch, :], ch) return C_cent if Npr % 2 == 0: pleg_col = int(Npr / 2. - 1) else: pleg_col = int((Npr + 1) / 2.) Cross = 0 * np.empty((Npr, Npr, rows)) r2mean = np.mean(r2, axis=0) text_start = r"$\left\langle r^{{2}}\right\rangle_" fig, ax = plt.subplots(1, 1) for ROW in ROWLIST: Cross_ROW = CrossCorr(ROW) CrossPleg = plegado(Cross_ROW, pleg_col) CrossMean = np.mean(CrossPleg, axis=0) CrossErr = np.std(CrossPleg, axis=0) / (CrossMean.shape[0])**.5 vecinos = range(1, CrossMean[1:].size + 1) text = text_start + str(ROW) + r"={0:.2f}$".format(r2mean[ROW]) # ax.plot(vecinos, CrossMean[1:],'-o', ms=3, label=text) ax.errorbar(vecinos, CrossMean[1:], yerr=CrossErr[1:], capsize=5, fmt='-o', ms=3, label=text) ax.axhline(0, color='k') Cross[:, :, ROW] = Cross_ROW ax.legend() return ax, Cross
def plot_stripes_ROW(ROWLIST, SETTINGS): xcm, vcm, fi_rows, R, t, imap, rmap = slicer(SETTINGS) RUNS, ini, end, rows, Name = SETTINGS r2 = R * cj(R) T, Npr, rows = fi_rows.shape DAT = [RUNS, ini, end, rows, Name, T, Npr] cm2in = lambda w, h: (w / 2.54, h / 2.54) print(len(ROWLIST)) fig_pend, ax_pend = plt.subplots(len(ROWLIST), 1) cmap = create_custom_cmap() # np.save("matrix", matrix ) for index, ROW in enumerate(ROWLIST): matrix = fi_rows[:, :, ROW].T # (osc, time) # matrix[0,:] = 0*matrix[0,:] labeled, n_obj = find_stripes(matrix) pendientes = [] tiempos = [] color_bar_TRUE = True if color_bar_TRUE: fig, ax = plt.subplots(1, 2, gridspec_kw={'width_ratios': [9, 1]}) axim = ax[0] axcb = ax[1] else: fig, ax = plt.subplots(1, 1) axim = ax p = 1. fig.set_size_inches(cm2in(p * 12, p * 12), forward=True) extent = [t[0], t[-1], 0, Npr] implot = axim.imshow( matrix, interpolation='none', cmap=cmap, # cmap="gray", vmin=0, vmax=2 * np.pi, extent=extent, aspect='auto', origin='lower') ytick_labels = np.arange(0, Npr, 10) ytick_pos = np.arange(0, Npr, 10) + .5 axim.set_xlabel(r'$Nº\;Corrida \: [10^6 \: \Delta t ] $', fontsize=13) axim.set_ylabel('Oscilador', fontsize=13) axim.set_ylim([0, Npr]) axim.set_xlim([t[0], t[-1]]) axim.set_yticks(ytick_pos) axim.set_yticklabels(ytick_labels) # Colorbar if color_bar_TRUE: axcb.set_axis_off() cbar = fig.colorbar(implot, ax=axcb, fraction=1) ticks = (np.arange(0, 2.5, .5)) * np.pi cbar.set_ticks(ticks) cbar.set_ticklabels([ r"$0$", r"$\frac{\pi}{2}$", r"$\pi$", r"$\frac{3\pi}{2}$", r"$2\pi$" ]) fig.tight_layout() # Taking means centers = np.empty((labeled.shape[0], n_obj)) centers[:, :] = np.nan for obj in range(1, n_obj + 1): # objects start at 1 filt = labeled == obj obj_i = np.where(filt) length = len(set(np.transpose(obj_i)[:, 0])) if length > int(Npr * .6): # stripe-length % of system for fila in range(centers.shape[0]): centers[fila, obj - 1] = np.mean(t[filt[fila, :]]) center_obj = centers[:, obj - 1] nanfilt = ~np.isnan(center_obj) if any(nanfilt): cent = center_obj[nanfilt] vec = (np.arange(0, Npr) + .5)[nanfilt] P = np.polyfit(vec, cent, 1) pendientes.append(P[0] * 10**3) tiempos.append(np.mean(cent)) # axim.plot( cent, vec, color='xkcd:blue', marker='o', ms=3, ls='', lw=3, zorder=2 ) # axim.plot( np.polyval(P, np.arange(0,Npr+1) ), np.arange(0,Npr+1), color='xkcd:orange', lw=4, zorder=1 ) # for m in range(11): # axim.axhline( 18.2*m, color='xkcd:green' ) # axim.axhline( 100, color='xkcd:green' ) size_ = (11.2, 4.8) fig_pend.set_size_inches(cm2in(*size_), forward=True) if type(ax_pend) == np.ndarray: ax_pend_current_plot = ax_pend[index] ax_pend[int(len(ROWLIST) * .5)].set_ylabel(r'$a/v\;[10^6 \Delta t]$') ax_pend[-1].set_xlabel(r'$Nº\;Corrida \: [10^6 \: \Delta t ] $') else: ax_pend_current_plot = ax_pend ax_pend.set_ylabel(r'$a/v\;[10^6 \Delta t]$') ax_pend.set_xlabel(r'$Nº\;Corrida \: [10^6 \: \Delta t ] $') ax_pend_current_plot.plot(tiempos, pendientes, 'o', ms=1) ax_pend_current_plot.set_xlim([t[0], t[-1]]) ax_pend_current_plot.text(-0.10, 0.99, "$\\times 10^{-" + str(3) + "}$", fontsize=9, transform=plt.gca().transAxes) # ax_pend[1].plot(t,r2[:,ROW].real, lw=.5) # ax_pend[1].set_xlabel(r'$Corrida \: [10^6 \: \Delta t ] $') # ax_pend[1].set_ylabel(r'$r^2$') # ax_pend[1].set_xlim([t[0],t[-1]]) fig_pend.tight_layout() if not color_bar_TRUE: p = 1 fig.set_size_inches(cm2in(p * 16, p * 11)) fig.tight_layout() plots = ([fig, ax], [fig_pend, ax_pend]) # fig_pend.savefig('pendientes.png') # md.add_meta('pendientes.png', meta) return plots
def plot_fft_x(sample, SETTINGS): xcm, vcm, fi_rows, R, t, imap, rmap = slicer(SETTINGS) RUNS, ini, end, rows, Name = SETTINGS #loadargs( sys.argv[2:] ) T, Npr, rows = fi_rows.shape r2 = (R * cj(R)).real label_bp = r'$\left\langle r^{{2}}\right\rangle _{{{0}}}={1:.2f}$' r2mean = np.mean(r2, axis=0) fig, ax = plt.subplots(1, 1) # size_zoom = (12.3, 10) #(11,10) # size_ = size_zoom size_ = (16, 8) fig.set_size_inches(cm2in(*size_), forward=True) for ROW in range(rows): x = xcm[:, :, ROW] v = vcm[:, :, ROW] F = np.fft.rfft(x, axis=0) Fv = np.fft.rfft(v, axis=0) E = (F * np.conjugate(F)).real Ev = (Fv * np.conjugate(Fv)).real f = np.fft.rfftfreq(x.shape[0], d=1. / sample) # print( x.shape[0], f.shape ) meanE = np.mean(E, axis=1) meanEv = np.mean(Ev, axis=1) # ax.plot(f, meanE, label = "{0}".format(ROW)) # ax.plot(f, meanE, label = label_bp.format(ROW, r2mean[ROW])) # ax.set_xlim([27.25,30]) # ax.set_ylim([10**5, 10**9.5]) ax.set_xlabel(r'$f\;[\frac{10^{-6}}{\Delta t}]$', size=15) ax.set_ylabel(r'$\mathscr{F}\cdot\mathscr{F}^{\mathscr{*}}$', size=15) # print(ROW, f[ np.argmax(meanE) ] ) try: meanRow += meanE meanRowv += meanEv except: meanRow = meanE meanRowv = meanEv ax.plot( f, meanRow / rows, label= r"$\left\langle \left\Vert \mathscr{F}[X_{CM}]\right\Vert ^{2}\right\rangle$", zorder=1) ax.plot( f, meanRowv / rows, label= r"$\left\langle \left\Vert \mathscr{F}[V_{CM}]\right\Vert ^{2}\right\rangle$", zorder=0) ax.legend(fontsize=11) ax.set_yscale('log') fig.tight_layout() dat = [f, meanRow / ROW] return ax, dat