def load_hdf5_chern(self, h5fn, load_paramsregs=False): # todo: test this method # Load data from hdf5 file fi = h5py.File(h5fn, "r") # Get subdir path from h5fn hfnsplit = self.cp['cpmeshfn'].split( '/' + self.haldane_lattice.lp['LatticeTop'] + '/') subgroup = hfnsplit[-1] self.chern_finsize = fi[subgroup].attrs['chern_finsize'] if load_paramsregs: # Load each kitaev region dictionary into the nested params_regs dictionary subg_preg = dio.prepdir(subgroup) + 'params_regs' if subg_preg in fi: preg_groups = fi[dio.prepdir(subgroup) + 'params_regs'] ind = 0 for preg_fn in preg_groups: if ind % 200 == 0: print 'Loading params_regs #', ind, ' of ', len( paramregdicts.attrs), '\n' ksizekey = preg_fn.split('ksize')[-1] pregdict = {} for key in fi[subg_preg + '/' + preg_fn].attrs: pregdict[key] = fi[subg_preg + '/' + preg_fn].attrs[key] self.params_regs[ksizekey] = pregdict ind += 1 else: print 'Could not load requested params_regs from hdf5...' fi.close()
def prepare_dispersion_params(hlat, kx=None, ky=None, nkxvals=50, nkyvals=20, outdir=None, name=None): """Prepare the filename and kx, ky for computing dispersion relation Returns """ if not hlat.lp['periodicBC']: raise RuntimeError('Cannot compute dispersion for open BC system') elif hlat.lp['periodic_strip']: print 'Evaluating infinite-system dispersion for strip: setting ky=constant=0.' ky = [0.] bboxx = max(hlat.lattice.lp['BBox'][:, 0]) - min( hlat.lattice.lp['BBox'][:, 0]) elif ky is None or kx is None: bboxx = max(hlat.lattice.lp['BBox'][:, 0]) - min( hlat.lattice.lp['BBox'][:, 0]) bboxy = max(hlat.lattice.lp['BBox'][:, 1]) - min( hlat.lattice.lp['BBox'][:, 1]) if kx is None: tmp = np.linspace(-1. / bboxx, 1. / bboxx, nkxvals - 1) step = np.diff(tmp)[0] kx = 2. * np.pi * np.linspace(-1. / bboxx, 1. / bboxx + step, nkxvals) # kx = np.linspace(-5., 5., 40) if ky is None: tmp = np.linspace(-1. / bboxy, 1. / bboxy, nkyvals - 1) step = np.diff(tmp)[0] ky = 2. * np.pi * np.linspace(-1. / bboxy, 1. / bboxy + step, nkyvals) # ky = np.linspace(-5., 5., 4) # First check for saved dispersion if outdir is None: outdir = dio.prepdir(hlat.lp['meshfn']) else: outdir = dio.prepdir(outdir) if name is None: name = 'dispersion' + hlat.lp['meshfn_exten'] + '_nx' + str( len(kx)) + '_ny' + str(len(ky)) name += '_maxkx{0:0.3f}'.format(np.max(np.abs(kx))).replace('.', 'p') name += '_maxky{0:0.3f}'.format(np.max(np.abs(ky))).replace('.', 'p') name = outdir + name return name, kx, ky
def prepare_generalized_dispersion_params(lat, kx=None, ky=None, nkxvals=50, nkyvals=20, outdir=None, name=None): """Prepare the filename and kx, ky for computing dispersion relation Returns """ if not lat.lp['periodicBC']: raise RuntimeError('Cannot compute dispersion for open BC system') elif lat.lp['periodic_strip']: print 'Evaluating infinite-system dispersion for strip: setting ky=constant=0.' ky = [0.] bboxx = max(lat.lp['BBox'][:, 0]) - min(lat.lp['BBox'][:, 0]) minx, maxx = -1. / bboxx, 1. / bboxx elif ky is None or kx is None: bzvtcs = lat.get_bz(attribute=True) minx, maxx = np.min(bzvtcs[:, 0]), np.max(bzvtcs[:, 0]) miny, maxy = np.min(bzvtcs[:, 1]), np.max(bzvtcs[:, 1]) if kx is None: kx = np.linspace(minx, maxx, nkxvals, endpoint=True) if ky is None: ky = np.linspace(miny, maxy, nkyvals, endpoint=True) # First check for saved dispersion if outdir is None: try: outdir = dio.prepdir(lat.lp['meshfn']) except: outdir = './' else: outdir = dio.prepdir(outdir) if name is None: try: name = 'generalized_dispersion' + lat.lp[ 'meshfn_exten'] + '_nx' + str(len(kx)) + '_ny' + str(len(ky)) except: name = 'generalized_dispersion' + '_nx' + str( len(kx)) + '_ny' + str(len(ky)) name += '_maxkx{0:0.3f}'.format(np.max(np.abs(kx))).replace('.', 'p') name += '_maxky{0:0.3f}'.format(np.max(np.abs(ky))).replace('.', 'p') name = outdir + name return name, kx, ky
def dispersion_abtransition_gapbounds(lp, abvals=None): """ Parameters ---------- lp 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) meshfn = le.find_meshfn(lp) lat = lattice_class.Lattice(lp) lat.load(check=lp['check']) lp['ABDelta'] = np.max(abvals) mglat = MagneticGyroLattice(lat, lp) outname = dio.prepdir(meshfn) + 'dispersion_abtrans' + mglat.lp[ 'meshfn_exten'] + '_gapbounds' gapbounds_glob = glob.glob(outname + '.txt') if gapbounds_glob: # Load the text file and save the image gapbounds = np.loadtxt(outname + '.txt') plot_gapbounds(gapbounds[:, 0], gapbounds[:, 1:], outname + '.png', lp) else: # Compute the dispersions and save the image (occurs inside dispersion_abtransition omegas, kx, ky = dispersion_abtransition(lp, save_plots=False, return_omegas=True)
def get_cpmeshfn(cp, lp): """Get the path for the specific bott calculation that uses the calc parameter dict cp on a glat with lattice parameters lp. """ if 'rootdir' in cp: cpmeshfn = get_cmeshfn(lp, rootdir=cp['rootdir']) print '\n kfns: get_cpmeshfn(): rootdir is found in cp:' print 'cpmeshfn ==> ', cpmeshfn, '\n' else: print '\n kfns: get_cpmeshfn(): rootdir is NOT found in cp!' cpmeshfn = get_cmeshfn(lp) cpmeshfn = dio.prepdir(cpmeshfn) # Form cp subdir if isinstance(cp['omegac'], np.ndarray): if 'check' in cp: if cp['check']: print "Warning: cp['omegac'] is numpy array, using first element to get cpmeshfn..." cpmeshfn += 'omc' + sf.float2pstr(cp['omegac'][0], ndigits=4) + '/' else: cpmeshfn += 'omc' + sf.float2pstr(cp['omegac'], ndigits=4) + '/' # cpmeshfn += cp['basis'] + '/' # print 'cpmeshfn = ', cpmeshfn # sys.exit() return cpmeshfn
def get_cmeshfn(lp, rootdir=None): """Prepare the path where the cherns for a particular lattice are stored. If rootdir is specified, use that for the base of the path. Otherwise, adopt the base of the path from the lattice_params dict (lp) of the lattice. Parameters ---------- lp : dict lattice parameters dictionary rootdir : str or None The root of the directory to which to save the chern calculation data Returns ------- cmeshfn : str """ meshfn_split = lp['meshfn'].split('/') ind = np.where(np.array(meshfn_split) == 'networks')[0][0] cmeshfn = '' if rootdir is None: for strseg in meshfn_split[0:ind]: cmeshfn += strseg + '/' else: cmeshfn = dio.prepdir(rootdir) cmeshfn += 'kspace_chern_magnetic_gyro/' for strseg in meshfn_split[(ind + 1):]: cmeshfn += strseg + '/' # Form physics subdir for interaction_range, aoverl, Omk, Omg, V0_pin_gauss, V0_spring_gauss cmeshfn += 'aol' + sf.float2pstr(lp['aoverl'], ndigits=8) + '/' if 'intrange' in lp['meshfn_exten']: cmeshfn += 'interaction_range{0:04d}'.format(lp['interaction_range']) + '/' eps = 1e-7 if 'ABDelta' in lp: if np.abs(lp['ABDelta']) > eps: cmeshfn += 'ABd' + '{0:0.4f}'.format(lp['ABDelta']).replace('.', 'p').replace('-', 'n') + '/' if 'OmKspec' in lp: if lp['OmKspec'] != '': cmeshfn += lp['OmKspec'] else: cmeshfn += 'Omk' + sf.float2pstr(lp['Omk'], ndigits=3) else: cmeshfn += 'Omk' + sf.float2pstr(lp['Omk'], ndigits=3) cmeshfn += '_Omg' + sf.float2pstr(lp['Omg'], ndigits=3) if 'pinconf' in lp: if lp['pinconf'] > 0: cmeshfn += '/pinconf' + '{0:04d}'.format(lp['pinconf']) #################################### # Now start final part of path's name print 'lp[V0_pin_gauss] = ', lp['V0_pin_gauss'] if lp['V0_pin_gauss'] > 0 or lp['V0_spring_gauss'] > 0: dcdisorder = True cmeshfn += '/pinV' + sf.float2pstr(lp['V0_pin_gauss'], ndigits=4) cmeshfn += '_sprV' + sf.float2pstr(lp['V0_spring_gauss'], ndigits=4) else: dcdisorder = False return cmeshfn
def data_on_disk_txt(bott): """Look to see if bott index is stored as txt file Returns ------- bool whether the data is stored """ if glob.glob(dio.prepdir(bott.cp['cpmeshfn']) + 'bott.txt'): return True else: return False
def compare_dispersion_to_dos(omegas, kx, ky, mlat, outdir=None): """Compare the projection of the dispersion onto the omega axis with the DOS of the MagneticGyroLattice Parameters ---------- omegas kx ky mlat outdir Returns ------- """ # Save DOS from projection if outdir is None: outdir = dio.prepdir(mlat.lp['meshfn']) else: outdir = dio.prepdir(outdir) name = outdir + 'dispersion_gyro' + mlat.lp['meshfn_exten'] + '_nx' + str(len(kx)) + '_ny' + str(len(ky)) name += '_maxkx{0:0.3f}'.format(np.max(np.abs(kx))).replace('.', 'p') name += '_maxky{0:0.3f}'.format(np.max(np.abs(ky))).replace('.', 'p') # initialize figure fig, ax = leplt.initialize_1panel_centered_fig() ax2 = ax.twinx() ax.hist(omegas.ravel(), bins=1000) # Compare the histograms of omegas to the dos and save the figure eigval = np.imag(mlat.get_eigval()) print 'eigval = ', eigval ax2.hist(eigval[eigval > 0], bins=50, color=lecmap.green(), alpha=0.2) ax.set_title('DOS from dispersion') xlims = ax.get_xlim() ax.set_xlim(0, xlims[1]) plt.savefig(name + '_dos.png', dpi=300)
def pointset(xy, outdir=None, save=True, ax=None, ptsz=None, facecolor='k', dpi=800, **kwargs): """Print an image of the pointset. Return the figure and axis Parameters ---------- xy : 2d float array outdir : path to save image save : bool Save the image in outdir or pwd ax : matplotlib axis instance or None Axis on which to draw the points ptsz : int size of the points to draw (in pixels) facecolor : color specifier The color of the points to draw dpi : int Resolution of the image to save, if save==True **kwargs : keyword arguments for plotting.initialize_1panel_fig() """ if outdir is None: infodir = './' else: infodir = dio.prepdir(outdir) if ax is None: fig, ax = leplt.initialize_1panel_fig(**kwargs) ax.set_axis_off() if ptsz is None: ptsz = max(min(25, len(xy) * 0.003), 0.5) ax.scatter(xy[:, 0], xy[:, 1], s=ptsz, edgecolor=None, facecolor=facecolor) if save: fname = infodir + 'pointset.png' plt.savefig(fname, dpi=dpi) else: plt.show()
def ensure_all_gyro_lattices(self): """Ensure that all gyro lattices called for by self.meshfns are loaded. """ # todo: add the ability to change glat.lp parameters (like Omk) at function call-- specify as list of lp's or as single lp print 'Ensuring all gyro lattices...' for ii in range(len(self.meshfns)): meshfn = self.meshfns[ii] if isinstance(meshfn, list): try: meshfn = meshfn[0] except IndexError: print 'self.meshfns = ', self.meshfns print 'meshfn = ', meshfn raise IndexError('list index out of range') print 'Ensuring ', meshfn try: self.gyro_lattices[ii] append_glat = False except IndexError: append_glat = True try: # Check if lp['meshfn'] of gyro_lattice matches meshfn self.gyro_lattices[ii].lp['meshfn'] # print('Already have gyro_lattice defined for ii='+str(ii)+': ', test) except IndexError: lp = le.load_params(dio.prepdir(meshfn), 'lattice_params') lat = lattice_class.Lattice(lp=lp) lat.load(meshfn=meshfn) lp['Omk'] = -1.0 lp['Omg'] = -1.0 if append_glat: self.gyro_lattices.append( gyro_lattice_class.GyroLattice(lat, lp)) else: self.gyro_lattices[ii] = gyro_lattice_class.GyroLattice( lat, lp) glat = gyro_lattice_class.GyroLattice( lat, self.gyro_lattices[ii].lp) self.gyro_lattices[ii] = glat
Example usage: python haldane_chern_collection_collection.py -LT iscentroid -N 15 -Nks 110 -singleksz_frac 0.3 -chern_varyloc_varyhlatparam -hlatparam ABDelta -paramV 0.0:0.1:1.0 python haldane_chern_collection_collection.py -LT iscentroid -N 20 -Nks 201 -singleksz_frac 0.3 -chern_varyloc_varyhlatparam -hlatparam ABDelta -paramV 0.0:0.1:2.0 """ meshfn = le.find_meshfn(lp) lp['meshfn'] = meshfn lat = lattice_class.Lattice(lp) lat.load() print 'For each hlat param, creating chern collection from single-lattice haldane_collection...' paramV = sf.string_sequence_to_numpy_array(args.paramV, dtype=float) lp_master = copy.deepcopy(lp) cp_master = copy.deepcopy(cp) hccollcoll = HaldaneChernCollectionCollection() outdir = dio.prepdir(lp['meshfn']).replace('networks', 'cherncollcolls') dio.ensure_dir(outdir) paramspec = str(args.hlatparam) + "_lenlppV" + str(len(paramV)) pklfn = outdir + "hccollcoll_chern_varyloc_varyhlatparam_" + paramspec + ".pkl" if args.maxchern: stillname = 'maxchern_varyloc' elif args.singleksz > 0: stillname = 'chern_ksz_' + '{0:0.2f}'.format(args.chern_singlesz).replace('.', 'p') + '_varyloc' elif args.singleksz_frac > 0: stillname = 'chern_kszfrac_' + '{0:0.2f}'.format(args.singleksz_frac).replace('.', 'p') + '_varyloc' else: stillname = 'chern_varyloc' imgdir = outdir + stillname + '_varyhlatparam_' + paramspec + '_stills/' dio.ensure_dir(imgdir)
def lowest_mode(mlat, nkxy=20, save=False, save_plot=True, name=None, outdir=None, imtype='png'): """ Parameters ---------- mlat : MassLattice class instance nkxy : int save :bool save_plot : bool name : str or None outdir : str or None imtype : str ('png', 'pdf', 'jpg', etc) Returns ------- omegas : n x 1 float array the frequencies at each evaluated point in kspace kxy : n x 2 float array the kspace points at which the frequency of modes are evaluated vtcs : #vertices x 2 float array the vertices of the brillouin zone in kspace """ # First check for saved dispersion if outdir is None: outdir = dio.prepdir(mlat.lp['meshfn']) else: outdir = dio.prepdir(outdir) if name is None: name = 'lowest_mode' + mlat.lp['meshfn_exten'] name += '_nkxy{0:06d}'.format(np.max(np.abs(nkxy))) name = outdir + name fn = glob.glob(name + '.pkl') if fn: with open(fn[0], "rb") as fn: res = pkl.load(fn) vtcs = res['vtcs'] kxy = res['kxy'] omegas = res['omegas'] else: pvs = mlat.lattice.PV a1, a2 = pvs[0], pvs[1] vtx, vty = bzf.bz_vertices(a1, a2) vtcs = np.dstack((vtx, vty))[0] polygon = np.dstack((vtx, vty))[0] xlims = (np.min(vtx), np.max(vtx)) ylims = (np.min(vty), np.max(vty)) xextent, yextent = xlims[1] - xlims[0], ylims[1] - ylims[0] step = float(max(xextent, yextent)) / float(nkxy) print 'extent = ', xextent print 'step = ', step pts = dh.generate_gridpts_in_polygons(xlims, ylims, [polygon], dx=step, dy=step) # print 'tkspacefns: pts = ', np.shape(pts) omegas = np.zeros(len(pts)) matk = lambda k: dynamical_matrix_kspace(k, mlat, eps=1e-10) ii = 0 for kxy in pts: print 'mlatkspace_fns: infinite_dispersion(): ii = ', ii # print 'jj = ', jj kx, ky = kxy[0], kxy[1] matrix = matk([kx, ky]) print 'mlatkspace_fns: diagonalizing...' eigval, eigvect = np.linalg.eig(matrix) si = np.argsort(np.real(-eigval)) omegas[ii] = np.real(np.min(np.sqrt(-eigval)[si])) ii += 1 # Save results to pickle if save == True res = {'omegas': omegas, 'kxy': pts, 'vtcs': vtcs} kxy = pts if save: with open(name + '.pkl', "wb") as fn: pkl.dump(res, fn) if save_plot: fig, ax, cax = leplt.initialize_1panel_cbar_cent(wsfrac=0.5, tspace=4) xgrid, ygrid, ZZ = dh.interpol_meshgrid(kxy[:, 0], kxy[:, 1], omegas, int(nkxy), method='nearest') inrois = dh.gridpts_in_polygons(xgrid, ygrid, [vtcs]) vmax = np.max(omegas) ZZ[~inrois] = 0.0 if ax is None: ax = plt.gca() pcm = ax.pcolormesh(xgrid, ygrid, ZZ, cmap=lecmaps.colormap_from_hex('#2F5179'), vmin=0., vmax=vmax, alpha=1.0) print 'vmax = ', vmax plt.colorbar(pcm, cax=cax, label=r'$\omega_0$', orientation='horizontal', ticks=[0., vmax]) ax.axis('off') ax.axis('scaled') plt.savefig(name + '.' + imtype) return omegas, kxy, vtcs
import glob import subprocess """Go through specified directories and dump all txt files of pinning disorder, etc into an hdf5 file""" parent_dir = '/Users/npmitchell/Dropbox/Soft_Matter/GPU/networks/hexagonal/' subdir = 'hexagonal_square_periodicBC_delta0p667_phi0p000_000031_x_000031*' subdirs = dio.find_subdirs(subdir, parent_dir) ellipses = '' doomg = False dopin = True if doomg: # Go through all matching subdirs, collect for subd in subdirs: subd = dio.prepdir(subd) omgpins = glob.glob(subd + 'Omg_mean*.txt') # dump these into a hdf5 h5fn = subd + 'omg_configs.hdf5' if glob.glob(h5fn): rw = "r+" else: rw = "w" with h5py.File(h5fn, rw) as fi: keys = fi.keys() # print 'keys = ', keys for omgpin in omgpins: pinname = omgpin.split('/')[-1].split('.')[0] # .lower()
def le_plot_gyros(xy, xy0, NL, KL, BM, params, t, ii, name, fig, ax, outdir, climv='auto', exaggerate=1.0, dpi=300, fontsize=12, title='', **kwargs): """Plots a single gyroscopic lattice time step using timestep plot. Parameters ---------- t : float time stamp for image ii : int index to name file ( ie 'name_000ii.png') name : string the name of the file (before _index.png) fig : matplotlib.pyplot figure handle, or 'none' the figure on which to plot the gyros. If 'none', uses plt.gcf() and clears figure. ax : matplotlib.pyplot axis handle, or 'none' the axis on which to plot the gyros. If 'none', uses plt.gca() outdir : string The output directory for the image climv : float or tuple Color limit for coloring bonds by bond strain, overriddes params['climv'] if climv!='auto' If 'climv' is not a key in params, and climv=='auto', then uses default min/max. If 'climv' is a key in params, and climv=='auto', then uses params['climv']. exaggerate : float (default 1.0 --> in which case it is ignored) Exaggerate the displacements of each particle from its initial position by this factor. Ignored if == 1.0 dpi : float pixels per inch, resolution of saved plot **kwargs: Additional timestep_plot() keyword arguments color_particles='k', fontsize=14, linewidth=2 Returns ---------- """ # If fig and ax are not supplied, declare them if fig is None or fig == 'none': fig = plt.gcf() plt.clf() if ax is None or ax == 'none': ax = plt.gca() # make output dir outdir = dio.prepdir(outdir) dio.ensure_dir(outdir) # set range of window from first values if 'xlimv' in params: xlimv = params['xlimv'] if 'ylimv' in params: ylimv = params['ylimv'] else: ylimv = (xlimv - max(xy0[:, 0])) + np.ceil(max(xy0[:, 1])) else: xlimv = np.ceil(max(xy0[:, 0]) * 5./ 4.) ylimv = (xlimv - max(xy0[:, 0])) + max(xy0[:, 1]) # save current data as stills index = '{0:08d}'.format(ii) outname = outdir + '/' + name + '_' + index + '.png' BL = le.NL2BL(NL, KL) # print 'BL = ', BL suptitle = copy.deepcopy(title) if 'prestrain' in params: prestrain = params['prestrain'] else: prestrain = 0. if 'shrinkrate' in params: shrinkrate = params['shrinkrate'] title = 't = ' + '%07.0f' % t + ' a = ' + '%07.5f' % (1. - shrinkrate * t - prestrain) elif 'prestrain' in params: shrinkrate = 0.0 title = 't = ' + '%07.0f' % t + ' a = ' + '%07.5f' % (1. - prestrain) else: shrinkrate = 0.0 title = 't = ' + '%07.0f' % t + r' $\Omega_g^{-1}$' if exaggerate != 1.0: title += ' amplified ' + str(int(exaggerate)) + 'x ' if 'Omk' in params and params['Omk'] != -1.: title += '\n' + r'$\Omega_g$=' + '{0:.3f}'.format(params['Omg']) if 'Omg' in params and params['Omk'] != -1.: title += r' $\Omega_k$=' + '{0:.3f}'.format(params['Omk'][0, 0]) if 'split_spin' in params: title += ' NV=' + str(int(params['NV'])) if 'split_k' in params: title += r' $k_s$=' + str(params['split_k']) # title +='\n' # if params['BCtype'] == 'excite': # title += r' $\omega_d$ = ' + '{0:.3f}'.format(params['frequency']) if 'eta' in params: if params['eta'] != 0.000: title += r' $\eta$=' + '{0:.3f}'.format(params['eta']) # calculate strain # bs = bond_strain_list(xy,BL,bL0) # if exaggerate==1.0: # movie_plot_2D_gyros(xy, BL, bs, outname, title, xlimv, ylimv, climv) # else: # xye = xy0+(xy-xy0)*exaggerate # movie_plot_2D_gyros(xye, BL, bs, outname, title, xlimv, ylimv, climv) if climv == 'auto': if 'climv' in params: climv = params['climv'] [scat_fg, lines_st, p] = leplt.timestep_plot(xy, xy0, NL, KL, BM, ax=ax, factor=exaggerate, amp=climv, title=title, fontsize=fontsize, suptitle=suptitle, **kwargs) # print 'color_particles = ', scat_fg ax.set_xlim(-xlimv, xlimv) ax.set_ylim(-ylimv, ylimv) plt.savefig(outname, dpi=dpi) # clear_array = [scat_fg, lines_st, p] # for i in range(len(clear_array)): # clear_array[i].remove() return [scat_fg, lines_st, p]
'spreading_dt': args.spreading_dt, 'kicksz': args.kicksz, 'intparam': args.intparam, } ####################### print 'LatticeTop = ', latticetop lattice = lattice_class.Lattice(lp) print '\nBuilding lattice...' lattice.build() print '\nSaving lattice...' lattice.save(skip_polygons=args.skip_polygons, check=lp['check']) if args.nice_plot: print 'Saving nice BW plot...' lattice.plot_BW_lat(meshfn=dio.prepdir(lattice.lp['meshfn'])) infodir = lattice.lp['meshfn'] + '/' if args.bondL_histogram: print 'Creating bond length histogram...' lattice.bond_length_histogram(fig=None, ax=None, outdir=infodir, check=args.check) glp = {'Omk': -1.0, 'Omg': -1.0} gyrolat = gyro_lattice_class.GyroLattice(lattice, glp) if not args.skip_gyroDOS: print '\n\nPerforming gyro DOS ...' gyrolat.save_eigval_eigvect()
def infinite_dispersion(mlat, kx=None, ky=None, nkxvals=50, nkyvals=20, save=True, save_plot=True, title='twisty dispersion relation', outdir=None, name=None, ax=None): """Compute the imaginary part of the eigvalues of the dynamical matrix for a grid of wavevectors kx, ky Parameters ---------- mlat : MassLattice class instance the twisty network whose dispersion we compute kx : n x 1 float array the x components of the wavevectors over which to diagonalize the dynamical matrix ky : m x 1 float array the y components of the wavevectors over which to diagonalize the dynamical matrix nkxvals : int If kx is unspecified, then nkxvals determines how many kvectors are sampled in x dimension. nkyvals : int If ky is unspecified and if network is not a periodic_strip, then nkyvals determines how many kvectors are sampled in y dimension. save : bool Save the omega vs k information in a pickle save_plot : bool Save the omega vs k info as a matplotlib figure png title : str title for the plot to save outdir : str or None The directory in which to output the image and pickle of the results if save == True Returns ------- """ if not mlat.lp['periodicBC']: raise RuntimeError('Cannot compute dispersion for open BC system') elif mlat.lp['periodic_strip']: print 'Evaluating infinite-system dispersion for strip: setting ky=constant=0.' ky = [0.] bboxx = max(mlat.lattice.lp['BBox'][:, 0]) - min(mlat.lattice.lp['BBox'][:, 0]) elif ky is None or kx is None: bboxx = max(mlat.lattice.lp['BBox'][:, 0]) - min(mlat.lattice.lp['BBox'][:, 0]) bboxy = max(mlat.lattice.lp['BBox'][:, 1]) - min(mlat.lattice.lp['BBox'][:, 1]) if kx is None: if nkxvals == 0: kx = np.array([0.]) else: tmp = np.linspace(-1. / bboxx, 1. / bboxx, nkxvals - 1) step = np.diff(tmp)[0] kx = 2. * np.pi * np.linspace(-1. / bboxx, 1. / bboxx + step, nkxvals) # kx = np.linspace(-5., 5., 40) if ky is None: if nkyvals == 0: ky = np.array([0.]) else: tmp = np.linspace(-1. / bboxy, 1. / bboxy, nkyvals - 1) step = np.diff(tmp)[0] ky = 2. * np.pi * np.linspace(-1. / bboxy, 1. / bboxy + step, nkyvals) # ky = np.linspace(-5., 5., 4) # First check for saved dispersion if outdir is None: outdir = dio.prepdir(mlat.lp['meshfn']) else: outdir = dio.prepdir(outdir) if name is None: name = 'dispersion' + mlat.lp['meshfn_exten'] + '_nx' + str(len(kx)) + '_ny' + str(len(ky)) name += '_maxkx{0:0.3f}'.format(np.max(np.abs(kx))).replace('.', 'p') name += '_maxky{0:0.3f}'.format(np.max(np.abs(ky))).replace('.', 'p') name = outdir + name print('checking for file: ' + name + '.pkl') if glob.glob(name + '.pkl'): saved = True with open(name + '.pkl', "rb") as fn: res = pkl.load(fn) omegas = res['omegas'] kx = res['kx'] ky = res['ky'] else: # dispersion is not saved, compute it! saved = False omegas = np.zeros((len(kx), len(ky), len(mlat.lattice.xy) * 2)) matk = lambda k: dynamical_matrix_kspace(k, mlat, eps=1e-10) ii = 0 for kxi in kx: print 'mlatkspace_fns: infinite_dispersion(): ii = ', ii jj = 0 for kyj in ky: # print 'jj = ', jj matrix = matk([kxi, kyj]) print 'mlatkspace_fns: diagonalizing...' eigval, eigvect = np.linalg.eig(matrix) si = np.argsort(np.real(eigval)) omegas[ii, jj, :] = np.real(np.sqrt(-eigval[si])) # print 'eigvals = ', eigval # print 'omegas --> ', omegas[ii, jj] jj += 1 ii += 1 if save_plot: if ax is None: fig, ax = leplt.initialize_1panel_centered_fig() axsupplied = False else: axsupplied = True for jj in range(len(ky)): for kk in range(len(omegas[0, jj, :])): ax.plot(kx, omegas[:, jj, kk], 'k-', lw=max(0.03, 5. / (len(kx) * len(ky)))) ax.set_title(title) ax.set_xlabel(r'$k_x$ $[\langle \ell \rangle ^{-1}]$') ax.set_ylabel(r'$\omega$') ylims = ax.get_ylim() ylim0 = min(ylims[0], -0.1 * ylims[1]) ax.set_ylim(ylim0, ylims[1]) # Save the plot plt.savefig(name + '.png', dpi=300) ax.set_ylim(max(ylim0, -0.05 * ylims[1]), 0.05 * ylims[1]) # Save the plot plt.savefig(name + '_zoom.png', dpi=300) # Fixed zoom ax.set_ylim(-0.3, 0.6) plt.savefig(name + '_zoom2.png', dpi=300) plt.close('all') # save plot of ky if no axis supplied if not axsupplied: fig, ax = leplt.initialize_1panel_centered_fig() for jj in range(len(kx)): for kk in range(len(omegas[jj, 0, :])): ax.plot(ky, omegas[jj, :, kk], 'k-', lw=max(0.03, 5. / (len(kx) * len(ky)))) ax.set_title(title) ax.set_xlabel(r'$k_y$ $[\langle \ell \rangle ^{-1}]$') ax.set_ylabel(r'$\omega$') ylims = ax.get_ylim() ylim0 = min(ylims[0], -0.1 * ylims[1]) ax.set_ylim(ylim0, ylims[1]) # Save the plot plt.savefig(name + '_ky.png', dpi=300) ax.set_ylim(max(ylim0, -0.05 * ylims[1]), 0.05 * ylims[1]) # Save the plot plt.savefig(name + '_zoom_ky.png', dpi=300) # Fixed zoom ax.set_ylim(-0.3, 0.6) plt.savefig(name + '_zoom2_ky.png', dpi=300) plt.close('all') # Plot in 3D # fig = plt.gcf() # ax = fig.add_subplot(projection='3d') # 111, # # rows will be kx, cols wll be ky # kyv = np.array([[ky[i].tolist()] * len(kx) for i in range(len(ky))]).ravel() # kxv = np.array([[kx.tolist()] * len(ky)]).ravel() # print 'kyv = ', np.shape(kyv) # print 'kxv = ', np.shape(kxv) # for kk in range(len(omegas[0, 0, :])): # ax.plot_trisurf(kxv, kyv, omegas[:, :, kk].ravel()) # # ax.view_init(elev=0, azim=0.) # ax.set_title(title) # ax.set_xlabel(r'$k_x$ $[1/\langle l \rangle]$') # ax.set_ylabel(r'$k_y$ $[1/\langle l \rangle]$') # plt.savefig(name + '_3d.png') if save: if not saved: res = {'omegas': omegas, 'kx': kx, 'ky': ky} with open(name + '.pkl', "wb") as fn: pkl.dump(res, fn) return omegas, kx, ky
def le_plot_gHST(xy, NL, KL, BM, params, t, ii, name, outdir, climv=0.1, xlimv='auto', exaggerate=1.0, PlanarLimit=False): """Plots a gliding heavy symmetric top network Parameters ---------- xy : NP x 5 array positions of pivots (x,y) and euler angles for all HSTs t : float time stamp for image ii : int index for naming name : string the name of the file (before _index.png) outdir : string The output directory for the image climv : float or tuple Color limit for coloring bonds by bond strain xlimv exaggerate : float (default 1.0 --> in which case it is ignored) Exaggerate the displacements of each particle from its initial position by this factor. Ignored if == 1.0 PlanarLimit : bool Returns ---------- """ # make output dir outdir = dio.prepdir(outdir) dio.ensure_dir(outdir) # set range of window from first values if xlimv == 'auto': xlimv = params['xlimv'] ylimv = xlimv # save current data as stills index = '{0:08d}'.format(ii) outname = outdir + '/' + name + '_' + index + '.png' BL = NL2BL(NL, KL) if 'prestrain' in params: prestrain = params['prestrain'] else: prestrain = 0. if 'shrinkrate' in params: shrinkrate = params['shrinkrate'] title = 't = ' + '%09.1f' % t + ' a = ' + '%07.5f' % (1. - shrinkrate * t - prestrain) elif 'prestrain' in params: shrinkrate = 0.0 title = 't = ' + '%09.1f' % t + ' a = ' + '%07.5f' % (1. - prestrain) else: shrinkrate = 0.0 title = 't = ' + '%09.1f' % t if exaggerate != 1.0: title += ' magnify=' + str(exaggerate) if 'Omg' in params: title += '\n' + r'$\Omega_g$=' + '{0:.3f}'.format(params['Omg']) if 'OmK' in params: title += r' $\Omega_k$=' + '{0:.3f}'.format(params['OmK']) if 'g' in params: gstr = str(params['g']) if len(gstr.split('.')[1]) > 3: gstr = '{0:.3f}'.format(params['g']) title += '\n' + r'$g$=' + gstr if 'k' in params: kstr = str(params['k']) if len(kstr.split('.')[1]) > 3: kstr = '{0:.3f}'.format(params['k']) title += r' $k$=' + kstr if 'Mm' in params: try: mstr = str(params['Mm'][0]) if len(mstr.split('.')[1]) > 3: mstr = '{0:.3f}'.format(params['Mm'][0]) title += r' $m$=' + mstr except: mstr = str(params['Mm']) if len(mstr.split('.')[1]) > 3: mstr = '{0:.3f}'.format(params['Mm']) title += r' $m$=' + mstr if 'l' in params: try: lstr = str(params['l'][0]) if len(lstr.split('.')[1]) > 3: lstr = '{0:.3f}'.format(params['l'][0]) title += r' $l$=' + lstr except: lstr = str(params['l']) if len(lstr.split('.')[1]) > 3: lstr = '{0:.3f}'.format(params['l']) title += r' $l$=' + lstr if 'w3' in params: try: if (params['w3'] - params['w3'][0] < 1e-5).all(): wstr = str(params['w3'][0]) if len(lstr.split('.')[1]) > 3: wstr = '{0:.3f}'.format(params['w3'][0]) title += r' $\omega_3$=' + wstr # Otherwise, don't print w3: it is heterogeneous except: wstr = str(params['w3']) if len(wstr.split('.')[1]) > 3: wstr = '{0:.3f}'.format(params['w3']) title += r' $\omega_3$=' + wstr if params['BCtype'] == 'excite': title += r' $\omega_d$=' + '{0:.5f}'.format(params['frequency']) # calculate strain # bs = bond_strain_list(xy,BL,bL0) # if exaggerate==1.0: # movie_plot_2D_gyros(xy, BL, bs, outname, title, xlimv, ylimv, climv) # else: # xye = xy0+(xy-xy0)*exaggerate # movie_plot_2D_gyros(xye, BL, bs, outname, title, xlimv, ylimv, climv) # set limits fig = plt.gcf() plt.clf() ax = plt.gca() ax.set_xlim(-xlimv, xlimv) ax.set_ylim(-ylimv, ylimv) if PlanarLimit: gHST_plot_PL(xy, NL, KL, BM, params, factor=exaggerate, climv=climv, title=title) else: gHST_plot(xy, NL, KL, BM, params, factor=exaggerate, climv=climv, title=title) plt.savefig(outname)
def data2stills_2Dgyros(datadir, simoutdir, params, framedir_name='stills', init_skip=10, climv=0.1, numbering='adopt', rough=False, roughmov=True, exaggerate=1.0, rm_stills=True, resolution=150, figsize='auto', color_particles='k', DOSexcite=None, lp=None, framerate=10, mov_exten='', title='', dos_meshfn_dir=None, movname=None, lw=2, **kwargs): """Converts a list of data into a stack of png images of gyroscopic lattice using timestep_plot for each timestep. Parameters ---------- simoutdir : string The output directory for the simulation (contains subdirs for xyv, KL) params : dict Parameters dictionary framedir_name : string Subdirectory of simoutdir in which to save movie images vsaved : bool whether the velocites are recorded (vsaved = False for Nash gyros, True for gHST, for example) init_skip : int One out of every init_skip frames will be written first, then the intermittent frames will be written, to see briefly what happens climv : float or tuple Color limit for coloring bonds by bond strain numbering : 'natural' or 'adopt' (default = 'adopt') Use indexing '0','1','2','3',... or adopt the index of the input file. rough : boolean Plot every init_skip files ONLY? (if False, writes every init_skip files first, then does the rest) exaggerate : float (default 1.0 --> in which case it is ignored) Exaggerate the displacements of each particle from its initial position by this factor. Ignored if == 1.0 rm_stills : bool Whether or not to delete the stills after making them. DOSexcite : tuple of floats or None (excitation frequency, stdev time), or else None if DOS plot is not desired lp : dict Lattice parameters. If not None, then if eigval is not found in main dir, attempts to load eigval from gyro network, but will not compute it framerate : int or float (optional, default=10) framerate for movie mov_exten : str (optional) additional description to append to movie name, if movname is None movname : str or None Name or full path with name of movie to output of the simulation **kwargs : keyword arguments for leplt.timestep_plot() such as bgcolor, cmap (the strain colormap), color_particles, mimic_expt Returns ---------- """ plt.close('all') print 'Running data2stills_2Dgyros with DOSexcite = ', DOSexcite # get dirs # vsaved denotes whether the velocites are recorded # vsaved = False for Nash gyros, True for gHST, for example print 'simoutdir = ', simoutdir try: xypath = sorted(glob.glob(simoutdir + 'xyv/'))[0] vsaved = True except IndexError: xypath = sorted(glob.glob(simoutdir + 'xy/'))[0] vsaved = False # list files xyfiles = sorted(glob.glob(xypath + '*.txt')) # load setup NLfile = sorted(glob.glob(datadir + 'NL.txt'))[0] NL = np.loadtxt(NLfile, dtype='int', delimiter=',') xy0file = sorted(glob.glob(datadir + 'xy.txt'))[0] xy0 = np.loadtxt(xy0file, delimiter=',', usecols=(0, 1)) if 'deform' in params: if params['deform']: deform_xy0 = True xy0path = sorted(glob.glob(simoutdir + 'xy0/'))[0] xy0files = sorted(glob.glob(xy0path + '*.txt')) else: deform_xy0 = False xy0files = [] try: KLpath = sorted(glob.glob(simoutdir + 'KL/'))[0] KLfiles = sorted(glob.glob(KLpath + '*.txt')) if KLfiles: print 'found KLfiles --> update KL each timestep' update_KL_each_timestep = True KL = np.loadtxt(KLfiles[0], delimiter=',') else: print 'KLfiles =', KLfiles, '\n --> do not update KL' update_KL_each_timestep = False KL = np.loadtxt(datadir + 'KL.txt', dtype='int', delimiter=',') BM0 = le.NL2BM(xy0, NL, KL) except IndexError: print 'no KLfiles --> do not update KL' update_KL_each_timestep = False KL = np.loadtxt(datadir + 'KL.txt', dtype='int', delimiter=',') BM0 = le.NL2BM(xy0, NL, KL) if 'h' in params: hh = params['h'] elif 'hh' in params: hh = params['hh'] else: hfile = sorted(glob.glob(datadir + 'h.txt'))[0] hh = np.loadtxt(hfile) # get base name from xyfile name = 'still' if vsaved: # name = (xyfiles[0].split('/')[-1]).split('xyv')[0] try: x, y, vx, vy = np.loadtxt(xyfiles[0], delimiter=',', unpack=True) except: x, y, z, vx, vy, vz = np.loadtxt(xyfiles[0], delimiter=',', unpack=True) else: # name = (xyfiles[0].split('/')[-1]).split('xy')[0] try: '''Data is 2D''' x, y = np.loadtxt(xyfiles[0], delimiter=',', unpack=True) except: try: '''Data is 3D''' x, y, z = np.loadtxt(xyfiles[0], delimiter=',', unpack=True) except: '''Data is X,Y,dX,dY''' X, Y, dX, dY = np.loadtxt(xyfiles[0], delimiter=',', unpack=True) # get length of index string from xyfile index_sz = str(len((xyfiles[0].split('_')[-1]).split('.')[0])) # make output dir outdir = simoutdir + framedir_name + '/' dio.ensure_dir(outdir) # set range of window from first values xlimv = np.ceil(max(x) * 5. / 4.) ylimv = np.ceil(max(y) * 5. / 4.) # Initial bond list and # count initial bonds (double counted) # nzcount = np.count_nonzero(KL) BL0 = le.NL2BL(NL, KL) bo = le.bond_length_list(xy0, BL0) # make list of indices to plot-- first sparse then dense do1 = [0] + range(0, len(xyfiles), init_skip) # Set up figure if figsize == 'auto': fig = plt.gcf() plt.clf() else: plt.close('all') fig = plt.figure(figsize=figsize) print 'DOSexcite = ', DOSexcite if DOSexcite is not None: # Load DOS eigvals: eigvalpklglob = glob.glob(datadir + 'eigval.pkl') if eigvalpklglob: with open(datadir + 'eigval.pkl', "rb") as input_file: eigval = cPickle.load(input_file) eval_loaded = True else: print 'Did not find eigval in simulation dir (datadir), attempting to load based on supplied meshfn...' # If you want to load eigvals from a lattice other than the one being simulated, put a "pointer file" # txt file with the path to that meshfn in your simulation directory: for ex, put 'meshfn_eigvals.txt' # in the simdir, with contents '/Users/username/...path.../hexagonal_square_delta0p667_...000010_x_000010/' if dos_meshfn_dir is None or dos_meshfn_dir == 'none': dos_meshfn_dir = datadir meshfn_specfn = glob.glob( dio.prepdir(dos_meshfn_dir) + 'meshfn_eig*.txt') print 'dos_meshfn_dir = ', dos_meshfn_dir print 'meshfn_specfn = ', meshfn_specfn if meshfn_specfn: with open(meshfn_specfn[0], 'r') as myfile: meshfn = myfile.read().replace('\n', '') if lp is not None: # Build correct eigval to load based on lp (gyro lattice parameters) by grabbing lp[meshfn_exten] import lepm.lattice_class import lepm.gyro_lattice_class # lp = {'LatticeTop': params['LatticeTop'], 'meshfn': params['meshfn']} lat = lepm.lattice_class.Lattice(lp=lp) lat.load() mlat = lepm.magnetic_gyro_lattice_class.MagneticGyroLattice( lat, lp) eigvalfn = dio.prepdir( meshfn) + 'eigval' + mlat.lp['meshfn_exten'] + '.pkl' else: print 'since no lp supplied, assuming eigval is default in datadir...' eigvalfn = dio.prepdir(meshfn) + 'eigval_magnetic.pkl' with open(eigvalfn, "rb") as fn: eigval = cPickle.load(fn) eval_loaded = True else: print 'plotting.time_domain_magnetic: Did not find eigval or eigval pointer file in datadir, ' + \ 'attempting to load based on lp...' if lp is not None: print 'Loading based on lp...' # No eigval saved in lattice GyroLattice's meshfn, seeking alternative import lepm.lattice_class import lepm.gyro_lattice_class # lp = {'LatticeTop': params['LatticeTop'], 'meshfn': params['meshfn']} lat = lepm.lattice_class.Lattice(lp=lp) lat.load() print 'lp = ', lp print 'lp[Omk] = ', lp['Omk'] mlat = lepm.magnetic_gyro_lattice_class.MagneticGyroLattice( lat, lp) eigval = mlat.load_eigval() if eigval is None: eigval = mlat.get_eigval() print 'Calculated eigval based on supplied GyroLattice instance, using lp dictionary.' else: print 'Loaded eigval from disk, from a location determined by the lp dictionary.' eval_loaded = True else: eval_loaded = False raise RuntimeError( 'Did not supply lp and eigval is not in datadir!') if eval_loaded: # Attempt to load ipr for network iprglob = glob.glob(datadir + 'ipr.pkl') if iprglob: with open(datadir + 'ipr.pkl', "rb") as input_file: ipr = cPickle.load(input_file) colorV = 1. / ipr linewidth = 0 cax_label = r'$p$' colormap = 'viridis_r' vmin_hdr = None vmax_hdr = None cbar_ticklabels = None cbar_nticks = 4 else: locglob = glob.glob(datadir + 'localization*.txt') if locglob: localization = np.loadtxt(locglob[0], delimiter=',') ill = localization[:, 2] ill_full = np.zeros(len(eigval), dtype=float) ill_full[0:int(len(eigval) * 0.5)] = ill[::-1] ill_full[int(len(eigval) * 0.5):len(eigval)] = ill colorV = ill_full linewidth = 0 cax_label = r'$\lambda^{-1}$' colormap = 'viridis' vmin_hdr = 0.0 vmax_hdr = 1. / (np.max(np.abs(xy0.ravel()))) cbar_ticklabels = ['0', r'$1/L$', r'$2/L$'] cbar_nticks = 3 else: print 'plotting.time_domain_magnetic: Did not find ipr in simulation dir (datadir), ' +\ 'attempting to load based on supplied meshfn...' # First seek directly supplied files in the simulation datadir meshfn_specfn = glob.glob(datadir + 'meshfn_*ipr.txt') if meshfn_specfn: with open(meshfn_specfn[0], 'r') as myfile: meshfn = myfile.read().replace('\n', '') with open( dio.prepdir(meshfn) + 'ipr' + lp['meshfn_exten'] + '.pkl', "rb") as fn: ipr = cPickle.load(fn) colorV = 1. / ipr cax_label = r'$p$' colormap = 'viridis_r' linewidth = 0 vmin_hdr = None vmax_hdr = None cbar_ticklabels = None cbar_nticks = 4 else: print '\n\n\nComputing localization from supplied meshfn\n\n\n' if dos_meshfn_dir is None or dos_meshfn_dir == 'none': dos_meshfn_dir = datadir meshfn_specfn = glob.glob( dio.prepdir(dos_meshfn_dir) + 'meshfn_*localization.txt') print 'meshfn_specfn = ', meshfn_specfn if meshfn_specfn: with open(meshfn_specfn[0], 'r') as myfile: meshfn = myfile.read().replace('\n', '') if lp is not None: print 'Loading based on lp...' import lepm.lattice_class import lepm.gyro_lattice_class # lp = {'LatticeTop': params['LatticeTop'], 'meshfn': params['meshfn']} lat = lepm.lattice_class.Lattice(lp=lp) lat.load() mlat = lepm.magnetic_gyro_lattice_class.MagneticGyroLattice( lat, lp) loczfn = dio.prepdir( meshfn) + 'localization' + mlat.lp[ 'meshfn_exten'] + '.txt' specmeshfn_xy = lat.xy else: print 'plotting.time_domain_magnetic: no lp supplied, assuming default lattice ' +\ 'params to load localization in attempt to load localization...' loczfn = dio.prepdir( meshfn) + 'localization_magnetic.txt' try: specmeshfn_xy = np.loadtxt(meshfn + '_xy.txt') except: specmeshfn_xy = np.loadtxt(meshfn + '_xy.txt', delimiter=',') localization = np.loadtxt(loczfn, delimiter=',') ill = localization[:, 2] ill_full = np.zeros(len(eigval), dtype=float) ill_full[0:int(len(eigval) * 0.5)] = ill[::-1] ill_full[int(len(eigval) * 0.5):len(eigval)] = ill colorV = ill_full linewidth = 0 cax_label = r'$\lambda^{-1}$' colormap = 'viridis' vmin_hdr = 0.0 vmax_hdr = 1. / (np.max( np.abs(specmeshfn_xy.ravel()))) cbar_ticklabels = ['0', r'$1/L$', r'$2/L$'] cbar_nticks = 3 else: print 'plotting.time_domain_magnetic: Did not find ipr or localization in datadirs,' +\ ' attempting to load based on lp...' if lp is not None: print 'Loading based on lp...' import lepm.lattice_class import lepm.gyro_lattice_class # lp = {'LatticeTop': params['LatticeTop'], 'meshfn': params['meshfn']} lat = lepm.lattice_class.Lattice(lp=lp) lat.load() mlat = lepm.magnetic_gyro_lattice_class.MagneticGyroLattice( lat, lp) if mlat.lp['periodicBC']: localization = mlat.get_localization() ill = localization[:, 2] ill_full = np.zeros(len(eigval), dtype=float) ill_full[0:int(len(eigval) * 0.5)] = ill[::-1] ill_full[int(len(eigval) * 0.5):len(eigval)] = ill colorV = ill_full cax_label = r'$\lambda^{-1}$' vmin_hdr = 0.0 vmax_hdr = 1. / (np.max(np.abs( xy0.ravel()))) else: ipr = mlat.get_ipr() colorV = 1. / ipr cax_label = r'$p$' colormap = 'viridis_r' vmin_hdr = None vmax_hdr = None cbar_ticklabels = None cbar_nticks = 4 linewidth = 0 else: print 'Did not supply lp and neither ipr nor localization are in datadir!' colorV = None linewidth = 1 cax_label = '' colormap = 'viridis' vmin_hdr = None vmax_hdr = None cbar_ticklabels = None cbar_nticks = 4 plt.close('all') if np.max(xy0[:, 0]) - np.min( xy0[:, 0]) > 2.0 * (np.max(xy0[:, 1]) - np.min(xy0[:, 1])): # Plot will be very wide, so initialize a wide plot (landscape 16:9) orientation = 'landscape' # Note: header axis is [0.30, 0.80, 0.45, 0.18] if title == '' or title is None: ax_pos = [0.1, 0.05, 0.8, 0.54] cbar_pos = [0.79, 0.80, 0.012, 0.15] else: ax_pos = [0.1, 0.03, 0.8, 0.50] cbar_pos = [0.79, 0.70, 0.012, 0.15] else: # Plot will be roughly square or tall, so initialize a portfolio-style plot orientation = 'portrait' if title == '' or title is None: ax_pos = [0.1, 0.10, 0.8, 0.60] cbar_pos = [0.79, 0.80, 0.012, 0.15] else: ax_pos = [0.1, 0.03, 0.8, 0.60] cbar_pos = [0.79, 0.75, 0.012, 0.15] # Determine line width if len(xy0) > 2000: lw = 1 else: lw = 2 if cax_label == r'$\lambda^{-1}$': if 'penrose' in lp['LatticeTop']: dos_ylabel = 'Density of states, ' + r'$D(\omega)$' + '\nfor periodic approximant' else: dos_ylabel = 'Density of states, ' + r'$D(\omega)$' + '\nfor periodic system' ylabel_pad = 30 ylabel_rot = 90 else: dos_ylabel = r'$D(\omega)$' ylabel_pad = 20 ylabel_rot = 0 print 'plt.get_fignums() = ', plt.get_fignums() fig, DOS_ax, ax = \ leplt.initialize_eigvect_DOS_header_plot(eigval, xy0, sim_type='gyro', page_orientation=orientation, ax_pos=ax_pos, cbar_pos=cbar_pos, colorV=colorV, vmin=vmin_hdr, vmax=vmax_hdr, DOSexcite=DOSexcite, linewidth=linewidth, cax_label=cax_label, colormap=colormap, cbar_nticks=cbar_nticks, cbar_tickfmt='%0.2f', cbar_ticklabels=cbar_ticklabels, cbar_labelpad=17, yaxis_ticks=[], ylabel=dos_ylabel, ylabel_rot=ylabel_rot, ylabel_pad=ylabel_pad, nbins=120, xlabel_pad=15) # DOSexcite = (frequency, sigma_time) # amp(x) = exp[- acoeff * time**2] # amp(k) = sqrt(pi/acoeff) * exp[- pi**2 * k**2 / acoeff] # So 1/(2 * sigma_freq**2) = pi**2 /acoeff # So sqrt(acoeff/(2 * pi**2)) = sigma_freq # sigmak = 1./DOSexcite[1] # xlims = DOS_ax.get_xlim() # ktmp = np.linspace(xlims[0], xlims[1], 300) # gaussk = 0.8 * DOS_ax.get_ylim()[1] * np.exp(-(ktmp - DOSexcite[0])**2 / (2. * sigmak)) # DOS_ax.plot(ktmp, gaussk, 'r-') # plt.sca(ax) else: print 'Could not find eigval.pkl to load for DOS portion of data2stills plots!' ax = plt.gca() else: ax = plt.gca() # Check for evolving rest lengths in params if 'prestrain' in params: prestrain = params['prestrain'] else: prestrain = 0. if 'shrinkrate' in params: shrinkrate = params['shrinkrate'] else: shrinkrate = 0.0 if roughmov: print 'creating rough gyro movie...' tdgyros.stills2mov_gyro(fig, ax, do1, xyfiles, KLfiles, xy0files, xy0, NL, KL, BM0, params, hh, numbering, index_sz, outdir, name, simoutdir, update_KL_each_timestep, deform_xy0, exaggerate, xlimv, ylimv, climv, resolution, color_particles, shrinkrate, prestrain, framerate=float(framerate) / 5., mov_exten='_rough', linewidth=lw, startind=0, title=title, show_bonds=False, **kwargs) # Now do detailed movie if rough is False if not rough: print 'creating fine gyro movie (not skipping any frames)...' doall = [0] + range(0, len(xyfiles)) # do2 = list(set(doall)-set(do1)) # ftodo = do1 + do2 print 'tdmagnetic: exiting here since it is broken here' # sys.exit() tdgyros.stills2mov_gyro(fig, ax, doall, xyfiles, KLfiles, xy0files, xy0, NL, KL, BM0, params, hh, numbering, index_sz, outdir, name, simoutdir, update_KL_each_timestep, deform_xy0, exaggerate, xlimv, ylimv, climv, resolution, color_particles, shrinkrate, prestrain, framerate=framerate, mov_exten=mov_exten, linewidth=lw, startind=0, title=title, movname=movname, show_bonds=False, **kwargs) if rm_stills: # Delete the original images print 'Deleting folder ' + simoutdir + 'stills/' subprocess.call(['rm', '-r', simoutdir + 'stills/'])
def projector_site_vs_dist_glatparam(gcoll, omegac, proj_XY, plot_mag=True, plot_diff=False, save_plt=True, alpha=1.0, maxdistlines=True, reverse_order=False, check=True): """THIS HAS NOT BEEN UPDATED FOR BOTT INDEX SPECIFIC CALC Compare the projector values at distances relative to a particular site (gyro at location proj_XY). Parameters ---------- gcoll : GyroCollection instance The collection of gyro_lattices for which to compare projectors as fn of distance from a given site. omegac : float Cutoff frequency for the projector proj_XY : 2 x 1 float numpy array The location at which to find the nearest gyro and consider projector elements relative to this site. plot : bool Whether to plot magproj vs dist for all GyroLattices in gcoll check : bool Display intermediate results Returns ------- dist_list : list of NP x NP float arrays Euclidean distances between points. Element i,j is the distance between particle i and j proj_list : list of evxyprojs (2 x 2*NP float arrays) Each element is like magproj, but with x and y components separate. So, element 0,2*j gives the magnitude of the x component of the projector connecting the site in question to the x component of particle j and element 1,2*j+1 gives the magnitude of the y component of the projector connecting the site in question to the y component of particle j. """ proj_list = [] dist_list = [] kk = 0 if plot_mag: # magnitude plot mfig, magax, mcbar = leplt.initialize_1panel_cbar_fig() if plot_diff: # difference plot dfig, dax, dcbar = leplt.initialize_1panel_cbar_fig() # difference fraction plot dffig, dfax, dfcbar = leplt.initialize_1panel_cbar_fig() if maxdistlines: maxdist = [] sat = 1 light = 0.6 colors = lecmaps.husl_palette(n_colors=len(gcoll.gyro_lattices), s=sat, l=light) if reverse_order: glat_list = gcoll.gyro_lattices[::-1] else: glat_list = gcoll.gyro_lattices for glat in glat_list: proj_ind = ((glat.lattice.xy - proj_XY)[:, 0]**2 + (glat.lattice.xy - proj_XY)[:, 1]**2).argmin() outdir = dio.prepdir(glat.lp['meshfn'].replace('networks', 'projectors')) outfn = outdir + glat.lp[ 'LatticeTop'] + "_dist_singlept_{0:06d}".format(proj_ind) + ".pkl" if check: print 'identified proj_ind = ', proj_ind newfig = plt.figure() glat.lattice.plot_numbered(ax=plt.gca()) # attempt to load if glob.glob(outfn): with open(outfn, "rb") as fn: dist = pickle.load(fn) outfn = outdir + glat.lp[ 'LatticeTop'] + "_evxyproj_singlept_{0:06d}".format( proj_ind) + ".pkl" with open(outfn, "rb") as fn: evxyproj = pickle.load(fn) else: # compute dists and evxyproj_proj_ind xydiff = glat.lattice.xy - glat.lattice.xy[proj_ind] dist = np.sqrt(xydiff[:, 0]**2 + xydiff[:, 1]**2) print 'bottmagneticgyrofns: calculating projector...' proj = calc_small_projector(glat, omegac, attribute=False) outdir = dio.prepdir(glat.lp['meshfn'].replace( 'networks', 'projectors')) le.ensure_dir(outdir) # save dist as pickle with open(outfn, "wb") as fn: pickle.dump(dist, fn) # evxyproj has dims 2 xlen(evect) evxyproj = np.dstack( (proj[2 * proj_ind, :], proj[2 * proj_ind + 1, :]))[0].T # save evxyproj as pickle outfn = outdir + glat.lp[ 'LatticeTop'] + "_evxyproj_singlept_{0:06d}".format( proj_ind) + ".pkl" with open(outfn, "wb") as fn: pickle.dump(evxyproj, fn) proj_list.append(evxyproj) dist_list.append(dist) if plot_mag: tmp = np.sqrt( np.abs(evxyproj[0]).ravel()**2 + np.abs(evxyproj[1]).ravel()**2) magproj = np.array([ np.sqrt(tmp[2 * ind].ravel()**2 + tmp[2 * ind + 1].ravel()**2) for ind in range(len(dist)) ]) magax.scatter(dist, np.log10(magproj), s=1, color=colors[kk], alpha=alpha) if plot_diff: if kk > 0: # find particles that are the same as in the reference network same_inds = np.where(le.dist_pts(glat.lattice.xy, xy0) == 0) # Order them by distance current = np.array( [[2 * same_inds[0][ii], 2 * same_inds[0][ii] + 1] for ii in range(len(same_inds[0]))]) current = current.ravel() orig = np.array( [[2 * same_inds[1][ii], 2 * same_inds[1][ii] + 1] for ii in range(len(same_inds[0]))]) orig = orig.ravel() # if check: # origfig = plt.figure() # origax = origfig.gca() # [origax, origaxcb] = glat.lattice.plot_numbered(fig=origfig, ax=origax, axis_off=False, # title='Original lattice for proj comparison') # origax.scatter(glat.lattice.xy[same_inds[0], 0], glat.lattice.xy[same_inds[0], 1]) # plt.pause(5) # plt.close() if len(current) > 0: evxydiff = evxyproj[:, current] - evxyproj0[:, orig] tmp = np.sqrt( np.abs(evxydiff[0]).ravel()**2 + np.abs(evxydiff[1]).ravel()**2) magdiff = np.array([ np.sqrt(tmp[2 * ind].ravel()**2 + tmp[2 * ind + 1].ravel()**2) for ind in range(len(same_inds[0])) ]) # magnitude of fractional difference magfdiff = np.array([ magdiff[same_inds[0][ii]] / mag0[same_inds[1][ii]] for ii in range(len(same_inds[0])) ]) dax.scatter(dist[same_inds[0]], magdiff, s=1, color=colors[kk], alpha=alpha) dfax.scatter(dist[same_inds[0]], magfdiff, s=1, color=colors[kk], alpha=alpha) if maxdistlines: maxdist.append(np.max(dist[same_inds[0]])) else: origfig = plt.figure() origax = origfig.gca() [origax, origaxcb] = glat.lattice.plot_numbered( fig=origfig, ax=origax, axis_off=False, title='Original lattice for proj comparison') origfig.show() plt.close() evxyproj0 = copy.deepcopy(evxyproj) xy0 = copy.deepcopy(glat.lattice.xy) tmp = np.sqrt( np.abs(evxyproj[0]).ravel()**2 + np.abs(evxyproj[1]).ravel()**2) mag0 = np.array([ np.sqrt(tmp[2 * ind].ravel()**2 + tmp[2 * ind + 1].ravel()**2) for ind in range(len(dist)) ]) kk += 1 # Save plots outsplit = dio.prepdir(glat.lp['meshfn'].replace('networks', 'projectors')).split('/') outdir = '/' for sdir in outsplit[0:-2]: outdir += sdir + '/' outdir += '/' if plot_mag: if maxdistlines and plot_diff: ylims = magax.get_ylim() print 'ylims = ', ylims ii = 1 for dd in maxdist: magax.plot([dd, dd], np.array([ylims[0], ylims[1]]), '-', color=colors[ii]) ii += 1 magax.set_title('Magnitude of projector vs distance') magax.set_xlabel(r'$|\mathbf{x}_i - \mathbf{x}_0|$') magax.set_ylabel(r'$|P_{i0}|$') # make a scalar mappable for colorbar' husl_cmap = lecmaps.husl_cmap(s=sat, l=light) sm = plt.cm.ScalarMappable(cmap=husl_cmap, norm=plt.Normalize(vmin=0, vmax=1)) sm._A = [] cbar = plt.colorbar(sm, cax=mcbar, ticks=[0, 1]) cbar.ax.set_ylabel(r'$\alpha$', rotation=0) if save_plt: print 'kfns: saving magnitude comparison plot for gcoll (usually run from kitaev_collection)...' mfig.savefig(outdir + glat.lp['LatticeTop'] + "_magproj_singlept.png", dpi=300) else: plt.show() if plot_diff: dax.set_title('Projector differences') dax.set_xlabel(r'$|\mathbf{x}_i - \mathbf{x}_0|$') dax.set_ylabel(r'$|\Delta P_{i0}|$') # make a scalar mappable for colorbar' husl_cmap = lecmaps.husl_cmap(s=sat, l=light) sm = plt.cm.ScalarMappable(cmap=husl_cmap, norm=plt.Normalize(vmin=0, vmax=1)) sm._A = [] cbar = plt.colorbar(sm, cax=dcbar, ticks=[0, 1]) cbar.ax.set_ylabel(r'$\alpha$', rotation=0) if maxdistlines: # Grab ylimits for setting after adding lines ylims = dax.get_ylim() df_ylims = dfax.get_ylim() ii = 1 for dd in maxdist: dax.plot([dd, dd], np.array([-0.05, -0.005]), '-', color=colors[ii]) dfax.plot([dd, dd], np.array([df_ylims[0], -0.01]), '-', color=colors[ii]) ii += 1 dax.set_ylim(-0.05, ylims[1]) dfax.set_ylim(df_ylims[0], df_ylims[1]) # now do fractional difference magnitude plot dfax.set_title('Fractional projector differences') dfax.set_xlabel(r'$|\mathbf{x}_i - \mathbf{x}_0|$') dfax.set_ylabel(r'$|\Delta P_{i0}|/|P_{i0}|$') # make a scalar mappable for colorbar' cbar = plt.colorbar(sm, cax=dfcbar, ticks=[0, 1]) cbar.ax.set_ylabel(r'$\alpha$', rotation=0) if save_plt: print 'kfns: saving diff plot for gcoll projecctors (usually run from kitaev_collection)...' dfig.savefig(outdir + glat.lp['LatticeTop'] + "_diffproj_singlept.png", dpi=300) dffig.savefig(outdir + glat.lp['LatticeTop'] + "_diffproj_singlept_fractionaldiff.png", dpi=300) dfax.set_ylim(-0.1, 1) dffig.savefig(outdir + glat.lp['LatticeTop'] + "_diffproj_singlept_fractionaldiff_zoom.png", dpi=300) dfax.set_ylim(-0.02, 0.1) dffig.savefig(outdir + glat.lp['LatticeTop'] + "_diffproj_singlept_fractionaldiff_extrazoom.png", dpi=300) elif not plot_mag: plt.show() return dist_list, proj_list
def get_cmeshfn(lp, rootdir=None): """Prepare the path where the cherns for a particular lattice are stored. If rootdir is specified, use that for the base of the path. Otherwise, adopt the base of the path from the lattice_params dict (lp) of the lattice. """ meshfn_split = lp['meshfn'].split('/') ind = np.where(np.array(meshfn_split) == 'networks')[0][0] cmeshfn = '' if rootdir is None: for strseg in meshfn_split[0:ind]: cmeshfn += strseg + '/' else: cmeshfn = dio.prepdir(rootdir) cmeshfn += 'bott_haldane/' for strseg in meshfn_split[(ind + 1):]: cmeshfn += strseg + '/' # Form physics subdir for t1, t2, V0_pin_gauss, V0_spring_gauss # Subdirs here eps = 1e-7 if np.abs(lp['t2a']) > eps: cmeshfn += 't2a_real/' elif 'pureimNNN' in lp: if lp['pureimNNN']: cmeshfn += 'pureimNNN/' if 'ABDelta' in lp: if lp['ABDelta'] > eps: cmeshfn += 'ABd' + '{0:0.4f}'.format(lp['ABDelta']).replace( '.', 'p') + '/' if 'pinconf' in lp: if lp['pinconf'] > 0: cmeshfn += 'pinconf' + '{0:04d}'.format(lp['pinconf']) + '/' if 'pureimNNN' in lp: if lp['pureimNNN']: cmeshfn += 'pureimNNN' + '_' if 't2angles' in lp: if lp['t2angles']: cmeshfn += 't2angles' + '/' else: if lp['t2'] != 0.1: cmeshfn += 't2_' + sf.float2pstr(lp['t2']) + '/' if 'ignore_tris' in lp: if lp['ignore_tris']: cmeshfn += 'ignore_tris' + '/' cmeshfn += 'pin' + sf.float2pstr(lp['pin']) cmeshfn += '_t1_' + sf.float2pstr(lp['t1']) cmeshfn += '_t2_' + sf.float2pstr(lp['t2']) if np.abs(lp['t2a']) > 1e-7: cmeshfn += '_t2a_' + sf.float2pstr(lp['t2a']) if lp['V0_pin_gauss'] > 0 or lp['V0_spring_gauss'] > 0: cmeshfn += '_pinV' + sf.float2pstr(lp['V0_pin_gauss']) if lp['V0_spring_gauss'] < eps: if 'pinconf' in lp: if lp['pinconf'] > 0: # Add pinconf tag first, then spring disorder strength cmeshfn += '_pinconf' + '{0:04d}'.format(lp['pinconf']) cmeshfn += '_sprV' + sf.float2pstr(lp['V0_spring_gauss']) else: cmeshfn += '_sprV' + sf.float2pstr(lp['V0_spring_gauss']) else: cmeshfn += '_sprV' + sf.float2pstr(lp['V0_spring_gauss']) else: # Add spring disorder strength FIRST, then configuration tag cmeshfn += '_sprV' + sf.float2pstr(lp['V0_spring_gauss']) cmeshfn += '_pinconf' + '{0:04d}'.format(lp['pinconf']) if 'ABDelta' in lp: if lp['ABDelta'] > 0: cmeshfn += '_ABd' + sf.float2pstr(lp['ABDelta']) return cmeshfn
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
def get_bcpath(cp, lp, rootdir=None, method='varyloc'): """Get the path for outputting info on a collection of chern calculations that uses the chern parameter dict cp. Parameters ---------- cp : dict parameters for chern collection lp : dict lattice parameters for the haldane lattice for which many cherns are computed rootdir : str Root path where info for collections of cherns are stored method : str String describing how to categorize the many cherns Returns ------- cpmesh : str cppath """ meshfn_split = lp['meshfn'].split('/') ind = np.where(np.array(meshfn_split) == 'networks')[0][0] ccmeshfn = '' if rootdir is None: for strseg in meshfn_split[0:ind]: ccmeshfn += strseg + '/' else: ccmeshfn = dio.prepdir(rootdir) ccmeshfn += 'cherns/' for strseg in meshfn_split[(ind + 1):]: ccmeshfn += strseg + '/' ccmeshfn += method # Form physics subdir for t1, t2, V0_pin_gauss, V0_spring_gauss if 'pureimNNN' in lp: if lp['pureimNNN']: cmeshfn += 'pureimNNN' + '_' if 't2angles' in lp: if lp['t2angles']: cmeshfn += 't2angles' + '_' cmeshfn += 'pin' + sf.float2pstr(lp['pin']) cmeshfn += '_t1_' + sf.float2pstr(lp['t1']) cmeshfn += '_t2_' + sf.float2pstr(lp['t2']) if np.abs(lp['t2a']) > 1e-7: cmeshfn += '_t2a_' + sf.float2pstr(lp['t2a']) # Form cp subdir if method != 'omegac': if isinstance(cp['omegac'], np.ndarray): print "Warning: cp['omegac'] is numpy array, using first element to get cpmeshfn..." ccmeshfn += '_omc' + sf.float2pstr(cp['omegac'][0]) else: ccmeshfn += '_omc' + sf.float2pstr(cp['omegac']) ccmeshfn += '_Nks' + str(int(len(cp['ksize_frac_arr']))) ccmeshfn += '_' + cp['shape'] ccmeshfn += '_a' + sf.float2pstr(cp['regalph']) ccmeshfn += '_b' + sf.float2pstr(cp['regbeta']) ccmeshfn += '_g' + sf.float2pstr(cp['reggamma']) ccmeshfn += '_polyT' + sf.float2pstr(cp['polyT']) if method != 'varyloc': ccmeshfn += '_polyoff' + sf.prepstr(cp['poly_offset']).replace( '/', '_') ccmeshfn += '_' + cp['basis'] + '/' return ccmeshfn
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 bottommiddletop_excitation(xy, eigvect, below=None, above=None, top=None, bottom=None, check=False, checkdir=None): """Determine if excitation is weighted toward top, middle or bottom: which chunk has the most excitation: 0-bottom, 0.5-middle, 1.0-top Returns ------- tmb : (#eigval*0.5) x 1 float array 0 for bottom, 0.5 for middle, 1.0 for top """ if above is None: if top is None: top = np.max(xy[:, 1]) if bottom is None: bottom = np.min(xy[:, 1]) above = (top - bottom) * 2. / 3. + bottom if below is None: if top is None: top = np.max(xy[:, 1]) if bottom is None: bottom = np.min(xy[:, 1]) below = (top - bottom) / 3. + bottom magevec = calc_magevecs(eigvect) # etop is the energy in the top third of the system, similar for ebot and emid # Note that each of etop ebot and emid should have lengths of #particles etop = np.sum(magevec[:, xy[:, 1] > above], axis=1) ebot = np.sum(magevec[:, xy[:, 1] < below], axis=1) emid = np.sum(magevec[:, np.logical_and(xy[:, 1] > below, xy[:, 1] < above)], axis=1) # Prepare ebot, emid, etop, indicator (0, 0.5, 1) as columns tmb = np.dstack((ebot, emid, etop, 0.5 * np.ones_like(xy[:, 0])))[0] tops = np.logical_and(etop > emid, etop > ebot) bots = np.logical_and(ebot > emid, ebot > etop) print 'bots = ', bots tmb[tops, 3] = 1.0 tmb[bots, 3] = 0.0 if check: # plot excitation magnitude, excitation, and result import lepm.plotting.plotting as leplt import lepm.dataio as dio fig, ax, cax = leplt.initialize_2panel_1cbar_centy() for (mag, kk) in zip(magevec, np.arange(len(xy[:, 0]))): ax[0].plot(xy[:, 1], mag, 'b.') ylims = ax[0].get_ylim() ax[0].plot([below, below], ylims, 'k--') ax[0].plot([above, above], ylims, 'k--') ax[0].set_title('tmb = {0:0.1f}'.format(tmb[kk])) ax[1].scatter(xy[:, 0], xy[:, 1], s=mag * 250) ax[1].set_ylim(np.min(xy[:, 1]), np.max(xy[:, 1])) ax[1].set_xlim(np.min(xy[:, 0]), np.max(xy[:, 0])) if checkdir is not None: plt.savefig( dio.prepdir(checkdir) + 'magevec_{0:06d}'.format(kk) + '.png') else: plt.pause(1) ax[0].cla() ax[1].cla() return tmb
def get_cmeshfn(lp, rootdir=None): """Prepare the path where the cherns for a particular lattice are stored. If rootdir is specified, use that for the base of the path. Otherwise, adopt the base of the path from the lattice_params dict (lp) of the lattice. Parameters ---------- lp : dict lattice parameters dictionary rootdir : str or None The root of the directory to which to save the chern calculation data Returns ------- cmeshfn : str """ meshfn_split = lp['meshfn'].split('/') ind = np.where(np.array(meshfn_split) == 'networks')[0][0] cmeshfn = '' if rootdir is None: for strseg in meshfn_split[0:ind]: cmeshfn += strseg + '/' else: cmeshfn = dio.prepdir(rootdir) cmeshfn += 'kspace_chern_gyro/' for strseg in meshfn_split[(ind + 1):]: cmeshfn += strseg + '/' # Form physics subdir for Omk, Omg, V0_pin_gauss, V0_spring_gauss eps = 1e-7 if 'ABDelta' in lp: if np.abs(lp['ABDelta']) > eps: cmeshfn += 'ABd' + '{0:0.4f}'.format(lp['ABDelta']).replace( '.', 'p').replace('-', 'n') + '/' if 'pinconf' in lp: if lp['pinconf'] > 0: cmeshfn += 'pinconf' + '{0:04d}'.format(lp['pinconf']) + '/' if 'OmKspec' in lp: if lp['OmKspec'] != '': cmeshfn += lp['OmKspec'] else: cmeshfn += 'Omk' + sf.float2pstr(lp['Omk']) else: cmeshfn += 'Omk' + sf.float2pstr(lp['Omk']) cmeshfn += '_Omg' + sf.float2pstr(lp['Omg']) if lp['V0_pin_gauss'] > 0 or lp['V0_spring_gauss'] > 0: cmeshfn += '_pinV' + sf.float2pstr(lp['V0_pin_gauss']) if np.abs(lp['V0_spring_gauss']) < eps: if 'pinconf' in lp: if lp['pinconf'] > 0: # Add pinconf tag first, then spring disorder strength cmeshfn += '_pinconf' + '{0:04d}'.format(lp['pinconf']) cmeshfn += '_sprV' + sf.float2pstr(lp['V0_spring_gauss']) else: # Add spring disorder strength FIRST, then configuration tag cmeshfn += '_sprV' + sf.float2pstr(lp['V0_spring_gauss']) cmeshfn += '_pinconf' + '{0:04d}'.format(lp['pinconf']) if 'ABDelta' in lp: if lp['ABDelta'] > 0: cmeshfn += '_ABd' + sf.float2pstr(lp['ABDelta']) return cmeshfn
def infinite_dispersion(mglat, kx=None, ky=None, nkxvals=50, nkyvals=20, save=True, save_plot=True, title='Dispersion relation', outdir=None): """ Parameters ---------- mglat : kx : ky : save : title : outdir : Returns ------- omegas, kx, ky """ if not mglat.lp['periodicBC']: raise RuntimeError('Cannot compute dispersion for open BC system') elif mglat.lp['periodic_strip']: print 'Evaluating infinite-system dispersion for strip: setting ky=constant=0.' ky = [0.] if ky is None or kx is None: bboxx = max(mglat.lattice.lp['BBox'][:, 0]) - min(mglat.lattice.lp['BBox'][:, 0]) bboxy = max(mglat.lattice.lp['BBox'][:, 1]) - min(mglat.lattice.lp['BBox'][:, 1]) if kx is None: tmp = np.linspace(-1. / bboxx, 1. / bboxx, nkxvals - 1) step = np.diff(tmp)[0] kx = 2. * np.pi * np.linspace(-1. / bboxx, 1. / bboxx + step, nkxvals) # kx = np.linspace(-5., 5., 40) if ky is None: tmp = np.linspace(-1. / bboxy, 1. / bboxy, nkyvals - 1) step = np.diff(tmp)[0] ky = 2. * np.pi * np.linspace(-1. / bboxy, 1. / bboxy + step, nkyvals) # ky = np.linspace(-5., 5., 4) # First check for saved dispersion if outdir is None: outdir = dio.prepdir(mglat.lp['meshfn']) else: outdir = dio.prepdir(outdir) name = outdir + 'dispersion' + mglat.lp['meshfn_exten'] + '_nx' + str(len(kx)) + '_ny' + str(len(ky)) name += '_maxkx{0:0.3f}'.format(np.max(np.abs(kx))).replace('.', 'p') name += '_maxky{0:0.3f}'.format(np.max(np.abs(ky))).replace('.', 'p') print('checking for file: ' + name + '.pkl') if glob.glob(name + '.pkl'): saved = True with open(name + '.pkl', "rb") as fn: res = pkl.load(fn) omegas = res['omegas'] kx = res['kx'] ky = res['ky'] else: # dispersion is not saved, compute it! saved = False # Use PVx and PVy to multiply exp(i*np.dot(k, PV[0,:])) to periodic vectors in x, similar in y omegas = np.zeros((len(kx), len(ky), len(mglat.lattice.xy) * 2)) matk = lambda k: dynamical_matrix_kspace(k, mglat, eps=1e-10) ii = 0 for kxi in kx: if ii % 25 == 0: print 'infinite_dispersion(): ii = ', ii jj = 0 for kyj in ky: # print 'jj = ', jj matrix = matk([kxi, kyj]) eigval, eigvect = np.linalg.eig(matrix) si = np.argsort(np.imag(eigval)) omegas[ii, jj, :] = np.imag(eigval[si]) # print 'omegas = ', omegas jj += 1 ii += 1 if save_plot: fig, ax = leplt.initialize_1panel_centered_fig() for jj in range(len(ky)): for kk in range(len(omegas[0, jj, :])): ax.plot(kx, omegas[:, jj, kk], 'k-', lw=max(0.03, 5. / (len(kx) * len(ky)))) ax.set_title(title) ax.set_xlabel(r'$k$ $[1/\langle l \rangle]$') ax.set_ylabel(r'$\omega$') print 'magnetic_gyro_kspace_functions: saving image to ' + name + '.png' plt.savefig(name + '.png') plt.close('all') # Plot in 3D # fig = plt.gcf() # ax = fig.add_subplot(projection='3d') # 111, # # rows will be kx, cols wll be ky # kyv = np.array([[ky[i].tolist()] * len(kx) for i in range(len(ky))]).ravel() # kxv = np.array([[kx.tolist()] * len(ky)]).ravel() # print 'kyv = ', np.shape(kyv) # print 'kxv = ', np.shape(kxv) # for kk in range(len(omegas[0, 0, :])): # ax.plot_trisurf(kxv, kyv, omegas[:, :, kk].ravel()) # # ax.view_init(elev=0, azim=0.) # ax.set_title(title) # ax.set_xlabel(r'$k_x$ $[1/\langle l \rangle]$') # ax.set_ylabel(r'$k_y$ $[1/\langle l \rangle]$') # plt.savefig(name + '_3d.png') if save: if not saved: res = {'omegas': omegas, 'kx': kx, 'ky': ky} with open(name + '.pkl', "wb") as fn: pkl.dump(res, fn) return omegas, kx, ky
proj_ind = ((lat.xy[:, 0] - xyloc[0])**2 + (lat.xy[:, 1] - xyloc[1])**2).argmin() print 'proj_ind = ', proj_ind else: proj_ind = args.proj_ind kpfns.plot_projector_locality_singlept(hlat, proj_ind, dists, magproj, outdir=None, network_str=network_str) # Save evxyproj as pkl evxyproj = np.dstack( (proj[2 * proj_ind, :], proj[2 * proj_ind + 1, :]))[0].T outdir = dio.prepdir(hlat.lp['meshfn'].replace('networks', 'projectors')) with open( outdir + hlat.lp['LatticeTop'] + "_evxyproj_singlept_{0:06d}".format(proj_ind) + ".pkl", "wb") as fn: pickle.dump(evxyproj, fn) fig, ax, cbar_ax = kpfns.plot_projector_singlept_network(hlat, evxyproj, fig=None, ax=None, wsfrac=0.5, vspace=0) plt.savefig(outdir + hlat.lp['LatticeTop'] + '_projector_singlept_network.pdf')
def infinite_dispersion(hlat, kx=None, ky=None, save=True, title='Dispersion relation', outdir=None): """Compute energy versus wavenumber for a grid of kx ky values for a haldane model network. If the network is a periodic strip, then ky is set to zero and we look at E(kx). Parameters ---------- hlat : HaldaneLattice instance the tight-binding network over which to compute the dispersion relation kx : N x 1 float array The x component of the wavenumbers to evaluate ky : M x 1 float array The y component of the wavenumbers to evaluate save : bool Whether to save the dispersion to disk title : str title of the plot to make if save is True outdir : str path to the place to save the plot if save is True Returns ------- """ if not hlat.lp['periodicBC']: raise RuntimeError('Cannot compute dispersion for open BC system') elif hlat.lp['periodic_strip']: print 'Evaluating infinite-system dispersion for strip: setting ky=constant=0.' ky = [0.] bboxx = max(hlat.lattice.lp['BBox'][:, 0]) - min( hlat.lattice.lp['BBox'][:, 0]) print 'bboxx = ', bboxx elif ky is None or kx is None: bboxx = max(hlat.lattice.lp['BBox'][:, 0]) - min( hlat.lattice.lp['BBox'][:, 0]) bboxy = max(hlat.lattice.lp['BBox'][:, 1]) - min( hlat.lattice.lp['BBox'][:, 1]) if kx is None: kx = np.linspace(-2. * np.pi / bboxx, 2. * np.pi / bboxx, 50) # kx = np.linspace(-5., 5., 40) if ky is None: ky = np.linspace(-2. * np.pi / bboxy, 2. * np.pi / bboxy, 5) # ky = np.linspace(-5., 5., 4) # First check for saved dispersion if outdir is None: outdir = dio.prepdir(hlat.lp['meshfn']) else: outdir = dio.prepdir(outdir) name = outdir + 'dispersion' + hlat.lp['meshfn_exten'] + '_nx' + str( len(kx)) + '_ny' + str(len(ky)) name += '_maxkx{0:0.3f}'.format(np.max(np.abs(kx))).replace('.', 'p') name += '_maxky{0:0.3f}'.format(np.max(np.abs(ky))).replace('.', 'p') print('checking for file: ' + name + '.pkl') if glob.glob(name + '.pkl'): saved = True with open(name + '.pkl', "rb") as fn: res = pkl.load(fn) omegas = res['omegas'] kx = res['kx'] ky = res['ky'] else: # dispersion is not saved, compute it! saved = False # Use PVx and PVy to multiply exp(i*np.dot(k, PV[0,:])) to periodic vectors in x, similar in y # First convert PVx and PVy to matrices that are the same shape as hlat.matrix # np.exp() omegas = np.zeros((len(kx), len(ky), len(hlat.lattice.xy))) matk = lambda k: dynamical_matrix_kspace(k, hlat, eps=1e-8) timer = Timer() ii = 0 for kxi in kx: print 'infinite_dispersion(): ii = ', ii jj = 0 for kyj in ky: # print 'jj = ', jj timer.restart() matrix = matk([kxi, kyj]) test = timer.get_time_ms() print 'test = ', test print('constructed matrix in: ' + timer.get_time_ms()) print 'diagonalizing...' eigval, eigvect = np.linalg.eig(matrix) timer.restart() print('diagonalized matrix in: ' + timer.get_time_ms()) si = np.argsort(np.real(eigval)) omegas[ii, jj, :] = eigval[si] # print 'omegas = ', omegas jj += 1 ii += 1 if save: fig, ax = leplt.initialize_1panel_centered_fig() for jj in range(len(ky)): for kk in range(len(omegas[0, jj, :])): ax.plot(kx, omegas[:, jj, kk], 'k-', lw=max(0.03, 5. / (len(kx) * len(ky)))) ax.set_title(title) ax.set_xlabel(r'$k$ $[1/\langle \ell \rangle]$') ax.set_ylabel(r'$\omega$') plt.savefig(name + '.png') plt.close('all') # Plot in 3D # fig = plt.gcf() # ax = fig.add_subplot(projection='3d') # 111, # # rows will be kx, cols wll be ky # kyv = np.array([[ky[i].tolist()] * len(kx) for i in range(len(ky))]).ravel() # kxv = np.array([[kx.tolist()] * len(ky)]).ravel() # print 'kyv = ', np.shape(kyv) # print 'kxv = ', np.shape(kxv) # for kk in range(len(omegas[0, 0, :])): # ax.plot_trisurf(kxv, kyv, omegas[:, :, kk].ravel()) # # ax.view_init(elev=0, azim=0.) # ax.set_title(title) # ax.set_xlabel(r'$k_x$ $[1/\langle l \rangle]$') # ax.set_ylabel(r'$k_y$ $[1/\langle l \rangle]$') # plt.savefig(name + '_3d.png') if not saved: res = {'omegas': omegas, 'kx': kx, 'ky': ky} with open(name + '.pkl', "wb") as fn: pkl.dump(res, fn) return omegas, kx, ky
def get_bcpath(cp, lp, rootdir=None, method='varyloc'): """Get the path for outputting info on a collection of bott calculations that uses the calc parameter dict cp. Parameters ---------- cp : dict parameters for bott collection lp : dict lattice parameters for the gyro lattice for which many botts are computed rootdir : str Root path where info for collections of botts are stored method : str String describing how to categorize the many botts Returns ------- bcmeshfn : str path for the bott collection """ meshfn_split = lp['meshfn'].split('/') ind = np.where(np.array(meshfn_split) == 'networks')[0][0] bcmeshfn = '' if rootdir is None: for strseg in meshfn_split[0:ind]: bcmeshfn += strseg + '/' else: bcmeshfn = dio.prepdir(rootdir) bcmeshfn += 'botts/' for strseg in meshfn_split[(ind + 1):]: bcmeshfn += strseg + '/' bcmeshfn += method # Form physics subdir for Omk, Omg, V0_pin_gauss, V0_spring_gauss if lp['Omk'] != -1.0: bcmeshfn += '_Omk' + sf.float2pstr(lp['Omk']) if lp['Omg'] != -1.0: bcmeshfn += '_Omg' + sf.float2pstr(lp['Omg']) if lp['V0_pin_gauss'] > 0 or lp['V0_spring_gauss'] > 0: bcmeshfn += '_pinV' + sf.float2pstr(lp['V0_pin_gauss']) bcmeshfn += '_sprV' + sf.float2pstr(lp['V0_spring_gauss']) # Form cp subdir if method != 'omegac': if isinstance(cp['omegac'], np.ndarray): print "Warning: cp['omegac'] is numpy array, using first element to get cpmeshfn..." bcmeshfn += '_omc' + sf.float2pstr(cp['omegac'][0]) else: bcmeshfn += '_omc' + sf.float2pstr(cp['omegac']) bcmeshfn += '_Nks' + str(int(len(cp['ksize_frac_arr']))) bcmeshfn += '_' + cp['shape'] bcmeshfn += '_a' + sf.float2pstr(cp['regalph']) bcmeshfn += '_b' + sf.float2pstr(cp['regbeta']) bcmeshfn += '_g' + sf.float2pstr(cp['reggamma']) bcmeshfn += '_polyT' + sf.float2pstr(cp['polyT']) if method != 'varyloc': bcmeshfn += '_polyoff' + sf.prepstr(cp['poly_offset']).replace( '/', '_') bcmeshfn += '_' + cp['basis'] + '/' return bcmeshfn
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)