ax = plot_spectrum_hist(eigval, fig) print 'saving to ', outdir dio.ensure_dir(outdir + 'sumproj_dot_e_minus_e/' + series + '/') plt.savefig(outdir + 'sumproj_dot_e_minus_e/' + series + '/sumproj_dot_eigvect_minus_e_' + sumstr) plt.clf() # Save sumproj for later checking if it squares to unity pp2 = np.dot(sumproj, sumproj) - sumproj maxsumpp2 = max(maxsumpp2, np.max(np.abs(pp2))) plt.clf() # Make movies imgname = outdir + 'proj/' + series + '/proj_band' movname = outdir + 'proj_' + series lemov.make_movie(imgname, movname, indexsz='03', framerate=fr) imgname = outdir + 'proj_p2minusp/' + series + '/p2minusp_' movname = outdir + 'proj_p2minusp_' + series lemov.make_movie(imgname, movname, indexsz='03', framerate=fr) imgname = outdir + 'sumproj_dot_e/' + series + '/sumproj_dot_eigvect_bands0through' movname = outdir + 'sumproj_dot_e_' + series lemov.make_movie(imgname, movname, indexsz='03', framerate=fr) imgname = outdir + 'sumproj_dot_e_minus_e/' + series + '/sumproj_dot_eigvect_minus_e_bands0through' movname = outdir + 'sumproj_dot_e_minus_e_' + series lemov.make_movie(imgname, movname, indexsz='03', framerate=fr) imgname = outdir + 'sumproj_p2minusp/' + series + '/sumproj_p2minusp_bands0through' movname = outdir + 'sumproj_p2minusp_' + series
def dispersion_abtransition(lp, save_plots=True, return_omegas=False, abvals=None, fullspectrum=False): """ Parameters ---------- lp : dictionary lattice parameter dictionary return_omegas : bool Return a list of the frequencies in the dispersion abvals : n x 1 float array or list The Delta_AB values for each spectrum Returns ------- """ # prepare the values of inversion symmetry breaking if abvals is None: # abvals = np.arange(0, 2.4, 0.1) abvals = np.arange(0, 1.0, 0.025) # Prepare magnetic gyro lattice meshfn = le.find_meshfn(lp) lp['meshfn'] = meshfn lpmaster = copy.deepcopy(lp) # create a place to put images outdir = dio.prepdir( meshfn) + 'dispersion_abtransition_aol' + sf.float2pstr( lp['aoverl']) + '/' dio.ensure_dir(outdir) fs = 20 if return_omegas: omegas_out = [] kx_out = [] ky_out = [] # go through each ab and make the image ii = 0 for ab in abvals: lp = copy.deepcopy(lpmaster) lp['ABDelta'] = ab lat = lattice_class.Lattice(lp) lat.load(check=lp['check']) glat = MagneticGyroLattice(lat, lp) # glat.get_eigval_eigvect(attribute=True) fig, ax = leplt.initialize_portrait(ax_pos=[0.12, 0.2, 0.76, 0.6]) omegas, kx, ky = glat.infinite_dispersion(save=False, nkxvals=50, nkyvals=50, outdir=outdir, save_plot=False) if return_omegas: omegas_out.append(omegas) kx_out.append(kx) ky_out.append(ky) if save_plots: # plot and save it title = r'$\Delta_{AB} =$' + '{0:0.2f}'.format(ab) for jj in range(len(ky)): for kk in range(len(omegas[0, jj, :])): ax.plot(kx, omegas[:, jj, kk], 'k-', lw=max(0.5, 30. / (len(kx) * len(ky)))) ax.set_title(title, fontsize=fs) ax.set_xlabel(r'$k$ $[\langle \ell \rangle ^{-1}]$', fontsize=fs) ax.set_ylabel(r'$\omega$', fontsize=fs) for tick in ax.xaxis.get_major_ticks(): tick.label.set_fontsize(fs) for tick in ax.yaxis.get_major_ticks(): tick.label.set_fontsize(fs) if ii == 0: ylims = ax.get_ylim() if fullspectrum: ax.set_ylim(-ylims[1] * 1.2, ylims[1] * 1.2) else: ax.set_ylim(0., ylims[1] * 1.2) # Save it name = outdir + 'dispersion{0:04d}'.format(ii) plt.savefig(name + '.png', dpi=300) plt.close('all') ii += 1 # Save a movie of the dispersions movname = dio.prepdir( meshfn) + 'dispersion_abtrans' + glat.lp['meshfn_exten'] if save_plots: # Turn images into a movie imgname = outdir + 'dispersion' lemov.make_movie(imgname, movname, indexsz='04', framerate=4, imgdir=outdir, rm_images=True, save_into_subdir=True) if return_omegas: # Save the gap bounds and return the arrays of kx, ky, and omega omegas, kx, ky = np.array(omegas_out), np.array(kx_out), np.array( ky_out) # Get gap bounds: botmin = [] botmax = [] topmin = [] topmax = [] for band in omegas: botmin.append(np.min(band[:, :, 2])) botmax.append(np.max(band[:, :, 2])) topmin.append(np.min(band[:, :, 3])) topmax.append(np.max(band[:, :, 3])) botmin = np.array(botmin) botmax = np.array(botmax) topmin = np.array(topmin) topmax = np.array(topmax) gapbounds = np.dstack((abvals, botmin, botmax, topmin, topmax))[0] outfn = movname + '_gapbounds.txt' print 'saving to ', outfn header = 'Delta_AB, band min frequency, band max frequency, band 2 min, band 2 max...' np.savetxt(outfn, gapbounds, header=header) plot_gapbounds(abvals, gapbounds, movname + '_gapbounds.png', lp) return omegas, kx, ky else: return None
import glob import lepm.plotting.movies as lemov import lepm.plotting.plotting as leplt import subprocess dir = '/Users/npmitchell/Desktop/for_movie/' new_basename = 'image' # movframedir = dir[:-1] + '_mov/' ims = sorted(glob.glob(dir + '*.png')) ii = 0 for im in ims: basename = im.split('.png')[0].split('/')[-1][:-5] rootname = im.split(basename)[0] if basename != new_basename: newname = rootname + new_basename + '{0:05d}'.format(ii) + '.png' print 'moving ', im, ' to ', newname subprocess.call(['mv', im, newname]) # Place image on a canvas that is the correct size for making an ffmpeg movie # fig, ax, header_ax, header_cbar, ax_cbar = \ # leplt.initialize_landscape_with_header(preset_cbar=False, ax_pos=[0.0, 0.0, 1., 1.]) # imf = plt. # ax.imshow() ii += 1 imgname = rootname + new_basename movname = dir + 'twist_spring.mov' lemov.make_movie(imgname, movname, framerate=9)
def twistbcs(lp): """Load a periodic lattice from file, twist the BCs by phases theta_twist and phi_twist with vals finely spaced between 0 and 2pi. Then compute the berry curvature associated with |alpha(theta, phi)> Example usage: python haldane_lattice_class.py -twistbcs -N 3 -LT hexagonal -shape square -periodic Parameters ---------- lp Returns ------- """ lp['periodicBC'] = True meshfn = le.find_meshfn(lp) lp['meshfn'] = meshfn lat = lattice_class.Lattice(lp) lat.load() # Make a big array of the eigvals: N x N x thetav x phiv # thetav = np.arange(0., 2. * np.pi, 0.5) # phiv = np.arange(0., 2. * np.pi, 0.5) # First just test for two values of theta and two of phi thetav = [0., 0.01] phiv = [0., 0.01] eigvects = {} ii = 0 for theta in thetav: eigvects[ii] = {} jj = 0 for phi in phiv: lpnew = copy.deepcopy(lp) lpnew['theta_twist'] = theta lpnew['phi_twist'] = phi hlat = HaldaneLattice(lat, lpnew) ev, evec = hlat.get_eigval_eigvect(attribute=True) if ii == 0 and jj == 0: eigval = copy.deepcopy(ev) ill = hlat.get_ill() eigvects[ii][jj] = evec jj += 1 ii += 1 # Dot the derivs of eigvects together # Ensure that there is a nonzero-amplitude wannier with matching phase dtheta = eigvects[1][0] - eigvects[0][0] dphi = eigvects[0][1] - eigvects[0][0] thetamov_fn = dio.prepdir( hlat.lp['meshfn'] ) + 'twistbc_theta' + hlat.lp['meshfn_exten'] + '_dos_ev.mov' if not glob.glob(thetamov_fn): # Plot differences fig, DOS_ax, eig_ax = leplt.initialize_eigvect_DOS_header_plot( ev, hlat.lattice.xy, sim_type='haldane', colorV=ill, colormap='viridis', linewidth=0, cax_label=r'$\xi^{-1}$', cbar_nticks=2, xlabel_pad=10, ylabel_pad=10, cbar_tickfmt='%0.3f') DOS_ax.set_title(r'$\partial_\phi \psi$') hlat.lattice.plot_BW_lat(fig=fig, ax=eig_ax, save=False, close=False, axis_off=False, title='') outdir = dio.prepdir( hlat.lp['meshfn'] ) + 'twistbc_theta' + hlat.lp['meshfn_exten'] + '/' dio.ensure_dir(outdir) for ii in range(len(ev)): fig, [scat_fg, scat_fg2, p, f_mark, lines_12_st], cw_ccw = \ hlatpfns.construct_haldane_eigvect_DOS_plot(hlat.lattice.xy, fig, DOS_ax, eig_ax, eigval, dtheta, ii, hlat.lattice.NL, hlat.lattice.KL, marker_num=0, color_scheme='default', normalization=1.) print 'saving theta ', ii plt.savefig(outdir + 'dos_ev' + '{0:05}'.format(ii) + '.png') scat_fg.remove() scat_fg2.remove() p.remove() f_mark.remove() lines_12_st.remove() plt.close('all') imgname = outdir + 'dos_ev' movname = dio.prepdir( hlat.lp['meshfn'] ) + 'twistbc_theta' + hlat.lp['meshfn_exten'] + '_dos_ev' lemov.make_movie(imgname, movname, rm_images=False) phimov_fn = dio.prepdir( hlat.lp['meshfn'] ) + 'twistbc_phi' + hlat.lp['meshfn_exten'] + '_dos_ev.mov' if not glob.glob(phimov_fn): fig, DOS_ax, eig_ax = leplt.initialize_eigvect_DOS_header_plot( ev, hlat.lattice.xy, sim_type='haldane', colorV=ill, colormap='viridis', linewidth=0, cax_label=r'$\xi^{-1}$', cbar_nticks=2, xlabel_pad=10, ylabel_pad=10, cbar_tickfmt='%0.3f') DOS_ax.set_title(r'$\partial_\phi \psi$') outdir = dio.prepdir( hlat.lp['meshfn']) + 'twistbc_phi' + hlat.lp['meshfn_exten'] + '/' dio.ensure_dir(outdir) for ii in range(len(ev)): fig, [scat_fg, scat_fg2, p, f_mark, lines_12_st], cw_ccw = \ hlatpfns.construct_haldane_eigvect_DOS_plot(hlat.lattice.xy, fig, DOS_ax, eig_ax, eigval, dphi, ii, hlat.lattice.NL, hlat.lattice.KL, marker_num=0, color_scheme='default', normalization=1.) print 'saving phi ', ii plt.savefig(outdir + 'dos_ev' + '{0:05}'.format(ii) + '.png') scat_fg.remove() scat_fg2.remove() p.remove() f_mark.remove() lines_12_st.remove() plt.close('all') imgname = outdir + 'dos_ev' movname = dio.prepdir( hlat.lp['meshfn'] ) + 'twistbc_phi' + hlat.lp['meshfn_exten'] + '_dos_ev' lemov.make_movie(imgname, movname, rm_images=False) # Check # print 'shape(dtheta) = ', np.shape(dtheta) # print 'shape(dphi) = ', np.shape(dphi) # le.plot_complex_matrix(dtheta, show=True, name='dtheta') # le.plot_complex_matrix(dphi, show=True, name='dphi') fig, ax = leplt.initialize_nxmpanel_fig(4, 1, wsfrac=0.6, x0frac=0.3) # < dphi | dtheta > dpdt = np.einsum('ij...,ij...->i...', dtheta, dphi.conj()) # < dtheta | dphi > dtdp = np.einsum('ij...,ij...->i...', dphi, dtheta.conj()) print 'dtdp = ', dtdp ax[0].plot(np.arange(len(dtdp)), dtdp, '-') ax[1].plot(np.arange(len(dpdt)), dpdt, '-') hc = 2. * np.pi * 1j * (dpdt - dtdp) ax[2].plot(np.arange(len(lat.xy)), hc, '.-') # Plot cumulative sum sumhc = np.cumsum(hc) ax[3].plot(np.arange(len(lat.xy)), sumhc, '.-') ax[2].set_xlabel(r'Eigvect number') ax[0].set_ylabel( r'$\langle \partial_{\theta} \alpha_i | \partial_{\phi} \alpha_i \rangle$' ) ax[2].set_xlabel(r'Eigvect number') ax[1].set_ylabel( r'$\langle \partial_{\phi} \alpha_i | \partial_{\theta} \alpha_i \rangle$' ) ax[2].set_xlabel(r'Eigvect number') ax[2].set_ylabel(r'$c_H$') ax[3].set_xlabel(r'Eigvect number') ax[3].set_ylabel(r'$\sum_{E_\alpha < E_c} c_H$') outdir = '/Users/npmitchell/Dropbox/Soft_Matter/GPU/twistbc_test/' dio.ensure_dir(outdir) print 'saving ', outdir + 'test' + hlat.lp['meshfn_exten'] + '.png' plt.savefig(outdir + 'test' + hlat.lp['meshfn_exten'] + '.png') # ### Now do the same thing but with different values of theta, phi # First just test for two values of theta and two of phi thetav = [1., 1.01] phiv = [1., 1.01] eigvects = {} ii = 0 for theta in thetav: eigvects[ii] = {} jj = 0 for phi in phiv: lpnew = copy.deepcopy(lp) lpnew['theta_twist'] = theta lpnew['phi_twist'] = phi hlat = HaldaneLattice(lat, lpnew) ev, evec = hlat.get_eigval_eigvect(attribute=True) if ii == 0 and jj == 0: eigval = copy.deepcopy(ev) ill = hlat.get_ill() eigvects[ii][jj] = evec jj += 1 ii += 1 # Dot the derivs of eigvects together dtheta = eigvects[1][0] - eigvects[0][0] dphi = eigvects[0][1] - eigvects[0][0] # Plot differences thetamov_fn = dio.prepdir( hlat.lp['meshfn'] ) + 'twistbc_theta' + hlat.lp['meshfn_exten'] + '_dos_ev.mov' if not glob.glob(thetamov_fn): fig, DOS_ax, eig_ax = leplt.initialize_eigvect_DOS_header_plot( ev, hlat.lattice.xy, sim_type='haldane', colorV=ill, colormap='viridis', linewidth=0, cax_label=r'$\xi^{-1}$', cbar_nticks=2, xlabel_pad=10, ylabel_pad=10, cbar_tickfmt='%0.3f') DOS_ax.set_title(r'$\partial_\theta \psi$') hlat.lattice.plot_BW_lat(fig=fig, ax=eig_ax, save=False, close=False, axis_off=False, title='') outdir = dio.prepdir( hlat.lp['meshfn'] ) + 'twistbc_theta' + hlat.lp['meshfn_exten'] + '/' dio.ensure_dir(outdir) for ii in range(len(ev)): fig, [scat_fg, scat_fg2, p, f_mark, lines_12_st], cw_ccw = \ hlatpfns.construct_haldane_eigvect_DOS_plot(hlat.lattice.xy, fig, DOS_ax, eig_ax, eigval, dtheta, ii, hlat.lattice.NL, hlat.lattice.KL, marker_num=0, color_scheme='default', normalization=1.) print 'saving theta ', ii plt.savefig(outdir + 'dos_ev' + '{0:05}'.format(ii) + '.png') scat_fg.remove() scat_fg2.remove() p.remove() f_mark.remove() lines_12_st.remove() plt.close('all') imgname = outdir + 'dos_ev' movname = dio.prepdir( hlat.lp['meshfn'] ) + 'twistbc_theta' + hlat.lp['meshfn_exten'] + '_dos_ev' lemov.make_movie(imgname, movname, rm_images=False) # Now do phi phimov_fn = dio.prepdir( hlat.lp['meshfn'] ) + 'twistbc_phi' + hlat.lp['meshfn_exten'] + '_dos_ev.mov' if not glob.glob(phimov_fn): fig, DOS_ax, eig_ax = leplt.initialize_eigvect_DOS_header_plot( ev, hlat.lattice.xy, sim_type='haldane', colorV=ill, colormap='viridis', linewidth=0, cax_label=r'$\xi^{-1}$', cbar_nticks=2, xlabel_pad=10, ylabel_pad=10, cbar_tickfmt='%0.3f') DOS_ax.set_title(r'$\partial_\phi \psi$') hlat.lattice.plot_BW_lat(fig=fig, ax=eig_ax, save=False, close=False, axis_off=False, title='') outdir = dio.prepdir( hlat.lp['meshfn']) + 'twistbc_phi' + hlat.lp['meshfn_exten'] + '/' dio.ensure_dir(outdir) for ii in range(len(ev)): fig, [scat_fg, scat_fg2, p, f_mark, lines_12_st], cw_ccw = \ hlatpfns.construct_haldane_eigvect_DOS_plot(hlat.lattice.xy, fig, DOS_ax, eig_ax, eigval, dphi, ii, hlat.lattice.NL, hlat.lattice.KL, marker_num=0, color_scheme='default', normalization=1.) print 'saving phi ', ii plt.savefig(outdir + 'dos_ev' + '{0:05}'.format(ii) + '.png') scat_fg.remove() scat_fg2.remove() p.remove() f_mark.remove() lines_12_st.remove() plt.close('all') imgname = outdir + 'dos_ev' movname = dio.prepdir( hlat.lp['meshfn'] ) + 'twistbc_phi' + hlat.lp['meshfn_exten'] + '_dos_ev' lemov.make_movie(imgname, movname, rm_images=False) # Check # print 'shape(dtheta) = ', np.shape(dtheta) # print 'shape(dphi) = ', np.shape(dphi) # le.plot_complex_matrix(dtheta, show=True, name='dtheta') # le.plot_complex_matrix(dphi, show=True, name='dphi') fig, ax = leplt.initialize_nxmpanel_fig(4, 1, wsfrac=0.6, x0frac=0.3) # < dphi | dtheta > dpdt = np.einsum('ij...,ij...->i...', dtheta, dphi.conj()) # < dtheta | dphi > dtdp = np.einsum('ij...,ij...->i...', dphi, dtheta.conj()) print 'dtdp = ', dtdp ax[0].plot(np.arange(len(dtdp)), dtdp, '-') ax[1].plot(np.arange(len(dpdt)), dpdt, '-') hc = 2. * np.pi * 1j * (dpdt - dtdp) ax[2].plot(np.arange(len(lat.xy)), hc, '.-') # Plot cumulative sum sumhc = np.cumsum(hc) ax[3].plot(np.arange(len(lat.xy)), sumhc, '.-') ax[2].set_xlabel(r'Eigvect number') ax[0].set_ylabel( r'$\langle \partial_{\theta} \alpha_i | \partial_{\phi} \alpha_i \rangle$' ) ax[2].set_xlabel(r'Eigvect number') ax[1].set_ylabel( r'$\langle \partial_{\phi} \alpha_i | \partial_{\theta} \alpha_i \rangle$' ) ax[2].set_xlabel(r'Eigvect number') ax[2].set_ylabel(r'$c_H$') ax[3].set_xlabel(r'Eigvect number') ax[3].set_ylabel(r'$\sum_{E_\alpha < E_c} c_H$') outdir = '/Users/npmitchell/Dropbox/Soft_Matter/GPU/twistbc_test/' dio.ensure_dir(outdir) plt.savefig(outdir + 'test' + hlat.lp['meshfn_exten'] + '_theta1p0.png') sys.exit() ######################################## # Now test for more theta values, more phi values thetav = np.arange(0., 0.14, 0.1) phiv = np.arange(0., 0.14, 0.1) eigvects = np.zeros((len(lat.xy), len(lat.xy), len(thetav), len(phiv)), dtype=complex) ii = 0 for theta in thetav: jj = 0 for phi in phiv: lpnew = copy.deepcopy(lp) lpnew['theta_twist'] = theta lpnew['phi_twist'] = phi hlat = HaldaneLattice(lat, lpnew) ev, evec = hlat.get_eigval_eigvect() eigvects[:, :, ii, jj] = evec jj += 1 ii += 1 # Dot the derivs of eigvects together print 'eigvects = ', eigvects dtheta = np.diff(eigvects, axis=2) dphi = np.diff(eigvects, axis=3) print 'dtheta = ', dtheta print 'shape(dtheta) = ', np.shape(dtheta) print 'shape(dphi) = ', np.shape(dphi) le.plot_complex_matrix(dtheta[:, :, 0, 0], show=True) le.plot_complex_matrix(dphi[:, :, 0, 0], show=True) dtheta = dtheta[:, :, :, 0:np.shape(dtheta)[3] - 1] dphi = dphi[:, :, 0:np.shape(dphi)[2] - 1, :] print 'shape(dtheta) = ', np.shape(dtheta) print 'shape(dphi) = ', np.shape(dphi) for ii in range(np.shape(dtheta)[-1]): le.plot_complex_matrix(dtheta[:, :, ii, 0], show=True) fig, ax = leplt.initialize_nxmpanel_fig(3, 1) for ii in range(np.shape(dphi)[-1]): for jj in range(np.shape(dphi)[-1]): # < dphi | dtheta > dpdt = np.dot(dtheta[:, :, ii, jj], dphi[:, :, ii, jj].conj().T) # < dtheta | dphi > dtdp = np.dot(dphi[:, :, ii, jj], dtheta[:, :, ii, jj].conj().T) print 'np.shape(dpdt) = ', np.shape(dpdt) print 'np.shape(dtdp) = ', np.shape(dtdp) ax[0].plot(np.arange(len(dtdp)), dtdp, '-') ax[1].plot(np.arange(len(dpdt)), dpdt, '-') hc = 2. * np.pi * 1j * (dpdt - dtdp) ax[2].plot(np.arange(len(lat.xy)), hc, '.-') ax[0].set_xlabel(r'$\theta$') ax[0].set_ylabel( r'$\langle \partial_{\theta} \alpha_i | \partial_{\phi} \alpha_i \rangle$' ) ax[1].set_xlabel(r'$\phi$') ax[1].set_ylabel( r'$\langle \partial_{\phi} \alpha_i | \partial_{\theta} \alpha_i \rangle$' ) ax[2].set_xlabel(r'Eigvect number') ax[2].set_ylabel(r'$\partial_{\phi} \alpha_i$') plt.show()
def make_mode_movie(seriesdir, amp=50, semilog=True, freqmin=None, freqmax=None, overwrite=False, percent_max=0.01): """ Parameters ---------- seriesdir : str The full path to the directory with all tracked cines for which to make mode decomposition movies amp : float The amplification factor for the displacements in the movie output semilog : bool plot the FFT intensity vs frequency in log-normal scale freqmin : float The minimum frequency to plot freqmax : float The maximum frequency to plot overwrite : bool Overwrite the saved images/movies if they exist Returns ------- """ pathlist = dio.find_subdirs('20*', seriesdir) freqstr = '' if freqmin is not None: freqstr += '_minfreq' + sf.float2pstr(freqmin) if freqmax is not None: freqstr += '_maxfreq' + sf.float2pstr(freqmax) for path in pathlist: movname = path + 'modes_amp{0:0.1f}'.format(amp).replace( '.', 'p') + freqstr + '.mov' movexist = glob.glob(movname) print 'mode_movie: movexist = ', movexist if not movexist or overwrite: # If the movie does not exist yet, make it here print 'building modes for ', path fn = os.path.join(path, 'com_data.hdf5') print 'mode_drawing_functions.mode_movie.make_mode_movie(): loading data from ', fn data = new_mf.load_linked_data_and_window(fn) tp, fft_x, fft_y, freq = nmf.ffts_and_add(data) high_power_inds = nmf.find_peaks(tp, percent_max=percent_max) # Check how many mode images have been done modespngs = glob.glob(path + 'modes' + freqstr + '/*.png') modespngs_traces = glob.glob(path + 'modes_traces' + freqstr + '/*.png') # If we haven't made images of all the modes, do that here print 'mode_movie.make_mode_movie(): len(modespngs) = ', len( modespngs) print 'mode_movie.make_mode_movie(): len(high_power_inds) = ', len( high_power_inds) if len(modespngs) < len(high_power_inds) or overwrite: # Check if mode pickle is saved modesfn_traces = path + 'modes_trackes' + freqstr + '.pkl' globfn = glob.glob(modesfn_traces) if globfn: with open(globfn[0], "rb") as fn: mode_data = cPickle.load(fn) coords = mode_data['xy'] mode_data = dh.removekey(mode_data, 'xy') for i in mode_data: if i % 10 == 0: print 'mode_movie.make_mode_movie(): Creating mode image #', i x_traces = mode_data[i][ 'x_traces'] # sf.float2pcstr(freq[high_power_inds[i]], ndigits=8)] y_traces = mode_data[i]['y_traces'] fig = sps.figure_in_mm(120, 155) ax_mode = sps.axes_in_mm(10, 10, 100, 100) ax_freq = sps.axes_in_mm(10, 120, 100, 30) axes = [ax_mode, ax_freq] new_mf.draw_mode(x_traces, y_traces, coords, [freq, tp], axes, i, freq[high_power_inds[i]], output_dir=os.path.join( path, 'modes'), amp=amp, semilog=semilog) else: # The mode data is not saved, so we must create it as we go along # data = new_mf.load_linked_data_and_window(fn) coords = np.array([data[2], data[3]]).T for i in xrange(len(high_power_inds)): if i % 10 == 0: print 'mode_movie.make_mode_movie(): Creating mode image #', i x_traces, y_traces, max_mag = new_mf.get_mode_drawing_data( fft_x, fft_y, freq, high_power_inds[i]) x_traces = np.array(x_traces) y_traces = np.array(y_traces) fig = sps.figure_in_mm(120, 155) ax_mode = sps.axes_in_mm(10, 10, 100, 100) ax_freq = sps.axes_in_mm(10, 120, 100, 30) axes = [ax_mode, ax_freq] new_mf.draw_mode(x_traces, y_traces, coords, [freq, tp], axes, i, freq[high_power_inds[i]], output_dir=os.path.join( path, 'modes'), amp=amp, semilog=semilog) # Obtain imagename and moviename, create movie if it doesn't exist modesfn = glob.glob(path + 'modes' + freqstr + '/*.png') imagename_split = modesfn[0].split('/')[-1].split('.png')[0] try: test = int(imagename_split) indexsz = len(imagename_split) imgname = path + 'modes' + freqstr + '/' except: print 'mode_movie.make_mode_movie(): imagename_split = ', imagename_split print 'mode_movie.make_mode_movie(): indexsz = ', len( imagename_split) raise RuntimeError( 'Imagename is not just an int -- write code to allow ') movies.make_movie(imgname, movname, indexsz=str(indexsz), framerate=10)
def movie_varyDeltaAB(t1, t2, dab_arr, nx, ny, maindir, outdir, fontsize=20, tick_fontsize=16, saveims=True, dual_panel=False, color_berry=False, cmap='coolwarm', vmin=0.49, vmax=0.51, plot3d=False): """Create a movie of band structure with varying DeltaAB Parameters ---------- t1 : float magnitude of real NN hopping t2 : float magnitude of complex NNN hopping dab_arr : n x 1 float array the DeltaAB values to use for each frame nn : int number of kx values (same as # ky values) maindir : str where to save the movie outdir : str where to save the images saveims : bool overwrite the existing images dual_panel : bool plot the 2d dispersion with calibration of gap opening as function of DeltaAB vmin : float the minimimum color value from 0 to 1, if color_berry=True vmax : float the maximum color value from 0 to 1, if color_berry = True plot3d : bool whether to plot the dispersion in 3d or not """ if isinstance(cmap, str): cmap = lecmaps.ensure_cmap(cmap) kk = 0 gaps = [] dabs = [] for mm in dab_arr: if color_berry: km, kv, energy1, energy2, berry1, berry2 = haldane_dispersion_berry( nx, ny, t1, t2, mm) else: km, kv, energy1, energy2 = haldane_dispersion(nx, ny, t1, t2, mm) gap = np.min(energy1) * 2. print 'gap = ', gap gaps.append(gap) dabs.append(mm) if saveims: if not plot3d: if dual_panel: fig, ax = leplt.initialize_2panel_3o4ar_cent( fontsize=fontsize, x0frac=0.085) ax, ax2 = ax[0], ax[1] # Make second figure ax2.plot() ax2.set_xlim(0, 0.2) ax2.set_ylim(0, 0.7) ax2.plot([np.min(t2arr), np.max(t2arr)], [0.0, 2 * np.max(t2arr)], '-', color='#a1bfdb', lw=3) ax2.scatter(dabs, gaps, color='k', zorder=9999999999) title = 'Gap size: ' + r'$\Delta\omega/t_1 \approx 2 \, \Delta_{AB}$' ax2.text(0.5, 1.1, title, ha='center', va='center', fontsize=fontsize, transform=ax2.transAxes) for tick in ax2.xaxis.get_major_ticks(): tick.label.set_fontsize(tick_fontsize) for tick in ax2.yaxis.get_major_ticks(): tick.label.set_fontsize(tick_fontsize) ax2.set_xlabel(r'$t_2 = \Omega_k^2/8\Omega_g$', fontsize=fontsize, labelpad=15) ax2.set_ylabel( r'$\Delta\omega/t_1 = 2 \Delta\omega/\Omega_k$', fontsize=fontsize, rotation=90, labelpad=35) else: fig, ax = leplt.initialize_1panel_centered_fig( Wfig=180, Hfig=180, wsfrac=0.7, fontsize=fontsize) if not color_berry: # check if topological or not print 't2 = ', t2 print 'mm = ', mm * (3. * np.sqrt(3.)) if t2 > mm / np.sqrt(3.): # yes, topological ax.plot(km[1], energy1.reshape(np.shape(km[0])), '-', color=band1color) ax.plot(km[1], energy2.reshape(np.shape(km[0])), '-', color=band2color) elif t2 < -mm / np.sqrt(3.): # flipped topology ax.plot(km[1], energy1.reshape(np.shape(km[0])), '-', color=band2color) ax.plot(km[1], energy2.reshape(np.shape(km[0])), '-', color=band1color) else: # not topological ax.plot(km[1], energy1.reshape(np.shape(km[0])), '-', color=graycolor) ax.plot(km[1], energy2.reshape(np.shape(km[0])), '-', color=graycolor) else: b1color = berry1.reshape(np.shape( km[0])) / (2. * np.pi) + 0.5 b2color = berry2.reshape(np.shape( km[0])) / (2. * np.pi) + 0.5 energy1 = energy1.reshape(np.shape(km[0])) energy2 = energy2.reshape(np.shape(km[0])) # ax.scatter([0., 0.5, 1.0], [0., 0.5, 1.0], c=[0., 0.5, 1.0], edgecolor='none', cmap=cmap, alpha=1) for ii in range(len(km[0])): ax.scatter(km[1][ii], energy1[ii], c=b1color[ii], edgecolor='none', cmap=cmap, alpha=0.1, vmin=vmin, vmax=vmax) ax.scatter(km[1][ii], energy2[ii], c=b2color[ii], edgecolor='none', cmap=cmap, alpha=0.1, vmin=vmin, vmax=vmax) plt.show() sys.exit() ax.set_ylabel(r'$\omega$', labelpad=15, fontsize=fontsize, rotation=0) # title = r'$\Delta \omega =$' + '{0:0.3f}'.format(gap) + r' $t_1$' title = r'$t_2 =$' + '{0:0.3f}'.format(t2) + r' $t_1$, ' + \ r'$\Delta_{AB} =$' + '{0:0.3f}'.format(mm) + r' $t_1$' ax.text(0.5, 1.1, title, ha='center', va='center', fontsize=fontsize, transform=ax.transAxes) else: # Plot it in 3d fig, ax = leplt.initialize_1panel_centered_fig( Wfig=180, Hfig=180, wsfrac=0.7, fontsize=fontsize) ax = fig.gca(projection='3d') # Reshape colors, energies b1color = cmap((berry1.reshape(np.shape(km[0])) / (2. * np.pi)) / (vmax - vmin) + 0.5) b2color = cmap((berry2.reshape(np.shape(km[0])) / (2. * np.pi)) / (vmax - vmin) + 0.5) energy1 = energy1.reshape(np.shape(km[0])) energy2 = energy2.reshape(np.shape(km[0])) print 'b1color = ', b1color # Plot surfaces surf = ax.plot_surface(km[0], km[1], energy1, facecolors=b1color, rstride=1, cstride=1, vmin=vmin, vmax=vmax, cmap=cmap, linewidth=1, antialiased=False) surf = ax.plot_surface(km[0], km[1], energy2, facecolors=b2color, rstride=1, cstride=1, vmin=vmin, vmax=vmax, cmap=cmap, linewidth=1, antialiased=False) ax.set_ylabel(r'$k_y$', labelpad=15, fontsize=fontsize) ax.yaxis.set_ticks([-np.pi, 0, np.pi]) ax.yaxis.set_ticklabels([r'-$\pi$', 0, r'$\pi$'], fontsize=tick_fontsize) for tick in ax.xaxis.get_major_ticks(): tick.label.set_fontsize(tick_fontsize) ax.set_zlabel(r'$\omega$', labelpad=15, fontsize=fontsize, rotation=90) # ax.zaxis.set_ticks([-np.pi, 0, np.pi]) # ax.zaxis.set_ticklabels([r'-$\pi$', 0, r'$\pi$'], fontsize=tick_fontsize) for tick in ax.zaxis.get_major_ticks(): tick.label.set_fontsize(tick_fontsize) ax.axis('scaled') ax.set_zlim(-np.pi, np.pi) ax.set_xlabel(r'$k_x$', labelpad=15, fontsize=fontsize) ax.xaxis.set_ticks([-np.pi, 0, np.pi]) ax.xaxis.set_ticklabels([r'-$\pi$', 0, r'$\pi$'], fontsize=tick_fontsize) for tick in ax.yaxis.get_major_ticks(): tick.label.set_fontsize(tick_fontsize) ax.axis('scaled') ax.set_xlim(-np.pi, np.pi) ax.set_ylim(-np.pi, np.pi) # Save it plt.savefig(outdir + 'dispersion_{0:04d}'.format(kk) + '.png'.format(t2), dpi=140) plt.close('all') kk += 1 print 'dirac = ', 2. * np.pi / 3., ', ', -2. * np.pi / ( 3. * np.sqrt(3.)) ind = np.argmin(energy1) dirac = kv[ind] print 'dirac where = ', dirac # print the fitting print 'dabs = ', dabs print 'gaps = ', gaps zz = np.polyfit(np.array(dabs), np.array(gaps), 1) pp = np.poly1d(zz) print 'pp = ', pp print 'zz[0] = ', zz[0] print 'zz[1] = ', zz[1] imgname = outdir + 'dispersion_' movname = maindir + 'dispersion_varyDeltaAB_{0:0.3f}'.format(t2).replace( '.', 'p') movname += '_nkx{0:06d}'.format(nx) + '_nky{0:06d}'.format(ny) lemov.make_movie(imgname, movname, indexsz='04', framerate=15)
hccollcoll.add_haldane_chern_collection(hccoll, lppval) print 'Plotting chern collection for hlatparam: ', args.hlatparam, '=', lppval title = r'Spatially-resolved Chern number, with $\Delta$ = ' + '{0:0.2f}'.format(lppval) hccoll.plot_cherns_varyloc(title=title, filename=stillname + '_{0:04d}'.format(ind), rootdir='auto', outdir=dio.prepdir(imgdir), exten='.png', max_boxfrac=None, max_boxsize=None, xlabel=None, ylabel=None, step=1.0, fracsteps=False, ax=None, cbar_ax=None, singleksz_frac=args.singleksz_frac, singleksz=args.singleksz, maxchern=args.maxchern, save=True, make_cbar=True, colorz=False, dpi=500) ind += 1 import lepm.plotting.movies as lemov movname = outdir + stillname + '_varyhlatparam_' + str(args.lpparam) + '_lenlppV' + str(len(paramV)) lemov.make_movie(imgdir + stillname + '_', movname, indexsz='04', framerate=2, imgdir=imgdir) with open(pklfn, "wb") as fn: pkl.dump(hccollcoll, fn) if args.plot_varyhlatparam_avgloc: """Print images of the averages of the chern 2D images (hlatparam vs ksize) over many spatially-varying voxels. This would be useful, for ex, for plotting ABDelta phase diagrams. Since we are varying hlatparam here, we are NOT changing the lattice used, just the HaldaneLattice. Example usage: python haldane_chern_collection_collection.py -LT hucentroid -N 20 -Nks 110 -plot_varyhlatparam_avgloc -hlatparam ABDelta -paramV 0.0:0.1:1.0 -locV n1.0:1.0 python haldane_chern_collection_collection.py -LT hucentroid -N 30 -Nks 201 -plot_varyhlatparam_avgloc -hlatparam ABDelta -paramV 0.0:0.1:1.0 -locV n1.0:1.0 """ import lepm.plotting.haldane_chern_plotting_functions as kpfns meshfn = le.find_meshfn(lp)
def movie_varyt2(t1, t2arr, mm, nx, ny, maindir, outdir, fontsize=20, tick_fontsize=16, saveims=True, dual_panel=False, color_berry=False, cmap='bbr0', vmin=0.499, vmax=0.501, plot3d=False): """Plot the band structure of the haldane model as we vary the NNN hopping Parameters ---------- t1 : float magnitude of real NN hopping t2 : float magnitude of complex NNN hopping dab_arr : n x 1 float array the DeltaAB values to use for each frame nn : int number of kx values (same as # ky values) maindir : str where to save the movie outdir : str where to save the images saveims : bool overwrite the existing images dual_panel : bool plot the 2d dispersion with calibration of gap opening as function of DeltaAB vmin : float the minimimum color value from 0 to 1, if color_berry=True vmax : float the maximum color value from 0 to 1, if color_berry = True plot3d : bool whether to plot the dispersion in 3d or not """ kk = 0 gaps = [] t2s = [] if isinstance(cmap, str): cmap = lecmaps.ensure_cmap(cmap) for t2 in t2arr: if color_berry: km, kv, energy1, energy2, berry1, berry2 = haldane_dispersion_berry( nx, t1, t2, mm) else: km, kv, energy1, energy2 = haldane_dispersion(nx, ny, t1, t2, mm) gap = np.min(energy1) * 2. print 'gap = ', gap gaps.append(gap) t2s.append(t2) if saveims: if dual_panel: fig, ax = leplt.initialize_2panel_3o4ar_cent(fontsize=fontsize, x0frac=0.085) ax, ax2 = ax[0], ax[1] else: fig, ax = leplt.initialize_1panel_centered_fig( Wfig=180, Hfig=180, wsfrac=0.7, fontsize=fontsize) if not color_berry: if t2 > mm / np.sqrt(3.): ax.plot(km[1], energy1.reshape(np.shape(km[0])), '-', color=band1color) ax.plot(km[1], energy2.reshape(np.shape(km[0])), '-', color=band2color) elif t2 < -mm / np.sqrt(3.): ax.plot(km[1], energy1.reshape(np.shape(km[0])), '-', color=band2color) ax.plot(km[1], energy2.reshape(np.shape(km[0])), '-', color=band1color) else: ax.plot(km[1], energy1.reshape(np.shape(km[0])), '-', color=graycolor) ax.plot(km[1], energy2.reshape(np.shape(km[0])), '-', color=graycolor) else: b1color = berry1.reshape(np.shape(km[0])) / (2. * np.pi) + 0.5 b2color = berry2.reshape(np.shape(km[0])) / (2. * np.pi) + 0.5 print 'b1color=', b1color # sys.exit() energy1 = energy1.reshape(np.shape(km[0])) energy2 = energy2.reshape(np.shape(km[0])) # ax.scatter([0., 0.5, 1.0], [0., 0.5, 1.0], c=[0., 0.5, 1.0], edgecolor='none', cmap=cmap, alpha=1) for ii in range(len(km[0])): ax.scatter(km[1][ii], energy1[ii], c=b1color, edgecolor='none', cmap=cmap, alpha=1., vmin=vmin, vmax=vmax) ax.scatter(km[1][ii], energy2[ii], c=b2color, edgecolor='none', cmap=cmap, alpha=1., vmin=vmin, vmax=vmax) # plt.show() # sys.exit() ax.set_xlabel(r'$k_x$', labelpad=15, fontsize=fontsize) ax.set_ylabel(r'$\omega$', labelpad=15, fontsize=fontsize, rotation=0) ax.xaxis.set_ticks([-np.pi, 0, np.pi]) ax.xaxis.set_ticklabels([r'-$\pi$', 0, r'$\pi$'], fontsize=tick_fontsize) for tick in ax.yaxis.get_major_ticks(): tick.label.set_fontsize(tick_fontsize) ax.axis('scaled') ax.set_xlim(-np.pi, np.pi) ax.set_ylim(-np.pi, np.pi) # title = r'$\Delta \omega =$' + '{0:0.3f}'.format(gap) + r' $t_1$' title = r'$t_2 =$' + '{0:0.3f}'.format(t2) + r' $t_1$, ' + \ r'$\Delta_{AB} =$' + '{0:0.3f}'.format(mm) + r' $t_1$' ax.text(0.5, 1.1, title, ha='center', va='center', fontsize=fontsize, transform=ax.transAxes) if dual_panel: # Make second figure ax2.plot() ax2.set_xlim(0, 0.2) ax2.set_ylim(0, 0.7) ax2.plot([np.min(t2arr), np.max(t2arr)], [0.0, 3.36864398885 * np.max(t2arr)], '-', color='#a1bfdb', lw=3) ax2.scatter(t2s, gaps, color='k', zorder=9999999999) title = 'Gap size: ' + r'$\Delta\omega/t_1 \approx 3.369\, t_2$' ax2.text(0.5, 1.1, title, ha='center', va='center', fontsize=fontsize, transform=ax2.transAxes) for tick in ax2.xaxis.get_major_ticks(): tick.label.set_fontsize(tick_fontsize) for tick in ax2.yaxis.get_major_ticks(): tick.label.set_fontsize(tick_fontsize) ax2.set_xlabel(r'$t_2 = \Omega_k^2/8\Omega_g$', fontsize=fontsize, labelpad=15) ax2.set_ylabel(r'$\Delta\omega/t_1 = 2 \Delta\omega/\Omega_k$', fontsize=fontsize, rotation=90, labelpad=35) # Save the image plt.savefig(outdir + 'dispersion_{0:04d}'.format(kk) + '.png', dpi=140) plt.close('all') kk += 1 print 'dirac = ', 2. * np.pi / 3., ', ', -2. * np.pi / ( 3. * np.sqrt(3.)) ind = np.argmin(energy1) dirac = kv[ind] print 'dirac where = ', dirac print 't2s = ', t2s print 'gaps = ', gaps zz = np.polyfit(np.array(t2s), np.array(gaps), 1) pp = np.poly1d(zz) print pp print zz[0] print zz[1] imgname = outdir + 'dispersion_' movname = maindir + 'dispersion_varyt2' movname += '_nkx{0:06d}'.format(nx) + '_nky{0:06d}'.format(ny) lemov.make_movie(imgname, movname, indexsz='04', framerate=15)
def polygon_phases_tune_junction(lp, args, nmode=None): """Plot the phase differences ccw around each polygon in the network for many glats as junction coupling is increased. Do this for the nth mode as the scaling parameter evolves (typically the bond strength between particles that are nearer than some threshold). Example usage: python gyro_lattice_class.py -polygon_phases_tune_junction -LT hexjunction2triads -N 1 -OmKspec union0p000in0p100 -alph 0.1 -periodic python gyro_lattice_class.py -polygon_phases_tune_junction -LT spindle -N 2 -OmKspec union0p000in0p100 -alph 0.0 -periodic -aratio 0.1 python gyro_lattice_class.py -polygon_phases_tune_junction -LT spindle -N 4 -OmKspec union0p000in0p100 -alph 0.0 -periodic -aratio 0.1 # for making lattices python ./build/make_lattice.py -LT spindle -N 4 -periodic -skip_gyroDOS -aratio 0.1 Parameters ---------- lp args nmode : int, int list, or None Returns ------- """ cmap = lecmaps.ensure_cmap('bbr0') nkvals = 50 if lp['LatticeTop'] in ['hexjunctiontriad', 'spindle', 'hexjunction2triads']: kvals = -np.unique(np.round(np.logspace(-1, 1., nkvals), 2)) # [::-1] dist_thres = lp['OmKspec'].split('union')[-1].split('in')[-1] lpmaster = copy.deepcopy(lp) lat = lattice_class.Lattice(lp) lat.load() if nmode is None: todo = np.arange(len(lat.xy[:, 0])) elif type(nmode) == int: todo = [nmode] else: todo = nmode ########################################################################## # First collect eigenvalue flow eigvals, first = [], True for (kval, dmyi) in zip(kvals, np.arange(len(kvals))): lp = copy.deepcopy(lpmaster) lp['OmKspec'] = 'union' + sf.float2pstr(kval, ndigits=3) + 'in' + dist_thres # lat = lattice_class.Lattice(lp) glat = GyroLattice(lat, lp) eigval, eigvect = glat.eig_vals_vects(attribute=True) if first: eigvals = np.zeros((len(kvals), len(eigval)), dtype=float) eigvals[dmyi, :] = np.imag(eigval) first = False ########################################################################## lp = copy.deepcopy(lpmaster) glat = GyroLattice(lat, lp) # add meshfn without OmKspecunion part mfe = glat.lp['meshfn_exten'] if mfe[0:13] == '_OmKspecunion': meshfnextenstr = mfe.split(mfe.split('_')[1])[-1] else: raise RuntimeError('Handle this case here -- should be easy: split meshfn_exten to pop OmKspec out') for ii in todo[::-1]: modefn = dio.prepdir(lat.lp['meshfn']) + 'glat_mode_phases_scaling_tune_junction_mode{0:05d}'.format(ii) +\ meshfnextenstr + '_nkvals{0:04}'.format(nkvals) + '.mov' globmodefn = glob.glob(modefn) if not globmodefn: modedir = dio.prepdir(lat.lp['meshfn']) + 'glat_mode_phases_tune_junction_mode{0:05d}'.format(ii) + \ meshfnextenstr + '/' dio.ensure_dir(modedir) previous_ev = None first = True dmyi = 0 for kval in kvals: lp = copy.deepcopy(lpmaster) lp['OmKspec'] = 'union' + sf.float2pstr(kval, ndigits=3) + 'in' + dist_thres # lat = lattice_class.Lattice(lp) glat = GyroLattice(lat, lp) eigval, eigvect = glat.eig_vals_vects(attribute=True) # plot the nth mode # fig, DOS_ax, eax = leplt.initialize_eigvect_DOS_header_plot(eigval, glat.lattice.xy, # sim_type='gyro', cbar_nticks=2, # cbar_tickfmt='%0.3f') fig, dos_ax, eax, ax1, cbar_ax = \ leplt.initialize_eigvect_DOS_header_twinplot(eigval, glat.lattice.xy, sim_type='gyro', ax0_pos=[0.0, 0.10, 0.45, 0.55], ax1_pos=[0.65, 0.15, 0.3, 0.60], header_pos=[0.1, 0.78, 0.4, 0.20], xlabel_pad=8, fontsize=8) cax = plt.axes([0.455, 0.10, 0.02, 0.55]) # Get the theta that minimizes the difference between the present and previous eigenvalue # IN ORDER TO CONNECT MODES PROPERLY if previous_ev is not None: realxy = np.real(previous_ev) thetas, eigvects = gdh.phase_fix_nth_gyro(glat.eigvect, ngyro=0, basis='XY') # only look at neighboring modes # (presumes sufficient resolution to disallow simultaneous crossings) mmin = max(modenum - 2, 0) mmax = min(modenum + 2, len(eigvects)) modenum = gdh.phase_difference_minimum(eigvects[mmin:mmax], realxy, basis='XY') modenum += mmin # print 'thetas = ', thetas # if theta < 1e-9: # print 'problem with theta' # sys.exit() else: thetas, eigvects = gdh.phase_fix_nth_gyro(glat.eigvect, ngyro=0, basis='XY') modenum = ii # Plot the lattice with bonds glat.lattice.plot_BW_lat(fig=fig, ax=eax, save=False, close=False, axis_off=False, title='') # plot excitation fig, [scat_fg, scat_fg2, pp, f_mark, lines_12_st], cw_ccw = \ leplt.construct_eigvect_DOS_plot(glat.lattice.xy, fig, dos_ax, eax, eigval, eigvects, modenum, 'gyro', glat.lattice.NL, glat.lattice.KL, marker_num=0, color_scheme='default', sub_lattice=-1, amplify=1., title='') # Plot the polygons colored by phase polys = glat.lattice.get_polygons() patches, colors = [], [] for poly in polys: addv = np.array([0., 0.]) # build up positions, taking care of periodic boundaries xys = np.zeros_like(glat.lattice.xy[poly], dtype=float) xys[0] = glat.lattice.xy[poly[0]] for (site, qq) in zip(poly[1:], range(len(poly) - 1)): if latfns.bond_is_periodic(poly[qq], site, glat.lattice.BL): toadd = latfns.get_periodic_vector(poly[qq], site, glat.lattice.PVx, glat.lattice.PVy, glat.lattice.NL, glat.lattice.KL) if np.shape(toadd)[0] > 1: raise RuntimeError('Handle the case of multiple periodic bonds between ii jj here') else: addv += toadd[0] xys[qq + 1] = glat.lattice.xy[site] + addv print 'site, poly[qq - 1] = ', (site, poly[qq]) print 'addv = ', addv xys = np.array(xys) polygon = Polygon(xys, True) patches.append(polygon) # Check the polygon # plt.close('all') # plt.plot(xys[:, 0], xys[:, 1], 'b-') # plt.show() # Get mean phase difference in this polygon # Use weighted arithmetic mean of (cos(angle), sin(angle)), then take the arctangent. yinds = 2 * np.array(poly) + 1 xinds = 2 * np.array(poly) weights = glatfns.calc_magevecs_full(eigvect[modenum]) # To take mean, follow # https://en.wikipedia.org/wiki/Mean_of_circular_quantities#Mean_of_angles # with weights from # https://en.wikipedia.org/wiki/Weighted_arithmetic_mean#Mathematical_definition # First take differences in angles phis = np.arctan2(np.real(eigvects[modenum, yinds]), np.real(eigvects[modenum, xinds])) print 'phis = ', phis phis = np.mod(phis, np.pi * 2) print 'phis = ', phis # Now convert to vectors, take mean of both x and y components. Then grab atan2(y,x) of result. xx, yy = np.mean(np.cos(np.diff(phis))), np.mean(np.sin(np.diff(phis))) dphi = np.arctan2(yy, xx) print 'dphi = ', dphi colors.append(dphi) # sys.exit() pp = PatchCollection(patches, alpha=0.4, cmap=cmap) pp.set_array(np.array(colors)) eax.add_collection(pp) pp.set_clim([-np.pi, np.pi]) cbar = fig.colorbar(pp, cax=cax) # Store this current eigvector as 'previous_ev' previous_ev = eigvects[modenum] # Plot where in evolution we are tracking ngyros = int(np.shape(eigvals)[1] * 0.5) halfev = eigvals[:, ngyros:] for row in halfev.T: ax1.loglog(np.abs(kvals), row, 'b-') trackmark = ax1.plot(np.abs(kval), np.abs(np.imag(eigval))[modenum], 'ro') ax1.set_xlabel(r"vertex coupling, $\Omega_k'$") ax1.set_ylabel(r"frequency, $\omega$") eax.xaxis.set_ticks([]) eax.yaxis.set_ticks([]) cbar.set_ticks([-np.pi, 0, np.pi]) cbar.set_ticklabels([r'-$\pi$', 0, r'$\pi$']) cbar.set_label(r'phase, $\Delta \phi$') dos_ax.set_xlim(xmin=0) plt.savefig(modedir + 'DOS_' + '{0:05}'.format(dmyi) + '.png', dpi=200) # remove plotted excitation scat_fg.remove() scat_fg2.remove() pp.remove() if f_mark is not None: f_mark.remove() lines_12_st.remove() eax.cla() dmyi += 1 first = False # Make movie imgname = modedir + 'DOS_' movname = modedir[:-1] + '_nkvals{0:04}'.format(nkvals) lemov.make_movie(imgname, movname, indexsz='05', framerate=5, rm_images=True, save_into_subdir=True, imgdir=modedir)
def mode_scaling_tune_junction(lp, args, nmode=None): """First plot scaling for all modes as junction coupling is increased. Then, plot the nth mode as the scaling parameter evolves (typically the bond strength between particles that are nearer than some threshold). Example usage: python gyro_lattice_class.py -mode_scaling_tune_junction -LT hexjunction2triads -N 1 -OmKspec union0p000in0p100 -alph 0.1 -periodic python gyro_lattice_class.py -mode_scaling_tune_junction -LT spindle -N 2 -OmKspec union0p000in0p100 -alph 0.0 -periodic -aratio 0.1 python gyro_lattice_class.py -mode_scaling_tune_junction -LT spindle -N 4 -OmKspec union0p000in0p100 -alph 0.0 -periodic -aratio 0.1 python ./build/make_lattice.py -LT spindle -N 1 -periodic -check -skip_polygons -skip_gyroDOS -aratio 0.1 python ./build/make_lattice.py -LT spindle -N 2 -periodic -check -skip_polygons -skip_gyroDOS -aratio 0.1 python ./build/make_lattice.py -LT spindle -N 4 -periodic -skip_polygons -skip_gyroDOS -aratio 0.1 python ./build/make_lattice.py -LT spindle -N 6 -periodic -skip_polygons -skip_gyroDOS -aratio 0.1 -check python ./build/make_lattice.py -LT spindle -N 8 -periodic -skip_polygons -skip_gyroDOS -aratio 0.1 -check Parameters ---------- lp args nmode : int, int list, or None Returns ------- """ nkvals = 50 if lp['LatticeTop'] in ['hexjunctiontriad', 'spindle', 'hexjunction2triads']: kvals = -np.unique(np.round(np.logspace(-1, 1., nkvals), 2)) # [::-1] dist_thres = lp['OmKspec'].split('union')[-1].split('in')[-1] lpmaster = copy.deepcopy(lp) lat = lattice_class.Lattice(lp) lat.load() if nmode is None: todo = np.arange(len(lat.xy[:, 0])) elif type(nmode) == int: todo = [nmode] else: todo = nmode ########################################################################## outfn = dio.prepdir(lat.lp['meshfn']) + 'glat_eigval_scaling_tune_junction' eigvals, first = [], True for (kval, dmyi) in zip(kvals, np.arange(len(kvals))): lp = copy.deepcopy(lpmaster) lp['OmKspec'] = 'union' + sf.float2pstr(kval, ndigits=3) + 'in' + dist_thres # lat = lattice_class.Lattice(lp) glat = GyroLattice(lat, lp) eigval, eigvect = glat.eig_vals_vects(attribute=True) if first: eigvals = np.zeros((len(kvals), len(eigval)), dtype=float) eigvals[dmyi, :] = np.imag(eigval) first = False # Plot flow of modes print 'eigvals = ', eigvals fig, axes = leplt.initialize_2panel_centy(Wfig=90, Hfig=65, x0frac=0.17, wsfrac=0.38) ax, ax1 = axes[0], axes[1] ymax = np.max(eigvals, axis=1) for kk in range(int(0.5 * len(eigvals[0])), len(eigvals[0])): ydat = eigvals[:, kk] ax.loglog(np.abs(kvals), ydat, 'b-') ax.set_ylim(ymin=0.1) ax.set_ylabel('frequency, $\omega$') ax.set_xlabel("coupling, $\Omega_k'$") if lp['LatticeTop'] == 'hexjunction2triads': ax.text(0.5, 0.9, 'Spectrum formation \n in double honeycomb junction', ha='center', va='center', transform=fig.transFigure) elif lp['LatticeTop'] == 'spindle': if lp['NH'] == lp['NV']: nstr = str(int(lp['NH'])) else: nstr = str(int(lp['NH'])) + ', ' + str(int(lp['NV'])) ax.text(0.5, 0.9, 'Spectrum formation \n ' + r'in spindle lattice ($N=$' + nstr + ')', ha='center', va='center', transform=fig.transFigure) lat.plot_BW_lat(fig=fig, ax=ax1, save=False, close=False, title='') plt.savefig(outfn + '_kmin' + sf.float2pstr(np.min(kvals)) + '_kmax' + sf.float2pstr(np.max(kvals)) + '.pdf') plt.show() ########################################################################## for ii in todo: modefn = dio.prepdir(lat.lp['meshfn']) + 'glat_mode_scaling_tune_junction_mode{0:05d}'.format(ii) +\ '_nkvals{0:04}'.format(nkvals) + '.mov' globmodefn = glob.glob(modefn) if not globmodefn: modedir = dio.prepdir(lat.lp['meshfn']) + 'glat_mode_scaling_tune_junction_mode{0:05d}/'.format(ii) dio.ensure_dir(modedir) previous_ev = None first = True dmyi = 0 for kval in kvals: lp = copy.deepcopy(lpmaster) lp['OmKspec'] = 'union' + sf.float2pstr(kval, ndigits=3) + 'in' + dist_thres # lat = lattice_class.Lattice(lp) glat = GyroLattice(lat, lp) eigval, eigvect = glat.eig_vals_vects(attribute=True) # plot the nth mode # fig, DOS_ax, eax = leplt.initialize_eigvect_DOS_header_plot(eigval, glat.lattice.xy, # sim_type='gyro', cbar_nticks=2, # cbar_tickfmt='%0.3f') fig, dos_ax, eax, ax1, cbar_ax = \ leplt.initialize_eigvect_DOS_header_twinplot(eigval, glat.lattice.xy, sim_type='gyro', ax0_pos=[0.0, 0.10, 0.6, 0.60], ax1_pos=[0.6, 0.15, 0.3, 0.60], header_pos=[0.1, 0.78, 0.4, 0.20], xlabel_pad=8, fontsize=8) # Get the theta that minimizes the difference between the present and previous eigenvalue if previous_ev is not None: realxy = np.real(previous_ev) thetas, eigvects = gdh.phase_fix_nth_gyro(glat.eigvect, ngyro=0, basis='XY') modenum = gdh.phase_difference_minimum(eigvects, realxy, basis='XY') # print 'thetas = ', thetas # if theta < 1e-9: # print 'problem with theta' # sys.exit() else: thetas, eigvects = gdh.phase_fix_nth_gyro(glat.eigvect, ngyro=0, basis='XY') modenum = ii glat.lattice.plot_BW_lat(fig=fig, ax=eax, save=False, close=False, axis_off=False, title='') fig, [scat_fg, scat_fg2, pp, f_mark, lines_12_st], cw_ccw = \ leplt.construct_eigvect_DOS_plot(glat.lattice.xy, fig, dos_ax, eax, eigval, eigvects, modenum, 'gyro', glat.lattice.NL, glat.lattice.KL, marker_num=0, color_scheme='default', sub_lattice=-1, amplify=1., title='') # fig, ax_tmp, [scat_fg, pp, f_mark, lines12_st] = \ # glat.plot_eigvect_excitation(ii, eigval=eigval, eigvect=eigvect, ax=eax, plot_lat=first, # theta=theta, normalization=1.0) # color=lecmaps.blue()) # Store this current eigvector as 'previous_ev' previous_ev = eigvects[modenum] # scat_fg.remove() # scat_fg2.remove() # pp.remove() # if f_mark is not None: # f_mark.remove() # lines_12_st.remove() # eax.cla() # Plot where in evolution we are tracking ngyros = int(np.shape(eigvals)[1] * 0.5) halfev = eigvals[:, ngyros:] for row in halfev.T: ax1.loglog(np.abs(kvals), row, 'b-') trackmark = ax1.plot(np.abs(kval), np.abs(np.imag(eigval))[modenum], 'ro') ax1.set_xlabel(r"vertex coupling, $\Omega_k'$") ax1.set_ylabel(r"frequency, $\omega$") dos_ax.set_xlim(xmin=0) plt.savefig(modedir + 'DOS_' + '{0:05}'.format(dmyi) + '.png', dpi=200) dmyi += 1 first = False # Make movie imgname = modedir + 'DOS_' movname = modedir[:-1] + '_nkvals{0:04}'.format(nkvals) lemov.make_movie(imgname, movname, indexsz='05', framerate=5, rm_images=True, save_into_subdir=True, imgdir=modedir)
def dispersion_abtransition(lp, invert_bg=False, color1=None, color2=None, color_thres=None, nkxvals=50, dab_step=0.005, dpi=100, plot_positive_only=True, ab_max=2.6): """ Parameters ---------- lp Returns ------- """ if invert_bg: plt.style.use('dark_background') if invert_bg: if color1 is None: # blue color1 = '#70a6ff' if color2 is None: # red color2 = '#ff7777' # '#90354c' # print 'color1, 2 = ', color1, color2 # sys.exit() else: cmap = lecmaps.diverging_cmap(250, 10, l=30) color1 = cmap(0.) color2 = cmap(1.) meshfn = le.find_meshfn(lp) lp['meshfn'] = meshfn lpmaster = copy.deepcopy(lp) ablist = np.arange(0, ab_max + dab_step, dab_step) # create a place to put images outdir = dio.prepdir(meshfn) + 'dispersion_abtransition/' dio.ensure_dir(outdir) fs = 20 # go through each ab and make the image ii = 0 for ab in ablist: print 'ab = ', ab lp = copy.deepcopy(lpmaster) lp['ABDelta'] = ab lat = lattice_class.Lattice(lp) lat.load(check=lp['check']) glat = GyroLattice(lat, lp) # glat.get_eigval_eigvect(attribute=True) fig, ax = leplt.initialize_portrait(ax_pos=[0.12, 0.2, 0.76, 0.6]) omegas, kx, ky = glat.infinite_dispersion(save=False, nkxvals=nkxvals, nkyvals=50, outdir=outdir, save_plot=False) # plot and save it title = r'$\Delta_{AB} =$' + '{0:0.2f}'.format(ab) for jj in range(len(ky)): for kk in range(len(omegas[0, jj, :])): if color_thres is None or ab > 0.26: if invert_bg: ax.plot(kx, omegas[:, jj, kk], 'w-', lw=max(1., 30. / (len(kx) * len(ky)))) else: ax.plot(kx, omegas[:, jj, kk], 'k-', lw=max(1., 30. / (len(kx) * len(ky)))) else: # if positive frequencies, color top band blue if len(np.where(omegas[:, jj, kk] > 0)[0]) > 0.5 * len(omegas[:, jj, kk]): # color top band blue if len(np.where(np.abs(omegas[:, jj, kk]) > color_thres)[0]) > 0.5 * len(omegas[:, jj, kk]): ax.plot(kx, omegas[:, jj, kk], '-', lw=max(1., 30. / (len(kx) * len(ky))), color=color1) else: ax.plot(kx, omegas[:, jj, kk], '-', lw=max(1., 30. / (len(kx) * len(ky))), color=color2) # if negative frequencies, color bottom band blue if len(np.where(omegas[:, jj, kk] < 0)[0]) > 0.5 * len(omegas[:, jj, kk]): # color bottom band blue if len(np.where(np.abs(omegas[:, jj, kk]) > color_thres)[0]) > 0.5 * len(omegas[:, jj, kk]): ax.plot(kx, omegas[:, jj, kk], '-', lw=max(1., 30. / (len(kx) * len(ky))), color=color2) else: ax.plot(kx, omegas[:, jj, kk], '-', lw=max(1., 30. / (len(kx) * len(ky))), color=color1) ax.text(0.5, 1.15, title, fontsize=fs, ha='center', va='center', transform=ax.transAxes) ax.set_xlim(-np.pi, np.pi) ax.xaxis.set_ticks([-np.pi, 0, np.pi]) ax.xaxis.set_ticklabels([r'$-\pi$', 0, r'$\pi$']) ax.set_xlabel(r'$k_x$', fontsize=fs) ax.set_ylabel(r'$\omega$', fontsize=fs) for tick in ax.xaxis.get_major_ticks(): tick.label.set_fontsize(fs) for tick in ax.yaxis.get_major_ticks(): tick.label.set_fontsize(fs) if ii == 0: ylims = ax.get_ylim() if plot_positive_only: ax.set_ylim(0., ylims[1]) else: ax.set_ylim(ylims[0], ylims[1]) # Save it name = outdir + 'dispersion{0:04d}'.format(ii) plt.savefig(name + '.png', dpi=dpi) plt.close('all') ii += 1 # Turn images into a movie imgname = outdir + 'dispersion' movname = dio.prepdir(meshfn) + 'dispersion_abtrans' + glat.lp['meshfn_exten'] lemov.make_movie(imgname, movname, indexsz='04', framerate=10, imgdir=outdir, rm_images=True, save_into_subdir=True)
def movie_varyt2(t1, t2arr, mm, nn, maindir, outdir, fontsize=20, tick_fontsize=16, saveims=True): kk = 0 gaps = [] t2s = [] for t2 in t2arr: km, kv, energy1, energy2 = haldane_dispersion(nn, t1, t2, mm) gap = np.min(energy1) * 2. print 'gap = ', gap gaps.append(gap) t2s.append(t2) if saveims: fig, ax = leplt.initialize_2panel_3o4ar_cent(fontsize=fontsize, x0frac=0.085) ax, ax2 = ax[0], ax[1] ax.plot(km[1], energy1.reshape(np.shape(km[0])), '-', color='#90354c') ax.plot(km[1], energy2.reshape(np.shape(km[0])), '-', color='#0A6890') ax.set_xlabel(r'$k_x$', labelpad=15, fontsize=fontsize) ax.set_ylabel(r'$\omega$', labelpad=15, fontsize=fontsize, rotation=0) ax.xaxis.set_ticks([-np.pi, 0, np.pi]) ax.xaxis.set_ticklabels([r'-$\pi$', 0, r'$\pi$'], fontsize=tick_fontsize) for tick in ax.yaxis.get_major_ticks(): tick.label.set_fontsize(tick_fontsize) ax.axis('scaled') ax.set_xlim(-np.pi, np.pi) ax.set_ylim(-np.pi, np.pi) title = r'$\Delta \omega =$' + '{0:0.3f}'.format(gap) + r' $t_1$' ax.text(0.5, 1.1, title, ha='center', va='center', fontsize=fontsize, transform=ax.transAxes) # Make second figure ax2.plot() ax2.set_xlim(0, 0.2) ax2.set_ylim(0, 0.7) ax2.plot([np.min(t2arr), np.max(t2arr)], [0.0, 3.36864398885*np.max(t2arr)], '-', color='#a1bfdb', lw=3) ax2.scatter(t2s, gaps, color='k', zorder=9999999999) title = 'Gap size: ' + r'$\Delta\omega/t_1 \approx 3.369\, t_2$' ax2.text(0.5, 1.1, title, ha='center', va='center', fontsize=fontsize, transform=ax2.transAxes) for tick in ax2.xaxis.get_major_ticks(): tick.label.set_fontsize(tick_fontsize) for tick in ax2.yaxis.get_major_ticks(): tick.label.set_fontsize(tick_fontsize) ax2.set_xlabel(r'$t_2 = \Omega_k^2/8\Omega_g$', fontsize=fontsize, labelpad=15) ax2.set_ylabel(r'$\Delta\omega/t_1 = 2 \Delta\omega/\Omega_k$', fontsize=fontsize, rotation=90, labelpad=35) plt.savefig(outdir + 'dispersion_{0:04d}'.format(kk) + '.png') plt.close('all') kk += 1 print 'dirac = ', 2.*np.pi/3., ', ', -2.*np.pi/(3.*np.sqrt(3.)) ind = np.argmin(energy1) dirac = kv[ind] print 'dirac where = ', dirac print 't2s = ', t2s print 'gaps = ', gaps zz = np.polyfit(np.array(t2s), np.array(gaps), 1) pp = np.poly1d(zz) print pp print zz[0] print zz[1] imgname = outdir + 'dispersion_' movname = maindir + 'dispersion_varyt2' lemov.make_movie(imgname, movname, indexsz='04', framerate=2)