Esempio n. 1
0
    def save_bott_txt(self):
        """Save the bott to disk as a txt file

        Returns
        -------
        None
        """
        # Make output directories
        print 'saving chern to: ', self.cp['cpmeshfn']
        dio.ensure_dir(self.cp['cpmeshfn'])

        # Save the chern calculation to cp['cpmeshfn']
        if self.bott is None:
            raise RuntimeError(
                'Cannot save bott calculation since it has not been computed!')

        # Save bott parameters
        fn = self.cp['cpmeshfn'] + 'bott_params.txt'
        header = 'Parameters for bott calculation'
        dio.save_dict(self.cp, fn, header)

        # Save chern_finsize
        fn = self.cp['cpmeshfn'] + 'bott.txt'

        print 'saving chern_finsize to ', fn
        with open(fn, "w") as txtfile:
            txtfile.write('{0:0.18e}'.format(self.bott))

        # Save lattice parameters too for convenience (gives info about disorder, spinning speeds etc)
        print 'saving lattice_params...'
        header = 'Lattice parameters, copied from meshfn: ' + self.haldane_lattice.lp[
            'meshfn']
        dio.save_dict(self.haldane_lattice.lp,
                      self.cp['cpmeshfn'] + 'lattice_params.txt', header)
Esempio n. 2
0
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'])
Esempio n. 3
0
def le_plot_gyros(xy, xy0, NL, KL, BM, params, t, ii, name, fig, ax, outdir, climv='auto', exaggerate=1.0,
                  dpi=300, fontsize=12, title='', **kwargs):
    """Plots a single gyroscopic lattice time step using timestep plot.

    Parameters
    ----------
    t : float
        time stamp for image
    ii : int
        index to name file ( ie 'name_000ii.png')
    name : string
        the name of the file (before _index.png)
    fig : matplotlib.pyplot figure handle, or 'none'
        the figure on which to plot the gyros. If 'none', uses plt.gcf() and clears figure.
    ax : matplotlib.pyplot axis handle, or 'none'
        the axis on which to plot the gyros. If 'none', uses plt.gca()
    outdir : string
        The output directory for the image
    climv : float or tuple
        Color limit for coloring bonds by bond strain, overriddes params['climv'] if climv!='auto'
        If 'climv' is not a key in params, and climv=='auto', then uses default min/max.
        If 'climv' is a key in params, and climv=='auto', then uses params['climv'].
    exaggerate : float (default 1.0 --> in which case it is ignored)
        Exaggerate the displacements of each particle from its initial position by this factor. Ignored if == 1.0
    dpi : float
        pixels per inch, resolution of saved plot
    **kwargs: Additional timestep_plot() keyword arguments
        color_particles='k', fontsize=14, linewidth=2

    Returns
    ----------
    """
    # If fig and ax are not supplied, declare them
    if fig is None or fig == 'none':
        fig = plt.gcf()
        plt.clf()
    if ax is None or ax == 'none':
        ax = plt.gca()

    # make output dir
    outdir = dio.prepdir(outdir)
    dio.ensure_dir(outdir)
    # set range of window from first values
    if 'xlimv' in params:
        xlimv = params['xlimv']
        if 'ylimv' in params:
            ylimv = params['ylimv']
        else:
            ylimv = (xlimv - max(xy0[:, 0])) + np.ceil(max(xy0[:, 1]))
    else:
        xlimv = np.ceil(max(xy0[:, 0]) * 5./ 4.)
        ylimv = (xlimv - max(xy0[:, 0])) + max(xy0[:, 1])

    # save current data as stills
    index = '{0:08d}'.format(ii)
    outname = outdir + '/' + name + '_' + index + '.png'
    BL = le.NL2BL(NL, KL)
    # print 'BL = ', BL

    suptitle = copy.deepcopy(title)

    if 'prestrain' in params:
        prestrain = params['prestrain']
    else:
        prestrain = 0.

    if 'shrinkrate' in params:
        shrinkrate = params['shrinkrate']
        title = 't = ' + '%07.0f' % t + '  a = ' + '%07.5f' % (1. - shrinkrate * t - prestrain)
    elif 'prestrain' in params:
        shrinkrate = 0.0
        title = 't = ' + '%07.0f' % t + '  a = ' + '%07.5f' % (1. - prestrain)
    else:
        shrinkrate = 0.0
        title = 't = ' + '%07.0f' % t + r' $\Omega_g^{-1}$'

    if exaggerate != 1.0:
        title += '   amplified ' + str(int(exaggerate)) + 'x  '

    if 'Omk' in params and params['Omk'] != -1.:
        title += '\n' + r'$\Omega_g$=' + '{0:.3f}'.format(params['Omg'])
    if 'Omg' in params and params['Omk'] != -1.:
        title += r'   $\Omega_k$=' + '{0:.3f}'.format(params['Omk'][0, 0])
    if 'split_spin' in params:
        title += ' NV=' + str(int(params['NV']))
        if 'split_k' in params:
            title += r'   $k_s$=' + str(params['split_k'])

    # title +='\n'

    # if params['BCtype'] == 'excite':
    #     title += r'   $\omega_d$ = ' + '{0:.3f}'.format(params['frequency'])

    if 'eta' in params:
        if params['eta'] != 0.000:
            title += r'   $\eta$=' + '{0:.3f}'.format(params['eta'])

            # calculate strain
            # bs = bond_strain_list(xy,BL,bL0)

            # if exaggerate==1.0:
            # movie_plot_2D_gyros(xy, BL, bs, outname, title, xlimv, ylimv, climv)
            # else:
            # xye = xy0+(xy-xy0)*exaggerate
            # movie_plot_2D_gyros(xye, BL, bs, outname, title, xlimv, ylimv, climv)

    if climv == 'auto':
        if 'climv' in params:
            climv = params['climv']

    [scat_fg, lines_st, p] = leplt.timestep_plot(xy, xy0, NL, KL, BM, ax=ax, factor=exaggerate, amp=climv, title=title,
                                                 fontsize=fontsize, suptitle=suptitle, **kwargs)

    # print 'color_particles = ', scat_fg
    ax.set_xlim(-xlimv, xlimv)
    ax.set_ylim(-ylimv, ylimv)

    plt.savefig(outname, dpi=dpi)

    # clear_array = [scat_fg, lines_st, p]
    # for i in range(len(clear_array)):
    #     clear_array[i].remove()

    return [scat_fg, lines_st, p]
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)
Esempio n. 5
0
def data2stills_2Dgyros(datadir,
                        simoutdir,
                        params,
                        framedir_name='stills',
                        init_skip=10,
                        climv=0.1,
                        numbering='adopt',
                        rough=False,
                        roughmov=True,
                        exaggerate=1.0,
                        rm_stills=True,
                        resolution=150,
                        figsize='auto',
                        color_particles='k',
                        DOSexcite=None,
                        lp=None,
                        framerate=10,
                        mov_exten='',
                        title='',
                        dos_meshfn_dir=None,
                        movname=None,
                        lw=2,
                        **kwargs):
    """Converts a list of data into a stack of png images of gyroscopic lattice using timestep_plot for each timestep.

    Parameters
    ----------
    simoutdir : string
        The output directory for the simulation (contains subdirs for xyv, KL)
    params : dict
        Parameters dictionary
    framedir_name : string
        Subdirectory of simoutdir in which to save movie images
    vsaved : bool
        whether the velocites are recorded (vsaved = False for Nash gyros, True for gHST, for example)
    init_skip : int
        One out of every init_skip frames will be written first, then the intermittent frames will be written, to see
        briefly what happens
    climv : float or tuple
        Color limit for coloring bonds by bond strain
    numbering : 'natural' or 'adopt' (default = 'adopt')
        Use indexing '0','1','2','3',... or adopt the index of the input file.
    rough : boolean
        Plot every init_skip files ONLY? (if False, writes every init_skip files first, then does the rest)
    exaggerate : float (default 1.0 --> in which case it is ignored)
        Exaggerate the displacements of each particle from its initial position by this factor. Ignored if == 1.0
    rm_stills : bool
        Whether or not to delete the stills after making them.
    DOSexcite : tuple of floats or None
        (excitation frequency, stdev time), or else None if DOS plot is not desired
    lp : dict
        Lattice parameters. If not None, then if eigval is not found in main dir, attempts to load eigval from gyro
        network, but will not compute it
    framerate : int or float (optional, default=10)
        framerate for movie
    mov_exten : str (optional)
        additional description to append to movie name, if movname is None
    movname : str or None
        Name or full path with name of movie to output of the simulation
    **kwargs : keyword arguments for leplt.timestep_plot()
        such as bgcolor, cmap (the strain colormap), color_particles, mimic_expt


    Returns
    ----------
    """
    plt.close('all')
    print 'Running data2stills_2Dgyros with DOSexcite = ', DOSexcite
    # get dirs
    # vsaved denotes whether the velocites are recorded
    # vsaved = False for Nash gyros, True for gHST, for example
    print 'simoutdir = ', simoutdir
    try:
        xypath = sorted(glob.glob(simoutdir + 'xyv/'))[0]
        vsaved = True
    except IndexError:
        xypath = sorted(glob.glob(simoutdir + 'xy/'))[0]
        vsaved = False
    # list files
    xyfiles = sorted(glob.glob(xypath + '*.txt'))
    # load setup
    NLfile = sorted(glob.glob(datadir + 'NL.txt'))[0]
    NL = np.loadtxt(NLfile, dtype='int', delimiter=',')
    xy0file = sorted(glob.glob(datadir + 'xy.txt'))[0]
    xy0 = np.loadtxt(xy0file, delimiter=',', usecols=(0, 1))

    if 'deform' in params:
        if params['deform']:
            deform_xy0 = True
            xy0path = sorted(glob.glob(simoutdir + 'xy0/'))[0]
            xy0files = sorted(glob.glob(xy0path + '*.txt'))
        else:
            deform_xy0 = False
            xy0files = []

    try:
        KLpath = sorted(glob.glob(simoutdir + 'KL/'))[0]
        KLfiles = sorted(glob.glob(KLpath + '*.txt'))
        if KLfiles:
            print 'found KLfiles --> update KL each timestep'
            update_KL_each_timestep = True
            KL = np.loadtxt(KLfiles[0], delimiter=',')
        else:
            print 'KLfiles =', KLfiles, '\n --> do not update KL'
            update_KL_each_timestep = False
            KL = np.loadtxt(datadir + 'KL.txt', dtype='int', delimiter=',')
            BM0 = le.NL2BM(xy0, NL, KL)
    except IndexError:
        print 'no KLfiles --> do not update KL'
        update_KL_each_timestep = False
        KL = np.loadtxt(datadir + 'KL.txt', dtype='int', delimiter=',')
        BM0 = le.NL2BM(xy0, NL, KL)

    if 'h' in params:
        hh = params['h']
    elif 'hh' in params:
        hh = params['hh']
    else:
        hfile = sorted(glob.glob(datadir + 'h.txt'))[0]
        hh = np.loadtxt(hfile)

    # get base name from xyfile
    name = 'still'
    if vsaved:
        # name = (xyfiles[0].split('/')[-1]).split('xyv')[0]
        try:
            x, y, vx, vy = np.loadtxt(xyfiles[0], delimiter=',', unpack=True)
        except:
            x, y, z, vx, vy, vz = np.loadtxt(xyfiles[0],
                                             delimiter=',',
                                             unpack=True)
    else:
        # name = (xyfiles[0].split('/')[-1]).split('xy')[0]
        try:
            '''Data is 2D'''
            x, y = np.loadtxt(xyfiles[0], delimiter=',', unpack=True)
        except:
            try:
                '''Data is 3D'''
                x, y, z = np.loadtxt(xyfiles[0], delimiter=',', unpack=True)
            except:
                '''Data is X,Y,dX,dY'''
                X, Y, dX, dY = np.loadtxt(xyfiles[0],
                                          delimiter=',',
                                          unpack=True)

    # get length of index string from xyfile
    index_sz = str(len((xyfiles[0].split('_')[-1]).split('.')[0]))
    # make output dir
    outdir = simoutdir + framedir_name + '/'
    dio.ensure_dir(outdir)
    # set range of window from first values
    xlimv = np.ceil(max(x) * 5. / 4.)
    ylimv = np.ceil(max(y) * 5. / 4.)

    # Initial bond list and
    # count initial bonds (double counted)
    # nzcount = np.count_nonzero(KL)
    BL0 = le.NL2BL(NL, KL)
    bo = le.bond_length_list(xy0, BL0)

    # make list of indices to plot-- first sparse then dense
    do1 = [0] + range(0, len(xyfiles), init_skip)

    # Set up figure
    if figsize == 'auto':
        fig = plt.gcf()
        plt.clf()
    else:
        plt.close('all')
        fig = plt.figure(figsize=figsize)

    print 'DOSexcite = ', DOSexcite
    if DOSexcite is not None:
        # Load DOS eigvals:
        eigvalpklglob = glob.glob(datadir + 'eigval.pkl')
        if eigvalpklglob:
            with open(datadir + 'eigval.pkl', "rb") as input_file:
                eigval = cPickle.load(input_file)
            eval_loaded = True
        else:
            print 'Did not find eigval in simulation dir (datadir), attempting to load based on supplied meshfn...'
            # If you want to load eigvals from a lattice other than the one being simulated, put a "pointer file"
            # txt file with the path to that meshfn in your simulation directory: for ex, put 'meshfn_eigvals.txt'
            # in the simdir, with contents '/Users/username/...path.../hexagonal_square_delta0p667_...000010_x_000010/'
            if dos_meshfn_dir is None or dos_meshfn_dir == 'none':
                dos_meshfn_dir = datadir

            meshfn_specfn = glob.glob(
                dio.prepdir(dos_meshfn_dir) + 'meshfn_eig*.txt')
            print 'dos_meshfn_dir = ', dos_meshfn_dir
            print 'meshfn_specfn = ', meshfn_specfn
            if meshfn_specfn:
                with open(meshfn_specfn[0], 'r') as myfile:
                    meshfn = myfile.read().replace('\n', '')
                if lp is not None:
                    # Build correct eigval to load based on lp (gyro lattice parameters) by grabbing lp[meshfn_exten]
                    import lepm.lattice_class
                    import lepm.gyro_lattice_class
                    # lp = {'LatticeTop': params['LatticeTop'], 'meshfn': params['meshfn']}
                    lat = lepm.lattice_class.Lattice(lp=lp)
                    lat.load()
                    mlat = lepm.magnetic_gyro_lattice_class.MagneticGyroLattice(
                        lat, lp)
                    eigvalfn = dio.prepdir(
                        meshfn) + 'eigval' + mlat.lp['meshfn_exten'] + '.pkl'
                else:
                    print 'since no lp supplied, assuming eigval is default in datadir...'
                    eigvalfn = dio.prepdir(meshfn) + 'eigval_magnetic.pkl'
                with open(eigvalfn, "rb") as fn:
                    eigval = cPickle.load(fn)
                eval_loaded = True
            else:
                print 'plotting.time_domain_magnetic: Did not find eigval or eigval pointer file in datadir, ' + \
                      'attempting to load based on lp...'
                if lp is not None:
                    print 'Loading based on lp...'
                    # No eigval saved in lattice GyroLattice's meshfn, seeking alternative
                    import lepm.lattice_class
                    import lepm.gyro_lattice_class
                    # lp = {'LatticeTop': params['LatticeTop'], 'meshfn': params['meshfn']}
                    lat = lepm.lattice_class.Lattice(lp=lp)
                    lat.load()
                    print 'lp = ', lp
                    print 'lp[Omk] = ', lp['Omk']
                    mlat = lepm.magnetic_gyro_lattice_class.MagneticGyroLattice(
                        lat, lp)
                    eigval = mlat.load_eigval()
                    if eigval is None:
                        eigval = mlat.get_eigval()
                        print 'Calculated eigval based on supplied GyroLattice instance, using lp dictionary.'
                    else:
                        print 'Loaded eigval from disk, from a location determined by the lp dictionary.'
                    eval_loaded = True
                else:
                    eval_loaded = False
                    raise RuntimeError(
                        'Did not supply lp and eigval is not in datadir!')

        if eval_loaded:
            # Attempt to load ipr for network
            iprglob = glob.glob(datadir + 'ipr.pkl')
            if iprglob:
                with open(datadir + 'ipr.pkl', "rb") as input_file:
                    ipr = cPickle.load(input_file)
                    colorV = 1. / ipr
                    linewidth = 0
                    cax_label = r'$p$'
                    colormap = 'viridis_r'
                    vmin_hdr = None
                    vmax_hdr = None
                    cbar_ticklabels = None
                    cbar_nticks = 4
            else:
                locglob = glob.glob(datadir + 'localization*.txt')
                if locglob:
                    localization = np.loadtxt(locglob[0], delimiter=',')
                    ill = localization[:, 2]
                    ill_full = np.zeros(len(eigval), dtype=float)
                    ill_full[0:int(len(eigval) * 0.5)] = ill[::-1]
                    ill_full[int(len(eigval) * 0.5):len(eigval)] = ill
                    colorV = ill_full
                    linewidth = 0
                    cax_label = r'$\lambda^{-1}$'
                    colormap = 'viridis'
                    vmin_hdr = 0.0
                    vmax_hdr = 1. / (np.max(np.abs(xy0.ravel())))
                    cbar_ticklabels = ['0', r'$1/L$', r'$2/L$']
                    cbar_nticks = 3
                else:
                    print 'plotting.time_domain_magnetic: Did not find ipr in simulation dir (datadir), ' +\
                          'attempting to load based on supplied meshfn...'
                    # First seek directly supplied files in the simulation datadir
                    meshfn_specfn = glob.glob(datadir + 'meshfn_*ipr.txt')
                    if meshfn_specfn:
                        with open(meshfn_specfn[0], 'r') as myfile:
                            meshfn = myfile.read().replace('\n', '')
                        with open(
                                dio.prepdir(meshfn) + 'ipr' +
                                lp['meshfn_exten'] + '.pkl', "rb") as fn:
                            ipr = cPickle.load(fn)
                        colorV = 1. / ipr
                        cax_label = r'$p$'
                        colormap = 'viridis_r'
                        linewidth = 0
                        vmin_hdr = None
                        vmax_hdr = None
                        cbar_ticklabels = None
                        cbar_nticks = 4
                    else:
                        print '\n\n\nComputing localization from supplied meshfn\n\n\n'
                        if dos_meshfn_dir is None or dos_meshfn_dir == 'none':
                            dos_meshfn_dir = datadir

                        meshfn_specfn = glob.glob(
                            dio.prepdir(dos_meshfn_dir) +
                            'meshfn_*localization.txt')
                        print 'meshfn_specfn = ', meshfn_specfn
                        if meshfn_specfn:
                            with open(meshfn_specfn[0], 'r') as myfile:
                                meshfn = myfile.read().replace('\n', '')
                            if lp is not None:
                                print 'Loading based on lp...'
                                import lepm.lattice_class
                                import lepm.gyro_lattice_class
                                # lp = {'LatticeTop': params['LatticeTop'], 'meshfn': params['meshfn']}
                                lat = lepm.lattice_class.Lattice(lp=lp)
                                lat.load()
                                mlat = lepm.magnetic_gyro_lattice_class.MagneticGyroLattice(
                                    lat, lp)
                                loczfn = dio.prepdir(
                                    meshfn) + 'localization' + mlat.lp[
                                        'meshfn_exten'] + '.txt'
                                specmeshfn_xy = lat.xy
                            else:
                                print 'plotting.time_domain_magnetic: no lp supplied, assuming default lattice ' +\
                                      'params to load localization in attempt to load localization...'
                                loczfn = dio.prepdir(
                                    meshfn) + 'localization_magnetic.txt'
                                try:
                                    specmeshfn_xy = np.loadtxt(meshfn +
                                                               '_xy.txt')
                                except:
                                    specmeshfn_xy = np.loadtxt(meshfn +
                                                               '_xy.txt',
                                                               delimiter=',')

                            localization = np.loadtxt(loczfn, delimiter=',')
                            ill = localization[:, 2]
                            ill_full = np.zeros(len(eigval), dtype=float)
                            ill_full[0:int(len(eigval) * 0.5)] = ill[::-1]
                            ill_full[int(len(eigval) * 0.5):len(eigval)] = ill
                            colorV = ill_full
                            linewidth = 0
                            cax_label = r'$\lambda^{-1}$'
                            colormap = 'viridis'
                            vmin_hdr = 0.0
                            vmax_hdr = 1. / (np.max(
                                np.abs(specmeshfn_xy.ravel())))
                            cbar_ticklabels = ['0', r'$1/L$', r'$2/L$']
                            cbar_nticks = 3
                        else:
                            print 'plotting.time_domain_magnetic: Did not find ipr or localization in datadirs,' +\
                                  ' attempting to load based on lp...'
                            if lp is not None:
                                print 'Loading based on lp...'
                                import lepm.lattice_class
                                import lepm.gyro_lattice_class
                                # lp = {'LatticeTop': params['LatticeTop'], 'meshfn': params['meshfn']}
                                lat = lepm.lattice_class.Lattice(lp=lp)
                                lat.load()
                                mlat = lepm.magnetic_gyro_lattice_class.MagneticGyroLattice(
                                    lat, lp)
                                if mlat.lp['periodicBC']:
                                    localization = mlat.get_localization()
                                    ill = localization[:, 2]
                                    ill_full = np.zeros(len(eigval),
                                                        dtype=float)
                                    ill_full[0:int(len(eigval) *
                                                   0.5)] = ill[::-1]
                                    ill_full[int(len(eigval) *
                                                 0.5):len(eigval)] = ill
                                    colorV = ill_full
                                    cax_label = r'$\lambda^{-1}$'
                                    vmin_hdr = 0.0
                                    vmax_hdr = 1. / (np.max(np.abs(
                                        xy0.ravel())))
                                else:
                                    ipr = mlat.get_ipr()
                                    colorV = 1. / ipr
                                    cax_label = r'$p$'
                                    colormap = 'viridis_r'
                                    vmin_hdr = None
                                    vmax_hdr = None
                                    cbar_ticklabels = None
                                    cbar_nticks = 4
                                linewidth = 0
                            else:
                                print 'Did not supply lp and neither ipr nor localization are in datadir!'
                                colorV = None
                                linewidth = 1
                                cax_label = ''
                                colormap = 'viridis'
                                vmin_hdr = None
                                vmax_hdr = None
                                cbar_ticklabels = None
                                cbar_nticks = 4

            plt.close('all')
            if np.max(xy0[:, 0]) - np.min(
                    xy0[:, 0]) > 2.0 * (np.max(xy0[:, 1]) - np.min(xy0[:, 1])):
                # Plot will be very wide, so initialize a wide plot (landscape 16:9)
                orientation = 'landscape'
                # Note: header axis is [0.30, 0.80, 0.45, 0.18]
                if title == '' or title is None:
                    ax_pos = [0.1, 0.05, 0.8, 0.54]
                    cbar_pos = [0.79, 0.80, 0.012, 0.15]
                else:
                    ax_pos = [0.1, 0.03, 0.8, 0.50]
                    cbar_pos = [0.79, 0.70, 0.012, 0.15]
            else:
                # Plot will be roughly square or tall, so initialize a portfolio-style plot
                orientation = 'portrait'
                if title == '' or title is None:
                    ax_pos = [0.1, 0.10, 0.8, 0.60]
                    cbar_pos = [0.79, 0.80, 0.012, 0.15]
                else:
                    ax_pos = [0.1, 0.03, 0.8, 0.60]
                    cbar_pos = [0.79, 0.75, 0.012, 0.15]

            # Determine line width
            if len(xy0) > 2000:
                lw = 1
            else:
                lw = 2

            if cax_label == r'$\lambda^{-1}$':
                if 'penrose' in lp['LatticeTop']:
                    dos_ylabel = 'Density of states, ' + r'$D(\omega)$' + '\nfor periodic approximant'
                else:
                    dos_ylabel = 'Density of states, ' + r'$D(\omega)$' + '\nfor periodic system'
                ylabel_pad = 30
                ylabel_rot = 90
            else:
                dos_ylabel = r'$D(\omega)$'
                ylabel_pad = 20
                ylabel_rot = 0

            print 'plt.get_fignums() = ', plt.get_fignums()
            fig, DOS_ax, ax = \
                leplt.initialize_eigvect_DOS_header_plot(eigval, xy0, sim_type='gyro',
                                                         page_orientation=orientation,
                                                         ax_pos=ax_pos, cbar_pos=cbar_pos,
                                                         colorV=colorV, vmin=vmin_hdr, vmax=vmax_hdr,
                                                         DOSexcite=DOSexcite, linewidth=linewidth,
                                                         cax_label=cax_label, colormap=colormap,
                                                         cbar_nticks=cbar_nticks,
                                                         cbar_tickfmt='%0.2f', cbar_ticklabels=cbar_ticklabels,
                                                         cbar_labelpad=17,
                                                         yaxis_ticks=[], ylabel=dos_ylabel,
                                                         ylabel_rot=ylabel_rot, ylabel_pad=ylabel_pad,
                                                         nbins=120, xlabel_pad=15)
            # DOSexcite = (frequency, sigma_time)
            # amp(x) = exp[- acoeff * time**2]
            # amp(k) = sqrt(pi/acoeff) * exp[- pi**2 * k**2 / acoeff]
            # So 1/(2 * sigma_freq**2) = pi**2 /acoeff
            # So sqrt(acoeff/(2 * pi**2)) = sigma_freq

            # sigmak = 1./DOSexcite[1]
            # xlims = DOS_ax.get_xlim()
            # ktmp = np.linspace(xlims[0], xlims[1], 300)
            # gaussk = 0.8 * DOS_ax.get_ylim()[1] * np.exp(-(ktmp - DOSexcite[0])**2 / (2. * sigmak))
            # DOS_ax.plot(ktmp, gaussk, 'r-')
            # plt.sca(ax)
        else:
            print 'Could not find eigval.pkl to load for DOS portion of data2stills plots!'
            ax = plt.gca()
    else:
        ax = plt.gca()

    # Check for evolving rest lengths in params
    if 'prestrain' in params:
        prestrain = params['prestrain']
    else:
        prestrain = 0.

    if 'shrinkrate' in params:
        shrinkrate = params['shrinkrate']
    else:
        shrinkrate = 0.0

    if roughmov:
        print 'creating rough gyro movie...'
        tdgyros.stills2mov_gyro(fig,
                                ax,
                                do1,
                                xyfiles,
                                KLfiles,
                                xy0files,
                                xy0,
                                NL,
                                KL,
                                BM0,
                                params,
                                hh,
                                numbering,
                                index_sz,
                                outdir,
                                name,
                                simoutdir,
                                update_KL_each_timestep,
                                deform_xy0,
                                exaggerate,
                                xlimv,
                                ylimv,
                                climv,
                                resolution,
                                color_particles,
                                shrinkrate,
                                prestrain,
                                framerate=float(framerate) / 5.,
                                mov_exten='_rough',
                                linewidth=lw,
                                startind=0,
                                title=title,
                                show_bonds=False,
                                **kwargs)

    # Now do detailed movie if rough is False
    if not rough:
        print 'creating fine gyro movie (not skipping any frames)...'
        doall = [0] + range(0, len(xyfiles))
        # do2 = list(set(doall)-set(do1))
        # ftodo = do1 + do2

        print 'tdmagnetic: exiting here since it is broken here'
        # sys.exit()
        tdgyros.stills2mov_gyro(fig,
                                ax,
                                doall,
                                xyfiles,
                                KLfiles,
                                xy0files,
                                xy0,
                                NL,
                                KL,
                                BM0,
                                params,
                                hh,
                                numbering,
                                index_sz,
                                outdir,
                                name,
                                simoutdir,
                                update_KL_each_timestep,
                                deform_xy0,
                                exaggerate,
                                xlimv,
                                ylimv,
                                climv,
                                resolution,
                                color_particles,
                                shrinkrate,
                                prestrain,
                                framerate=framerate,
                                mov_exten=mov_exten,
                                linewidth=lw,
                                startind=0,
                                title=title,
                                movname=movname,
                                show_bonds=False,
                                **kwargs)

        if rm_stills:
            # Delete the original images
            print 'Deleting folder ' + simoutdir + 'stills/'
            subprocess.call(['rm', '-r', simoutdir + 'stills/'])
    elif hostname[0:10] == 'nsit-dhcp-' or hostname[0:10] == 'npmitchell':
        rootdir = '/Users/npmitchell/Dropbox/Soft_Matter/GPU/'
        cprootdir = '/Volumes/research4TB/Soft_Matter/GPU/'
    elif hostname == 'Messiaen.local' or hostname[0:8] == 'wireless':
        rootdir = '/Users/npmitchell/Dropbox/Soft_Matter/GPU/'
        cprootdir = '/Volumes/research2TB/Soft_Matter/GPU/'
        if not os.path.isdir(cprootdir):
            cprootdir = '/Users/npmitchell/Desktop/data_local/GPU/'
    elif hostname[0:5] == 'cvpn-':
        rootdir = '/Users/npmitchell/Dropbox/Soft_Matter/GPU/'
        cprootdir = '/Volumes/research2TB/Soft_Matter/GPU/'
    else:
        rootdir = '/Users/npmitchell/Dropbox/Soft_Matter/GPU/'

    outdir = rootdir + 'experiments/DOS_scaling/' + args.LatticeTop + '/'
    dio.ensure_dir(outdir)
    print 'cprootdir = ', cprootdir

    dcdisorder = args.V0_pin_gauss > 0 or args.V0_spring_gauss > 0

    lp = {'LatticeTop': args.LatticeTop,
          'shape': shape,
          'NH': NH,
          'NV': NV,
          'NP_load': args.NP_load,
          'rootdir': rootdir,
          'phi_lattice': args.phi_lattice,
          'delta_lattice': args.delta_lattice,
          'theta': args.theta,
          'eta': args.eta,
          'x1': args.x1,
Esempio n. 7
0
    def plot_cherns_vary_param(self, param_type='glat', sz_param_nu=None,
                              reverse=False, param='percolation_density',
                              title='Chern index calculation', xlabel=None):
        """Plot chern indices with x axis being the parameter which is varying between networks.
        If there are multiple chern calculations of a particular lattice, average nu over them all.

        Parameters
        ----------
        param_type : str ('glat' or 'lat')
            Whether we are varying a lattice parameter (different lattices) or a gyrolattice parameter (same lattice,
            different physics)
        sz_param_nu : None or 'glat' or ('lat' or 'lp' -- last two do same thing)
            string specifier for how to vary params
        reverse : bool
            Compute cherns for GyroLattice instances in self.mgyro_collection in reverse order
        param : string
            string specifier for GyroLattice parameter to vary between networks; key for mglat.lp dict
        title : str
            title of the plot
        xlabel : str
            xlabel, if desired to be other than default for param (ie, param.replace('_', ' '))

        """
        if sz_param_nu is None:
            if param_type == 'lat' or param_type == 'lp':
                param_nu = self.collect_cherns_vary_lpparam(param=param, reverse=reverse)
            elif param_type == 'glat':
                param_nu = self.collect_cherns_vary_glatparam(param=param, reverse=reverse)
            else:
                raise RuntimeError("param_type argument passed is not 'glat' or 'lat/lp'")

        # Plot it as colormap
        plt.close('all')

        paramV = param_nu[:, 0]
        nu = param_nu[:, 1]

        # Make figure
        import lepm.plotting.plotting as leplt
        fig, ax = leplt.initialize_1panel_centered_fig(wsfrac=0.5, tspace=4)

        if xlabel is None:
            xlabel = param.replace('_', ' ')

        # Plot the curve
        # first sort the paramV values
        if isinstance(paramV[0], float):
            si = np.argsort(paramV)
        else:
            si = np.arange(len(paramV), dtype=int)
        ax.plot(paramV[si], nu[si], '.-')
        ax.set_xlabel(xlabel)

        # Add title
        ax.text(0.5, 0.95, title, transform=fig.transFigure, ha='center', va='center')

        # Save the plot
        if param_type == 'glat':
            outdir = rootdir + 'kspace_cherns_mgyro/chern_glatparam/' + param + '/'
            dio.ensure_dir(outdir)

            # Add meshfn name to the output filename
            outbase = self.cherns[self.cherns.items()[0][0]][0].mgyro_lattice.lp['meshfn']
            if outbase[-1] == '/':
                outbase = outbase[:-1]
            outbase = outbase.split('/')[-1]

            outd_ex = self.cherns[self.cherns.items()[0][0]][0].mgyro_lattice.lp['meshfn_exten']
            # If the parameter name is part of the meshfn_exten, replace its value with XXX in
            # the meshfnexten part of outdir.
            mfestr = glat_param2meshfnexten_name(param)
            if mfestr in outd_ex:
                'param is in meshfn_exten, splitting...'
                # split the outdir by the param string
                od_split = outd_ex.split(mfestr)
                # split the second part by the value of the param string and the rest
                od2val_rest = od_split[1].split('_')
                odrest = od_split[1].split(od2val_rest[0])[1]
                print 'odrest = ', odrest
                print 'od2val_rest = ', od2val_rest
                outd_ex = od_split[0] + param + 'XXX'
                outd_ex += odrest
                print 'outd_ex = ', outd_ex
            else:
                outd_ex += '_' + param + 'XXX'
        elif param_type == 'lat':
            outdir = rootdir + 'kspace_cherns_mgyro/chern_lpparam/' + param + '/'
            outbase = self.cherns[self.cherns.items()[0][0]][0].mgyro_lattice.lp['meshfn']
            # Take apart outbase to parse out the parameter that is varying
            mfestr = lat_param2meshfn_name(param)
            if mfestr in outbase :
                'param is in meshfn_exten, splitting...'
                # split the outdir by the param string
                od_split = outbase.split(mfestr)
                # split the second part by the value of the param string and the rest
                od2val_rest = od_split[1].split('_')
                odrest = od_split[1].split(od2val_rest[0])[1]
                print 'odrest = ', odrest
                print 'od2val_rest = ', od2val_rest
                outd_ex = od_split[0] + param + 'XXX'
                outd_ex += odrest
                print 'outd_ex = ', outd_ex
            else:
                outbase += '_' + param + 'XXX'

            outd_ex = self.cherns[self.cherns.items()[0][0]][0].mgyro_lattice.lp['meshfn_exten']

        dio.ensure_dir(outdir)

        fname = outdir + outbase
        fname += '_chern_' + param + '_Ncoll' + '{0:03d}'.format(len(self.mgyro_collection.mgyro_lattices))
        fname += outd_ex
        print 'saving to ' + fname + '.png'
        plt.savefig(fname + '.png')
        plt.clf()
Esempio n. 8
0
def twistbcs(lp):
    """Load a periodic lattice from file, twist the BCs by phases theta_twist and phi_twist with vals finely spaced
    between 0 and 2pi. Then compute the berry curvature associated with |alpha(theta, phi)>

    Example usage:
    python haldane_lattice_class.py -twistbcs -N 3 -LT hexagonal -shape square -periodic

    Parameters
    ----------
    lp

    Returns
    -------

    """
    lp['periodicBC'] = True
    meshfn = le.find_meshfn(lp)
    lp['meshfn'] = meshfn
    lat = lattice_class.Lattice(lp)
    lat.load()
    # Make a big array of the eigvals: N x N x thetav x phiv
    # thetav = np.arange(0., 2. * np.pi, 0.5)
    # phiv = np.arange(0., 2. * np.pi, 0.5)

    # First just test for two values of theta and two of phi
    thetav = [0., 0.01]
    phiv = [0., 0.01]
    eigvects = {}
    ii = 0
    for theta in thetav:
        eigvects[ii] = {}
        jj = 0
        for phi in phiv:
            lpnew = copy.deepcopy(lp)
            lpnew['theta_twist'] = theta
            lpnew['phi_twist'] = phi
            hlat = HaldaneLattice(lat, lpnew)
            ev, evec = hlat.get_eigval_eigvect(attribute=True)
            if ii == 0 and jj == 0:
                eigval = copy.deepcopy(ev)
                ill = hlat.get_ill()
            eigvects[ii][jj] = evec
            jj += 1
        ii += 1

    # Dot the derivs of eigvects together
    # Ensure that there is a nonzero-amplitude wannier with matching phase
    dtheta = eigvects[1][0] - eigvects[0][0]
    dphi = eigvects[0][1] - eigvects[0][0]

    thetamov_fn = dio.prepdir(
        hlat.lp['meshfn']
    ) + 'twistbc_theta' + hlat.lp['meshfn_exten'] + '_dos_ev.mov'
    if not glob.glob(thetamov_fn):
        # Plot differences
        fig, DOS_ax, eig_ax = leplt.initialize_eigvect_DOS_header_plot(
            ev,
            hlat.lattice.xy,
            sim_type='haldane',
            colorV=ill,
            colormap='viridis',
            linewidth=0,
            cax_label=r'$\xi^{-1}$',
            cbar_nticks=2,
            xlabel_pad=10,
            ylabel_pad=10,
            cbar_tickfmt='%0.3f')
        DOS_ax.set_title(r'$\partial_\phi \psi$')
        hlat.lattice.plot_BW_lat(fig=fig,
                                 ax=eig_ax,
                                 save=False,
                                 close=False,
                                 axis_off=False,
                                 title='')
        outdir = dio.prepdir(
            hlat.lp['meshfn']
        ) + 'twistbc_theta' + hlat.lp['meshfn_exten'] + '/'
        dio.ensure_dir(outdir)
        for ii in range(len(ev)):
            fig, [scat_fg, scat_fg2, p, f_mark, lines_12_st], cw_ccw = \
                hlatpfns.construct_haldane_eigvect_DOS_plot(hlat.lattice.xy, fig, DOS_ax, eig_ax, eigval,
                                                            dtheta, ii, hlat.lattice.NL, hlat.lattice.KL,
                                                            marker_num=0, color_scheme='default', normalization=1.)
            print 'saving theta ', ii
            plt.savefig(outdir + 'dos_ev' + '{0:05}'.format(ii) + '.png')
            scat_fg.remove()
            scat_fg2.remove()
            p.remove()
            f_mark.remove()
            lines_12_st.remove()

        plt.close('all')

        imgname = outdir + 'dos_ev'
        movname = dio.prepdir(
            hlat.lp['meshfn']
        ) + 'twistbc_theta' + hlat.lp['meshfn_exten'] + '_dos_ev'
        lemov.make_movie(imgname, movname, rm_images=False)

    phimov_fn = dio.prepdir(
        hlat.lp['meshfn']
    ) + 'twistbc_phi' + hlat.lp['meshfn_exten'] + '_dos_ev.mov'
    if not glob.glob(phimov_fn):
        fig, DOS_ax, eig_ax = leplt.initialize_eigvect_DOS_header_plot(
            ev,
            hlat.lattice.xy,
            sim_type='haldane',
            colorV=ill,
            colormap='viridis',
            linewidth=0,
            cax_label=r'$\xi^{-1}$',
            cbar_nticks=2,
            xlabel_pad=10,
            ylabel_pad=10,
            cbar_tickfmt='%0.3f')
        DOS_ax.set_title(r'$\partial_\phi \psi$')
        outdir = dio.prepdir(
            hlat.lp['meshfn']) + 'twistbc_phi' + hlat.lp['meshfn_exten'] + '/'
        dio.ensure_dir(outdir)
        for ii in range(len(ev)):
            fig, [scat_fg, scat_fg2, p, f_mark, lines_12_st], cw_ccw = \
                hlatpfns.construct_haldane_eigvect_DOS_plot(hlat.lattice.xy, fig, DOS_ax, eig_ax, eigval,
                                                            dphi, ii, hlat.lattice.NL, hlat.lattice.KL,
                                                            marker_num=0, color_scheme='default', normalization=1.)
            print 'saving phi ', ii
            plt.savefig(outdir + 'dos_ev' + '{0:05}'.format(ii) + '.png')
            scat_fg.remove()
            scat_fg2.remove()
            p.remove()
            f_mark.remove()
            lines_12_st.remove()

        plt.close('all')

        imgname = outdir + 'dos_ev'
        movname = dio.prepdir(
            hlat.lp['meshfn']
        ) + 'twistbc_phi' + hlat.lp['meshfn_exten'] + '_dos_ev'
        lemov.make_movie(imgname, movname, rm_images=False)

    # Check
    # print 'shape(dtheta) = ', np.shape(dtheta)
    # print 'shape(dphi) = ', np.shape(dphi)
    # le.plot_complex_matrix(dtheta, show=True, name='dtheta')
    # le.plot_complex_matrix(dphi, show=True, name='dphi')

    fig, ax = leplt.initialize_nxmpanel_fig(4, 1, wsfrac=0.6, x0frac=0.3)
    # < dphi | dtheta >
    dpdt = np.einsum('ij...,ij...->i...', dtheta, dphi.conj())
    # < dtheta | dphi >
    dtdp = np.einsum('ij...,ij...->i...', dphi, dtheta.conj())
    print 'dtdp = ', dtdp
    ax[0].plot(np.arange(len(dtdp)), dtdp, '-')
    ax[1].plot(np.arange(len(dpdt)), dpdt, '-')
    hc = 2. * np.pi * 1j * (dpdt - dtdp)
    ax[2].plot(np.arange(len(lat.xy)), hc, '.-')
    # Plot cumulative sum
    sumhc = np.cumsum(hc)
    ax[3].plot(np.arange(len(lat.xy)), sumhc, '.-')

    ax[2].set_xlabel(r'Eigvect number')
    ax[0].set_ylabel(
        r'$\langle \partial_{\theta} \alpha_i | \partial_{\phi} \alpha_i \rangle$'
    )
    ax[2].set_xlabel(r'Eigvect number')
    ax[1].set_ylabel(
        r'$\langle \partial_{\phi} \alpha_i | \partial_{\theta} \alpha_i \rangle$'
    )
    ax[2].set_xlabel(r'Eigvect number')
    ax[2].set_ylabel(r'$c_H$')
    ax[3].set_xlabel(r'Eigvect number')
    ax[3].set_ylabel(r'$\sum_{E_\alpha < E_c} c_H$')
    outdir = '/Users/npmitchell/Dropbox/Soft_Matter/GPU/twistbc_test/'
    dio.ensure_dir(outdir)
    print 'saving ', outdir + 'test' + hlat.lp['meshfn_exten'] + '.png'
    plt.savefig(outdir + 'test' + hlat.lp['meshfn_exten'] + '.png')

    # ### Now do the same thing but with different values of theta, phi
    # First just test for two values of theta and two of phi
    thetav = [1., 1.01]
    phiv = [1., 1.01]
    eigvects = {}
    ii = 0
    for theta in thetav:
        eigvects[ii] = {}
        jj = 0
        for phi in phiv:
            lpnew = copy.deepcopy(lp)
            lpnew['theta_twist'] = theta
            lpnew['phi_twist'] = phi
            hlat = HaldaneLattice(lat, lpnew)
            ev, evec = hlat.get_eigval_eigvect(attribute=True)
            if ii == 0 and jj == 0:
                eigval = copy.deepcopy(ev)
                ill = hlat.get_ill()
            eigvects[ii][jj] = evec
            jj += 1
        ii += 1

    # Dot the derivs of eigvects together
    dtheta = eigvects[1][0] - eigvects[0][0]
    dphi = eigvects[0][1] - eigvects[0][0]

    # Plot differences
    thetamov_fn = dio.prepdir(
        hlat.lp['meshfn']
    ) + 'twistbc_theta' + hlat.lp['meshfn_exten'] + '_dos_ev.mov'
    if not glob.glob(thetamov_fn):
        fig, DOS_ax, eig_ax = leplt.initialize_eigvect_DOS_header_plot(
            ev,
            hlat.lattice.xy,
            sim_type='haldane',
            colorV=ill,
            colormap='viridis',
            linewidth=0,
            cax_label=r'$\xi^{-1}$',
            cbar_nticks=2,
            xlabel_pad=10,
            ylabel_pad=10,
            cbar_tickfmt='%0.3f')
        DOS_ax.set_title(r'$\partial_\theta \psi$')
        hlat.lattice.plot_BW_lat(fig=fig,
                                 ax=eig_ax,
                                 save=False,
                                 close=False,
                                 axis_off=False,
                                 title='')
        outdir = dio.prepdir(
            hlat.lp['meshfn']
        ) + 'twistbc_theta' + hlat.lp['meshfn_exten'] + '/'
        dio.ensure_dir(outdir)
        for ii in range(len(ev)):
            fig, [scat_fg, scat_fg2, p, f_mark, lines_12_st], cw_ccw = \
                hlatpfns.construct_haldane_eigvect_DOS_plot(hlat.lattice.xy, fig, DOS_ax, eig_ax, eigval,
                                                            dtheta, ii, hlat.lattice.NL, hlat.lattice.KL,
                                                            marker_num=0, color_scheme='default', normalization=1.)
            print 'saving theta ', ii
            plt.savefig(outdir + 'dos_ev' + '{0:05}'.format(ii) + '.png')
            scat_fg.remove()
            scat_fg2.remove()
            p.remove()
            f_mark.remove()
            lines_12_st.remove()

        plt.close('all')

        imgname = outdir + 'dos_ev'
        movname = dio.prepdir(
            hlat.lp['meshfn']
        ) + 'twistbc_theta' + hlat.lp['meshfn_exten'] + '_dos_ev'
        lemov.make_movie(imgname, movname, rm_images=False)

    # Now do phi
    phimov_fn = dio.prepdir(
        hlat.lp['meshfn']
    ) + 'twistbc_phi' + hlat.lp['meshfn_exten'] + '_dos_ev.mov'
    if not glob.glob(phimov_fn):
        fig, DOS_ax, eig_ax = leplt.initialize_eigvect_DOS_header_plot(
            ev,
            hlat.lattice.xy,
            sim_type='haldane',
            colorV=ill,
            colormap='viridis',
            linewidth=0,
            cax_label=r'$\xi^{-1}$',
            cbar_nticks=2,
            xlabel_pad=10,
            ylabel_pad=10,
            cbar_tickfmt='%0.3f')
        DOS_ax.set_title(r'$\partial_\phi \psi$')
        hlat.lattice.plot_BW_lat(fig=fig,
                                 ax=eig_ax,
                                 save=False,
                                 close=False,
                                 axis_off=False,
                                 title='')
        outdir = dio.prepdir(
            hlat.lp['meshfn']) + 'twistbc_phi' + hlat.lp['meshfn_exten'] + '/'
        dio.ensure_dir(outdir)
        for ii in range(len(ev)):
            fig, [scat_fg, scat_fg2, p, f_mark, lines_12_st], cw_ccw = \
                hlatpfns.construct_haldane_eigvect_DOS_plot(hlat.lattice.xy, fig, DOS_ax, eig_ax, eigval,
                                                            dphi, ii, hlat.lattice.NL, hlat.lattice.KL,
                                                            marker_num=0, color_scheme='default', normalization=1.)
            print 'saving phi ', ii
            plt.savefig(outdir + 'dos_ev' + '{0:05}'.format(ii) + '.png')
            scat_fg.remove()
            scat_fg2.remove()
            p.remove()
            f_mark.remove()
            lines_12_st.remove()

        plt.close('all')

        imgname = outdir + 'dos_ev'
        movname = dio.prepdir(
            hlat.lp['meshfn']
        ) + 'twistbc_phi' + hlat.lp['meshfn_exten'] + '_dos_ev'
        lemov.make_movie(imgname, movname, rm_images=False)

    # Check
    # print 'shape(dtheta) = ', np.shape(dtheta)
    # print 'shape(dphi) = ', np.shape(dphi)
    # le.plot_complex_matrix(dtheta, show=True, name='dtheta')
    # le.plot_complex_matrix(dphi, show=True, name='dphi')

    fig, ax = leplt.initialize_nxmpanel_fig(4, 1, wsfrac=0.6, x0frac=0.3)
    # < dphi | dtheta >
    dpdt = np.einsum('ij...,ij...->i...', dtheta, dphi.conj())
    # < dtheta | dphi >
    dtdp = np.einsum('ij...,ij...->i...', dphi, dtheta.conj())
    print 'dtdp = ', dtdp
    ax[0].plot(np.arange(len(dtdp)), dtdp, '-')
    ax[1].plot(np.arange(len(dpdt)), dpdt, '-')
    hc = 2. * np.pi * 1j * (dpdt - dtdp)
    ax[2].plot(np.arange(len(lat.xy)), hc, '.-')
    # Plot cumulative sum
    sumhc = np.cumsum(hc)
    ax[3].plot(np.arange(len(lat.xy)), sumhc, '.-')

    ax[2].set_xlabel(r'Eigvect number')
    ax[0].set_ylabel(
        r'$\langle \partial_{\theta} \alpha_i | \partial_{\phi} \alpha_i \rangle$'
    )
    ax[2].set_xlabel(r'Eigvect number')
    ax[1].set_ylabel(
        r'$\langle \partial_{\phi} \alpha_i | \partial_{\theta} \alpha_i \rangle$'
    )
    ax[2].set_xlabel(r'Eigvect number')
    ax[2].set_ylabel(r'$c_H$')
    ax[3].set_xlabel(r'Eigvect number')
    ax[3].set_ylabel(r'$\sum_{E_\alpha < E_c} c_H$')
    outdir = '/Users/npmitchell/Dropbox/Soft_Matter/GPU/twistbc_test/'
    dio.ensure_dir(outdir)
    plt.savefig(outdir + 'test' + hlat.lp['meshfn_exten'] + '_theta1p0.png')

    sys.exit()
    ########################################
    # Now test for more theta values, more phi values
    thetav = np.arange(0., 0.14, 0.1)
    phiv = np.arange(0., 0.14, 0.1)
    eigvects = np.zeros((len(lat.xy), len(lat.xy), len(thetav), len(phiv)),
                        dtype=complex)
    ii = 0
    for theta in thetav:
        jj = 0
        for phi in phiv:
            lpnew = copy.deepcopy(lp)
            lpnew['theta_twist'] = theta
            lpnew['phi_twist'] = phi
            hlat = HaldaneLattice(lat, lpnew)
            ev, evec = hlat.get_eigval_eigvect()
            eigvects[:, :, ii, jj] = evec
            jj += 1
        ii += 1

    # Dot the derivs of eigvects together
    print 'eigvects = ', eigvects
    dtheta = np.diff(eigvects, axis=2)
    dphi = np.diff(eigvects, axis=3)
    print 'dtheta = ', dtheta

    print 'shape(dtheta) = ', np.shape(dtheta)
    print 'shape(dphi) = ', np.shape(dphi)
    le.plot_complex_matrix(dtheta[:, :, 0, 0], show=True)
    le.plot_complex_matrix(dphi[:, :, 0, 0], show=True)

    dtheta = dtheta[:, :, :, 0:np.shape(dtheta)[3] - 1]
    dphi = dphi[:, :, 0:np.shape(dphi)[2] - 1, :]
    print 'shape(dtheta) = ', np.shape(dtheta)
    print 'shape(dphi) = ', np.shape(dphi)

    for ii in range(np.shape(dtheta)[-1]):
        le.plot_complex_matrix(dtheta[:, :, ii, 0], show=True)

    fig, ax = leplt.initialize_nxmpanel_fig(3, 1)
    for ii in range(np.shape(dphi)[-1]):
        for jj in range(np.shape(dphi)[-1]):
            # < dphi | dtheta >
            dpdt = np.dot(dtheta[:, :, ii, jj], dphi[:, :, ii, jj].conj().T)
            # < dtheta | dphi >
            dtdp = np.dot(dphi[:, :, ii, jj], dtheta[:, :, ii, jj].conj().T)
            print 'np.shape(dpdt) = ', np.shape(dpdt)
            print 'np.shape(dtdp) = ', np.shape(dtdp)
            ax[0].plot(np.arange(len(dtdp)), dtdp, '-')
            ax[1].plot(np.arange(len(dpdt)), dpdt, '-')

            hc = 2. * np.pi * 1j * (dpdt - dtdp)
            ax[2].plot(np.arange(len(lat.xy)), hc, '.-')

    ax[0].set_xlabel(r'$\theta$')
    ax[0].set_ylabel(
        r'$\langle \partial_{\theta} \alpha_i | \partial_{\phi} \alpha_i \rangle$'
    )
    ax[1].set_xlabel(r'$\phi$')
    ax[1].set_ylabel(
        r'$\langle \partial_{\phi} \alpha_i | \partial_{\theta} \alpha_i \rangle$'
    )
    ax[2].set_xlabel(r'Eigvect number')
    ax[2].set_ylabel(r'$\partial_{\phi} \alpha_i$')
    plt.show()
def draw_edge_localization_plots(hlat,
                                 elocz,
                                 eigval,
                                 eigvect,
                                 outdir=None,
                                 alpha=1.0,
                                 fontsize=12):
    """Draw plots of each normal mode excitation with colormap behind it denoting the fitted exponential localization

    Parameters
    ----------
    hlat : HaldaneLattice instance
        The gyro lattice whose modes we plot
    elocz : NP x 5 float array (ie, int(len(eigval)*0.5) x 5 float array)
        edge localization fit details: A, K, uncertainty_A, covariance_AK, uncertainty_K
    eigval : 2*N x 1 complex array
        eigenvalues of the matrix, sorted by order of imaginary components
    eigvect : typically 2*N x 2*N complex array
        eigenvectors of the matrix, sorted by order of imaginary components of eigvals
        Eigvect is stored as NModes x NP*2 array, with x and y components alternating, like:
        x0, y0, x1, y1, ... xNP, yNP.
    outdir : str or None
        the output directory to use for saving localization plots. If None, uses pwd as ouput dir
    alpha : float
        The opacity of the excitation ellipses
    fontsize : int
        The fontsize to use for labels, etc

    Returns
    -------
    fig, dos_ax, ax
    """
    if outdir is None:
        print 'Outputting images in current working directory...'
        outdir = './'
    else:
        dio.ensure_dir(outdir)
    ipr = hlat.get_ipr()

    # Get third largest value for ipr vmax
    # ipr_vmax = np.max(1. / ipr.sort())[3]
    ipr_vmax = float(np.floor(10 * heapq.nlargest(6, 1. / ipr)[-1])) / 10.
    fig, dos_ax, ax = leplt.initialize_eigvect_DOS_header_plot(
        eigval,
        hlat.lattice.xy,
        sim_type='haldane',
        preset_cbar=True,
        colorV=1. / ipr,
        colormap='viridis_r',
        norm=None,
        facecolor='#80D080',
        nbins=75,
        fontsize=fontsize,
        vmin=0.0,
        vmax=ipr_vmax,
        linewidth=0,
        make_cbar=True,
        climbars=True,
        xlabel='Energy $E/t_1$',
        ylabel=r'$D(E)$',
        ylabel_pad=20,
        cax_label=r'$p$',
        cbar_labelpad=10,
        ticks=[0., ipr_vmax],
        cbar_nticks=None,
        cbar_tickfmt=None,
        orientation='vertical',
        cbar_orientation='vertical',
        invert_xaxis=False,
        yaxis_tickright=False,
        yaxis_ticks=None,
        ylabel_right=False,
        ylabel_rot=0,
        DOSexcite=None,
        DOSexcite_color='r')
    # Make axis for showing quality of fit
    x0 = 0.1
    y0 = 0.2
    w = 0.8
    h = 0.2
    ax.set_position([x0, y0, w, h])
    eax_w = 0.5
    eax_h = 0.15
    eax_x0 = x0 + (w - eax_w) * 0.5
    eax_y0 = y0 + h * 1.7
    exp_ax = fig.add_axes([eax_x0, eax_y0, eax_w, eax_h])

    hlat.lattice.plot_BW_lat(fig=fig,
                             ax=ax,
                             meshfn='none',
                             save=False,
                             close=False,
                             axis_off=True,
                             title='')

    # If periodic, use LL to plot localization fit assuming periodic boundaries
    if hlat.lp['periodicBC']:
        if hlat.lp['periodic_strip']:
            magevecs = np.abs(eigvect)
            # Also get distance of each particle from boundary
            bseg_tuple = hlat.lattice.get_boundary_linesegs()
            xydists = []
            for bsegs in bseg_tuple:
                xydists.append(
                    linesegs.mindist_from_multiple_linesegs(
                        hlat.lattice.xy, bsegs))

            # Convert list xydists into NP x 2 array
            xydists = np.dstack(tuple(xydists))[0]
        else:
            # There are two periodic vectos, so there can be no boundary --> exit with error
            raise RuntimeError(
                'Cannot compute distance to boundary in a fully periodic sample '
                + '--> there is no boundary.')
    else:
        # Not periodic, no LL, so use lattice boundary to connect consecutive linesegments
        magevecs = hlat.calc_magevecs(eigvect)
        bndry_segs = hlat.lattice.get_boundary_linesegs()
        xydists = linesegs.mindist_from_multiple_linesegs(
            hlat.lattice.xy, bndry_segs)

    # Get the xlims and ylims for plotting the exponential decay fit
    xlims_fit = [-0.1, np.max(xydists.ravel()) + 1]
    xlims = [
        np.min(hlat.lattice.xy[:, 0]) - 1,
        np.max(hlat.lattice.xy[:, 0]) + 1
    ]
    ylims = [
        np.min(hlat.lattice.xy[:, 1]) - 1,
        np.max(hlat.lattice.xy[:, 1]) + 1
    ]

    dmyi = 0
    # Look at all states
    todo = np.hstack((np.array([0]), np.arange(len(eigval))))
    for en in todo:
        fig, [scat_fg, pp, f_mark, lines12_st] =\
            plot_eigvect_excitation_haldane(hlat.lattice.xy, fig, dos_ax, ax, eigval, eigvect, en,
                                            marker_num=0, black_t0lines=True)
        locz = elocz[en]
        if hlat.lp['periodic_strip']:
            localz_handle = plot_edge_localization_heatmap_periodicstrip(
                locz, bseg_tuple, ax, xlims=xlims, ylims=ylims, alpha=1.0)
            title = ax.get_title()

            # Draw the exponential localization fit
            plt_handle, fit_handle = plot_localization_dists(
                locz,
                xydists[:, int(locz[5] % 2)],
                magevecs[en],
                exp_ax,
                xlims=xlims_fit)
        else:
            # assuming no periodicity
            localz_handle = plot_edge_localization_heatmap(locz,
                                                           bndry_segs,
                                                           ax,
                                                           xlims=xlims,
                                                           ylims=ylims,
                                                           alpha=1.0)
            title = ax.get_title()

            # Draw the exponential localization fit
            plt_handle, fit_handle = plot_localization_dists(locz,
                                                             xydists,
                                                             magevecs[en],
                                                             exp_ax,
                                                             xlims=xlims_fit)

        ax.set_title(title + r', $|\psi(r)| \approx$ $($' +
                     '{0:0.3f}'.format(locz[0]) + r'$\pm$' +
                     '{0:0.3f}'.format(locz[2]) + r'$)$ ' + r'$\exp[($' +
                     '{0:0.3f}'.format(locz[1]) + r'$\pm$' +
                     '{0:0.3f}'.format(locz[4]) + '$)\, r]$',
                     fontsize=fontsize)

        # Add axis labels
        exp_ax.set_xlabel('Distance from boundary, $r$', fontsize=12)
        exp_ax.set_ylabel('Excitation, $|\psi|$', fontsize=12)

        # Save this image
        outname = outdir + 'localization_edge' + hlat.lp[
            'meshfn_exten'] + '_{0:06d}'.format(en) + '.png'
        print 'saving image to ', outname
        plt.savefig(outname)

        # cleanup
        localz_handle.remove()
        scat_fg.remove()
        pp.remove()
        f_mark.remove()
        lines12_st.remove()
        if hlat.lp['periodic_strip']:
            exp_ax.cla()

        del localz_handle
        del scat_fg
        del pp
        del f_mark
        del lines12_st
        dmyi += 1

    return fig, dos_ax, ax
Esempio n. 10
0
def build_jammed(lp):
    """Use bonds from jammed packing --> already near isostatic, but can't tune above it, only below.

    Parameters
    ----------
    lp

    Returns
    -------

    """
    # Use bonds from jammed packing --> already near isostatic, but can't tune above it, only below.
    shape = lp['shape']
    nh = lp['NH']
    nv = lp['NV']
    networkdir = dio.ensure_dir(lp['rootdir']) + 'networks/'

    print('Loading isostatic file to build jammed lattice...')
    # Now load
    use_hexner = (lp['source'] == 'hexner')
    if use_hexner:
        print 'lp[periodicBC] = ', lp['periodicBC']
        points, BL, LLv, numberstr, sizestr, lp = load_hexner_jammed(
            lp, BL_load=True)
        sourcestr = '_hexner'
    else:
        # Use Stephan Ulrich's lattices
        if lp['periodicBC']:
            RuntimeError('Not sure if Stephan Ulrich lattices are periodic!')
        zindex = '{0:03d}'.format(int(lp['loadlattice_z']))
        number = '{0:03d}'.format(int(lp['conf']))
        points = np.loadtxt(networkdir + 'isostatic_source/isostatic_homog_z' +
                            zindex + '_conf' + number + '_nodes.txt')
        BL = np.loadtxt(networkdir + 'isostatic_source/isostatic_homog_z' +
                        zindex + '_conf' + number + '_bonds.txt',
                        usecols=(0, 1),
                        dtype=int)
        sourcestr = '_ulrich_homog'
        print 'BL[100] = ', BL[100]
        # Loaded BL uses indexing starting at 1, not 0
        BL -= 1
        print 'BL[100] = ', BL[100]
        numberstr = number[1:]

    if check:
        le.display_lattice_2D(points,
                              np.abs(BL),
                              title='points and bonds loaded, before pruning')
    xy = points - np.mean(points, axis=0)
    NL, KL = le.BL2NLandKL(BL, NN='min')

    # Remove any points with no bonds
    print 'Removing points without any bonds...'
    keep = KL.any(axis=1)
    xy, NL, KL, BL = le.remove_pts(keep, xy, BL, NN='min')
    print 'len(xy) = ', len(xy)

    if check:
        le.display_lattice_2D(
            xy,
            np.abs(BL),
            title='Before tuning z (down) and before fixing PBCs')

    if lp['cutz_method'] == 'random':
        NL, KL, BL = le.cut_bonds_z_random(xy,
                                           NL,
                                           KL,
                                           BL,
                                           lp['target_z'],
                                           bulk_determination='Endpts')
    elif lp['cutz_method'] == 'highest':
        NL, KL, BL = le.cut_bonds_z_highest(xy,
                                            NL,
                                            KL,
                                            BL,
                                            lp['target_z'],
                                            check=check)
    elif lp['cutz_method'] == 'none':
        pass

    if lp['periodicBC'] or lp['NP_load'] > 0:
        print 'Building periodicBC PVs...'
        lp['periodicBC'] = True
        LL = (LLv, LLv)
        polygon = 0.5 * np.array([[-LLv, -LLv], [LLv, -LLv], [LLv, LLv],
                                  [-LLv, LLv]])
        BBox = polygon
        PV = np.array([[LLv, 0.0], [LLv, LLv], [LLv, -LLv], [0.0, 0.0],
                       [0.0, LLv], [0.0, -LLv], [-LLv, 0.0], [-LLv, LLv],
                       [-LLv, -LLv]])
        PVxydict = le.BL2PVxydict(BL, xy, PV)
        PVx, PVy = le.PVxydict2PVxPVy(PVxydict, NL)

        if lp['check']:
            le.display_lattice_2D(xy,
                                  BL,
                                  NL=NL,
                                  KL=KL,
                                  PVx=PVx,
                                  PVy=PVy,
                                  title='Checking periodic BCs',
                                  close=False,
                                  colorz=False)
            for ii in range(len(xy)):
                plt.text(xy[ii, 0] + 0.1, xy[ii, 1], str(ii))
            plt.plot(xy[:, 0], xy[:, 1], 'go')
            plt.show()
    else:
        polygon = blf.auto_polygon(shape, nh, nv, eps=0.00)
        BBox = polygon
        print('Trimming lattice to be NH x NV...')
        keep = np.logical_and(
            abs(xy[:, 0]) < nh * 0.5,
            abs(xy[:, 1]) < nv * 0.5)
        print "Check that if lp['NP_load'] !=0 then len(keep) == len(xy):", len(
            keep) == len(xy)
        xy, NL, KL, BL = le.remove_pts(keep, xy, BL, NN='min')
        LL = (nh, nv)
        PVx = []
        PVy = []
        PVxydict = {}

    z = le.compute_bulk_z(xy, NL, KL, BL)
    print 'FOUND z = ', z

    if lp['periodicBC']:
        periodicBCstr = '_periodicBC'
    else:
        periodicBCstr = ''

    print('Defining lattice_exten...')
    lattice_exten = 'jammed_' + shape + sourcestr + periodicBCstr + '_z' + '{0:0.03f}'.format(z) + '_conf' + \
                    numberstr + '_zmethod' + lp['cutz_method']
    LV = 'none'
    UC = 'none'
    LVUC = 'none'
    return xy, NL, KL, BL, PVx, PVy, PVxydict, LVUC, BBox, LL, LV, UC, lattice_exten, lp
Esempio n. 11
0
def projector_site_vs_dist_hlatparam(hcoll,
                                     omegac,
                                     proj_XY,
                                     plot_mag=True,
                                     plot_diff=False,
                                     save_plt=True,
                                     alpha=1.0,
                                     maxdistlines=True,
                                     reverse_order=False,
                                     check=True):
    """
    Compare the projector values at distances relative to a particular site (site at location proj_XY).

    Parameters
    ----------
    hcoll : HaldaneCollection instance
        The collection of haldane_lattices for which to compare projectors as fn of distance from a given site.
    omegac : float
        Cutoff frequency for the projector
    proj_XY : 2 x 1 float numpy array
        The location at which to find the nearest site and consider projector elements relative to this site.
    plot : bool
        Whether to plot magproj vs dist for all HaldaneLattices in hcoll
    check : bool
        Display intermediate results

    Returns
    -------
    dist_list : list of NP x NP float arrays
        Euclidean distances between points. Element i,j is the distance between particle i and j
    proj_list : list of evxyprojs (2 x 2*NP float arrays)
        Each element is like magproj, but with x and y components separate.
        So, element 0,2*j gives the magnitude of the x component of the projector connecting the site in question
        to the x component of particle j and element 1,2*j+1 gives the
        magnitude of the y component of the projector connecting the site in question to the y component of particle j.
    """
    raise RuntimeError(
        "Haven't finished this code yet! Need to adapt to Haldane lattice structure"
    )
    proj_list = []
    dist_list = []
    kk = 0
    if plot_mag:
        # magnitude plot
        mfig, magax, mcbar = leplt.initialize_1panel_cbar_fig()
    if plot_diff:
        # difference plot
        dfig, dax, dcbar = leplt.initialize_1panel_cbar_fig()
        # difference fraction plot
        dffig, dfax, dfcbar = leplt.initialize_1panel_cbar_fig()
        if maxdistlines:
            maxdist = []

    sat = 1
    light = 0.6
    colors = lecmaps.husl_palette(n_colors=len(hcoll.haldane_lattices),
                                  s=sat,
                                  l=light)
    if reverse_order:
        hlat_list = hcoll.haldane_lattices[::-1]
    else:
        hlat_list = hcoll.haldane_lattices

    for hlat in hlat_list:
        proj_ind = ((hlat.lattice.xy - proj_XY)[:, 0]**2 +
                    (hlat.lattice.xy - proj_XY)[:, 1]**2).argmin()
        outdir = dio.prepdir(hlat.lp['meshfn'].replace('networks',
                                                       'projectors'))
        outfn = outdir + hlat.lp[
            'LatticeTop'] + "_dist_singlept_{0:06d}".format(proj_ind) + ".pkl"

        if check:
            print 'identified proj_ind = ', proj_ind
            newfig = plt.figure()
            hlat.lattice.plot_numbered(ax=plt.gca())

        # attempt to load
        if glob.glob(outfn):
            with open(outfn, "rb") as fn:
                dist = pickle.load(fn)

            outfn = outdir + hlat.lp[
                'LatticeTop'] + "_evxyproj_singlept_{0:06d}".format(
                    proj_ind) + ".pkl"
            with open(outfn, "rb") as fn:
                evxyproj = pickle.load(fn)
        else:
            # compute dists and evxyproj_proj_ind
            xydiff = hlat.lattice.xy - hlat.lattice.xy[proj_ind]
            dist = np.sqrt(xydiff[:, 0]**2 + xydiff[:, 1]**2)
            print 'calculating projector...'
            proj = calc_projector(hlat, omegac, attribute=False)

            outdir = dio.prepdir(hlat.lp['meshfn'].replace(
                'networks', 'projectors'))
            dio.ensure_dir(outdir)
            # save dist as pickle
            with open(outfn, "wb") as fn:
                pickle.dump(dist, fn)

            # evxyproj has dims 2 xlen(evect)
            evxyproj = np.dstack(
                (proj[2 * proj_ind, :], proj[2 * proj_ind + 1, :]))[0].T
            # save evxyproj as pickle
            outfn = outdir + hlat.lp[
                'LatticeTop'] + "_evxyproj_singlept_{0:06d}".format(
                    proj_ind) + ".pkl"
            with open(outfn, "wb") as fn:
                pickle.dump(evxyproj, fn)

        proj_list.append(evxyproj)
        dist_list.append(dist)

        if plot_mag:
            tmp = np.sqrt(
                np.abs(evxyproj[0]).ravel()**2 +
                np.abs(evxyproj[1]).ravel()**2)
            magproj = np.array([
                np.sqrt(tmp[2 * ind].ravel()**2 + tmp[2 * ind + 1].ravel()**2)
                for ind in range(len(dist))
            ])
            magax.scatter(dist,
                          np.log10(magproj),
                          s=1,
                          color=colors[kk],
                          alpha=alpha)

        if plot_diff:
            if kk > 0:
                # find particles that are the same as in the reference network
                same_inds = np.where(le.dist_pts(hlat.lattice.xy, xy0) == 0)
                # Order them by distance
                current = np.array(
                    [[2 * same_inds[0][ii], 2 * same_inds[0][ii] + 1]
                     for ii in range(len(same_inds[0]))])
                current = current.ravel()
                orig = np.array(
                    [[2 * same_inds[1][ii], 2 * same_inds[1][ii] + 1]
                     for ii in range(len(same_inds[0]))])
                orig = orig.ravel()

                # if check:
                #     origfig = plt.figure()
                #     origax = origfig.gca()
                #     [origax, origaxcb] = hlat.lattice.plot_numbered(fig=origfig, ax=origax, axis_off=False,
                #                                                     title='Original lattice for proj comparison')
                #     origax.scatter(hlat.lattice.xy[same_inds[0], 0], hlat.lattice.xy[same_inds[0], 1])
                #     plt.pause(5)
                #     plt.close()
                if len(current) > 0:
                    evxydiff = evxyproj[:, current] - evxyproj0[:, orig]
                    tmp = np.sqrt(
                        np.abs(evxydiff[0]).ravel()**2 +
                        np.abs(evxydiff[1]).ravel()**2)
                    magdiff = np.array([
                        np.sqrt(tmp[2 * ind].ravel()**2 +
                                tmp[2 * ind + 1].ravel()**2)
                        for ind in range(len(same_inds[0]))
                    ])
                    # magnitude of fractional difference
                    magfdiff = np.array([
                        magdiff[same_inds[0][ii]] / mag0[same_inds[1][ii]]
                        for ii in range(len(same_inds[0]))
                    ])
                    dax.scatter(dist[same_inds[0]],
                                magdiff,
                                s=1,
                                color=colors[kk],
                                alpha=alpha)
                    dfax.scatter(dist[same_inds[0]],
                                 magfdiff,
                                 s=1,
                                 color=colors[kk],
                                 alpha=alpha)
                    if maxdistlines:
                        maxdist.append(np.max(dist[same_inds[0]]))

            else:
                origfig = plt.figure()
                origax = origfig.gca()
                [origax, origaxcb] = hlat.lattice.plot_numbered(
                    fig=origfig,
                    ax=origax,
                    axis_off=False,
                    title='Original lattice for proj comparison')
                origfig.show()
                plt.close()
                evxyproj0 = copy.deepcopy(evxyproj)
                xy0 = copy.deepcopy(hlat.lattice.xy)
                tmp = np.sqrt(
                    np.abs(evxyproj[0]).ravel()**2 +
                    np.abs(evxyproj[1]).ravel()**2)
                mag0 = np.array([
                    np.sqrt(tmp[2 * ind].ravel()**2 +
                            tmp[2 * ind + 1].ravel()**2)
                    for ind in range(len(dist))
                ])

        kk += 1

    # Save plots
    outsplit = dio.prepdir(hlat.lp['meshfn'].replace('networks',
                                                     'projectors')).split('/')
    outdir = '/'
    for sdir in outsplit[0:-2]:
        outdir += sdir + '/'
    outdir += '/'

    if plot_mag:
        if maxdistlines and plot_diff:
            ylims = magax.get_ylim()
            print 'ylims = ', ylims
            ii = 1
            for dd in maxdist:
                magax.plot([dd, dd],
                           np.array([ylims[0], ylims[1]]),
                           '-',
                           color=colors[ii])
                ii += 1

        magax.set_title('Magnitude of projector vs distance')
        magax.set_xlabel(r'$|\mathbf{x}_i - \mathbf{x}_0|$')
        magax.set_ylabel(r'$|P_{i0}|$')
        # make a scalar mappable for colorbar'
        husl_cmap = lecmaps.husl_cmap(s=sat, l=light)
        sm = plt.cm.ScalarMappable(cmap=husl_cmap,
                                   norm=plt.Normalize(vmin=0, vmax=1))
        sm._A = []
        cbar = plt.colorbar(sm, cax=mcbar, ticks=[0, 1])
        cbar.ax.set_ylabel(r'$\alpha$', rotation=0)
        if save_plt:
            print 'kfns: saving magnitude comparison plot for hcoll (usually run from kitaev_collection)...'
            mfig.savefig(outdir + hlat.lp['LatticeTop'] +
                         "_magproj_singlept.png",
                         dpi=300)
        else:
            plt.show()
    if plot_diff:
        dax.set_title('Projector differences')
        dax.set_xlabel(r'$|\mathbf{x}_i - \mathbf{x}_0|$')
        dax.set_ylabel(r'$|\Delta P_{i0}|$')
        # make a scalar mappable for colorbar'
        husl_cmap = lecmaps.husl_cmap(s=sat, l=light)
        sm = plt.cm.ScalarMappable(cmap=husl_cmap,
                                   norm=plt.Normalize(vmin=0, vmax=1))
        sm._A = []
        cbar = plt.colorbar(sm, cax=dcbar, ticks=[0, 1])
        cbar.ax.set_ylabel(r'$\alpha$', rotation=0)
        if maxdistlines:
            # Grab ylimits for setting after adding lines
            ylims = dax.get_ylim()
            df_ylims = dfax.get_ylim()
            ii = 1
            for dd in maxdist:
                dax.plot([dd, dd],
                         np.array([-0.05, -0.005]),
                         '-',
                         color=colors[ii])
                dfax.plot([dd, dd],
                          np.array([df_ylims[0], -0.01]),
                          '-',
                          color=colors[ii])
                ii += 1
            dax.set_ylim(-0.05, ylims[1])
            dfax.set_ylim(df_ylims[0], df_ylims[1])
        # now do fractional difference magnitude plot
        dfax.set_title('Fractional projector differences')
        dfax.set_xlabel(r'$|\mathbf{x}_i - \mathbf{x}_0|$')
        dfax.set_ylabel(r'$|\Delta P_{i0}|/|P_{i0}|$')
        # make a scalar mappable for colorbar'
        cbar = plt.colorbar(sm, cax=dfcbar, ticks=[0, 1])
        cbar.ax.set_ylabel(r'$\alpha$', rotation=0)
        if save_plt:
            print 'kfns: saving diff plot for hcoll projecctors (usually run from kitaev_collection)...'
            dfig.savefig(outdir + hlat.lp['LatticeTop'] +
                         "_diffproj_singlept.png",
                         dpi=300)
            dffig.savefig(outdir + hlat.lp['LatticeTop'] +
                          "_diffproj_singlept_fractionaldiff.png",
                          dpi=300)
            dfax.set_ylim(-0.1, 1)
            dffig.savefig(outdir + hlat.lp['LatticeTop'] +
                          "_diffproj_singlept_fractionaldiff_zoom.png",
                          dpi=300)
            dfax.set_ylim(-0.02, 0.1)
            dffig.savefig(outdir + hlat.lp['LatticeTop'] +
                          "_diffproj_singlept_fractionaldiff_extrazoom.png",
                          dpi=300)
        elif not plot_mag:
            plt.show()

    return dist_list, proj_list
        description = 'kagomized hyperuniform'
    elif args.LatticeTop == 'kagper_hucent':
        description = 'kagome decoration percolation'

    if socket.gethostname()[0:6] == 'midway':
        rootdir = '/home/npmitchell/scratch-midway/'
        cp_rootdir = rootdir
    elif socket.gethostname()[0:8] == 'Messiaen' or socket.gethostname()[0:5] == 'cvpn-':
        rootdir = '/Users/npmitchell/Dropbox/Soft_Matter/GPU/'
        cp_rootdir = '/Users/npmitchell/Desktop/GPU/'
    else:
        rootdir = '/Users/npmitchell/Dropbox/Soft_Matter/GPU/'
        cp_rootdir = '/Volumes/research4TB/Soft_Matter/GPU/'

    outdir = rootdir + 'experiments/DOS_scaling/' + args.LatticeTop + '/'
    dio.ensure_dir(outdir)

    dcdisorder = args.V0_pin_gauss > 0 or args.V0_spring_gauss > 0

    lp = {'LatticeTop': args.LatticeTop,
          'shape': shape,
          'NH': NH,
          'NV': NV,
          'NP_load': args.NP_load,
          'rootdir': rootdir,
          'phi_lattice': args.phi_lattice,
          'delta_lattice': args.delta_lattice,
          'theta': args.theta,
          'eta': args.eta,
          'x1': x1,
          'x2': x2,
Esempio n. 13
0
    lemov.make_movie(imgname, movname, indexsz='04', framerate=15)


# Parameters
# number of sampling points
nx = 200
ny = 300
full3dplot = False
saveims = True
fontsize = 20
tick_fontsize = 16
maindir = '/Users/npmitchell/Dropbox/Soft_Matter/GPU/haldane_model/'
outdir = '/Users/npmitchell/Dropbox/Soft_Matter/GPU/haldane_model/t2_movie/'
outdir_dab = '/Users/npmitchell/Dropbox/Soft_Matter/GPU/haldane_model/DeltaAB_movie/'
outdir_dabt2 = '/Users/npmitchell/Dropbox/Soft_Matter/GPU/haldane_model/DeltaAB_movie_t20p20/'
dio.ensure_dir(outdir)
dio.ensure_dir(outdir_dab)
dio.ensure_dir(outdir_dabt2)
# hopping strengths
t1 = 1.
t2max = 0.20
t2arr = np.arange(0, t2max + 1e-9, 0.01)
mmarr = np.arange(0, 3 * t2max + 1e-9, 0.01)
mm = 0.

# Create movie and image sequence
movie_varyDeltaAB(t1,
                  0.,
                  mmarr,
                  nx,
                  ny,
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)
Esempio n. 15
0
def save_normal_modes_haldane(haldane_lattice,
                              datadir='auto',
                              rm_images=True,
                              gapims_only=False,
                              save_into_subdir=False,
                              overwrite=True,
                              color='pr'):
    """
    Plot the normal modes of a haldane model lattice with fixed pivot points and make a movie of them.

    Parameters
    ----------
    haldane_lattice : HaldaneLattice() instance
        the complex-NNN hopping lattice for which to plot the normal modes
    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.
    """
    hlat = haldane_lattice
    NP = len(hlat.lattice.xy)
    print 'Getting eigenvals/vects of dynamical matrix...'
    # Find eigval/vect
    eigval, eigvect = hlat.get_eigval_eigvect()
    t2 = hlat.t2
    pin = hlat.pin

    # prepare DOS output dir
    if datadir == 'auto':
        datadir = hlat.lp['meshfn']

    if 'meshfn_exten' in hlat.lp:
        exten = hlat.lp['meshfn_exten']
    elif hlat.lp['dcdisorder']:
        raise RuntimeError(
            'lemov: Since dcdisorder is True, there should be a meshfn_exten in lp'
        )
        # there should be meshfn_exten defined in lp, but since there is not, we make it here
        # exten = 'pin_mean' + sf.float2pstr(hlat.lp['pin']) + \
        #         '_pinV' + sf.float2pstr(hlat.lp['V0_pin_gauss']) + \
        #         '_strV' + sf.float2pstr(hlat.lp['V0_spring_gauss'])
    else:
        exten = ''

    DOSdir = datadir + 'DOS_haldane' + exten + '/'
    dio.ensure_dir(DOSdir)

    #####################################
    # Prepare for plotting
    #####################################
    print 'Preparing plot settings...'
    # Options for how to color the DOS header
    if color == 'pr':
        ipr = hlat.get_ipr()
        colorV = 1. / ipr
        lw = 0
        cbar_label = r'$p$'
        colormap = 'viridis_r'
    elif color == 'ipr':
        ipr = hlat.get_ipr()
        colorV = ipr
        lw = 0
        cbar_label = r'$p^{-1}$'
        colormap = 'viridis'
    elif color == 'ill':
        ill = hlat.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,
        hlat.lattice.xy,
        sim_type='haldane',
        colorV=colorV,
        colormap=colormap,
        linewidth=lw,
        cax_label=cbar_label,
        cbar_nticks=2,
        xlabel_pad=10,
        ylabel_pad=10,
        cbar_tickfmt='%0.3f')

    dostitle = r'$V = $' + '{0:0.2f}'.format(hlat.lp['pin'])
    if hlat.lp['ABDelta']:
        dostitle += r'$\pm$' + '{0:0.2f}'.format(hlat.lp['ABDelta'])
    elif hlat.lp['V0_pin_gauss']:
        dostitle += r'$\pm \sigma$, with $\sigma = $' + '{0:0.2f}'.format(
            hlat.lp['V0_pin_gauss'])

    dostitle += r' $t_1=$' + '{0:0.2f}'.format(hlat.lp['t1'])
    if abs(hlat.lp['t2a']) > 1e-7:
        dostitle += r' $t_2=$' + '{0:0.2f}'.format(
            hlat.lp['t2a']) + r'+$i$' + '{0:0.2f}'.format(hlat.lp['t2'])
    else:
        dostitle += r' $t_2=$' + '{0:0.2f}'.format(hlat.lp['t2'])
    DOS_ax.set_title(dostitle)
    hlat.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' + haldane_lattice.lp['meshfn_exten']
            else:
                movname += names[ii]

    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(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)
                    # hlat.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 = \
                        hlatpfns.construct_haldane_eigvect_DOS_plot(hlat.lattice.xy, fig, DOS_ax, eig_ax, eigval,
                                                                    eigvect, ii, hlat.lattice.NL, hlat.lattice.KL,
                                                                    marker_num=0, color_scheme='default')
                    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'])
Esempio n. 16
0
def save_normal_modes_twisty(tlat,
                             datadir='auto',
                             sim_type='xywz',
                             rm_images=True,
                             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.

    Parameters
    ----------
    tlat : TwistyLattice instance
        with attributes lp, Omg, xy_inner
    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
    save_into_subdir: bool
        Whether to save the movie in the same sudir where the DOS/ directory (containing the frames) is placed.
    """
    NP = len(tlat.xy_inner)
    print 'Getting eigenvals/vects of dynamical matrix...'
    # Find eigval/vect
    eigval, eigvect = tlat.get_eigval_eigvect()

    # prepare DOS output dir
    if datadir == 'auto':
        datadir = tlat.lp['meshfn']

    if 'meshfn_exten' in tlat.lp:
        exten = tlat.lp['meshfn_exten']
    else:
        raise RuntimeError('No meshfn_exten in tlat.lp')

    DOSdir = datadir + 'DOS' + exten + '/'
    dio.ensure_dir(DOSdir)

    #####################################
    # Prepare for plotting
    #####################################
    print 'Preparing plot settings...'

    # Options for how to color the DOS header
    if color == 'pr' or len(tlat.lattice.xy) < 3:
        ipr = tlat.get_ipr()
        colorV = 1. / ipr
        lw = 0
        cbar_label = r'$p$'
        colormap = 'viridis_r'
    elif color == 'ipr':
        ipr = tlat.get_ipr()
        colorV = ipr
        lw = 0
        cbar_label = r'$p^{-1}$'
        colormap = 'viridis'
    elif color == 'ill':
        ill = tlat.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,
        tlat.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'$k = $' + '{0:0.2f}'.format(tlat.lp['kk'])
    if tlat.lp['ABDelta_k']:
        dostitle += r'$\pm$' + '{0:0.2f}'.format(tlat.lp['ABDelta_k'])
    dostitle += r' $g = $' + '{0:0.2f}'.format(tlat.lp['gg'])
    if tlat.lp['ABDelta_g']:
        dostitle += r'$\pm$' + '{0:0.2f}'.format(tlat.lp['ABDelta_g'])
    dostitle += r' $c = $' + '{0:0.2f}'.format(tlat.lp['cc'])
    if tlat.lp['ABDelta_c']:
        dostitle += r'$\pm$' + '{0:0.2f}'.format(tlat.lp['ABDelta_c'])
    DOS_ax.set_title(dostitle)
    tlat.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
    text2show = tlat.lp['meshfn_exten'][1:]
    fig.text(0.01,
             0.01,
             text2show,
             horizontalalignment='left',
             verticalalignment='bottom')

    #####################################
    # 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
            todo = np.arange(len(eigval))
            todo_subset = np.setdiff1d(todo, np.arange(done_pngs))
            todo_subset = np.hstack((np.array([todo_subset[0]]), todo_subset))
            # print 'todo = ', todo_subset
            # sys.exit()

            if done_pngs < len(todo):
                dmyi = 0
                for ii in todo_subset:
                    if np.mod(ii, 50) == 0:
                        print 'plotting eigvect ', ii, ' of ', len(eigval)
                    # tlat.lattice.plot_BW_lat(fig=fig, ax=DOS_ax, save=False, close=False, axis_off=False, title='')
                    fig, [scat_fg, scat_fg2, f_mark, polygons, tiltgons], cw_ccw = \
                        twistyplt.construct_eigvect_DOS_plot(tlat.xy_inner, fig, DOS_ax, eig_ax, eigval, eigvect,
                                                             ii, sim_type, tlat.NL_t, tlat.KL_t,
                                                             marker_num=0, color_scheme='default', sub_lattice=-1)
                    plt.savefig(DOSdir + 'DOS_' + '{0:05}'.format(ii) + '.png')
                    scat_fg.remove()
                    scat_fg2.remove()
                    polygons.remove()
                    tiltgons.remove()
                    # for pp in polygons:
                    #     pp.remove()
                    # for tt in tiltgons:
                    #     tt.remove()

                    f_mark.remove()
                    # plt.show()
                    # sys.exit()
                    # lines_12_st.remove()
                    # eig_ax.cla()
                    if ii > 0:
                        dmyi += 1

        fig.clf()
        plt.close('all')

    print 'eigvect = ', eigvect

    ######################
    # 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'])
Esempio n. 17
0
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'])
Esempio n. 18
0
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 draw_edge_localization_plots(glat, elocz, eigval, eigvect, outdir=None, alpha=1.0, fontsize=12):
    """Draw plots of each normal mode excitation with colormap behind it denoting the fitted exponential localization

    Parameters
    ----------
    glat : GyroLattice instance
        The gyro lattice whose modes we plot
    elocz : NP x 5 float array (ie, int(len(eigval)*0.5) x 5 float array)
        edge localization fit details: A, K, uncertainty_A, covariance_AK, uncertainty_K
    eigval : 2*N x 1 complex array
        eigenvalues of the matrix, sorted by order of imaginary components
    eigvect : typically 2*N x 2*N complex array
        eigenvectors of the matrix, sorted by order of imaginary components of eigvals
        Eigvect is stored as NModes x NP*2 array, with x and y components alternating, like:
        x0, y0, x1, y1, ... xNP, yNP.
    outdir : str or None
        the output directory to use for saving localization plots. If None, uses pwd as ouput dir
    alpha : float
        The opacity of the excitation ellipses
    fontsize : int
        The fontsize to use for labels, etc

    Returns
    -------
    fig, dos_ax, ax
    """
    if outdir is None:
        print 'Outputting images in current working directory...'
        outdir = './'
    else:
        dio.ensure_dir(outdir)
    ipr = glat.get_ipr()

    # Get third largest value for ipr vmax
    # ipr_vmax = np.max(1. / ipr.sort())[3]
    ipr_vmax = float(np.floor(10 * heapq.nlargest(6, 1. / ipr)[-1])) / 10.
    inds = np.arange(int(0.5 * len(eigval)), len(eigval))
    fig, dos_ax, ax = leplt.initialize_eigvect_DOS_header_plot(eigval[inds], glat.lattice.xy,
                                                               sim_type='gyro',
                                                               preset_cbar=True,
                                                               colorV=1. / ipr[inds], colormap='viridis_r',
                                                               norm=None,
                                                               facecolor='#80D080', nbins=75, fontsize=fontsize,
                                                               vmin=0.0, vmax=ipr_vmax,
                                                               linewidth=0,
                                                               make_cbar=True, climbars=True,
                                                               xlabel='Oscillation frequency $\omega/\Omega_g$',
                                                               ylabel=r'$D(\omega)$', ylabel_pad=20,
                                                               cax_label=r'$p$',
                                                               cbar_labelpad=10, ticks=[0., ipr_vmax],
                                                               cbar_nticks=None,
                                                               cbar_tickfmt=None,
                                                               orientation='vertical', cbar_orientation='vertical',
                                                               invert_xaxis=False, yaxis_tickright=False,
                                                               yaxis_ticks=None, ylabel_right=False, ylabel_rot=0,
                                                               DOSexcite=None, DOSexcite_color='r')
    # Make axis for showing quality of fit
    x0 = 0.1
    y0 = 0.2
    w = 0.8
    h = 0.2
    ax.set_position([x0, y0, w, h])
    eax_w = 0.5
    eax_h = 0.15
    eax_x0 = x0 + (w - eax_w) * 0.5
    eax_y0 = y0 + h * 1.7
    exp_ax = fig.add_axes([eax_x0, eax_y0, eax_w, eax_h])

    glat.lattice.plot_BW_lat(fig=fig, ax=ax, meshfn='none', save=False, close=False, axis_off=True, title='')

    # If fully periodic, escape
    if glat.lp['periodicBC'] and not glat.lp['periodic_strip']:
        # There are two periodic vectos, so there can be no boundary --> exit with error
        raise RuntimeError('Cannot compute distance to boundary in a periodic sample --> there is no boundary.')

    # Compute magnitude of excitation at each site
    magevecs = glat.calc_magevecs(eigvect)
    # Also get distance of each particle from boundary
    bndry_segs = glat.lattice.get_boundary_linesegs()
    if isinstance(bndry_segs, tuple):
        xydists = []
        for bsegii in bndry_segs:
            xydists.append(linesegs.mindist_from_multiple_linesegs(glat.lattice.xy, bsegii))

        # Convert list xydists into NP x 2 array
        xydists = np.dstack(tuple(xydists))[0]
    else:
        # There is only one boundary, so use lattice boundary to connect consecutive linesegments
        xydists = linesegs.mindist_from_multiple_linesegs(glat.lattice.xy, bndry_segs)

    # Check if there are multiple boundaries
    multiple_boundaries = len(np.shape(xydists)) > 1

    # Get the xlims and ylims for plotting the exponential decay fit
    xlims_fit = [-0.1, np.max(xydists.ravel()) + 1]
    xlims = [np.min(glat.lattice.xy[:, 0]) - 1, np.max(glat.lattice.xy[:, 0]) + 1]
    ylims = [np.min(glat.lattice.xy[:, 1]) - 1, np.max(glat.lattice.xy[:, 1]) + 1]

    # defining dmyi to be -1 so that the zeroth frame (first one saved) gets done twice to fix formatting
    dmyi = -1
    # Look at all states with positive frequency
    todo = np.hstack((np.array([int(len(eigval) * 0.5)]), np.arange(int(len(eigval) * 0.5), len(eigval))))
    for en in todo:
        if en % 10 == 0:
            print 'glat_plottingfns: eigval = ', dmyi, '/', len(todo)
        # magind is the index of current eigval as seen by an array that knows only about the top half of
        # the eigenvectors.
        magind = int(en - len(eigval) * 0.5)

        fig, [scat_fg, pp, f_mark, lines12_st] =\
            leplt.plot_eigvect_excitation(glat.lattice.xy, fig, dos_ax, ax, eigval, eigvect, en,
                                          marker_num=0, black_t0lines=True)
        locz = elocz[magind]

        if multiple_boundaries:
            localz_handle = plot_edge_localization_heatmap_periodicstrip(locz, bndry_segs, ax, xlims=xlims,
                                                                         ylims=ylims, alpha=1.0)
            title = ax.get_title()
            # Draw the exponential localization fit
            plt_handle, fit_handle = plot_localization_dists(locz, xydists[:, int(locz[5] % 2)], magevecs[magind],
                                                             exp_ax, xlims=xlims_fit)
        else:
            # assuming no periodicity
            # Plot heat map for decay from min distance to any boundary segments
            localz_handle = plot_edge_localization_heatmap(locz, bndry_segs, ax, xlims=xlims, ylims=ylims, alpha=1.0)
            title = ax.get_title()
            # Draw the exponential localization fit
            # If there are multiple boundaries, pick out the one that distances are fit from
            if len(np.shape(xydists)) > 1:
                xydists_temp = xydists[:, int(locz[5] % 2)]
            else:
                xydists_temp = xydists

            plt_handle, fit_handle = plot_localization_dists(locz, xydists_temp, magevecs[en], exp_ax, xlims=xlims_fit)

        ax.set_title(title + r', $|\psi(r)| \approx$ $($' +
                     '{0:0.3f}'.format(locz[0]) + r'$\pm$' + '{0:0.3f}'.format(locz[2]) + r'$)$ ' +
                     r'$\exp[($' + '{0:0.3f}'.format(locz[1]) + r'$\pm$' + '{0:0.3f}'.format(locz[4]) + '$)\, r]$',
                     fontsize=fontsize)

        # labels for the localization fit
        exp_ax.set_xlabel('Distance from boundary, $x$', fontsize=12)
        exp_ax.set_ylabel('Excitation, $|\psi|$', fontsize=12)

        # Save this image
        if en % 10 == 0:
            print 'saving image to ', outdir + 'localization' + glat.lp['meshfn_exten'] + \
                                      '_{0:06d}'.format(max(0, dmyi)) + '.png'
        plt.savefig(outdir + 'localization' + glat.lp['meshfn_exten'] + '_{0:06d}'.format(max(0, dmyi)) + '.png')

        # cleanup
        localz_handle.remove()
        scat_fg.remove()
        pp.remove()
        f_mark.remove()
        lines12_st.remove()
        exp_ax.cla()

        del localz_handle
        del scat_fg
        del pp
        del f_mark
        del lines12_st
        dmyi += 1

    return fig, dos_ax, ax
Esempio n. 20
0
        print '\n\nWe are on Midway!\n\n\n\n'
        rootdir = '/home/npmitchell/scratch-midway/'
        cprootdir = '/home/npmitchell/scratch-midway/'
    elif socket.gethostname()[0:10] == 'nsit-dhcp-':
        rootdir = '/Users/npmitchell/Dropbox/Soft_Matter/GPU/'
        cprootdir = '/Volumes/research4TB/Soft_Matter/GPU/'
    elif socket.gethostname() == 'Messiaen.local':
        rootdir = '/Users/npmitchell/Dropbox/Soft_Matter/GPU/'
        cprootdir = '/Volumes/research4TB/Soft_Matter/GPU/'
        if not glob.glob(cprootdir):
            cprootdir = '/Volumes/research2TB/Soft_Matter/GPU/'
            if not glob.glob(cprootdir):
                cprootdir = '/Users/npmitchell/Desktop/data_local/GPU/'
                if not glob.glob(cprootdir):
                    if not glob.glob(cprootdir):
                        dio.ensure_dir(cprootdir)
    elif socket.gethostname()[0:5] == 'cvpn-':
        rootdir = '/Users/npmitchell/Dropbox/Soft_Matter/GPU/'
        cprootdir = '/Volumes/research2TB/Soft_Matter/GPU/'
    else:
        rootdir = '/Users/npmitchell/Dropbox/Soft_Matter/GPU/'

    lp = {
        'LatticeTop': args.LatticeTop,
        'shape': shape,
        'NH': NH,
        'NV': NV,
        'NP_load': args.NP_load,
        'rootdir': rootdir,
        'phi_lattice': args.phi_lattice,
        'delta_lattice': '{0:0.3f}'.format(args.delta_lattice),
Esempio n. 21
0
        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(
                    gamma) + '_epsilon{0:0.0e}'.format(eps) + '.pkl'
                globfn = glob.glob(fn)
                if globfn:
Esempio n. 22
0
    def save_chern(self):
        # Make output directories
        print 'saving chern to: ', self.cp['cpmeshfn']
        dio.ensure_dir(self.cp['cpmeshfn'])
        # if self.params_regs or self.contribs is not None:
        #     dio.ensure_dir(self.cp['cpmeshfn'] + 'params_regs/')
        # if self.contribs is not None:
        #     dio.ensure_dir(self.cp['cpmeshfn'] + 'contribs/')

        # Save the chern calculation to cp['cpmeshfn']
        if self.chern_finsize is None:
            raise RuntimeError(
                'Cannot save chern calculation since it has not been computed!'
            )

        # Save chern parameters
        fn = self.cp['cpmeshfn'] + 'chern_params.txt'
        header = 'Parameters for chern calculation'
        dio.save_dict(self.cp, fn, header)

        # Save chern_finsize
        fn = self.cp['cpmeshfn'] + 'chern_finsize.txt'
        header = 'Nreg1, ksize_frac, ksize, ksys_size (note this is NP_summed), ksys_frac, nu' + \
                 'for Chern calculation: basis=' + \
                 self.cp['basis'] + ' pin=' + '{0:0.3f}'.format(self.haldane_lattice.lp['pin']) + \
                 ' V0_pin_gauss=' + '{0:0.3f}'.format(self.haldane_lattice.lp['V0_pin_gauss']) + \
                 ' t1=' + '{0:0.3f}'.format(self.haldane_lattice.lp['t1']) +\
                 ' t2=' + '{0:0.3f}'.format(self.haldane_lattice.lp['t2'])

        print 'saving chern_finsize to ', fn
        np.savetxt(fn, self.chern_finsize, delimiter=',', header=header)

        # Save chern_finsize as a plot
        plt.clf()
        plt.plot(self.chern_finsize[:, -2], self.chern_finsize[:, -1], 'o-')
        plt.title('Chern number versus system size')
        plt.xlabel('Fraction of system size in sum')
        plt.ylabel('Chern number')
        plt.savefig(self.cp['cpmeshfn'] + 'chern_finsize_ksizeSum.png')
        plt.close('all')

        # Save kitaev region parameters for each ksize
        # if self.params_regs or self.contribs is not None:
        #     for ksize in self.params_regs:
        #         header = 'Indices of kitaev regions: ksize = ' + sf.prepstr(ksize)
        #         fn = self.cp['cpmeshfn']+'params_regs/params_regs_ksize' + sf.prepstr(ksize) + '.txt'
        #         dio.save_dict(self.params_regs[ksize], fn, header)
        #
        #     print 'saved (many) params_regs. Last one was:', fn

        # Save kitaev region parameters as pkl
        with open(self.cp['cpmeshfn'] + 'params_regs.pkl', "wb") as fn:
            pickle.dump(self.params_regs, fn)

        # Save lattice parameters too for convenience (gives info about disorder, spinning speeds etc)
        print 'saving lattice_params...'
        header = 'Lattice parameters, copied from meshfn: ' + self.haldane_lattice.lp[
            'meshfn']
        dio.save_dict(self.haldane_lattice.lp,
                      self.cp['cpmeshfn'] + 'lattice_params.txt', header)

        if self.contribs is not None:
            # Save kitaev region parameters for each ksize
            # for ksize in self.contribs:
            #     header = 'Saving contribs for ksize = ' + sf.prepstr(ksize)
            #     fn = self.cp['cpmeshfn'] + 'contribs/contribs_ksize' + sf.prepstr(ksize) + '.txt'
            #     dio.save_dict(self.contribs[ksize], fn, header)
            with open(self.cp['cpmeshfn'] + 'contribs.pkl', "wb") as fn:
                pickle.dump(self.contribs, fn)
Esempio n. 23
0
def calc_chern(matk,
               cp,
               lattice,
               appendstr=None,
               verbose=True,
               bz_cutoff=1e14,
               kxy=None,
               overwrite=False,
               signed_norm=False):
    """Compute the chern number using the wedge product of the projector

    Parameters
    ----------
    kchern : KChernGyro class instance
        kspace Chern calculation class
    bz_cutoff : float
        if BZ has a dimension larger than bz_cutoff, then we return zero chern number and no bands

    Returns
    -------
    kchern.chern
    """
    # this is really the only function you need to change to do a different kind of lattice.
    # mM, vertex_points, od, fn, ar = lf.honeycomb_sheared(tvals, delta, phi, ons, base_dir)
    # matk = glatkfns.lambda_matrix_kspace(kchern.gyro_lattice, eps=1e-10)
    bzvtcs = lattice.get_bz(attribute=True)

    # Define the brillouin zone polygon
    bzarea = dh.polygon_area(bzvtcs)

    # Check if a similar results file exists --> new data is appended to the old data, if it exists
    savedir = cp['cpmeshfn']
    dio.ensure_dir(savedir)
    savefn, cp, search_density_fn = prepare_chern_filename(cp,
                                                           appendstr=appendstr)
    print 'established savefn: ', cp['savefn']

    if kxy is None:
        globs = sorted(glob.glob(search_density_fn))
        # Obtain the filename with the density that is smaller than the requested one
        if globs and not overwrite:
            densities = np.array([
                int(
                    globfn.split('density')[-1].split('.pkl')[0].split('_')[0])
                for globfn in globs
            ])
            if (densities < cp['density']).any():
                biggestsmall = densities[densities < cp['density']][-1]
                smallerfn = savedir + 'kspacechern_density{0:07d}'.format(
                    biggestsmall)
                if cp['ortho']:
                    smallerfn += '_ortho'
                if 'deriv_res' in cp:
                    if cp['deriv_res'] != 1e-5:
                        smallerfn += '_dres{0:0.3e}'.format(
                            cp['deriv_res']).replace('-',
                                                     'n').replace('.', 'p')

                smallerfn += appendstr
                smallerfn += '.pkl'
            else:
                smallerfn = False
        else:
            smallerfn = False

        if verbose:
            print 'kchern_gyro_fns: looking for saved file ' + savefn
        if os.path.isfile(savefn) and overwrite:
            if verbose:
                print 'kchern_gyro_fns: chern file exists, overwriting: ', savefn
            # initialize empty lists to be filled up
            kkx, kky = [], []
            bands, traces = [], []
            npts = int(cp['density'] * bzarea)
        elif os.path.isfile(savefn):
            # File of same size exists
            chern = load_chern(cp, appendstr=appendstr, verbose=True)
            print 'generalized_kchern_fns: loaded chern, returning chern'
            return chern
        elif smallerfn:
            if verbose:
                print 'kchern_gyro_fns: chern file with smaller density exists, loading to append...'
            with open(smallerfn, 'rb') as of:
                data = pkl.load(of)
                # Convert contents to lists so that we can append to them
                bands = list(data['bands'])
                kkx = list(data['kx'])
                kky = list(data['ky'])
                traces = list(data['traces'])

            # figure out how many points to append to reach desired density
            npts = int(cp['density'] * bzarea) - len(kkx)
        else:
            if verbose:
                print 'generalized_kchern_fns: no chern file with smaller density exists, computing from scratch...'
            # initialize empty lists to be filled up
            kkx, kky = [], []
            bands, traces = [], []
            npts = int(cp['density'] * bzarea)

        # Make the kx, ky points to add to current results
        # Handle cases where the BZ is too elongated to populate in reasonable time
        try:
            kxy = dh.generate_random_xy_in_polygon(npts, bzvtcs, sorted=True)
            if len(kxy) == 0:
                if (bzvtcs > bz_cutoff).any():
                    print 'The BZ is too large to fill with kvec points'
                    kkx, kky = np.zeros(10), np.zeros(10)
                    bv = np.zeros(2 * len(lattice.xy[:, 0]))
                    bands = np.nan * np.ones(2 * len(lattice.xy[:, 0]))
                    traces = np.nan * np.ones((2 * len(lattice.xy[:, 0]), 10))
                    dat_dict = {
                        'kx': kkx,
                        'ky': kky,
                        'chern': bv,
                        'bands': bands,
                        'traces': traces,
                        'bzvtcs': bzvtcs
                    }
                    chern = dat_dict
                    return chern
                else:
                    print 'generalized_kchern_fns: bzvtcs = ', bzvtcs
                    print 'generalized_kchern_fns: kxy = ', kxy
                    raise RuntimeError(
                        'Could not generate random xy in polygon, but BZ is not larger than cutoff in any dim.'
                    )
        except ValueError:
            print 'The BZ is too large to fill with kvec points'
            if (np.abs(bzvtcs) > bz_cutoff).any():
                print 'The BZ is too large to fill with kvec points'
                kkx, kky = np.zeros(10), np.zeros(10)
                bv = np.zeros(2 * len(lattice.xy[:, 0]))
                bands = np.nan * np.ones(2 * len(lattice.xy[:, 0]))
                traces = np.nan * np.ones((2 * len(lattice.xy[:, 0]), 10))
                dat_dict = {
                    'kx': kkx,
                    'ky': kky,
                    'chern': bv,
                    'bands': bands,
                    'traces': traces,
                    'bzvtcs': bzvtcs
                }
                chern = dat_dict
                return chern
            else:
                print 'kchern_gyro_fns: bzvtcs = ', bzvtcs
                print 'bz_cutoff = ', bz_cutoff
                # print 'generalized_kchern_fns: kxy = ', kxy
                raise RuntimeError(
                    'Could not generate random xy in polygon, but BZ is not larger than cutoff in any dim.'
                )
                dat_dict = {
                    'kx': kkx,
                    'ky': kky,
                    'chern': bv,
                    'bands': bands,
                    'traces': traces,
                    'bzvtcs': bzvtcs
                }
    else:
        # kxy is supplied -- compute at those locations
        print 'kxy is supplied, computing berry at supplied points'
        kkx, kky = [], []
        bands, traces = [], []

    start_time = time.time()
    for ii in range(len(kxy)):
        # time for evaluating point index ii
        tpi = []
        # Display how much time is left
        if ii % 4000 == 1999 and verbose:
            end_time = time.time()
            tpi.append(abs((start_time - end_time) / (ii + 1)))
            total_time = np.mean(tpi) * len(kxy)
            printstr = 'Estimated time remaining: ' + '%0.2f s' % (
                total_time - (end_time - start_time))
            printstr += ', ii = ' + str(ii + 1) + '/' + str(len(kxy))
            print printstr

        eigval, tr = calc_bands(matk,
                                kxy[ii, 0],
                                kxy[ii, 1],
                                h=cp['deriv_res'],
                                ortho=cp['ortho'],
                                signed_norm=signed_norm)
        kkx.append(kxy[ii, 0])
        kky.append(kxy[ii, 1])
        traces.append(tr)
        bands.append(eigval)

    bands = np.array(bands)
    traces = np.array(traces)
    kkx = np.array(kkx)
    kky = np.array(kky)

    bv = []
    if verbose:
        print 'kchern_gyro_fns: np.shape(bands) = ', np.shape(bands)
        print 'kchern_gyro_fns: np.shape(traces) = ', np.shape(traces)
    for ii in range(len(bands[0])):
        chern = ((1j / (2. * np.pi)) * np.mean(traces[:, ii]) * bzarea
                 )  # chern numbers for bands
        bv.append(chern)

    dat_dict = {
        'kx': kkx,
        'ky': kky,
        'chern': bv,
        'bands': bands,
        'traces': traces,
        'bzvtcs': bzvtcs
    }
    chern = dat_dict

    return chern
Esempio n. 24
0
def le_plot_gHST(xy, NL, KL, BM, params, t, ii, name, outdir, climv=0.1, xlimv='auto',
                 exaggerate=1.0, PlanarLimit=False):
    """Plots a gliding heavy symmetric top network

    Parameters
    ----------
    xy : NP x 5 array
        positions of pivots (x,y) and euler angles for all HSTs
    t : float
        time stamp for image
    ii : int
        index for naming
    name : string
        the name of the file (before _index.png)
    outdir : string
        The output directory for the image
    climv : float or tuple
        Color limit for coloring bonds by bond strain
    xlimv
    exaggerate : float (default 1.0 --> in which case it is ignored)
        Exaggerate the displacements of each particle from its initial position by this factor. Ignored if == 1.0
    PlanarLimit : bool

    Returns
    ----------
    """
    # make output dir
    outdir = dio.prepdir(outdir)
    dio.ensure_dir(outdir)
    # set range of window from first values
    if xlimv == 'auto':
        xlimv = params['xlimv']
    ylimv = xlimv

    # save current data as stills
    index = '{0:08d}'.format(ii)
    outname = outdir + '/' + name + '_' + index + '.png'
    BL = NL2BL(NL, KL)

    if 'prestrain' in params:
        prestrain = params['prestrain']
    else:
        prestrain = 0.

    if 'shrinkrate' in params:
        shrinkrate = params['shrinkrate']
        title = 't = ' + '%09.1f' % t + '  a = ' + '%07.5f' % (1. - shrinkrate * t - prestrain)
    elif 'prestrain' in params:
        shrinkrate = 0.0
        title = 't = ' + '%09.1f' % t + '  a = ' + '%07.5f' % (1. - prestrain)
    else:
        shrinkrate = 0.0
        title = 't = ' + '%09.1f' % t

    if exaggerate != 1.0:
        title += ' magnify=' + str(exaggerate)

    if 'Omg' in params:
        title += '\n' + r'$\Omega_g$=' + '{0:.3f}'.format(params['Omg'])
    if 'OmK' in params:
        title += r' $\Omega_k$=' + '{0:.3f}'.format(params['OmK'])
    if 'g' in params:
        gstr = str(params['g'])
        if len(gstr.split('.')[1]) > 3:
            gstr = '{0:.3f}'.format(params['g'])
        title += '\n' + r'$g$=' + gstr
    if 'k' in params:
        kstr = str(params['k'])
        if len(kstr.split('.')[1]) > 3:
            kstr = '{0:.3f}'.format(params['k'])
        title += r' $k$=' + kstr
    if 'Mm' in params:
        try:
            mstr = str(params['Mm'][0])
            if len(mstr.split('.')[1]) > 3:
                mstr = '{0:.3f}'.format(params['Mm'][0])
            title += r' $m$=' + mstr
        except:
            mstr = str(params['Mm'])
            if len(mstr.split('.')[1]) > 3:
                mstr = '{0:.3f}'.format(params['Mm'])
            title += r' $m$=' + mstr
    if 'l' in params:
        try:
            lstr = str(params['l'][0])
            if len(lstr.split('.')[1]) > 3:
                lstr = '{0:.3f}'.format(params['l'][0])
            title += r' $l$=' + lstr
        except:
            lstr = str(params['l'])
            if len(lstr.split('.')[1]) > 3:
                lstr = '{0:.3f}'.format(params['l'])
            title += r' $l$=' + lstr
    if 'w3' in params:
        try:
            if (params['w3'] - params['w3'][0] < 1e-5).all():
                wstr = str(params['w3'][0])
                if len(lstr.split('.')[1]) > 3:
                    wstr = '{0:.3f}'.format(params['w3'][0])
                title += r' $\omega_3$=' + wstr
                # Otherwise, don't print w3: it is heterogeneous
        except:
            wstr = str(params['w3'])
            if len(wstr.split('.')[1]) > 3:
                wstr = '{0:.3f}'.format(params['w3'])
            title += r' $\omega_3$=' + wstr

    if params['BCtype'] == 'excite':
        title += r' $\omega_d$=' + '{0:.5f}'.format(params['frequency'])

    # calculate strain
    # bs = bond_strain_list(xy,BL,bL0)
    # if exaggerate==1.0:
    #   movie_plot_2D_gyros(xy, BL, bs, outname, title, xlimv, ylimv, climv)
    # else:
    #   xye = xy0+(xy-xy0)*exaggerate
    #   movie_plot_2D_gyros(xye, BL, bs, outname, title, xlimv, ylimv, climv)

    # set limits
    fig = plt.gcf()
    plt.clf()

    ax = plt.gca()
    ax.set_xlim(-xlimv, xlimv)
    ax.set_ylim(-ylimv, ylimv)

    if PlanarLimit:
        gHST_plot_PL(xy, NL, KL, BM, params, factor=exaggerate, climv=climv, title=title)
    else:
        gHST_plot(xy, NL, KL, BM, params, factor=exaggerate, climv=climv, title=title)

    plt.savefig(outname)
Esempio n. 25
0
def calc_chern(kchern, verbose=True):
    """Compute the chern number using the wedge product of the projector

    Parameters
    ----------
    kchern : KChernGyro class instance
        kspace Chern calculation class

    Returns
    -------

    """
    # Unpack kchern a bit
    cp = kchern.cp
    # this is really the only function you need to change to do a different kind of lattice.
    # mM, vertex_points, od, fn, ar = lf.honeycomb_sheared(tvals, delta, phi, ons, base_dir)
    matk = glatkfns.lambda_matrix_kspace(kchern.gyro_lattice, eps=1e-10)
    bzvtcs = kchern.gyro_lattice.lattice.get_bz(attribute=True)

    # set the directory for saving images and data.  The function above actually creates these directories for you.
    #  I know this isn't exaclty ideal.
    bzarea = dh.polygon_area(bzvtcs)

    # Check if a similar results file exists --> new data is appended to the old data, if it exists
    savedir = cp['cpmeshfn']
    dio.ensure_dir(savedir)
    savefn = savedir + 'kspacechern_density{0:07d}.pkl'.format(cp['density'])
    globs = sorted(glob.glob(savedir + 'kspacechern_density*.pkl'))
    # Obtain the filename with the density that is smaller than the requested one
    if globs:
        densities = np.array([
            int(globfn.split('density')[-1].split('.pkl')[0])
            for globfn in globs
        ])
        if (densities < cp['density']).any():
            biggestsmall = densities[densities < cp['density']][-1]
            smallerfn = savedir + 'kspacechern_density{0:07d}.pkl'.format(
                biggestsmall)
        else:
            smallerfn = False
    else:
        smallerfn = False

    if verbose:
        print 'kchern_gyro_fns: looking for saved file ' + savefn
    if os.path.isfile(savefn):
        if verbose:
            print 'kchern_gyro_fns: chern file exists, overwriting: ', savefn
        # initialize empty lists to be filled up
        kkx, kky = [], []
        bands, traces = [], []
        npts = int(cp['density'] * bzarea)
    elif smallerfn:
        if verbose:
            print 'kchern_gyro_fns: chern file with smaller density exists, loading to append...'
        with open(smallerfn, 'rb') as of:
            data = pkl.load(of)
            # Convert contents to lists so that we can append to them
            bands = list(data['bands'])
            kkx = list(data['kx'])
            kky = list(data['ky'])
            traces = list(data['traces'])

        # figure out how many points to append to reach desired density
        npts = int(cp['density'] * bzarea) - len(kkx)
    else:
        # initialize empty lists to be filled up
        kkx, kky = [], []
        bands, traces = [], []
        npts = int(cp['density'] * bzarea)

    # Make the kx, ky points to add to current results
    kxy = dh.generate_random_xy_in_polygon(npts, bzvtcs, sorted=True)

    start_time = time.time()
    for ii in range(len(kxy)):
        # time for evaluating point index ii
        tpi = []
        # Display how much time is left
        if ii % 4000 == 1999 and verbose:
            end_time = time.time()
            tpi.append(abs((start_time - end_time) / (ii + 1)))
            total_time = np.mean(tpi) * len(kxy)
            printstr = 'Estimated time remaining: ' + '%0.2f s' % (
                total_time - (end_time - start_time))
            printstr += ', ii = ' + str(ii + 1) + '/' + str(len(kxy))
            print printstr

        eigval, tr = calc_bands(matk, kxy[ii, 0], kxy[ii, 1])
        kkx.append(kxy[ii, 0])
        kky.append(kxy[ii, 1])
        traces.append(tr)
        bands.append(eigval)

    bands = np.array(bands)
    traces = np.array(traces)
    kkx = np.array(kkx)
    kky = np.array(kky)

    bv = []
    if verbose:
        print 'kchern_gyro_fns: np.shape(bands) = ', np.shape(bands)
        print 'kchern_gyro_fns: np.shape(traces) = ', np.shape(traces)
    for ii in range(len(bands[0])):
        chern = ((1j / (2. * np.pi)) * np.mean(traces[:, ii]) * bzarea
                 )  # chern numbers for bands
        bv.append(chern)

    dat_dict = {
        'kx': kkx,
        'ky': kky,
        'chern': bv,
        'bands': bands,
        'traces': traces,
        'bzvtcs': bzvtcs
    }
    kchern.chern = dat_dict

    return kchern.chern
def dispersion_abtransition(lp, invert_bg=False, color1=None, color2=None, color_thres=None,
                            nkxvals=50, dab_step=0.005, dpi=100, plot_positive_only=True, ab_max=2.6):
    """

    Parameters
    ----------
    lp

    Returns
    -------

    """
    if invert_bg:
        plt.style.use('dark_background')

    if invert_bg:
        if color1 is None:
            # blue
            color1 = '#70a6ff'
        if color2 is None:
            # red
            color2 = '#ff7777'  # '#90354c'
        # print 'color1, 2 = ', color1, color2
        # sys.exit()
    else:
        cmap = lecmaps.diverging_cmap(250, 10, l=30)
        color1 = cmap(0.)
        color2 = cmap(1.)

    meshfn = le.find_meshfn(lp)
    lp['meshfn'] = meshfn
    lpmaster = copy.deepcopy(lp)
    ablist = np.arange(0, ab_max + dab_step, dab_step)
    # create a place to put images
    outdir = dio.prepdir(meshfn) + 'dispersion_abtransition/'
    dio.ensure_dir(outdir)
    fs = 20

    # go through each ab and make the image
    ii = 0
    for ab in ablist:
        print 'ab = ', ab
        lp = copy.deepcopy(lpmaster)
        lp['ABDelta'] = ab
        lat = lattice_class.Lattice(lp)
        lat.load(check=lp['check'])

        glat = GyroLattice(lat, lp)
        # glat.get_eigval_eigvect(attribute=True)
        fig, ax = leplt.initialize_portrait(ax_pos=[0.12, 0.2, 0.76, 0.6])
        omegas, kx, ky = glat.infinite_dispersion(save=False, nkxvals=nkxvals, nkyvals=50, outdir=outdir, save_plot=False)

        # plot and save it
        title = r'$\Delta_{AB} =$' + '{0:0.2f}'.format(ab)
        for jj in range(len(ky)):
            for kk in range(len(omegas[0, jj, :])):
                if color_thres is None or ab > 0.26:
                    if invert_bg:
                        ax.plot(kx, omegas[:, jj, kk], 'w-', lw=max(1., 30. / (len(kx) * len(ky))))
                    else:
                        ax.plot(kx, omegas[:, jj, kk], 'k-', lw=max(1., 30. / (len(kx) * len(ky))))
                else:
                    # if positive frequencies, color top band blue
                    if len(np.where(omegas[:, jj, kk] > 0)[0]) > 0.5 * len(omegas[:, jj, kk]):
                        # color top band blue
                        if len(np.where(np.abs(omegas[:, jj, kk]) > color_thres)[0]) > 0.5 * len(omegas[:, jj, kk]):
                            ax.plot(kx, omegas[:, jj, kk], '-', lw=max(1., 30. / (len(kx) * len(ky))), color=color1)
                        else:
                            ax.plot(kx, omegas[:, jj, kk], '-', lw=max(1., 30. / (len(kx) * len(ky))), color=color2)

                    # if negative frequencies, color bottom band blue
                    if len(np.where(omegas[:, jj, kk] < 0)[0]) > 0.5 * len(omegas[:, jj, kk]):
                        # color bottom band blue
                        if len(np.where(np.abs(omegas[:, jj, kk]) > color_thres)[0]) > 0.5 * len(omegas[:, jj, kk]):
                            ax.plot(kx, omegas[:, jj, kk], '-', lw=max(1., 30. / (len(kx) * len(ky))), color=color2)
                        else:
                            ax.plot(kx, omegas[:, jj, kk], '-', lw=max(1., 30. / (len(kx) * len(ky))), color=color1)

        ax.text(0.5, 1.15, title, fontsize=fs, ha='center', va='center', transform=ax.transAxes)
        ax.set_xlim(-np.pi, np.pi)
        ax.xaxis.set_ticks([-np.pi, 0, np.pi])
        ax.xaxis.set_ticklabels([r'$-\pi$', 0, r'$\pi$'])
        ax.set_xlabel(r'$k_x$', fontsize=fs)
        ax.set_ylabel(r'$\omega$', fontsize=fs)
        for tick in ax.xaxis.get_major_ticks():
            tick.label.set_fontsize(fs)
        for tick in ax.yaxis.get_major_ticks():
            tick.label.set_fontsize(fs)
        if ii == 0:
            ylims = ax.get_ylim()

        if plot_positive_only:
            ax.set_ylim(0., ylims[1])
        else:
            ax.set_ylim(ylims[0], ylims[1])

        # Save it
        name = outdir + 'dispersion{0:04d}'.format(ii)
        plt.savefig(name + '.png', dpi=dpi)
        plt.close('all')

        ii += 1

    # Turn images into a movie
    imgname = outdir + 'dispersion'
    movname = dio.prepdir(meshfn) + 'dispersion_abtrans' + glat.lp['meshfn_exten']
    lemov.make_movie(imgname, movname, indexsz='04', framerate=10, imgdir=outdir, rm_images=True,
                     save_into_subdir=True)