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 build_hex_kagperframe(lp): """Build a hyperuniform centroidal lattice with partially kagomized points beyond a distance alph*Radius/Halfwidth of sample. "per" here means "percolation", referring to the randomly added kagomized elements. Parameters ---------- lp : dict lattice parameters dictionary """ xy, NL, KL, BL, LVUC, LV, UC, PVxydict, PVx, PVy, PV, lattice_exten = bhex.generate_honeycomb_lattice( lp) max_x = np.max(xy[:, 0]) max_y = np.max(xy[:, 1]) min_x = np.min(xy[:, 0]) min_y = np.min(xy[:, 1]) LL = (max_x - min_x, max_y - min_y) BBox = np.array([[min_x, min_y], [min_x, max_y], [max_x, max_y], [max_x, min_y]]) # Grab indices (vertices) to kagomize: select the ones farther than alph*characteristic length from center if lp['shape'] == 'square': lenscaleX = np.max(BBox[:, 0]) * lp['alph'] lenscaleY = np.max(BBox[:, 1]) * lp['alph'] kaginds = np.where( np.logical_or( np.abs(xy[:, 0]) > lenscaleX, np.abs(xy[:, 1]) > lenscaleY))[0] elif lp['shape'] == 'circle': # todo: handle circles pass elif lp['hexagon'] == 'hexagon': # todo: handle hexagons pass # Select some fraction of vertices (which are points) --> xypick gives Nkag of the vertices (xy) Nkag = round(lp['percolation_density'] * len(kaginds)) ind_shuffled = np.random.permutation(np.arange(len(kaginds))) xypick = np.sort(ind_shuffled[0:Nkag]) xy, BL = blf.decorate_kagome_elements(xy, BL, kaginds[xypick], viewmethod=lp['viewmethod'], check=lp['check']) NL, KL = le.BL2NLandKL(BL) if (BL < 0).any(): # todo: make this work print 'Creating periodic boundary vector dictionary for kagper_hucent network...' PV = np.array([]) PVxydict = le.BL2PVxydict(BL, xy, PV) PVx, PVy = le.PVxydict2PVxPVy(PVxydict, NL) # If the meshfn going to overwrite a previous realization? lattice_exten = 'hex_kagperframe' + lattice_exten[9:] +\ '_perd' + sf.float2pstr(lp['percolation_density'], ndigits=2) +\ '_alph' + sf.float2pstr(lp['alph'], ndigits=2) return xy, NL, KL, BL, PVx, PVy, PVxydict, LVUC, BBox, LL, LV, UC, lattice_exten, lp
def build_hyperuniform_annulus(lp): """Build an annular sample of hyperuniform centroid network structure. Parameters ---------- lp : dict lattice parameters dictionary. Uses lp['alph'] to determine the fraction of the system that is cut from the center Returns ------- xy, NL, KL, BL, PVxydict, PVx, PVy, LVUC, BBox, LL, LV, UC, lattice_exten """ xy, NL, KL, BL, PVxydict, PVx, PVy, LL, LVUC, LV, UC, BBox, lattice_exten = build_hyperuniform( lp) # Cut out the center and all particles more than radius away from center. radius = min(np.max(xy[:, 0]), np.max(xy[:, 1])) rad_inner = radius * lp['alph'] dist = np.sqrt(xy[:, 0]**2 + xy[:, 1]**2) keep = np.logical_and(dist > rad_inner, dist < radius) # PVxydict and PV should really not be necessary here, since the network is not periodic if PVxydict: print 'PVxydict = ', PVxydict raise RuntimeError( 'Annulus function is not designed for periodic BCs -- what are you doing?' ) else: xy, NL, KL, BL = le.remove_pts( keep, xy, BL, check=lp['check']) # , PVxydict=PVxydict, PV=PV) lattice_exten += '_alph' + sf.float2pstr(lp['alph']) return xy, NL, KL, BL, PVxydict, PVx, PVy, LVUC, BBox, LL, LV, UC, lattice_exten
def build_isocent_kagframe(lp): """Build a hyperuniform centroidal lattice with kagomized points beyond distance alph*Radius/Halfwidth of sample Parameters ---------- lp : dict lattice parameters dictionary """ from lepm.build import build_iscentroid # if lp['NP_load'] < 1: # lp['NH'] += 5 # lp['NV'] += 5 xy, NL, KL, BL, PVx, PVy, PVxydict, LVUC, BBox, LL, LV, UC, lattice_exten = build_iscentroid.build_iscentroid( lp) # Grab indices (vertices) to kagomize: select the ones farther than alph*characteristic length from center if 'kagframe' in lp['LatticeTop']: lenscaleX = np.max(BBox[:, 0]) * lp['alph'] lenscaleY = np.max(BBox[:, 1]) * lp['alph'] kaginds = np.where( np.logical_or( np.abs(xy[:, 0]) > lenscaleX, np.abs(xy[:, 1]) > lenscaleY))[0] elif 'kagcframe' in lp['LatticeTop']: eps = 1e-9 lenscale = np.max( np.sqrt(xy[:, 0]**2 + xy[:, 1]**2)) * lp['alph'] + eps kaginds = np.where(np.sqrt(xy[:, 0]**2 + xy[:, 1]**2) > lenscale)[0] elif lp['hexagon'] == 'hexagon': # todo: handle hexagons pass xy, BL = blf.decorate_kagome_elements(xy, BL, kaginds, viewmethod=lp['viewmethod'], check=lp['check']) # if trim_after: # print 'trim here' NL, KL = le.BL2NLandKL(BL) if (BL < 0).any(): # todo: make this work print 'Creating periodic boundary vector dictionary for kagper_hucent network...' PV = np.array([]) PVxydict = le.BL2PVxydict(BL, xy, PV) PVx, PVy = le.PVxydict2PVxPVy(PVxydict, NL) # name the output network lattice_exten = lp['LatticeTop'] + lattice_exten[ 10:] + '_alph' + sf.float2pstr(lp['alph'], ndigits=2) return xy, NL, KL, BL, PVx, PVy, PVxydict, LVUC, BBox, LL, LV, UC, lattice_exten, lp
def get_cpmeshfn(cp, lp): """Get the path for the specific haldane model's chern calculation that uses the chern parameter dict cp. """ 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) # 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=7) else: cpmeshfn += '/omc' + sf.float2pstr(cp['omegac'], ndigits=7) cpmeshfn += '/' # + cp['basis'] + '/' 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 build_hex_kagframe(lp): """Build a hyperuniform centroidal lattice with kagomized points beyond distance alph*Radius/Halfwidth of sample Parameters ---------- lp : dict lattice parameters dictionary """ xy, NL, KL, BL, LVUC, LV, UC, PVxydict, PVx, PVy, PV, lattice_exten = bhex.generate_honeycomb_lattice( lp) max_x = np.max(xy[:, 0]) max_y = np.max(xy[:, 1]) min_x = np.min(xy[:, 0]) min_y = np.min(xy[:, 1]) LL = (max_x - min_x, max_y - min_y) BBox = np.array([[min_x, min_y], [min_x, max_y], [max_x, max_y], [max_x, min_y]]) # Grab indices (vertices) to kagomize: select the ones farther than alph*characteristic length from center eps = 1e-9 if lp['shape'] == 'square': lenscaleX = np.max(np.abs(BBox[:, 0])) * lp['alph'] + eps lenscaleY = np.max(np.abs(BBox[:, 1])) * lp['alph'] + eps kaginds = np.where( np.logical_or( np.abs(xy[:, 0]) > lenscaleX, np.abs(xy[:, 1]) > lenscaleY))[0] elif lp['shape'] == 'circle': # todo: handle circles pass elif lp['hexagon'] == 'hexagon': # todo: handle hexagons pass xy, BL = blf.decorate_kagome_elements(xy, BL, kaginds, viewmethod=lp['viewmethod'], check=lp['check']) NL, KL = le.BL2NLandKL(BL) if (BL < 0).any(): # todo: make this work print 'Creating periodic boundary vector dictionary for kagper_hucent network...' PV = np.array([]) PVxydict = le.BL2PVxydict(BL, xy, PV) PVx, PVy = le.PVxydict2PVxPVy(PVxydict, NL) # If the meshfn going to overwrite a previous realization? lattice_exten = 'hex_kagframe' + lattice_exten[9:] +\ '_alph' + sf.float2pstr(lp['alph'], ndigits=2) return xy, NL, KL, BL, PVx, PVy, PVxydict, LVUC, BBox, LL, LV, UC, lattice_exten, lp
def build_kaghu_centframe(lp): """Build a hyperuniform centroidal lattice with kagomized points inside distance alph*Radius/Halfwidth of sample Parameters ---------- lp : dict lattice parameters dictionary """ xy, NL, KL, BL, PVx, PVy, PVxydict, LVUC, BBox, LL, LV, UC, lattice_exten = bhex.build_hucentroid( lp) # Grab indices (vertices) to kagomize: select the ones farther than alph*characteristic length from center if lp['shape'] == 'square': lenscaleX = np.max(BBox[:, 0]) * lp['alph'] lenscaleY = np.max(BBox[:, 1]) * lp['alph'] kaginds = np.where( np.logical_and( np.abs(xy[:, 0]) < lenscaleX, np.abs(xy[:, 1]) < lenscaleY))[0] elif lp['shape'] == 'circle': # todo: handle circles pass elif lp['hexagon'] == 'hexagon': # todo: handle hexagons pass xy, BL = blf.decorate_kagome_elements(xy, BL, kaginds, NL=NL, PVxydict=PVxydict, viewmethod=lp['viewmethod'], check=lp['check']) NL, KL = le.BL2NLandKL(BL) if (BL < 0).any(): print 'Creating periodic boundary vector dictionary for kagper_hucent network...' # The ith row of PV is the vector taking the ith side of the polygon (connecting polygon[i] to # polygon[i+1 % len(polygon)] PV = np.array([[LL[0], 0.0], [LL[0], LL[1]], [LL[0], -LL[1]], [0.0, 0.0], [0.0, LL[1]], [0.0, -LL[1]], [-LL[0], 0.0], [-LL[0], LL[1]], [-LL[0], -LL[1]]]) PVxydict = le.BL2PVxydict(BL, xy, PV) PVx, PVy = le.PVxydict2PVxPVy(PVxydict, NL) # If the meshfn going to overwrite a previous realization? lattice_exten = 'kaghu_centframe' + lattice_exten[10:] +\ '_alph' + sf.float2pstr(lp['alph'], ndigits=2) return xy, NL, KL, BL, PVx, PVy, PVxydict, LVUC, BBox, LL, LV, UC, lattice_exten, lp
def build_kagper_hucent(lp): """Build a hyperuniform centroidal lattice with some density of kagomization (kagper = kagome percolation) Parameters ---------- lp : dict lattice parameters dictionary """ xy, NL, KL, BL, PVx, PVy, PVxydict, LVUC, BBox, LL, LV, UC, lattice_exten = build_hucentroid( lp) # Select some fraction of vertices (which are points) --> xypick gives Nkag of the vertices (xy) Nkag = round(lp['percolation_density'] * len(xy)) ind_shuffled = np.random.permutation(np.arange(len(xy))) xypick = np.sort(ind_shuffled[0:Nkag]) xy, BL = blf.decorate_kagome_elements(xy, BL, xypick, viewmethod=lp['viewmethod'], check=lp['check']) NL, KL = le.BL2NLandKL(BL) if (BL < 0).any(): print 'Creating periodic boundary vector dictionary for kagper_hucent network...' PV = np.array([]) PVxydict = le.BL2PVxydict(BL, xy, PV) PVx, PVy = le.PVxydict2PVxPVy(PVxydict, NL) # If the meshfn going to overwrite a previous realization? mfok = le.meshfn_is_used(le.build_meshfn(lp)[0]) while mfok: lp['subconf'] += 1 mfok = le.meshfn_is_used(le.build_meshfn(lp)[0]) lattice_exten = 'kagper_hucent' + lattice_exten[10:] + \ '_perd' + sf.float2pstr(lp['percolation_density'], ndigits=2) + \ '_r' + '{0:02d}'.format(int(lp['subconf'])) return xy, NL, KL, BL, PVx, PVy, PVxydict, LVUC, BBox, LL, LV, UC, lattice_exten, lp
def movie_cherns_varyloc(ccoll, title='Chern number calculation for varied positions', filename='chern_varyloc', rootdir=None, exten='.png', max_boxfrac=None, max_boxsize=None, xlabel=None, ylabel=None, step=0.5, fracsteps=False, framerate=3): """Plot the chern as a function of space for each haldane_lattice examined Parameters ---------- ccoll : ChernCollection instance The collection of varyloc chern calcs to make into a movie title : str title of the movie filename : str the name of the files to save rootdir : str or None The cproot directory to use (usually self.cp['rootdir']) exten : str (.png, .jpg, etc) file type extension max_boxfrac : float Fraction of spatial extent of the sample to use as maximum bound for kitaev sum max_boxsize : float or None If None, uses max_boxfrac * spatial extent of the sample asmax_boxsize xlabel : str label for x axis ylabel : str label for y axis step : float (default=1.0) how far apart to sample kregion vertices in varyloc fracsteps : bool framerate : int The framerate at which to save the movie max_boxfrac : float Fraction of spatial extent of the sample to use as maximum bound for kitaev sum max_boxsize : float or None If None, uses max_boxfrac * spatial extent of the sample asmax_boxsize """ rad = 1.0 divgmap = cmaps.diverging_cmap(250, 10, l=30) # plot it for hlat_name in ccoll.cherns: hlat = ccoll.cherns[hlat_name][0].haldane_lattice if hlat.lp['shape'] == 'square': # get extent of the network from Bounding box Radius = np.abs(hlat.lp['BBox'][0, 0]) else: # todo: allow different geometries pass # Initialize the figure h_mm = 90 w_mm = 120 # To get space between subplots, figure out how far away ksize region needs to be, based on first chern # Compare max ksize to be used with spatial extent of the lattice. If comparable, make hspace large. # Otherwise, use defaults ksize = ccoll.cherns[hlat_name][0].chern_finsize[:, 2] cgll = ccoll.cherns[hlat_name][0].haldane_lattice.lattice maxsz = max(np.max(cgll.xy[:, 0]) - np.min(cgll.xy[:, 0]), np.max(cgll.xy[:, 1]) - np.min(cgll.xy[:, 1])) if max_boxsize is not None: ksize = ksize[ksize < max_boxsize] else: if max_boxfrac is not None: max_boxsize = max_boxfrac * maxsz ksize = ksize[ksize < max_boxsize] else: ksize = ksize max_boxsize = np.max(ksize) if max_boxsize > 0.9 * maxsz: center0_frac = 0.3 center2_frac = 0.75 elif max_boxsize > 0.65 * maxsz: center0_frac = 0.35 center2_frac = 0.72 elif max_boxsize > 0.55 * maxsz: center0_frac = 0.375 center2_frac = 0.71 else: center0_frac = 0.4 center2_frac = 0.7 fig, ax = initialize_1p5panelcbar_fig(Wfig=w_mm, Hfig=h_mm, wsfrac=0.4, wssfrac=0.4, center0_frac=center0_frac, center2_frac=center2_frac) # dimensions of video in pixels final_h = 720 final_w = 960 actual_dpi = final_h / (float(h_mm) / 25.4) # Add the network to the figure hlat = ccoll.cherns[hlat_name][0].haldane_lattice netvis.movie_plot_2D(hlat.lattice.xy, hlat.lattice.BL, 0 * hlat.lattice.BL[:, 0], None, None, ax=ax[0], fig=fig, axcb=None, xlimv='auto', ylimv='auto', climv=0.1, colorz=False, ptcolor=None, figsize='auto', colormap='BlueBlackRed', bgcolor='#ffffff', axis_off=True, axis_equal=True, lw=0.2) # Add title if title is not None: ax[0].annotate(title, xy=(0.5, .95), xycoords='figure fraction', horizontalalignment='center', verticalalignment='center') if xlabel is not None: ax[0].set_xlabel(xlabel) if ylabel is not None: ax[0].set_xlabel(ylabel) # Position colorbar sm = plt.cm.ScalarMappable(cmap=divgmap, norm=plt.Normalize(vmin=-1, vmax=1)) # fake up the array of the scalar mappable. sm._A = [] cbar = plt.colorbar(sm, cax=ax[1], orientation='horizontal', ticks=[-1, 0, 1]) ax[1].set_xlabel(r'$\nu$') ax[1].xaxis.set_label_position("top") ax[2].axis('off') # Add patches (rectangles from cherns at each site) to the figure print 'Opening hlat_name = ', hlat_name done = False ind = 0 while done is False: rectps = [] colorL = [] for chernii in ccoll.cherns[hlat_name]: # Grab small, medium, and large circles ksize = chernii.chern_finsize[:, 2] if max_boxsize is not None: ksize = ksize[ksize < max_boxsize] else: if max_boxfrac is not None: cgll = chernii.haldane_lattice.lattice maxsz = max(np.max(cgll.xy[:, 0]) - np.min(cgll.xy[:, 0]), np.max(cgll.xy[:, 1]) - np.min(cgll.xy[:, 1])) max_boxsize = max_boxfrac * maxsz ksize = ksize[ksize < max_boxsize] else: ksize = ksize max_boxsize = np.max(ksize) # print 'ksize = ', ksize # print 'max_boxsize = ', max_boxsize xx = float(chernii.cp['poly_offset'].split('/')[0]) yy = float(chernii.cp['poly_offset'].split('/')[1]) nu = chernii.chern_finsize[:, -1] rad = step rect = plt.Rectangle((xx-rad*0.5, yy-rad*0.5), rad, rad, ec="none") colorL.append(nu[ind]) rectps.append(rect) p = PatchCollection(rectps, cmap=divgmap, alpha=1.0, edgecolors='none') p.set_array(np.array(np.array(colorL))) p.set_clim([-1., 1.]) # Add the patches of nu calculations for each site probed ax[0].add_collection(p) # Draw the kitaev cartoon in second axis with size ksize[ind] polygon1, polygon2, polygon3 = kfns.get_kitaev_polygons(ccoll.cp['shape'], ccoll.cp['regalph'], ccoll.cp['regbeta'], ccoll.cp['reggamma'], ksize[ind]) patchlist = [] patchlist.append(patches.Polygon(polygon1, color='r')) patchlist.append(patches.Polygon(polygon2, color='g')) patchlist.append(patches.Polygon(polygon3, color='b')) polypatches = PatchCollection(patchlist, cmap=cm.jet, alpha=0.4, zorder=99, linewidths=0.4) colors = np.linspace(0, 1, 3)[::-1] polypatches.set_array(np.array(colors)) ax[2].add_collection(polypatches) ax[2].set_xlim(ax[0].get_xlim()) ax[2].set_ylim(ax[0].get_ylim()) # Save the plot # make index string indstr = '_{0:06d}'.format(ind) hlat_cmesh = kfns.get_cmeshfn(ccoll.cherns[hlat_name][0].haldane_lattice.lp, rootdir=rootdir) specstr = '_Nks' + '{0:03d}'.format(len(ksize)) + '_step' + sf.float2pstr(step) \ + '_maxbsz' + sf.float2pstr(max_boxsize) outdir = hlat_cmesh + '_' + hlat.lp['LatticeTop'] + '_varyloc_stills' + specstr + '/' fnout = outdir + filename + specstr + indstr + exten print 'saving figure: ' + fnout le.ensure_dir(outdir) fig.savefig(fnout, dpi=actual_dpi*2) # Save at lower res after antialiasing f_img = Image.open(fnout) f_img.resize((final_w, final_h), Image.ANTIALIAS).save(fnout) # clear patches p.remove() polypatches.remove() # del p # Update index ind += 1 if ind == len(ksize): done = True # Turn into movie imgname = outdir + filename + specstr movname = hlat_cmesh + filename + specstr + '_mov' subprocess.call(['./ffmpeg', '-framerate', str(int(framerate)), '-i', imgname + '_%06d' + exten, movname + '.mov', '-vcodec', 'libx264', '-profile:v', 'main', '-crf', '12', '-threads', '0', '-r', '30', '-pix_fmt', 'yuv420p'])
def mode_scaling_tune_junction(lp, args, nmode=None): """First plot scaling for all modes as junction coupling is increased. Then, plot the nth mode as the scaling parameter evolves (typically the bond strength between particles that are nearer than some threshold). Example usage: python gyro_lattice_class.py -mode_scaling_tune_junction -LT hexjunction2triads -N 1 -OmKspec union0p000in0p100 -alph 0.1 -periodic python gyro_lattice_class.py -mode_scaling_tune_junction -LT spindle -N 2 -OmKspec union0p000in0p100 -alph 0.0 -periodic -aratio 0.1 python gyro_lattice_class.py -mode_scaling_tune_junction -LT spindle -N 4 -OmKspec union0p000in0p100 -alph 0.0 -periodic -aratio 0.1 python ./build/make_lattice.py -LT spindle -N 1 -periodic -check -skip_polygons -skip_gyroDOS -aratio 0.1 python ./build/make_lattice.py -LT spindle -N 2 -periodic -check -skip_polygons -skip_gyroDOS -aratio 0.1 python ./build/make_lattice.py -LT spindle -N 4 -periodic -skip_polygons -skip_gyroDOS -aratio 0.1 python ./build/make_lattice.py -LT spindle -N 6 -periodic -skip_polygons -skip_gyroDOS -aratio 0.1 -check python ./build/make_lattice.py -LT spindle -N 8 -periodic -skip_polygons -skip_gyroDOS -aratio 0.1 -check Parameters ---------- lp args nmode : int, int list, or None Returns ------- """ nkvals = 50 if lp['LatticeTop'] in ['hexjunctiontriad', 'spindle', 'hexjunction2triads']: kvals = -np.unique(np.round(np.logspace(-1, 1., nkvals), 2)) # [::-1] dist_thres = lp['OmKspec'].split('union')[-1].split('in')[-1] lpmaster = copy.deepcopy(lp) lat = lattice_class.Lattice(lp) lat.load() if nmode is None: todo = np.arange(len(lat.xy[:, 0])) elif type(nmode) == int: todo = [nmode] else: todo = nmode ########################################################################## outfn = dio.prepdir(lat.lp['meshfn']) + 'glat_eigval_scaling_tune_junction' eigvals, first = [], True for (kval, dmyi) in zip(kvals, np.arange(len(kvals))): lp = copy.deepcopy(lpmaster) lp['OmKspec'] = 'union' + sf.float2pstr(kval, ndigits=3) + 'in' + dist_thres # lat = lattice_class.Lattice(lp) glat = GyroLattice(lat, lp) eigval, eigvect = glat.eig_vals_vects(attribute=True) if first: eigvals = np.zeros((len(kvals), len(eigval)), dtype=float) eigvals[dmyi, :] = np.imag(eigval) first = False # Plot flow of modes print 'eigvals = ', eigvals fig, axes = leplt.initialize_2panel_centy(Wfig=90, Hfig=65, x0frac=0.17, wsfrac=0.38) ax, ax1 = axes[0], axes[1] ymax = np.max(eigvals, axis=1) for kk in range(int(0.5 * len(eigvals[0])), len(eigvals[0])): ydat = eigvals[:, kk] ax.loglog(np.abs(kvals), ydat, 'b-') ax.set_ylim(ymin=0.1) ax.set_ylabel('frequency, $\omega$') ax.set_xlabel("coupling, $\Omega_k'$") if lp['LatticeTop'] == 'hexjunction2triads': ax.text(0.5, 0.9, 'Spectrum formation \n in double honeycomb junction', ha='center', va='center', transform=fig.transFigure) elif lp['LatticeTop'] == 'spindle': if lp['NH'] == lp['NV']: nstr = str(int(lp['NH'])) else: nstr = str(int(lp['NH'])) + ', ' + str(int(lp['NV'])) ax.text(0.5, 0.9, 'Spectrum formation \n ' + r'in spindle lattice ($N=$' + nstr + ')', ha='center', va='center', transform=fig.transFigure) lat.plot_BW_lat(fig=fig, ax=ax1, save=False, close=False, title='') plt.savefig(outfn + '_kmin' + sf.float2pstr(np.min(kvals)) + '_kmax' + sf.float2pstr(np.max(kvals)) + '.pdf') plt.show() ########################################################################## for ii in todo: modefn = dio.prepdir(lat.lp['meshfn']) + 'glat_mode_scaling_tune_junction_mode{0:05d}'.format(ii) +\ '_nkvals{0:04}'.format(nkvals) + '.mov' globmodefn = glob.glob(modefn) if not globmodefn: modedir = dio.prepdir(lat.lp['meshfn']) + 'glat_mode_scaling_tune_junction_mode{0:05d}/'.format(ii) dio.ensure_dir(modedir) previous_ev = None first = True dmyi = 0 for kval in kvals: lp = copy.deepcopy(lpmaster) lp['OmKspec'] = 'union' + sf.float2pstr(kval, ndigits=3) + 'in' + dist_thres # lat = lattice_class.Lattice(lp) glat = GyroLattice(lat, lp) eigval, eigvect = glat.eig_vals_vects(attribute=True) # plot the nth mode # fig, DOS_ax, eax = leplt.initialize_eigvect_DOS_header_plot(eigval, glat.lattice.xy, # sim_type='gyro', cbar_nticks=2, # cbar_tickfmt='%0.3f') fig, dos_ax, eax, ax1, cbar_ax = \ leplt.initialize_eigvect_DOS_header_twinplot(eigval, glat.lattice.xy, sim_type='gyro', ax0_pos=[0.0, 0.10, 0.6, 0.60], ax1_pos=[0.6, 0.15, 0.3, 0.60], header_pos=[0.1, 0.78, 0.4, 0.20], xlabel_pad=8, fontsize=8) # Get the theta that minimizes the difference between the present and previous eigenvalue if previous_ev is not None: realxy = np.real(previous_ev) thetas, eigvects = gdh.phase_fix_nth_gyro(glat.eigvect, ngyro=0, basis='XY') modenum = gdh.phase_difference_minimum(eigvects, realxy, basis='XY') # print 'thetas = ', thetas # if theta < 1e-9: # print 'problem with theta' # sys.exit() else: thetas, eigvects = gdh.phase_fix_nth_gyro(glat.eigvect, ngyro=0, basis='XY') modenum = ii glat.lattice.plot_BW_lat(fig=fig, ax=eax, save=False, close=False, axis_off=False, title='') fig, [scat_fg, scat_fg2, pp, f_mark, lines_12_st], cw_ccw = \ leplt.construct_eigvect_DOS_plot(glat.lattice.xy, fig, dos_ax, eax, eigval, eigvects, modenum, 'gyro', glat.lattice.NL, glat.lattice.KL, marker_num=0, color_scheme='default', sub_lattice=-1, amplify=1., title='') # fig, ax_tmp, [scat_fg, pp, f_mark, lines12_st] = \ # glat.plot_eigvect_excitation(ii, eigval=eigval, eigvect=eigvect, ax=eax, plot_lat=first, # theta=theta, normalization=1.0) # color=lecmaps.blue()) # Store this current eigvector as 'previous_ev' previous_ev = eigvects[modenum] # scat_fg.remove() # scat_fg2.remove() # pp.remove() # if f_mark is not None: # f_mark.remove() # lines_12_st.remove() # eax.cla() # Plot where in evolution we are tracking ngyros = int(np.shape(eigvals)[1] * 0.5) halfev = eigvals[:, ngyros:] for row in halfev.T: ax1.loglog(np.abs(kvals), row, 'b-') trackmark = ax1.plot(np.abs(kval), np.abs(np.imag(eigval))[modenum], 'ro') ax1.set_xlabel(r"vertex coupling, $\Omega_k'$") ax1.set_ylabel(r"frequency, $\omega$") dos_ax.set_xlim(xmin=0) plt.savefig(modedir + 'DOS_' + '{0:05}'.format(dmyi) + '.png', dpi=200) dmyi += 1 first = False # Make movie imgname = modedir + 'DOS_' movname = modedir[:-1] + '_nkvals{0:04}'.format(nkvals) lemov.make_movie(imgname, movname, indexsz='05', framerate=5, rm_images=True, save_into_subdir=True, imgdir=modedir)
def save_normal_modes_mass(mass_lattice, datadir='auto', rm_images=True, save_into_subdir=False, overwrite=True, color='pr', start_number=0): """ Plot the normal modes of a coupled gyros with fixed pivot points and make a movie of them. Note that b and c are built INTO the signs of OmK and Omg. --> b (0 -> 'hang', 1 -> 'stand'). --> c (0 -> aligned with a, 1 -> aligned with a) Parameters ---------- mass_lattice : MassLattice instance with attributes including .lattice, .lp, etc datadir: string directory where simulation data is stored rm_images : bool Whether or not to delete all the images after a movie has been made of the DOS gapims_only : bool Whether to just plot modes near the middle of the DOS frequency range save_into_subdir: bool Whether to save the movie in the same sudir where the DOS/ directory (containing the frames) is placed. """ mlat = mass_lattice NP = len(mlat.lattice.xy) print 'Getting eigenvals/vects of dynamical matrix...' # Find eigval/vect eigval, eigvect = mlat.get_eigval_eigvect() kk = mlat.kk mass = mlat.mass # prepare DOS output dir if datadir == 'auto': datadir = mlat.lp['meshfn'] if 'meshfn_exten' in mlat.lp: exten = mlat.lp['meshfn_exten'] elif mlat.lp['dcdisorder']: # there should be meshfn_exten defined in lp, but since there is not, we make it here if 'V0_pin_gauss' in mlat.lp: if mlat.lp['V0_pin_gauss'] > 0: exten = '_pinV' + sf.float2pstr(mlat.lp['V0_pin_gauss']) + \ '_strV' + sf.float2pstr(mlat.lp['V0_spring_gauss']) if 'V0_pin_flat' in mlat.lp: if mlat.lp['V0_pin_flat'] > 0: exten = '_pinVf' + sf.float2pstr(mlat.lp['V0_pin_flat']) + \ '_strVf' + sf.float2pstr(mlat.lp['V0_spring_flat']) else: exten = '' DOSdir = datadir + 'DOS' + exten + '/' dio.ensure_dir(DOSdir) ##################################### # Prepare for plotting ##################################### # Options for how to color the DOS header if color == 'pr': ipr = mlat.get_ipr() colorV = 1. / ipr lw = 0 cbar_label = r'$p$' colormap = 'viridis_r' elif color == 'ipr': ipr = mlat.get_ipr() colorV = ipr lw = 0 cbar_label = r'$p^{-1}$' colormap = 'viridis' elif color == 'ill': ill = mlat.get_ill() colorV = ill cbar_label = r'$\lambda^{-1}$' lw = 0 colormap = 'viridis' else: colorV = None lw = 1. cbar_label = '' colormap = 'viridis' print 'plotting...' # print 'lemov: eigval = ', eigval # plt.plot(np.arange(len(eigval)), eigval, '.-') # plt.show() # sys.exit() fig, DOS_ax, eig_ax = leplt.initialize_eigvect_DOS_header_plot( eigval, mlat.lattice.xy, sim_type='mass', colorV=colorV, colormap=colormap, linewidth=lw, cax_label=cbar_label, cbar_nticks=2, cbar_tickfmt='%0.3f') dostitle = r'$m = $' + '{0:0.2f}'.format(mlat.lp['mass']) if mlat.lp['ABDelta']: dostitle += r'$\pm$' + '{0:0.2f}'.format(mlat.lp['ABDelta']) dostitle += r' $k=$' + '{0:0.2f}'.format(mlat.lp['kk']) DOS_ax.set_title(dostitle) mlat.lattice.plot_BW_lat(fig=fig, ax=eig_ax, save=False, close=False, axis_off=False, title='') ##################################### # SAVE eigenvals/vects as images ##################################### # First check that we actually need to make the images: if rm_images == True and the movie exists, then stop if # overwrite==False # Construct movname names = DOSdir.split('/')[0:-1] # Construct movie name from datadir path string movname = '' for ii in range(len(names)): if ii < len(names) - 1: movname += names[ii] + '/' else: if save_into_subdir: movname += names[ii] + '/' + names[ii] + '_DOS' else: movname += names[ii] # movname += '_DOS' + gyro_lattice.lp['meshfn_exten'] if not (not overwrite and rm_images and glob.glob(movname + '.mov')): done_pngs = len(glob.glob(DOSdir + 'DOS_*.png')) # check if normal modes have already been done if not done_pngs: # decide on which eigs to plot totN = len(eigval) todo = range(int(round(len(eigval)))) if done_pngs < len(todo): dmyi = 0 for ii in todo: if np.mod(ii, 50) == 0: print 'plotting eigvect ', ii, ' of ', len(eigval) # mlat.lattice.plot_BW_lat(fig=fig, ax=DOS_ax, save=False, close=False, axis_off=False, title='') fig, [scat_fg, scat_fg2, p, f_mark, lines_12_st], cw_ccw = \ leplt.construct_eigvect_DOS_plot(mlat.lattice.xy, fig, DOS_ax, eig_ax, eigval, eigvect, ii, 'mass', mlat.lattice.NL, mlat.lattice.KL, marker_num=0, color_scheme='default', sub_lattice=-1) plt.savefig(DOSdir + 'DOS_' + '{0:05}'.format(dmyi) + '.png') scat_fg.remove() scat_fg2.remove() p.remove() f_mark.remove() lines_12_st.remove() dmyi += 1 fig.clf() plt.close('all') ###################### # Save DOS as movie ###################### imgname = DOSdir + 'DOS_' subprocess.call([ './ffmpeg', '-i', imgname + '%05d.png', movname + '.mov', '-vcodec', 'libx264', '-profile:v', 'main', '-crf', '12', '-threads', '0', '-r', '100', '-pix_fmt', 'yuv420p', '-start_number', str(start_number) ]) if rm_images: # Delete the original images if not save_into_subdir: print 'Deleting folder ' + DOSdir subprocess.call(['rm', '-r', DOSdir]) else: print 'Deleting folder contents ' + DOSdir + 'DOS_*.png' subprocess.call(['rm', '-r', DOSdir + 'DOS_*.png'])
def save_normal_modes_Nashgyro(gyro_lattice, datadir='auto', dispersion=[], sim_type='gyro', rm_images=True, gapims_only=False, save_into_subdir=False, overwrite=True, color='pr', do_bc=False): """ Plot the normal modes of a coupled gyros with fixed pivot points and make a movie of them. Note that b and c are built INTO the signs of OmK and Omg. --> b (0 -> 'hang', 1 -> 'stand'). --> c (0 -> aligned with a, 1 -> aligned with a) Parameters ---------- datadir: string directory where simulation data is stored R : NP x dim array position array in 2d (3d might work with 3rd dim ignored) NL : NP x NN array Neighbor list KL : NP x NN array spring connectivity array OmK : float or NP x NN array OmK (spring frequency array, for Nash limit: (-1)^(c+b)kl^2/Iw' Omg : float or NP x 1 array gravitational frequency array, for Nash limit: (-1)^(c+1)mgl/Iw params : dict parameters dictionary dispersion : array or list dispersion relation of... rm_images : bool Whether or not to delete all the images after a movie has been made of the DOS gapims_only : bool Whether to just plot modes near the middle of the DOS frequency range save_into_subdir: bool Whether to save the movie in the same sudir where the DOS/ directory (containing the frames) is placed. """ glat = gyro_lattice NP = len(glat.lattice.xy) print 'Getting eigenvals/vects of dynamical matrix...' # Find eigval/vect eigval, eigvect = glat.get_eigval_eigvect() OmK = glat.OmK Omg = glat.Omg # prepare DOS output dir if datadir == 'auto': datadir = glat.lp['meshfn'] if 'meshfn_exten' in glat.lp: exten = glat.lp['meshfn_exten'] elif glat.lp['dcdisorder']: # there should be meshfn_exten defined in lp, but since there is not, we make it here if glat.lp['V0_pin_gauss'] > 0: exten = '_pinV' + sf.float2pstr(glat.lp['V0_pin_gauss']) + \ '_strV' + sf.float2pstr(glat.lp['V0_spring_gauss']) elif glat.lp['V0_pin_flat'] > 0: exten = '_pinVf' + sf.float2pstr(glat.lp['V0_pin_flat']) + \ '_strVf' + sf.float2pstr(glat.lp['V0_spring_flat']) else: exten = '' DOSdir = datadir + 'DOS' + exten + '/' dio.ensure_dir(DOSdir) ##################################### # Prepare for plotting ##################################### print 'Preparing plot settings...' omg, omk, do_bc_determined, bcstr, btmp, ctmp, pin = determine_bc_pin( Omg, OmK) do_bc = do_bc and do_bc_determined # Options for how to color the DOS header if color == 'pr': ipr = glat.get_ipr() colorV = 1. / ipr lw = 0 cbar_label = r'$p$' colormap = 'viridis_r' elif color == 'ipr': ipr = glat.get_ipr() colorV = ipr lw = 0 cbar_label = r'$p^{-1}$' colormap = 'viridis' elif color == 'ill': ill = glat.get_ill() colorV = ill cbar_label = r'$\lambda^{-1}$' lw = 0 colormap = 'viridis' else: colorV = None lw = 1. cbar_label = '' colormap = 'viridis' print 'plotting...' fig, DOS_ax, eig_ax = leplt.initialize_eigvect_DOS_header_plot( eigval, glat.lattice.xy, sim_type=sim_type, colorV=colorV, colormap=colormap, linewidth=lw, cax_label=cbar_label, cbar_nticks=2, cbar_tickfmt='%0.3f') dostitle = r'$\Omega_g = $' + '{0:0.2f}'.format(glat.lp['Omg']) if glat.lp['ABDelta']: dostitle += r'$\pm$' + '{0:0.2f}'.format(glat.lp['ABDelta']) dostitle += r' $\Omega_k=$' + '{0:0.2f}'.format(glat.lp['Omk']) DOS_ax.set_title(dostitle) glat.lattice.plot_BW_lat(fig=fig, ax=eig_ax, save=False, close=False, axis_off=False, title='') # Make strings for spring, pin, k, and g values if do_bc: springstr_Hz = '{0:.03f}'.format(omk[0] / (2. * np.pi)) pinstr_Hz = '{0:.03f}'.format(omg[0] / (2. * np.pi)) else: springstr_Hz = '' pinstr_Hz = '' if springstr_Hz != '' and pinstr_Hz != '': text2show = 'spring = ' + springstr_Hz + ' Hz, pin = ' + pinstr_Hz + ' Hz\n' + '\n' + bcstr fig.text(0.4, 0.1, text2show, horizontalalignment='center', verticalalignment='center') # Add schematic of hanging/standing top spinning with dir if do_bc: schem_ax = plt.axes([0.85, 0.0, .025 * 5, .025 * 7], axisbg='w') # drawing schem_ax.plot([0., 0.2], [1 - btmp, btmp], 'k-') schem_ax.scatter([0.2], [btmp], s=150, c='k') schem_ax.arrow(0.2, btmp, -(-1)**ctmp * 0.06, 0.3 * (-1)**(btmp + ctmp), head_width=0.3, head_length=0.1, fc='b', ec='b') wave_x = np.arange(-0.07 * 5, 0.0, 0.001) wave_y = 0.1 * np.sin(wave_x * 100) + 1. - btmp schem_ax.plot(wave_x, wave_y, 'k-') schem_ax.set_xlim(-0.1 * 5, .21 * 5) schem_ax.set_ylim(-0.1 * 7, .21 * 7) schem_ax.axis('off') ##################################### # SAVE eigenvals/vects as images ##################################### # First check that we actually need to make the images: if rm_images == True and the movie exists, then stop if # overwrite==False # Construct movname names = DOSdir.split('/')[0:-1] # Construct movie name from datadir path string movname = '' for ii in range(len(names)): if ii < len(names) - 1: movname += names[ii] + '/' else: if save_into_subdir: movname += names[ii] + '/' + names[ii] + '_DOS' else: movname += names[ii] # movname += '_DOS' + gyro_lattice.lp['meshfn_exten'] if not (not overwrite and rm_images and glob.glob(movname + '.mov')): done_pngs = len(glob.glob(DOSdir + 'DOS_*.png')) # check if normal modes have already been done if not done_pngs: # decide on which eigs to plot totN = len(eigval) if gapims_only: middle = int(round(totN * 0.25)) ngap = int(round(np.sqrt(totN))) todo = range(middle - ngap, middle + ngap) else: todo = range(int(round(len(eigval) * 0.5))) if done_pngs < len(todo): dmyi = 0 for ii in todo: if np.mod(ii, 50) == 0: print 'plotting eigvect ', ii, ' of ', len(eigval) # glat.lattice.plot_BW_lat(fig=fig, ax=DOS_ax, save=False, close=False, axis_off=False, title='') fig, [scat_fg, scat_fg2, p, f_mark, lines_12_st], cw_ccw = \ leplt.construct_eigvect_DOS_plot(glat.lattice.xy, fig, DOS_ax, eig_ax, eigval, eigvect, ii, sim_type, glat.lattice.NL, glat.lattice.KL, marker_num=0, color_scheme='default', sub_lattice=-1) plt.savefig(DOSdir + 'DOS_' + '{0:05}'.format(dmyi) + '.png') scat_fg.remove() scat_fg2.remove() p.remove() f_mark.remove() lines_12_st.remove() dmyi += 1 fig.clf() plt.close('all') ###################### # Save DOS as movie ###################### imgname = DOSdir + 'DOS_' subprocess.call([ './ffmpeg', '-i', imgname + '%05d.png', movname + '.mov', '-vcodec', 'libx264', '-profile:v', 'main', '-crf', '12', '-threads', '0', '-r', '100', '-pix_fmt', 'yuv420p' ]) if rm_images: # Delete the original images if not save_into_subdir: print 'Deleting folder ' + DOSdir subprocess.call(['rm', '-r', DOSdir]) else: print 'Deleting folder contents ' + DOSdir + 'DOS_*.png' subprocess.call(['rm', '-r', DOSdir + 'DOS_*.png'])
def build_lattice(lattice): """Build the lattice based on the values stored in the lp dictionary attribute of supplied lattice instance. Returns ------- lattice : lattice_class lattice instance The instance of the lattice class, with the following attributes populated: lattice.xy = xy lattice.NL = NL lattice.KL = KL lattice.BL = BL lattice.PVx = PVx lattice.PVy = PVy lattice.PVxydict = PVxydict lattice.PV = PV lattice.lp['BBox'] : #vertices x 2 float array BBox is the polygon used to crop the lattice or defining the extent of the lattice; could be hexagonal, for instance. lattice.lp['LL'] : tuple of 2 floats LL are the linear extent in each dimension of the lattice. For ex: ( np.max(xy[:,0])-np.min(xy[:,0]), np.max(xy[:,1])-np.min(xy[:,1]) ) lattice.lp['LV'] = LV lattice.lp['UC'] = UC lattice.lp['lattice_exten'] : str A string specifier for the lattice built lattice.lp['slit_exten'] = slit_exten """ # Define some shortcut variables lattice_type = lattice.lp['LatticeTop'] shape = lattice.lp['shape'] NH = lattice.lp['NH'] NV = lattice.lp['NV'] lp = lattice.lp networkdir = lattice.lp['rootdir'] + 'networks/' check = lattice.lp['check'] if lattice_type == 'hexagonal': from build_hexagonal import build_hexagonal xy, NL, KL, BL, PVxydict, PVx, PVy, PV, LL, LVUC, LV, UC, BBox, lattice_exten = build_hexagonal( lp) elif lattice_type == 'hexmeanfield': from build_hexagonal import build_hexmeanfield xy, NL, KL, BL, PVxydict, PVx, PVy, PV, LL, LVUC, LV, UC, BBox, lattice_exten = build_hexmeanfield( lp) elif lattice_type == 'hexmeanfield3gyro': from build_hexagonal import build_hexmeanfield3gyro xy, NL, KL, BL, PVxydict, PVx, PVy, PV, LL, LVUC, LV, UC, BBox, lattice_exten = build_hexmeanfield3gyro( lp) elif 'selregion' in lattice_type: # amorphregion_isocent or amorphregion_kagome_isocent, for ex # Example usage: python ./build/make_lattice.py -LT selregion_randorg_gammakick1p60_cent -spreadt 0.8 -NP 225 # python ./build/make_lattice.py -LT selregion_iscentroid -N 30 # python ./build/make_lattice.py -LT selregion_hyperuniform -N 80 from lepm.build.build_select_region import build_select_region xy, NL, KL, BL, PVx, PVy, PVxydict, LVUC, BBox, LL, LV, UC, lattice_exten, lp = build_select_region( lp) elif lattice_type == 'frame1dhex': from build_hexagonal import build_frame1dhex # keep only the boundary of the lattice, eliminate the bulk xy, NL, KL, BL, PVxydict, PVx, PVy, LL, LVUC, LV, UC, BBox, lattice_exten = build_frame1dhex( lp) elif lattice_type == 'square': import lepm.build.build_square as bs print '\nCreating square lattice...' xy, NL, KL, BL, lattice_exten = bs.generate_square_lattice( shape, NH, NV, lp['eta'], lp['theta']) print 'lattice_exten = ', lattice_exten PVx = [] PVy = [] PVxydict = {} LL = (NH + 1, NV + 1) LVUC = 'none' UC = 'none' LV = 'none' BBox = np.array([[-LL[0] * 0.5, -LL[1] * 0.5], [LL[0] * 0.5, -LL[1] * 0.5], [LL[0] * 0.5, LL[1] * 0.5], [-LL[0] * 0.5, LL[1] * 0.5]]) elif lattice_type == 'triangular': import lepm.build.build_triangular as bt xy, NL, KL, BL, PVxydict, PVx, PVy, LL, LVUC, LV, UC, BBox, lattice_exten = bt.build_triangular_lattice( lp) elif lattice_type == 'linear': from lepm.build.build_linear_lattices import build_zigzag_lattice xy, NL, KL, BL, PVxydict, PVx, PVy, LL, LVUC, LV, UC, BBox, lattice_exten = build_zigzag_lattice( lp) lp['NV'] = 1 elif lattice_type == 'deformed_kagome': from lepm.build.build_kagome import generate_deformed_kagome xy, NL, KL, BL, PVxydict, PVx, PVy, PV, LL, LVUC, LV, UC, BBox, lattice_exten = generate_deformed_kagome( lp) elif lattice_type == 'deformed_martini': from lepm.build.build_martini import build_deformed_martini xy, NL, KL, BL, PVxydict, PVx, PVy, LL, LVUC, LV, UC, BBox, lattice_exten = build_deformed_martini( lp) elif lattice_type == 'twisted_kagome': from lepm.build.build_kagome import build_twisted_kagome xy, NL, KL, BL, PVxydict, PVx, PVy, LL, LVUC, LV, UC, BBox, lattice_exten = build_twisted_kagome( lp) elif lattice_type == 'hyperuniform': from lepm.build.build_hyperuniform import build_hyperuniform xy, NL, KL, BL, PVxydict, PVx, PVy, LL, LVUC, LV, UC, BBox, lattice_exten = build_hyperuniform( lp) elif lattice_type == 'hyperuniform_annulus': from lepm.build.build_hyperuniform import build_hyperuniform_annulus xy, NL, KL, BL, PVxydict, PVx, PVy, LL, LVUC, LV, UC, BBox, lattice_exten = build_hyperuniform_annulus( lp) lp['shape'] = 'annulus' elif lattice_type == 'isostatic': from lepm.build.build_jammed import build_isostatic # Manually tune coordination of jammed packing (lets you tune through isostatic point) xy, NL, KL, BL, PVxydict, PVx, PVy, LL, LVUC, LV, UC, BBox, lattice_exten = build_isostatic( lp) elif lattice_type == 'jammed': from lepm.build.build_jammed import build_jammed xy, NL, KL, BL, PVxydict, PVx, PVy, LL, LVUC, LV, UC, BBox, lattice_exten = build_jammed( lp) elif lattice_type == 'triangularz': from lepm.build.build_triangular import build_triangularz xy, NL, KL, BL, PVxydict, PVx, PVy, LL, LVUC, LV, UC, BBox, lattice_exten = build_triangularz( lp) elif lattice_type == 'hucentroid': from lepm.build.build_hucentroid import build_hucentroid xy, NL, KL, BL, PVxydict, PVx, PVy, LL, LVUC, LV, UC, BBox, lattice_exten = build_hucentroid( lp) elif lattice_type == 'hucentroid_annulus': from lepm.build.build_hucentroid import build_hucentroid_annulus xy, NL, KL, BL, PVxydict, PVx, PVy, LL, LVUC, LV, UC, BBox, lattice_exten = build_hucentroid_annulus( lp) lp['shape'] = 'annulus' elif lattice_type == 'huvoronoi': from lepm.build.build_voronoized import build_huvoronoi xy, NL, KL, BL, PVx, PVy, PVxydict, LL, BBox, lattice_exten = build_huvoronoi( lp) LVUC = 'none' LV = 'none' UC = 'none' elif lattice_type == 'kagome_hucent': from lepm.build.build_hucentroid import build_kagome_hucent xy, NL, KL, BL, PVxydict, PVx, PVy, LL, LVUC, LV, UC, BBox, lattice_exten = build_kagome_hucent( lp) elif lattice_type == 'kagome_hucent_annulus': from lepm.build.build_hucentroid import build_kagome_hucent_annulus xy, NL, KL, BL, PVxydict, PVx, PVy, LL, LVUC, LV, UC, BBox, lattice_exten = build_kagome_hucent_annulus( lp) lp['shape'] = 'annulus' elif lattice_type == 'kagome_huvor': from lepm.build.build_voronoized import build_kagome_huvor print('Loading hyperuniform to build lattice...') xy, NL, KL, BL, PVx, PVy, PVxydict, LL, BBox, lattice_exten = build_kagome_huvor( lp) LV, LVUC, UC = 'none', 'none', 'none' elif lattice_type == 'iscentroid': from lepm.build.build_iscentroid import build_iscentroid print('Loading isostatic to build lattice...') xy, NL, KL, BL, PVx, PVy, PVxydict, LVUC, BBox, LL, LV, UC, lattice_exten = build_iscentroid( lp) elif lattice_type == 'kagome_isocent': from lepm.build.build_iscentroid import build_kagome_isocent xy, NL, KL, BL, PVx, PVy, PVxydict, LVUC, BBox, LL, LV, UC, lattice_exten = build_kagome_isocent( lp) elif lattice_type == 'overcoordinated1': from lepm.build.build_overcoordinated import generate_overcoordinated1_lattice xy, NL, KL, BL, SBL, LV, UC, LVUC, lattice_exten = generate_overcoordinated1_lattice( NH, NV) PVxydict = {} PVx = [] PVy = [] if lp['check']: le.display_lattice_2D(xy, BL) elif lattice_type == 'circlebonds': from lepm.build.build_linear_lattices import generate_circle_lattice xy, NL, KL, BL, LV, UC, LVUC, lattice_exten = generate_circle_lattice( NH) PVxydict = {} PVx = [] PVy = [] lp['NV'] = 1 minx = np.min(xy[:, 0]) maxx = np.max(xy[:, 0]) miny = np.min(xy[:, 1]) maxy = np.max(xy[:, 1]) BBox = np.array([[minx, miny], [minx, maxy], [maxx, maxy], [maxx, miny]]) LL = (maxx - minx, maxy - miny) elif lattice_type == 'dislocatedRand': from lepm.build.build_dislocatedlattice import build_dislocated_lattice xy, NL, KL, BL, PVx, PVy, PVxydict, LL, BBox, lattice_exten = build_dislocated_lattice( lp) elif lattice_type == 'dislocated': if lp['dislocation_xy'] != 'none': dislocX = lp['dislocation_xy'].split('/')[0] dislocY = lp['dislocation_xy'].split('/')[1] dislocxy_exten = '_dislocxy_' + dislocX + '_' + dislocY pt = np.array([[float(dislocX), float(dislocY)]]) else: pt = np.array([[0., 0.]]) dislocxy_exten = '' if lp['Bvec'] == 'random': Bvecs = 'W' else: Bvecs = lp['Bvec'] xy, NL, KL, BL, lattice_exten = generate_dislocated_hexagonal_lattice( shape, NH, NV, pt, Bvecs=Bvecs, check=lp['check']) lattice_exten += dislocxy_exten PVx = [] PVy = [] PVxydict = {} LL = (np.max(xy[:, 0]) - np.min(xy[:, 0]), np.max(xy[:, 1]) - np.min(xy[:, 1])) BBox = np.array([[np.min(xy[:, 0]), np.min(xy[:, 1])], [np.max(xy[:, 0]), np.min(xy[:, 1])], [np.max(xy[:, 0]), np.max(xy[:, 1])], [np.min(xy[:, 0]), np.max(xy[:, 1])]]) LV = 'none' UC = 'none' LVUC = 'none' elif lattice_type == 'penroserhombTri': if lp['periodicBC']: from lepm.build.build_quasicrystal import generate_periodic_penrose_rhombic xy, NL, KL, BL, PVxydict, BBox, PV, lattice_exten = generate_periodic_penrose_rhombic( lp) LL = (PV[0, 0], PV[1, 1]) PVx, PVy = le.PVxydict2PVxPVy(PVxydict, NL) else: from lepm.build.build_quasicrystal import generate_penrose_rhombic_lattice xy, NL, KL, BL, lattice_exten, Num_sub = generate_penrose_rhombic_lattice( shape, NH, NV, check=lp['check']) LL = (np.max(xy[:, 0]) - np.min(xy[:, 0]), np.max(xy[:, 1]) - np.min(xy[:, 1])) BBox = blf.auto_polygon(shape, NH, NV, eps=0.00) PVx = [] PVy = [] PVxydict = {} LVUC = 'none' LV = 'none' UC = 'none' elif lattice_type == 'penroserhombTricent': from lepm.build.build_quasicrystal import generate_penrose_rhombic_centroid_lattice xy, NL, KL, BL, PVxydict, PV, LL, BBox, lattice_exten = generate_penrose_rhombic_centroid_lattice( lp) # deepcopy PVxydict to generate new pointers PVxydict = copy.deepcopy(PVxydict) if lp['periodicBC']: PVx, PVy = le.PVxydict2PVxPVy(PVxydict, NL) else: PVx, PVy = [], [] # Rescale so that median bond length is unity bL = le.bond_length_list(xy, BL, NL=NL, KL=KL, PVx=PVx, PVy=PVy) scale = 1. / np.median(bL) xy *= scale PV *= scale print 'PV = ', PV BBox *= scale LL = (LL[0] * scale, LL[1] * scale) print 'after updating other things: PVxydict = ', PVxydict if lp['periodicBC']: PVx *= scale PVy *= scale PVxydict.update( (key, val * scale) for key, val in PVxydict.items()) else: PVx = [] PVy = [] LVUC = 'none' LV = 'none' UC = 'none' elif lattice_type == 'kagome_penroserhombTricent': from build.build_quasicrystal import generate_penrose_rhombic_centroid_lattice xy, NL, KL, BL, lattice_exten = generate_penrose_rhombic_centroid_lattice( shape, NH + 5, NV + 5, check=lp['check']) # Decorate lattice as kagome print('Decorating lattice as kagome...') xy, BL, PVxydict = blf.decorate_as_kagome(xy, BL) lattice_exten = 'kagome_' + lattice_exten xy, NL, KL, BL = blf.mask_with_polygon(shape, NH, NV, xy, BL, eps=0.00, check=False) # Rescale so that median bond length is unity bL = le.bond_length_list(xy, BL) xy *= 1. / np.median(bL) minx = np.min(xy[:, 0]) miny = np.min(xy[:, 1]) maxx = np.max(xy[:, 0]) maxy = np.max(xy[:, 1]) BBox = np.array([[minx, miny], [minx, maxy], [maxx, maxy], [maxx, miny]]) LL = (np.max(xy[:, 0]) - np.min(xy[:, 0]), np.max(xy[:, 1]) - np.min(xy[:, 1])) PVx = [] PVy = [] PVxydict = {} LVUC = 'none' LV = 'none' UC = 'none' elif lattice_type == 'random': xx = np.random.uniform(low=-NH * 0.5 - 10, high=NH * 0.5 + 10, size=(NH + 20) * (NV + 20)) yy = np.random.uniform(low=-NV * 0.5 - 10, high=NV * 0.5 + 10, size=(NH + 20) * (NV + 20)) xy = np.dstack((xx, yy))[0] Dtri = Delaunay(xy) TRI = Dtri.vertices BL = le.Tri2BL(TRI) NL, KL = le.BL2NLandKL(BL, NN='min') # Crop to polygon (instead of trimming boundaries) # NL, KL, BL, TRI = le.delaunay_cut_unnatural_boundary(xy, NL, KL, BL, TRI, thres=lp['trimbound_thres']) shapedict = {shape: [NH, NV]} keep = blf.argcrop_lattice_to_polygon(shapedict, xy, check=check) xy, NL, KL, BL = le.remove_pts(keep, xy, BL, NN='min') lattice_exten = lattice_type + '_square_thres' + sf.float2pstr( lp['trimbound_thres']) polygon = blf.auto_polygon(shape, NH, NV, eps=0.00) BBox = polygon LL = (np.max(BBox[:, 0]) - np.min(BBox[:, 0]), np.max(BBox[:, 1]) - np.min(BBox[:, 1])) PVx = [] PVy = [] PVxydict = {} LVUC = 'none' LV = 'none' UC = 'none' elif lattice_type == 'randomcent': from lepm.build.build_random import build_randomcent xy, NL, KL, BL, PVxydict, PVx, PVy, LL, LVUC, LV, UC, BBox, lattice_exten = build_randomcent( lp) elif lattice_type == 'kagome_randomcent': from lepm.build.build_random import build_kagome_randomcent xy, NL, KL, BL, PVxydict, PVx, PVy, LL, LVUC, LV, UC, BBox, lattice_exten = build_kagome_randomcent( lp) elif lattice_type == 'randomspreadcent': from lepm.build.build_randomspread import build_randomspreadcent xy, NL, KL, BL, PVxydict, PVx, PVy, LL, LVUC, LV, UC, BBox, lattice_exten = build_randomspreadcent( lp) elif lattice_type == 'kagome_randomspread': from lepm.build.build_randomspread import build_kagome_randomspread xy, NL, KL, BL, PVxydict, PVx, PVy, LL, LVUC, LV, UC, BBox, lattice_exten = build_kagome_randomspread( lp) elif 'randorg_gammakick' in lattice_type and 'kaghi' not in lattice_type: # lattice_type is like 'randorg_gamma0p20_cent' and uses Hexner pointsets # NH is width, NV is height, NP_load is total number of points. This is different than other conventions. from build_randorg_gamma import build_randorg_gamma_spread xy, NL, KL, BL, PVxydict, PVx, PVy, LL, LVUC, LV, UC, BBox, lattice_exten = build_randorg_gamma_spread( lp) elif 'randorg_gamma' in lattice_type and 'kaghi' not in lattice_type: # lattice_type is like 'randorg_gamma0p20_cent' and uses Hexner pointsets from build_randorg_gamma import build_randorg_gamma_spread_hexner xy, NL, KL, BL, PVxydict, PVx, PVy, LL, LVUC, LV, UC, BBox, lattice_exten = \ build_randorg_gamma_spread_hexner(lp) elif 'random_organization' in lattice_type: try: if isinstance(lp['relax_timesteps'], str): relax_tag = lp['relax_timesteps'] else: relax_tag = '{0:02d}'.format(lp['relax_timesteps']) except: raise RuntimeError( 'lattice parameters dictionary lp needs key relax_timesteps') points = np.loadtxt( networkdir + 'random_organization_source/random_organization/random/' + 'random_kick_' + relax_tag + 'relax/out_d' + '{0:02d}'.format(int(lp['conf'])) + '_xy.txt') points -= np.mean(points, axis=0) xytmp, trash1, trash2, trash3 = blf.mask_with_polygon(shape, NH, NV, points, [], eps=0.00) xy, NL, KL, BL = le.delaunay_centroid_lattice_from_pts(xytmp, polygon='auto', check=check) polygon = blf.auto_polygon(shape, NH, NV, eps=0.00) if check: le.display_lattice_2D(xy, BL) # Rescale so that median bond length is unity bL = le.bond_length_list(xy, BL, NL=NL, KL=KL, PVx=PVx, PVy=PVy) xy *= 1. / np.median(bL) polygon *= 1. / np.median(bL) lattice_exten = lattice_type + '_relax' + relax_tag + '_' + shape + '_d' + \ '{0:02d}'.format(int(lp['loadlattice_number'])) LL = (np.max(xy[:, 0]) - np.min(xy[:, 0]), np.max(xy[:, 1]) - np.min(xy[:, 1])) PVxydict = {} PVx = [] PVy = [] BBox = polygon elif lattice_type == 'flattenedhexagonal': from lepm.build.build_hexagonal import generate_flattened_honeycomb_lattice xy, NL, KL, BL, LVUC, LV, UC, PVxydict, PVx, PVy, lattice_exten = \ generate_flattened_honeycomb_lattice(shape, NH, NV, lp['aratio'], lp['delta'], lp['phi'], eta=0., rot=0., periodicBC=False, check=check) elif lattice_type == 'cairo': from lepm.build.build_cairo import build_cairo xy, NL, KL, BL, PVxydict, PVx, PVy, LL, LVUC, LV, UC, BBox, lattice_exten = build_cairo( lp) elif lattice_type == 'kagper_hucent': from lepm.build.build_hucentroid import build_kagper_hucent xy, NL, KL, BL, PVx, PVy, PVxydict, LVUC, BBox, LL, LV, UC, lattice_exten, lp = build_kagper_hucent( lp) elif lattice_type == 'hex_kagframe': from lepm.build.build_kagcentframe import build_hex_kagframe # Use lp['alph'] to determine the beginning of the kagomized frame, surrounding hexagonal lattice xy, NL, KL, BL, PVx, PVy, PVxydict, LVUC, BBox, LL, LV, UC, lattice_exten, lp = build_hex_kagframe( lp) elif lattice_type == 'hex_kagcframe': from lepm.build.build_kagcentframe import build_hex_kagcframe # Use lp['alph'] to determine the beginning of the kagomized frame, surrounding hexagonal lattice # as circlular annulus xy, NL, KL, BL, PVx, PVy, PVxydict, LVUC, BBox, LL, LV, UC, lattice_exten, lp = build_hex_kagcframe( lp) elif lattice_type in ['hucent_kagframe', 'hucent_kagcframe']: from lepm.build.build_kagcentframe import build_hucent_kagframe # Use lp['alph'] to determine the beginning of the kagomized frame, surrounding hucentroid decoration xy, NL, KL, BL, PVx, PVy, PVxydict, LVUC, BBox, LL, LV, UC, lattice_exten, lp = build_hucent_kagframe( lp) elif lattice_type == 'kaghu_centframe': from lepm.build.build_kagcentframe import build_kaghu_centframe # Use lp['alph'] to determine the beginning of the centroid frame, surrounding kagomized decoration xy, NL, KL, BL, PVx, PVy, PVxydict, LVUC, BBox, LL, LV, UC, lattice_exten, lp = build_kaghu_centframe( lp) elif lattice_type in ['isocent_kagframe', 'isocent_kagcframe']: from lepm.build.build_kagcentframe import build_isocent_kagframe # Use lp['alph'] to determine the beginning of the kagomized frame, surrounding hucentroid decoration xy, NL, KL, BL, PVx, PVy, PVxydict, LVUC, BBox, LL, LV, UC, lattice_exten, lp = build_isocent_kagframe( lp) elif lattice_type == 'kagsplit_hex': from lepm.build.build_kagome import build_kagsplit_hex # Use lp['alph'] to determine what fraction (on the right) is kagomized xy, NL, KL, BL, PVx, PVy, PVxydict, LVUC, BBox, LL, LV, UC, lattice_exten, lp = build_kagsplit_hex( lp) elif lattice_type == 'kagper_hex': from lepm.build.build_kagome import build_kagper_hex # Use lp['alph'] to determine what fraction of the radius/width (in the center) is kagomized xy, NL, KL, BL, PVx, PVy, PVxydict, LVUC, BBox, LL, LV, UC, lattice_exten, lp = build_kagper_hex( lp) elif lattice_type == 'hex_kagperframe': from lepm.build.build_kagcentframe import build_hex_kagperframe # Use lp['alph'] to determine what fraction of the radius/width (in the center) is partially kagomized xy, NL, KL, BL, PVx, PVy, PVxydict, LVUC, BBox, LL, LV, UC, lattice_exten, lp = build_hex_kagperframe( lp) elif lattice_type == 'kagome': from lepm.build.build_kagome import build_kagome # lets you make a square kagome xy, NL, KL, BL, PVx, PVy, PVxydict, PV, LVUC, BBox, LL, LV, UC, lattice_exten, lp = build_kagome( lp) elif 'uofc' in lattice_type: from lepm.build.build_kagcent_words import build_uofc # ['uofc_hucent', 'uofc_kaglow_hucent', 'uofc_kaghi_hucent', 'uofc_kaglow_isocent']: xy, NL, KL, BL, PVx, PVy, PVxydict, LVUC, BBox, LL, LV, UC, lattice_exten, lp = build_uofc( lp) elif 'chicago' in lattice_type: from lepm.build.build_kagcent_words import build_chicago xy, NL, KL, BL, PVx, PVy, PVxydict, LVUC, BBox, LL, LV, UC, lattice_exten, lp = build_chicago( lp) elif 'chern' in lattice_type: from lepm.build.build_kagcent_words import build_kagcentchern xy, NL, KL, BL, PVx, PVy, PVxydict, LVUC, BBox, LL, LV, UC, lattice_exten, lp = build_kagcentchern( lp) elif 'csmf' in lattice_type: from lepm.build.build_kagcent_words import build_kagcentcsmf xy, NL, KL, BL, PVx, PVy, PVxydict, LVUC, BBox, LL, LV, UC, lattice_exten, lp = build_kagcentcsmf( lp) elif 'thanks' in lattice_type: # example: # python ./build/make_lattice.py -LT kaghi_isocent_thanks -skip_gyroDOS -NH 300 -NV 70 -thres 5.5 -skip_polygons from lepm.build.build_kagcent_words import build_kagcentthanks xy, NL, KL, BL, PVx, PVy, PVxydict, LVUC, BBox, LL, LV, UC, lattice_exten, lp = build_kagcentthanks( lp) elif 'curvys' in lattice_type: # for lattice_type in ['kaghi_isocent_curvys', 'kaglow_isocent_curvys', # 'kaghi_hucent_curvys', 'kaglow_hucent_curvys', kaghi_randorg_gammakick1p60_cent_curvys', # 'kaghi_randorg_gammakick0p50_cent_curvys', ... ] # example usage: # python ./build/make_lattice.py -LT kaghi_isocent_curvys -NH 100 -NV 70 -thres 5.5 -skip_polygons -skip_gyroDOS from lepm.build.build_kagcent_words import build_kagcentcurvys xy, NL, KL, BL, PVx, PVy, PVxydict, LVUC, BBox, LL, LV, UC, lattice_exten, lp = build_kagcentcurvys( lp) elif 'hexannulus' in lattice_type: from lepm.build.build_conformal import build_hexannulus xy, NL, KL, BL, lattice_exten, lp = build_hexannulus(lp) LL = (np.max(xy[:, 0]) - np.min(xy[:, 0]), np.max(xy[:, 1]) - np.min(xy[:, 1])) PVxydict = {} PVx = [] PVy = [] UC = np.array([0, 0]) LV = 'none' LVUC = 'none' minx = np.min(xy[:, 0]) miny = np.min(xy[:, 1]) maxx = np.max(xy[:, 0]) maxy = np.max(xy[:, 1]) BBox = np.array([[minx, miny], [minx, maxy], [maxx, maxy], [maxx, miny]]) elif 'accordion' in lattice_type: # accordionhex accordiony accordionkagy # Example usage: # python ./build/make_lattice.py -LT accordionkag -alph 0.9 -intparam 2 -N 6 -skip_polygons -skip_gyroDOS # nzag controlled by lp['intparam'], and the rotation of the kagome element is controlled by lp['alph'] if lattice_type == 'accordionhex': from lepm.build.build_hexagonal import build_accordionhex xy, NL, KL, BL, PVx, PVy, PVxydict, LVUC, BBox, LL, LV, UC, lattice_exten, lp, xyvx = build_accordionhex( lp) elif lattice_type == 'accordionkag': from lepm.build.build_kagome import build_accordionkag xy, NL, KL, BL, PVx, PVy, PVxydict, PV, LVUC, BBox, LL, LV, UC, lattice_exten, lp = build_accordionkag( lp) elif lattice_type == 'accordionkag_hucent': from lepm.build.build_hucentroid import build_accordionkag_hucent xy, NL, KL, BL, PVxydict, PVx, PVy, LL, LVUC, LV, UC, BBox, lattice_exten = \ build_accordionkag_hucent(lp) elif lattice_type == 'accordionkag_isocent': from lepm.build.build_iscentroid import build_accordionkag_isocent xy, NL, KL, BL, PVxydict, PVx, PVy, LL, LVUC, LV, UC, BBox, lattice_exten = \ build_accordionkag_isocent(lp) elif 'spindle' in lattice_type: if lattice_type == 'spindle': from lepm.build.build_spindle import build_spindle xy, NL, KL, BL, PVxydict, PVx, PVy, PV, LL, LVUC, LV, UC, BBox, lattice_exten = build_spindle( lp) elif lattice_type == 'stackedrhombic': from lepm.build.build_rhombic import build_stacked_rhombic xy, NL, KL, BL, PVxydict, PVx, PVy, PV, LL, LVUC, LV, UC, BBox, lattice_exten = build_stacked_rhombic( lp) elif 'junction' in lattice_type: # accordionhex accordiony accordionkagy if lattice_type == 'hexjunction': from lepm.build.build_hexagonal import build_hexjunction xy, NL, KL, BL, PVx, PVy, PVxydict, LVUC, BBox, LL, LV, UC, lattice_exten, lp, xyvx = build_hexjunction( lp) elif lattice_type == 'kagjunction': from lepm.build.build_kagome import build_kagjunction xy, NL, KL, BL, PVx, PVy, PVxydict, LVUC, BBox, LL, LV, UC, lattice_exten, lp = build_kagjunction( lp) ########### # For reference: this is how to change z # le.cut_bonds_z(BL,lp['target_z']) # ##cut N bonds for z # N2cut = int(round((z_start-target_z)*len(BL)/z_start)) # allrows = range(len(BL)) # inds = random.sample(allrows, N2cut) # keep = np.setdiff1d(allrows,inds) # bnd_z = BL[keep] # Cut slit if lp['make_slit']: print('Cuting notch or slit...') L = max(xy[:, 0]) - min(xy[:, 0]) cutL = L * lp['cutLfrac'] x0 = -L * 0. + cutL * 0.5 - 1. # 0.25*L+0.5 BL, xy = blf.cut_slit(BL, xy, cutL + 1e-3, x0, y0=0.2) slit_exten = '_cutL' + str(cutL / L) + 'L_x0_' + str(x0) print('Rebuilding NL,KL...') NP = len(xy) if latticetop == 'deformed_kagome': nn = 4 elif lattice_type == 'linear': if NP == 1: nn = 0 else: nn = 2 else: nn = 'min' NL, KL = le.BL2NLandKL(BL, NP=NP, NN=nn) # remake BL too BL = le.NL2BL(NL, KL) else: slit_exten = '' NP = len(xy) if lp['check']: print 'make_lattice: Showing lattice before saving...' # print 'PVx = ', PVx # print 'PVy = ', PVy le.display_lattice_2D(xy, BL, PVxydict=PVxydict) ################ lattice.xy = xy lattice.NL = NL lattice.KL = KL lattice.BL = BL lattice.PVx = PVx lattice.PVy = PVy lattice.PVxydict = PVxydict lattice.LVUC = LVUC lattice.lp = lp lattice.lp['BBox'] = BBox lattice.lp['LL'] = LL lattice.lp['LV'] = LV lattice.lp['UC'] = UC lattice.lp['lattice_exten'] = lattice_exten lattice.lp['slit_exten'] = slit_exten lattice.lp['Nparticles'] = NP return lattice
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 build_OmK(mglat, lp, OmK): """Construct OmK from supplied OmK (may be None or 'none') and lattice parameter dictionary lp Parameters ---------- mglat : MagneticGyroLattice instance The mgnetic gyro lattice for which to build interaction strength matrix (each element is l^2 k_m / I omega) Note: the distance between two particles is NOT included in OmK. Instead it is computed on the fly in dynamical matrix construction OmK : N x max(#NN) float array or None or 'none' bond frequencies matching the KL and NL arrays, with bonds weakened along gridlines lp : dict lattice parameter dictionary Returns ------- OmK : lp_Omk : float value for key 'Omk' to be added to lp lp_meshfn_exten : str value for key 'meshfn_exten' to be added to lp """ if OmK == 'auto' or OmK is None: # Check if a string specifier for OmK is given. If it can be understood, create that bond strength pattern. # If it is an unknown string, then OmK must be supplied. if 'OmKspec' in lp: if lp['OmKspec'] not in ['', 'none', None]: if 'gridlines' in lp['OmKspec']: raise RuntimeError( 'Should OmKspec be built on lattice (NN) or magnetic (long range) connections?' ) # Here, OmKspec must be of the form: # 'gridlines{0:0.2f}'.format(gridspacing).replace('.', 'p') + \ # 'strong{0:0.3f}'.format(lp['Omk']).replace('.', 'p').replace('-', 'n') + \ # 'weak{0:0.3f}'.format(args.weakbond_val).replace('.', 'p').replace('-', 'n') spec = lp['OmKspec'].split('gridlines')[1] gridspacing = float( spec.split('strong')[0].replace('p', '.')) strong = float( spec.split('strong')[1].split('weak')[0].replace( 'p', '.').replace('n', '-')) weak = float( spec.split('weak')[1].replace('p', '.').replace('n', '-')) maxval = max(np.max(np.abs(mglat.lattice.xy[:, 0])), np.max(np.abs(mglat.lattice.xy[:, 1]))) + 1 OmK = OmK_spec_gridlines(mglat.lattice, lp, gridspacing, maxval, strong, weak) else: raise RuntimeError( 'OmKspec in lp cannot be translated into OmK, must supply OmK or edit to' + ' interpret given OmKspec') lp_meshfn_exten = '_OmKspec' + lp['OmKspec'] if (OmK == OmK[np.nonzero(OmK)][0] * mglat.KL).all(): # This is just the boring case where OmK is not special (all bonds are equal). lp_Omk = OmK[np.nonzero(OmK)][0] if lp_Omk != -1.0: lp_meshfn_exten = '_Omk' + sf.float2pstr(lp['Omk']) else: lp_meshfn_exten = '' elif (OmK != lp['Omk'] * np.abs(mglat.KL)).any(): lp_Omk = -5000 else: lp_Omk = lp['Omk'] done = True else: # OmKspec is in lp, but it is None or 'none'. Try a different method to obtain OmK. done = False else: # OmKspec is not in lp. Try a different method to obtain OmK. done = False if not done: if 'Omk' in lp: # print 'magnetic_gyro_functions: using Omk from lp...' OmK = lp['Omk'] * np.abs(mglat.KL) lp_Omk = lp['Omk'] if lp_Omk != -1.0: lp_meshfn_exten = '_Omk' + sf.float2pstr(lp['Omk']) else: lp_meshfn_exten = '' else: print 'magnetic_gyro_functions: giving OmK the default value of -1s...' OmK = -1.0 * np.abs(mglat.KL) lp_Omk = -1.0 lp_meshfn_exten = '' else: # This is the case where OmK is specified. Pass it along to output and discern what to give for lp_meshfn_exten # Output OmK <-- input OmK # Use given OmK to define lp_Omk (for lp['Omk']) and lp[meshfn_exten]. # If Omk is a key in lp, correct it if it does not match supplied OmK if 'Omk' in lp: if (OmK == lp['Omk'] * np.abs(mglat.KL)).any(): # This is the case that OmK = Omk * np.abs(KL). Give a nontrivial meshfn_exten if Omk != -1.0 lp_Omk = lp['Omk'] if lp_Omk != -1.0: lp_meshfn_exten = '_Omk' + sf.float2pstr(lp['Omk']) else: lp_meshfn_exten = '' else: # OmK given is either some constant times KL, or something complicated # If it is a constant, discern that constant and update lp kinds = np.nonzero(OmK) if len(kinds[0]) > 0: # There are some nonzero elements in OmK. Check if all the same OmKravel = OmK.ravel() KLravel = mglat.KL.ravel() if (OmKravel[np.where(abs(KLravel))] == OmKravel[np.where( abs(KLravel))[0]]).all(): print 'Updating lp[Omk] to reflect specified OmK, since OmK = constant * np.abs(KL)...' lp_Omk = OmKravel[np.where(abs(KLravel))[0]] else: # OmK is something complicated, so tell meshfn_exten that OmK is specified. lp_meshfn_exten = '_OmKspec' if 'OmKspec' in lp: lp_meshfn_exten = '_Omkspec' + lp['OmKspec'] lp_Omk = -5000 else: lp_Omk = 0.0 lp_meshfn_exten = '_Omk0p00' else: # Check if the values of all elements are identical kinds = np.nonzero(OmK) if len(kinds[0]) > 0: # There are some nonzero elements in OmK. Check if all the same value = OmK[kinds[0][0], kinds[1][0]] if (OmK[kinds] == value).all(): lp_Omk = value else: lp_Omk = -5000 else: lp_Omk = 0.0 lp_meshfn_exten = '_Omk0p00' return OmK, lp_Omk, lp_meshfn_exten
# mgc.add_mgyro_lattice(mglat) lpii = copy.deepcopy(lp_submaster) lpii[args.glatparam] = paramV[0] mglat = magnetic_gyro_lattice_class.MagneticGyroLattice(lat, lpii) mglat.load() mgc.add_mgyro_lattice(mglat) print 'Creating bott collection from single-lattice magnetic_gyro_collection...' bmgcoll = bott_magnetic_gyro_collection.BottMagneticGyroCollection(mgc, cp=cp) bmgcollcoll.add_bott_mgyro_collection(bmgcoll, delta) bmgcoll.calc_botts_vary_glatparam('ABDelta', paramV, reverse=args.glatparam_reverse, auto_omegac=True, save_eigv=False, force_hdf5_eigv=False) print '\n\n\n\nbmgcollcoll.bott_mgyro_collections = ', bmgcollcoll.bott_mgyro_collections outname = cprootdir + 'bott_magnetic_gyro/' + lp['LatticeTop'] + '_NH' + str(lp['NH']) + \ '_aol' + sf.float2pstr(lp['aoverl'], ndigits=8) + \ '_vpin' + sf.float2pstr(lp['V0_pin_gauss'], ndigits=8) + \ '_abphase.png' dio.ensure_dir(cprootdir + 'bott_magnetic_gyro/') # Form title title = 'Bott phase diagram ' + r'$a/\ell$=' + '{0:0.2f}'.format(lp['aoverl']) + \ r' $V_{p}$=' + '{0:0.2f}'.format(lp['V0_pin_gauss']) bmgcollcoll.plot_bott_lpparam_glatparam(outname=outname, title=title, glatparam=args.glatparam) # # Collate botts for one lattice with a mgyro_lattice parameter that varies between instances of that lattice # lp_master = copy.deepcopy(lp) # paramV = sf.string_sequence_to_numpy_array(args.paramV, dtype=float) # if args.lpparam == 'delta': # # vary delta between lattices # deltaV = np.arange(0.7, 1.31, 0.1)
else: deltagrid = np.vstack((deltagrid, deltas)) abdgrid = np.vstack((abdgrid, abds)) cherngrid = np.vstack((cherngrid, cherns)) plt.close('all') fig, ax, cax = leplt.initialize_1panel_cbar_cent() lecmaps.register_colormaps() cmap = 'bbr0' # deltagrid.reshape((len(abds), -1)) # abdgrid.reshape((len(abds), -1)) # cherngrid.reshape((len(abds), -1)) # leplt.plot_pcolormesh_scalar(deltagrid, abdgrid, cherngrid, outpath=None, cmap=cmap, vmin=-1.0, vmax=1.0) leplt.plot_pcolormesh(deltagrid / np.pi, abdgrid, cherngrid, 100, ax=ax, make_cbar=False, cmap=cmap, vmin=-1.0, vmax=1.0) # ax.scatter(deltagrid, abdgrid, c=cherngrid, cmap=cmap, vmin=-1.0, vmax=1.0) sm = leplt.empty_scalar_mappable(vmin=-1.0, vmax=1.0, cmap=cmap) cb = plt.colorbar(sm, cax=cax, orientation='horizontal') cb.set_label(label=r'Chern number, $\nu$', labelpad=-35) cb.set_ticks([-1, 0, 1]) ax.set_xlabel(r'Lattice deformation angle, $\delta/\pi$') ax.set_ylabel(r'Inversion symmetry breaking, $\Delta$') specstr = '_aol' + sf.float2pstr(lp['aoverl']) + '_Omk' + sf.float2pstr(lp['Omk']) specstr += '_delta' + sf.float2pstr(np.min(deltagrid)) + '_' + sf.float2pstr(np.max(deltagrid)) specstr += '_abd' + sf.float2pstr(np.min(abdgrid)) + '_' + sf.float2pstr(np.max(abdgrid)) specstr += '_ndeltas{0:05d}'.format(len(deltas)) + '_nabd{0:05d}'.format(len(abds)) specstr += '_density{0:07d}'.format(cp['density']) plt.savefig(rootdir + 'kspace_cherns_mgyro/abtransition' + specstr + '.png')
def make_mode_movie(seriesdir, amp=50, semilog=True, freqmin=None, freqmax=None, overwrite=False, percent_max=0.01): """ Parameters ---------- seriesdir : str The full path to the directory with all tracked cines for which to make mode decomposition movies amp : float The amplification factor for the displacements in the movie output semilog : bool plot the FFT intensity vs frequency in log-normal scale freqmin : float The minimum frequency to plot freqmax : float The maximum frequency to plot overwrite : bool Overwrite the saved images/movies if they exist Returns ------- """ pathlist = dio.find_subdirs('20*', seriesdir) freqstr = '' if freqmin is not None: freqstr += '_minfreq' + sf.float2pstr(freqmin) if freqmax is not None: freqstr += '_maxfreq' + sf.float2pstr(freqmax) for path in pathlist: movname = path + 'modes_amp{0:0.1f}'.format(amp).replace( '.', 'p') + freqstr + '.mov' movexist = glob.glob(movname) print 'mode_movie: movexist = ', movexist if not movexist or overwrite: # If the movie does not exist yet, make it here print 'building modes for ', path fn = os.path.join(path, 'com_data.hdf5') print 'mode_drawing_functions.mode_movie.make_mode_movie(): loading data from ', fn data = new_mf.load_linked_data_and_window(fn) tp, fft_x, fft_y, freq = nmf.ffts_and_add(data) high_power_inds = nmf.find_peaks(tp, percent_max=percent_max) # Check how many mode images have been done modespngs = glob.glob(path + 'modes' + freqstr + '/*.png') modespngs_traces = glob.glob(path + 'modes_traces' + freqstr + '/*.png') # If we haven't made images of all the modes, do that here print 'mode_movie.make_mode_movie(): len(modespngs) = ', len( modespngs) print 'mode_movie.make_mode_movie(): len(high_power_inds) = ', len( high_power_inds) if len(modespngs) < len(high_power_inds) or overwrite: # Check if mode pickle is saved modesfn_traces = path + 'modes_trackes' + freqstr + '.pkl' globfn = glob.glob(modesfn_traces) if globfn: with open(globfn[0], "rb") as fn: mode_data = cPickle.load(fn) coords = mode_data['xy'] mode_data = dh.removekey(mode_data, 'xy') for i in mode_data: if i % 10 == 0: print 'mode_movie.make_mode_movie(): Creating mode image #', i x_traces = mode_data[i][ 'x_traces'] # sf.float2pcstr(freq[high_power_inds[i]], ndigits=8)] y_traces = mode_data[i]['y_traces'] fig = sps.figure_in_mm(120, 155) ax_mode = sps.axes_in_mm(10, 10, 100, 100) ax_freq = sps.axes_in_mm(10, 120, 100, 30) axes = [ax_mode, ax_freq] new_mf.draw_mode(x_traces, y_traces, coords, [freq, tp], axes, i, freq[high_power_inds[i]], output_dir=os.path.join( path, 'modes'), amp=amp, semilog=semilog) else: # The mode data is not saved, so we must create it as we go along # data = new_mf.load_linked_data_and_window(fn) coords = np.array([data[2], data[3]]).T for i in xrange(len(high_power_inds)): if i % 10 == 0: print 'mode_movie.make_mode_movie(): Creating mode image #', i x_traces, y_traces, max_mag = new_mf.get_mode_drawing_data( fft_x, fft_y, freq, high_power_inds[i]) x_traces = np.array(x_traces) y_traces = np.array(y_traces) fig = sps.figure_in_mm(120, 155) ax_mode = sps.axes_in_mm(10, 10, 100, 100) ax_freq = sps.axes_in_mm(10, 120, 100, 30) axes = [ax_mode, ax_freq] new_mf.draw_mode(x_traces, y_traces, coords, [freq, tp], axes, i, freq[high_power_inds[i]], output_dir=os.path.join( path, 'modes'), amp=amp, semilog=semilog) # Obtain imagename and moviename, create movie if it doesn't exist modesfn = glob.glob(path + 'modes' + freqstr + '/*.png') imagename_split = modesfn[0].split('/')[-1].split('.png')[0] try: test = int(imagename_split) indexsz = len(imagename_split) imgname = path + 'modes' + freqstr + '/' except: print 'mode_movie.make_mode_movie(): imagename_split = ', imagename_split print 'mode_movie.make_mode_movie(): indexsz = ', len( imagename_split) raise RuntimeError( 'Imagename is not just an int -- write code to allow ') movies.make_movie(imgname, movname, indexsz=str(indexsz), framerate=10)
def save_mode_data(seriesdir, thres=0.005, overwrite=False, freqmin=None, freqmax=None): """Save the mode data if it doesn't already exist. Parameters ---------- seriesdir : str The full path to the directory with all tracked cines for which to make mode decomposition movies thres : float fraction of the maximum amplitude in fft for including the mode in the saved data Returns ------- """ pathlist = dio.find_subdirs('201*', seriesdir) freqstr = '' if freqmin is not None: freqstr += '_minfreq' + sf.float2pstr(freqmin) if freqmax is not None: freqstr += '_maxfreq' + sf.float2pstr(freqmax) for path in pathlist: print 'building modes for ', path fn = os.path.join(path, 'com_data.hdf5') outfn = path + 'modes' + freqstr + '.pkl' outfn_traces = path + 'modes_traces' + freqstr + '.pkl' if not glob.glob(outfn) or not glob.glob(outfn_traces) or overwrite: # Note that fft_x,y are NP x #modes complex arrays print 'mode_drawing_functions.new_mode_functions.make_mode_movie(): loading data from ', fn data = load_linked_data_and_window(fn) tp, fft_x, fft_y, freq = nmf.ffts_and_add(data) high_power_inds = nmf.find_peaks(tp, percent_max=thres) if freqmin is not None: tmp_inds = np.argwhere(freq[high_power_inds] > freqmin) high_power_inds = high_power_inds[tmp_inds] if freqmax is not None: tmp_inds = np.argwhere(freq[high_power_inds] < freqmax) high_power_inds = high_power_inds[tmp_inds] # get the rest positions of the gyros, xy # xydata = load_linked_data_and_window(fn) meanx_arr, meany_arr = data[2], data[3] # Create dictionary of all the modes mode_data = {'xy': np.dstack((meanx_arr, meany_arr))[0]} mode_traces = {'xy': np.dstack((meanx_arr, meany_arr))[0]} for i in xrange(len(high_power_inds)): if i % 10 == 0: print 'Constructing data for mode #', i x_traces, y_traces, max_mag = get_mode_drawing_data( fft_x, fft_y, freq, high_power_inds[i]) # Get total magnitude in this maode (different from max_mag which is biggest magnitude of a single site) # print 'np.shape(fft_x) = ', np.shape(fft_x) # print 'high_power_inds = ', high_power_inds # Note that fft_x,y are NP x #modes complex arrays tot_mag = np.sum( np.sqrt( np.abs(fft_x[:, high_power_inds[i]])**2 + np.abs(fft_y[:, high_power_inds[i]])**2)) x_traces = np.array(x_traces) y_traces = np.array(y_traces) mode_data[i] = { 'max_mag': max_mag, 'tot_mag': tot_mag, 'fft_x': fft_x[:, high_power_inds[i]], 'fft_y': fft_y[:, high_power_inds[i]], 'freq': freq[high_power_inds[i]], } mode_traces[i] = { 'x_traces': x_traces, 'y_traces': y_traces, 'freq': freq[high_power_inds[i]], 'max_mag': max_mag, 'tot_mag': tot_mag, } # print 'np.shape(fft_x) = ', np.shape(fft_x[:, i]) # save the dictionary in pickle print 'saving the dictionary here: ' + outfn with open(outfn, "wb") as fn: cPickle.dump(mode_data, fn) with open(outfn_traces, "wb") as fn: cPickle.dump(mode_traces, fn) else: print 'Found mode data on disk, skipping...'
def build_kk(lattice, lp, kk): """Construct kk from supplied kk (may be None or 'none') and lattice parameter dictionary lp Parameters ---------- lattice : lattice_class.Lattice() instance kk : N x max(#NN) float array or None or 'none' spring constants matching the KL and NL arrays, with bonds weakened along gridlines lp : dict lattice parameter dictionary Returns ------- kk :N x max(#NN) float array spring constants matching the KL and NL arrays, with bonds weakened along gridlines lp_kk : float value for key 'kk' to be added to lp lp_meshfn_exten : str value for key 'meshfn_exten' to be added to lp """ if kk == 'auto' or kk is None: # Check if a string specifier for kk is given. If it can be understood, create that bond strength pattern. # If it is an unknown string, then kk must be supplied. if 'kkspec' in lp: if lp['kkspec'] not in ['', 'none', None]: if 'gridlines' in lp['kkspec']: # Here, kkspec must be of the form: # 'gridlines{0:0.2f}'.format(gridspacing).replace('.', 'p') + \ # 'strong{0:0.3f}'.format(lp['kk']).replace('.', 'p').replace('-', 'n') + \ # 'weak{0:0.3f}'.format(args.weakbond_val).replace('.', 'p').replace('-', 'n') spec = lp['kkspec'].split('gridlines')[1] gridspacing = float(spec.split('strong')[0].replace('p', '.')) strong = float(spec.split('strong')[1].split('weak')[0].replace('p', '.').replace('n', '-')) weak = float(spec.split('weak')[1].replace('p', '.').replace('n', '-')) maxval = max(np.max(np.abs(lattice.xy[:, 0])), np.max(np.abs(lattice.xy[:, 1]))) + 1 kk = kk_spec_gridlines(lattice, lp, gridspacing, maxval, strong, weak) else: raise RuntimeError('kkspec in lp cannot be translated into kk, must supply kk or edit to' + ' interpret given kkspec') lp_meshfn_exten = '_kkspec' + lp['kkspec'] if (kk == kk[np.nonzero(kk)][0] * lattice.KL).all(): # This is just the boring case where kk is not special (all bonds are equal). lp_kk = kk[np.nonzero(kk)][0] if lp_kk != 1.0: lp_meshfn_exten = '_kk' + sf.float2pstr(lp['kk']) else: lp_meshfn_exten = '' elif (kk != lp['kk'] * np.abs(lattice.KL)).any(): lp_kk = -5000 else: lp_kk = lp['kk'] done = True else: # kkspec is in lp, but it is None or 'none'. Try a different method to obtain kk. done = False else: # kkspec is not in lp. Try a different method to obtain kk. done = False if not done: if 'kk' in lp: print 'gyro_lattice_class: using kk from lp...' kk = lp['kk'] * np.abs(lattice.KL) lp_kk = lp['kk'] if lp_kk != 1.0: lp_meshfn_exten = '_kk' + sf.float2pstr(lp['kk']) else: lp_meshfn_exten = '' else: print 'giving kk the default value of 1s...' kk = 1.0 * np.abs(lattice.KL) lp_kk = 1.0 lp_meshfn_exten = '' else: # This is the case where kk is specified. Pass it along to output and discern what to give for lp_meshfn_exten # Output kk <-- input kk # Use given kk to define lp_kk (for lp['kk']) and lp[meshfn_exten]. # If kk is a key in lp, correct it if it does not match supplied kk if 'kk' in lp: if (kk == lp['kk'] * np.abs(lattice.KL)).any(): # This is the case that kk = kk * np.abs(KL). Give a nontrivial meshfn_exten if kk != 1.0 lp_kk = lp['kk'] if lp_kk != 1.0: lp_meshfn_exten = '_kk' + sf.float2pstr(lp['kk']) else: lp_meshfn_exten = '' else: # kk given is either some constant times KL, or something complicated # If it is a constant, discern that constant and update lp kinds = np.nonzero(kk) if len(kinds[0]) > 0: # There are some nonzero elements in kk. Check if all the same kkravel = kk.ravel() KLravel = lattice.KL.ravel() if (kkravel[np.where(abs(KLravel))] == kkravel[np.where(abs(KLravel))[0]]).all(): print 'Updating lp[kk] to reflect specified kk, since kk = constant * np.abs(KL)...' lp_kk = kkravel[np.where(abs(KLravel))[0]] else: # kk is something complicated, so tell meshfn_exten that kk is specified. lp_meshfn_exten = '_kkspec' if 'kkspec' in lp: lp_meshfn_exten = '_kkspec' + lp['kkspec'] lp_kk = -5000 else: lp_kk = 0.0 lp_meshfn_exten = '_kk0p00' else: # Check if the values of all elements are identical kinds = np.nonzero(kk) if len(kinds[0]) > 0: # There are some nonzero elements in kk. Check if all the same value = kk[kinds[0][0], kinds[1][0]] if (kk[kinds] == value).all(): lp_kk = value else: lp_kk = -5000 else: lp_kk = 0.0 lp_meshfn_exten = '_kk0p00' return kk, lp_kk, lp_meshfn_exten
def build_hex_kagcframe(lp): """Build a hyperuniform centroidal lattice with kagomized points beyond distance alph*Radius/Halfwidth of sample Parameters ---------- lp : dict lattice parameters dictionary """ hclp = copy.deepcopy(lp) hclp['eta'] = 0.0 xy, tr1, tr2, BL, tr3, tr4, tr5, PVxydict, PVx, PVy, PV, lattice_exten = bhex.generate_honeycomb_lattice( hclp) max_x = np.max(xy[:, 0]) max_y = np.max(xy[:, 1]) min_x = np.min(xy[:, 0]) min_y = np.min(xy[:, 1]) LL = (max_x - min_x, max_y - min_y) BBox = np.array([[min_x, min_y], [min_x, max_y], [max_x, max_y], [max_x, min_y]]) # Grab indices (vertices) to kagomize: select the ones farther than alph*characteristic length from center eps = 1e-9 lenscale = np.max(np.sqrt(xy[:, 0]**2 + xy[:, 1]**2)) * lp['alph'] + eps print "lp['alph'] = ", lp['alph'] print "lp['alph'] * np.abs(BBox[:, 0])) = ", lp['alph'] * np.abs(BBox[:, 0]) print 'lenscale = ', lenscale kaginds = np.where(np.sqrt(xy[:, 0]**2 + xy[:, 1]**2) > lenscale)[0] xy, BL = blf.decorate_kagome_elements(xy, BL, kaginds, viewmethod=lp['viewmethod'], check=lp['check']) NL, KL = le.BL2NLandKL(BL) if (BL < 0).any(): # todo: make this work print 'Creating periodic boundary vector dictionary for kagper_hucent network...' PV = np.array([]) PVxydict = le.BL2PVxydict(BL, xy, PV) PVx, PVy = le.PVxydict2PVxPVy(PVxydict, NL) # Only randomly displace the gyros in frame, and only if eta >0 if lp['eta'] > 0.0: if 'eta_alph' not in lp: lp['eta_alph'] = lp['alph'] eta_lenscale = np.max( np.sqrt(xy[:, 0]**2 + xy[:, 1]**2)) * lp['eta_alph'] + eps print '\n\n\n\n\n\n\n\n\n\n\n\n\n\n\neta_lenscale = ', eta_lenscale print '\n\n\n\n\n\n\n\n\n\n\n\n\n\n\neta_alph = ', lp['eta_alph'] etainds = np.where( np.sqrt(xy[:, 0]**2 + xy[:, 1]**2) > eta_lenscale)[0] displ = lp['eta'] * (np.random.rand(len(etainds), 2) - 0.5) xy[etainds, :] += displ addstr = '_eta' + sf.float2pstr(lp['eta'], ndigits=3) addstr += '_etaalph' + sf.float2pstr(lp['eta_alph'], ndigits=3) else: addstr = '' # If the meshfn going to overwrite a previous realization? lattice_exten = 'hex_kagcframe' + lattice_exten[9:] +\ '_alph' + sf.float2pstr(lp['alph'], ndigits=2) + addstr LV = 'none' UC = 'none' LVUC = 'none' return xy, NL, KL, BL, PVx, PVy, PVxydict, LVUC, BBox, LL, LV, UC, lattice_exten, lp
def polygon_phases_tune_junction(lp, args, nmode=None): """Plot the phase differences ccw around each polygon in the network for many glats as junction coupling is increased. Do this for the nth mode as the scaling parameter evolves (typically the bond strength between particles that are nearer than some threshold). Example usage: python gyro_lattice_class.py -polygon_phases_tune_junction -LT hexjunction2triads -N 1 -OmKspec union0p000in0p100 -alph 0.1 -periodic python gyro_lattice_class.py -polygon_phases_tune_junction -LT spindle -N 2 -OmKspec union0p000in0p100 -alph 0.0 -periodic -aratio 0.1 python gyro_lattice_class.py -polygon_phases_tune_junction -LT spindle -N 4 -OmKspec union0p000in0p100 -alph 0.0 -periodic -aratio 0.1 # for making lattices python ./build/make_lattice.py -LT spindle -N 4 -periodic -skip_gyroDOS -aratio 0.1 Parameters ---------- lp args nmode : int, int list, or None Returns ------- """ cmap = lecmaps.ensure_cmap('bbr0') nkvals = 50 if lp['LatticeTop'] in ['hexjunctiontriad', 'spindle', 'hexjunction2triads']: kvals = -np.unique(np.round(np.logspace(-1, 1., nkvals), 2)) # [::-1] dist_thres = lp['OmKspec'].split('union')[-1].split('in')[-1] lpmaster = copy.deepcopy(lp) lat = lattice_class.Lattice(lp) lat.load() if nmode is None: todo = np.arange(len(lat.xy[:, 0])) elif type(nmode) == int: todo = [nmode] else: todo = nmode ########################################################################## # First collect eigenvalue flow eigvals, first = [], True for (kval, dmyi) in zip(kvals, np.arange(len(kvals))): lp = copy.deepcopy(lpmaster) lp['OmKspec'] = 'union' + sf.float2pstr(kval, ndigits=3) + 'in' + dist_thres # lat = lattice_class.Lattice(lp) glat = GyroLattice(lat, lp) eigval, eigvect = glat.eig_vals_vects(attribute=True) if first: eigvals = np.zeros((len(kvals), len(eigval)), dtype=float) eigvals[dmyi, :] = np.imag(eigval) first = False ########################################################################## lp = copy.deepcopy(lpmaster) glat = GyroLattice(lat, lp) # add meshfn without OmKspecunion part mfe = glat.lp['meshfn_exten'] if mfe[0:13] == '_OmKspecunion': meshfnextenstr = mfe.split(mfe.split('_')[1])[-1] else: raise RuntimeError('Handle this case here -- should be easy: split meshfn_exten to pop OmKspec out') for ii in todo[::-1]: modefn = dio.prepdir(lat.lp['meshfn']) + 'glat_mode_phases_scaling_tune_junction_mode{0:05d}'.format(ii) +\ meshfnextenstr + '_nkvals{0:04}'.format(nkvals) + '.mov' globmodefn = glob.glob(modefn) if not globmodefn: modedir = dio.prepdir(lat.lp['meshfn']) + 'glat_mode_phases_tune_junction_mode{0:05d}'.format(ii) + \ meshfnextenstr + '/' dio.ensure_dir(modedir) previous_ev = None first = True dmyi = 0 for kval in kvals: lp = copy.deepcopy(lpmaster) lp['OmKspec'] = 'union' + sf.float2pstr(kval, ndigits=3) + 'in' + dist_thres # lat = lattice_class.Lattice(lp) glat = GyroLattice(lat, lp) eigval, eigvect = glat.eig_vals_vects(attribute=True) # plot the nth mode # fig, DOS_ax, eax = leplt.initialize_eigvect_DOS_header_plot(eigval, glat.lattice.xy, # sim_type='gyro', cbar_nticks=2, # cbar_tickfmt='%0.3f') fig, dos_ax, eax, ax1, cbar_ax = \ leplt.initialize_eigvect_DOS_header_twinplot(eigval, glat.lattice.xy, sim_type='gyro', ax0_pos=[0.0, 0.10, 0.45, 0.55], ax1_pos=[0.65, 0.15, 0.3, 0.60], header_pos=[0.1, 0.78, 0.4, 0.20], xlabel_pad=8, fontsize=8) cax = plt.axes([0.455, 0.10, 0.02, 0.55]) # Get the theta that minimizes the difference between the present and previous eigenvalue # IN ORDER TO CONNECT MODES PROPERLY if previous_ev is not None: realxy = np.real(previous_ev) thetas, eigvects = gdh.phase_fix_nth_gyro(glat.eigvect, ngyro=0, basis='XY') # only look at neighboring modes # (presumes sufficient resolution to disallow simultaneous crossings) mmin = max(modenum - 2, 0) mmax = min(modenum + 2, len(eigvects)) modenum = gdh.phase_difference_minimum(eigvects[mmin:mmax], realxy, basis='XY') modenum += mmin # print 'thetas = ', thetas # if theta < 1e-9: # print 'problem with theta' # sys.exit() else: thetas, eigvects = gdh.phase_fix_nth_gyro(glat.eigvect, ngyro=0, basis='XY') modenum = ii # Plot the lattice with bonds glat.lattice.plot_BW_lat(fig=fig, ax=eax, save=False, close=False, axis_off=False, title='') # plot excitation fig, [scat_fg, scat_fg2, pp, f_mark, lines_12_st], cw_ccw = \ leplt.construct_eigvect_DOS_plot(glat.lattice.xy, fig, dos_ax, eax, eigval, eigvects, modenum, 'gyro', glat.lattice.NL, glat.lattice.KL, marker_num=0, color_scheme='default', sub_lattice=-1, amplify=1., title='') # Plot the polygons colored by phase polys = glat.lattice.get_polygons() patches, colors = [], [] for poly in polys: addv = np.array([0., 0.]) # build up positions, taking care of periodic boundaries xys = np.zeros_like(glat.lattice.xy[poly], dtype=float) xys[0] = glat.lattice.xy[poly[0]] for (site, qq) in zip(poly[1:], range(len(poly) - 1)): if latfns.bond_is_periodic(poly[qq], site, glat.lattice.BL): toadd = latfns.get_periodic_vector(poly[qq], site, glat.lattice.PVx, glat.lattice.PVy, glat.lattice.NL, glat.lattice.KL) if np.shape(toadd)[0] > 1: raise RuntimeError('Handle the case of multiple periodic bonds between ii jj here') else: addv += toadd[0] xys[qq + 1] = glat.lattice.xy[site] + addv print 'site, poly[qq - 1] = ', (site, poly[qq]) print 'addv = ', addv xys = np.array(xys) polygon = Polygon(xys, True) patches.append(polygon) # Check the polygon # plt.close('all') # plt.plot(xys[:, 0], xys[:, 1], 'b-') # plt.show() # Get mean phase difference in this polygon # Use weighted arithmetic mean of (cos(angle), sin(angle)), then take the arctangent. yinds = 2 * np.array(poly) + 1 xinds = 2 * np.array(poly) weights = glatfns.calc_magevecs_full(eigvect[modenum]) # To take mean, follow # https://en.wikipedia.org/wiki/Mean_of_circular_quantities#Mean_of_angles # with weights from # https://en.wikipedia.org/wiki/Weighted_arithmetic_mean#Mathematical_definition # First take differences in angles phis = np.arctan2(np.real(eigvects[modenum, yinds]), np.real(eigvects[modenum, xinds])) print 'phis = ', phis phis = np.mod(phis, np.pi * 2) print 'phis = ', phis # Now convert to vectors, take mean of both x and y components. Then grab atan2(y,x) of result. xx, yy = np.mean(np.cos(np.diff(phis))), np.mean(np.sin(np.diff(phis))) dphi = np.arctan2(yy, xx) print 'dphi = ', dphi colors.append(dphi) # sys.exit() pp = PatchCollection(patches, alpha=0.4, cmap=cmap) pp.set_array(np.array(colors)) eax.add_collection(pp) pp.set_clim([-np.pi, np.pi]) cbar = fig.colorbar(pp, cax=cax) # Store this current eigvector as 'previous_ev' previous_ev = eigvects[modenum] # Plot where in evolution we are tracking ngyros = int(np.shape(eigvals)[1] * 0.5) halfev = eigvals[:, ngyros:] for row in halfev.T: ax1.loglog(np.abs(kvals), row, 'b-') trackmark = ax1.plot(np.abs(kval), np.abs(np.imag(eigval))[modenum], 'ro') ax1.set_xlabel(r"vertex coupling, $\Omega_k'$") ax1.set_ylabel(r"frequency, $\omega$") eax.xaxis.set_ticks([]) eax.yaxis.set_ticks([]) cbar.set_ticks([-np.pi, 0, np.pi]) cbar.set_ticklabels([r'-$\pi$', 0, r'$\pi$']) cbar.set_label(r'phase, $\Delta \phi$') dos_ax.set_xlim(xmin=0) plt.savefig(modedir + 'DOS_' + '{0:05}'.format(dmyi) + '.png', dpi=200) # remove plotted excitation scat_fg.remove() scat_fg2.remove() pp.remove() if f_mark is not None: f_mark.remove() lines_12_st.remove() eax.cla() dmyi += 1 first = False # Make movie imgname = modedir + 'DOS_' movname = modedir[:-1] + '_nkvals{0:04}'.format(nkvals) lemov.make_movie(imgname, movname, indexsz='05', framerate=5, rm_images=True, save_into_subdir=True, imgdir=modedir)
def 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
if args.calibrate_Sk_epsilon: """Calibrate S(k) scaling versus epsilon""" import lepm.structure as struct nksteps = 200 klim_frac = 0.1 LL = (float(nh), float(nv)) print 'LL = ', LL gammav = np.arange(0.1, 1., 0.2) epsv = [1e-15, 1e-11, 1e-7, 1e-3, 1., 10] colorv = lecmaps.husl_palette(len(epsv)) # Naming seriesname = 'structure/nksteps{0:03d}'.format(nksteps) + '_sz{0:04d}'.format(nh) + '{0:04d}'.format(nv) + \ '_klim' + sf.float2pstr(klim_frac) + 'LL' caloutdir = args.rootdir + 'calibration/' + seriesname + '/' datoutdir = args.rootdir + 'calibration_data/' + seriesname + '/' dio.ensure_dir(caloutdir) dio.ensure_dir(datoutdir) kk = 0 for gamma in gammav: kk = 0 ymax = 0. fig, ax = leplt.initialize_1panel_fig(wsfrac=0.45, hsfrac=0.35, y0frac=0.14, x0frac=0.17) for eps in epsv: fn = datoutdir + 'gamma' + sf.float2pstr(
cmap = 'bbr0' # deltagrid.reshape((len(abds), -1)) # abdgrid.reshape((len(abds), -1)) # cherngrid.reshape((len(abds), -1)) # leplt.plot_pcolormesh_scalar(deltagrid, abdgrid, cherngrid, outpath=None, cmap=cmap, vmin=-1.0, vmax=1.0) leplt.plot_pcolormesh(deltagrid / np.pi, abdgrid, cherngrid, 100, ax=ax, make_cbar=False, cmap=cmap, vmin=-1.0, vmax=1.0) # ax.scatter(deltagrid, abdgrid, c=cherngrid, cmap=cmap, vmin=-1.0, vmax=1.0) sm = leplt.empty_scalar_mappable(vmin=-1.0, vmax=1.0, cmap=cmap) cb = plt.colorbar(sm, cax=cax, orientation='horizontal') cb.set_label(label=r'Chern number, $\nu$', labelpad=-35) cb.set_ticks([-1, 0, 1]) ax.set_xlabel(r'Lattice deformation angle, $\delta/\pi$') ax.set_ylabel(r'Inversion symmetry breaking, $\Delta$') specstr = '_delta' + sf.float2pstr( np.min(deltagrid)) + '_' + sf.float2pstr(np.max(deltagrid)) specstr += '_abd' + sf.float2pstr( np.min(abdgrid)) + '_' + sf.float2pstr(np.max(abdgrid)) specstr += '_ndeltas{0:05d}'.format( len(deltas)) + '_nabd{0:05d}'.format(len(abds)) specstr += '_density{0:07d}'.format(cp['density']) plt.savefig(rootdir + 'kspace_cherns_gyro/abtransition' + specstr + '.png')
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 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 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
# print '\n\n Could not find lattice --> creating it!' # meshfn, trash = le.build_meshfn(lp) # lp['meshfn'] = meshfn # lat = lattice_class.Lattice(lp) # lat.build() # lat.save() hlat = haldane_lattice_class.HaldaneLattice(lat, lp) hlat.load() print '\n\n\n', hlat.lattice.lp, '\n' chern = HaldaneChern(hlat, cp=cp) if args.title == '': title = None else: print 'title = ', eval("r'" + args.title.replace('_', ' ') + "'") title = eval("r'" + args.title.replace('_', ' ') + "'") title += r', with $t_1 = $' + sf.float2pstr(lp['t1']) title += r' $t_2 = $' + sf.float2pstr(lp['t2']) if hlat.lp['V0_pin_gauss']: title += r' $V \pm \sigma = $' + sf.float2pstr( lp['pin']) + r'$\pm$' + sf.float2pstr(lp['V0_pin_gauss']) else: title += r' $V = $' + str(int(lp['pin'])) chern.calc_haldane_chern(check=args.check, title=title) chern.save_chern() if args.ensure_chern: # Calc chern number for specified network if it does not already exist # try: meshfn = le.find_meshfn(lp) lp['meshfn'] = meshfn lat = lattice_class.Lattice(lp)