Пример #1
0
def plot_chernbands(kchern,
                    fig=None,
                    ax=None,
                    cax=None,
                    outpath=None,
                    eps=1e-10,
                    cmap='bbr0',
                    vmin=-1.0,
                    vmax=1.0,
                    ticks=None,
                    round_chern=True,
                    dpi=150,
                    alpha=1.0):
    """

    Parameters
    ----------
    kchern : KChernGyro class instance
    fig : matplotlib figure instance or None
    ax : matplotlib axis instance or None

    Returns
    -------
    fig, ax
    """
    vertex_points = kchern.chern['bzvtcs']
    kkx = kchern.chern['kx']
    kky = kchern.chern['ky']
    bands = kchern.chern['bands']
    chern = kchern.chern['chern']
    # b = ((1j / (2 * np.pi)) * np.mean(traces[:, i]) * bzarea)
    if ax is None:
        fig, ax, cax = leplt.initialize_1panel_cbar_fig(wsfrac=0.5, tspace=4)

    if isinstance(cmap, str):
        cmap = lecmaps.ensure_cmap(cmap)

    xmax, ymax = 0., 0.
    for kk in range(len(bands[0, :])):
        band = bands[:, kk]
        # If round_chern is True, round Chern number to the nearest integer
        if round_chern:
            colorval = (round(np.real(chern[kk])) - vmin) / (vmax - vmin)
        else:
            # Don't round to the nearest integer
            colorval = (np.real(chern[kk]) - vmin) / (vmax - vmin)
        # ax.plot(kkx, band, color=cmap(colorval))
        polygon = dh.approx_bounding_polygon(np.dstack((kkx, band))[0],
                                             ngridpts=np.sqrt(len(kkx)) * 0.5)
        # Add approx bounding polygon to the axis
        poly = Polygon(polygon,
                       closed=True,
                       fill=True,
                       lw=0.00,
                       alpha=alpha,
                       color=cmap(colorval),
                       edgecolor=None)
        xmax = max(xmax, np.max(np.abs(kkx)))
        ymax = max(ymax, np.max(np.abs(band)))
        ax.add_artist(poly)
        # ax.plot(polygon[:, 0], polygon[:, 1], 'k.-')

    ax.set_xlim(-xmax, xmax)
    ax.set_ylim(-ymax, ymax)

    if cax is not None:
        if vmin is None:
            vmin = np.min(np.real(np.array(chern)))
        if vmax is None:
            vmax = np.max(np.real(np.array(chern)))
        if ticks is None:
            ticks = [int(vmin), int(vmax)]

        sm = leplt.empty_scalar_mappable(cmap=cmap, vmin=vmin, vmax=vmax)
        plt.colorbar(sm,
                     cax=cax,
                     ticks=ticks,
                     label=r'Chern number, $C$',
                     alpha=alpha)

    if outpath is not None:
        plt.savefig(outpath, dpi=dpi)
        plt.close()

    return fig, ax, cax
    ax.yaxis.set_ticks([])
    ylim = ax.get_ylim()
    ax.plot([eigval[ii], eigval[ii]], [ylim[0], ylim[1]], 'r-')
    ax.set_ylim(ylim)
    return ax


x0, x1 = 0.0, 0.5
sz = 0.5
wcbar = 0.3
ax1loc = [x0, 0.2, sz, sz]
ax2loc = [x1, 0.2, sz, sz]
cax1loc = [x0 + (sz - wcbar) * 0.5, 0.1, wcbar, 0.025]
cax2loc = [x1 + (sz - wcbar) * 0.5, 0.1, wcbar, 0.025]
fr = 30
cmap = lecmaps.ensure_cmap('rwb0')
outdir = '/Users/npmitchell/Dropbox/Soft_Matter/PAPER/review_paper/'
outdir += 'test_symmetries_ari_largesystem/'
# IrvineLabCodes/noah/noah/lepm/lepm/test_symmetries/'

# open boundary condition hexagonal
latticetop = 'iscentroid'
haldane = False
if haldane:
    outdir += 'haldane_'
nn = 64
npload = 64
outdir += latticetop + '_nn{0:03d}'.format(nn)
if npload > 0:
    outdir += '_npload{0:03d}'.format(npload) + '/'
else:
Пример #3
0
def movie_varyt2(t1,
                 t2arr,
                 mm,
                 nx,
                 ny,
                 maindir,
                 outdir,
                 fontsize=20,
                 tick_fontsize=16,
                 saveims=True,
                 dual_panel=False,
                 color_berry=False,
                 cmap='bbr0',
                 vmin=0.499,
                 vmax=0.501,
                 plot3d=False):
    """Plot the band structure of the haldane model as we vary the NNN hopping

    Parameters
    ----------
    t1 : float
        magnitude of real NN hopping
    t2 : float
        magnitude of complex NNN hopping
    dab_arr : n x 1 float array
        the DeltaAB values to use for each frame
    nn : int
        number of kx values (same as # ky values)
    maindir : str
        where to save the movie
    outdir : str
        where to save the images
    saveims : bool
        overwrite the existing images
    dual_panel : bool
        plot the 2d dispersion with calibration of gap opening as function of DeltaAB
    vmin : float
        the minimimum color value from 0 to 1, if color_berry=True
    vmax : float
        the maximum color value from 0 to 1, if color_berry = True
    plot3d : bool
        whether to plot the dispersion in 3d or not
    """
    kk = 0
    gaps = []
    t2s = []
    if isinstance(cmap, str):
        cmap = lecmaps.ensure_cmap(cmap)

    for t2 in t2arr:
        if color_berry:
            km, kv, energy1, energy2, berry1, berry2 = haldane_dispersion_berry(
                nx, t1, t2, mm)
        else:
            km, kv, energy1, energy2 = haldane_dispersion(nx, ny, t1, t2, mm)
        gap = np.min(energy1) * 2.
        print 'gap = ', gap
        gaps.append(gap)
        t2s.append(t2)

        if saveims:
            if dual_panel:
                fig, ax = leplt.initialize_2panel_3o4ar_cent(fontsize=fontsize,
                                                             x0frac=0.085)
                ax, ax2 = ax[0], ax[1]
            else:
                fig, ax = leplt.initialize_1panel_centered_fig(
                    Wfig=180, Hfig=180, wsfrac=0.7, fontsize=fontsize)

            if not color_berry:
                if t2 > mm / np.sqrt(3.):
                    ax.plot(km[1],
                            energy1.reshape(np.shape(km[0])),
                            '-',
                            color=band1color)
                    ax.plot(km[1],
                            energy2.reshape(np.shape(km[0])),
                            '-',
                            color=band2color)
                elif t2 < -mm / np.sqrt(3.):
                    ax.plot(km[1],
                            energy1.reshape(np.shape(km[0])),
                            '-',
                            color=band2color)
                    ax.plot(km[1],
                            energy2.reshape(np.shape(km[0])),
                            '-',
                            color=band1color)
                else:
                    ax.plot(km[1],
                            energy1.reshape(np.shape(km[0])),
                            '-',
                            color=graycolor)
                    ax.plot(km[1],
                            energy2.reshape(np.shape(km[0])),
                            '-',
                            color=graycolor)
            else:
                b1color = berry1.reshape(np.shape(km[0])) / (2. * np.pi) + 0.5
                b2color = berry2.reshape(np.shape(km[0])) / (2. * np.pi) + 0.5
                print 'b1color=', b1color
                # sys.exit()
                energy1 = energy1.reshape(np.shape(km[0]))
                energy2 = energy2.reshape(np.shape(km[0]))
                # ax.scatter([0., 0.5, 1.0], [0., 0.5, 1.0], c=[0., 0.5, 1.0], edgecolor='none', cmap=cmap, alpha=1)
                for ii in range(len(km[0])):
                    ax.scatter(km[1][ii],
                               energy1[ii],
                               c=b1color,
                               edgecolor='none',
                               cmap=cmap,
                               alpha=1.,
                               vmin=vmin,
                               vmax=vmax)
                    ax.scatter(km[1][ii],
                               energy2[ii],
                               c=b2color,
                               edgecolor='none',
                               cmap=cmap,
                               alpha=1.,
                               vmin=vmin,
                               vmax=vmax)
                # plt.show()
                # sys.exit()

            ax.set_xlabel(r'$k_x$', labelpad=15, fontsize=fontsize)
            ax.set_ylabel(r'$\omega$',
                          labelpad=15,
                          fontsize=fontsize,
                          rotation=0)
            ax.xaxis.set_ticks([-np.pi, 0, np.pi])
            ax.xaxis.set_ticklabels([r'-$\pi$', 0, r'$\pi$'],
                                    fontsize=tick_fontsize)
            for tick in ax.yaxis.get_major_ticks():
                tick.label.set_fontsize(tick_fontsize)
            ax.axis('scaled')
            ax.set_xlim(-np.pi, np.pi)
            ax.set_ylim(-np.pi, np.pi)
            # title = r'$\Delta \omega =$' + '{0:0.3f}'.format(gap) + r' $t_1$'
            title = r'$t_2 =$' + '{0:0.3f}'.format(t2) + r' $t_1$,   ' + \
                    r'$\Delta_{AB} =$' + '{0:0.3f}'.format(mm) + r' $t_1$'
            ax.text(0.5,
                    1.1,
                    title,
                    ha='center',
                    va='center',
                    fontsize=fontsize,
                    transform=ax.transAxes)

            if dual_panel:
                # Make second figure
                ax2.plot()
                ax2.set_xlim(0, 0.2)
                ax2.set_ylim(0, 0.7)
                ax2.plot([np.min(t2arr), np.max(t2arr)],
                         [0.0, 3.36864398885 * np.max(t2arr)],
                         '-',
                         color='#a1bfdb',
                         lw=3)
                ax2.scatter(t2s, gaps, color='k', zorder=9999999999)
                title = 'Gap size: ' + r'$\Delta\omega/t_1 \approx 3.369\, t_2$'
                ax2.text(0.5,
                         1.1,
                         title,
                         ha='center',
                         va='center',
                         fontsize=fontsize,
                         transform=ax2.transAxes)
                for tick in ax2.xaxis.get_major_ticks():
                    tick.label.set_fontsize(tick_fontsize)
                for tick in ax2.yaxis.get_major_ticks():
                    tick.label.set_fontsize(tick_fontsize)
                ax2.set_xlabel(r'$t_2 = \Omega_k^2/8\Omega_g$',
                               fontsize=fontsize,
                               labelpad=15)
                ax2.set_ylabel(r'$\Delta\omega/t_1 = 2 \Delta\omega/\Omega_k$',
                               fontsize=fontsize,
                               rotation=90,
                               labelpad=35)

            # Save the image
            plt.savefig(outdir + 'dispersion_{0:04d}'.format(kk) + '.png',
                        dpi=140)
            plt.close('all')
            kk += 1
            print 'dirac = ', 2. * np.pi / 3., ', ', -2. * np.pi / (
                3. * np.sqrt(3.))
            ind = np.argmin(energy1)
            dirac = kv[ind]
            print 'dirac where = ', dirac

    print 't2s = ', t2s
    print 'gaps = ', gaps
    zz = np.polyfit(np.array(t2s), np.array(gaps), 1)
    pp = np.poly1d(zz)
    print pp
    print zz[0]
    print zz[1]

    imgname = outdir + 'dispersion_'
    movname = maindir + 'dispersion_varyt2'
    movname += '_nkx{0:06d}'.format(nx) + '_nky{0:06d}'.format(ny)
    lemov.make_movie(imgname, movname, indexsz='04', framerate=15)
Пример #4
0
def movie_varyDeltaAB(t1,
                      t2,
                      dab_arr,
                      nx,
                      ny,
                      maindir,
                      outdir,
                      fontsize=20,
                      tick_fontsize=16,
                      saveims=True,
                      dual_panel=False,
                      color_berry=False,
                      cmap='coolwarm',
                      vmin=0.49,
                      vmax=0.51,
                      plot3d=False):
    """Create a movie of band structure with varying DeltaAB

    Parameters
    ----------
    t1 : float
        magnitude of real NN hopping
    t2 : float
        magnitude of complex NNN hopping
    dab_arr : n x 1 float array
        the DeltaAB values to use for each frame
    nn : int
        number of kx values (same as # ky values)
    maindir : str
        where to save the movie
    outdir : str
        where to save the images
    saveims : bool
        overwrite the existing images
    dual_panel : bool
        plot the 2d dispersion with calibration of gap opening as function of DeltaAB
    vmin : float
        the minimimum color value from 0 to 1, if color_berry=True
    vmax : float
        the maximum color value from 0 to 1, if color_berry = True
    plot3d : bool
        whether to plot the dispersion in 3d or not
    """
    if isinstance(cmap, str):
        cmap = lecmaps.ensure_cmap(cmap)

    kk = 0
    gaps = []
    dabs = []
    for mm in dab_arr:
        if color_berry:
            km, kv, energy1, energy2, berry1, berry2 = haldane_dispersion_berry(
                nx, ny, t1, t2, mm)
        else:
            km, kv, energy1, energy2 = haldane_dispersion(nx, ny, t1, t2, mm)

        gap = np.min(energy1) * 2.
        print 'gap = ', gap
        gaps.append(gap)
        dabs.append(mm)

        if saveims:
            if not plot3d:
                if dual_panel:
                    fig, ax = leplt.initialize_2panel_3o4ar_cent(
                        fontsize=fontsize, x0frac=0.085)
                    ax, ax2 = ax[0], ax[1]

                    # Make second figure
                    ax2.plot()
                    ax2.set_xlim(0, 0.2)
                    ax2.set_ylim(0, 0.7)
                    ax2.plot([np.min(t2arr), np.max(t2arr)],
                             [0.0, 2 * np.max(t2arr)],
                             '-',
                             color='#a1bfdb',
                             lw=3)
                    ax2.scatter(dabs, gaps, color='k', zorder=9999999999)
                    title = 'Gap size: ' + r'$\Delta\omega/t_1 \approx 2 \, \Delta_{AB}$'
                    ax2.text(0.5,
                             1.1,
                             title,
                             ha='center',
                             va='center',
                             fontsize=fontsize,
                             transform=ax2.transAxes)
                    for tick in ax2.xaxis.get_major_ticks():
                        tick.label.set_fontsize(tick_fontsize)
                    for tick in ax2.yaxis.get_major_ticks():
                        tick.label.set_fontsize(tick_fontsize)
                    ax2.set_xlabel(r'$t_2 = \Omega_k^2/8\Omega_g$',
                                   fontsize=fontsize,
                                   labelpad=15)
                    ax2.set_ylabel(
                        r'$\Delta\omega/t_1 = 2 \Delta\omega/\Omega_k$',
                        fontsize=fontsize,
                        rotation=90,
                        labelpad=35)
                else:
                    fig, ax = leplt.initialize_1panel_centered_fig(
                        Wfig=180, Hfig=180, wsfrac=0.7, fontsize=fontsize)

                if not color_berry:
                    # check if topological or not
                    print 't2 = ', t2
                    print 'mm = ', mm * (3. * np.sqrt(3.))
                    if t2 > mm / np.sqrt(3.):
                        # yes, topological
                        ax.plot(km[1],
                                energy1.reshape(np.shape(km[0])),
                                '-',
                                color=band1color)
                        ax.plot(km[1],
                                energy2.reshape(np.shape(km[0])),
                                '-',
                                color=band2color)
                    elif t2 < -mm / np.sqrt(3.):
                        # flipped topology
                        ax.plot(km[1],
                                energy1.reshape(np.shape(km[0])),
                                '-',
                                color=band2color)
                        ax.plot(km[1],
                                energy2.reshape(np.shape(km[0])),
                                '-',
                                color=band1color)
                    else:
                        # not topological
                        ax.plot(km[1],
                                energy1.reshape(np.shape(km[0])),
                                '-',
                                color=graycolor)
                        ax.plot(km[1],
                                energy2.reshape(np.shape(km[0])),
                                '-',
                                color=graycolor)
                else:
                    b1color = berry1.reshape(np.shape(
                        km[0])) / (2. * np.pi) + 0.5
                    b2color = berry2.reshape(np.shape(
                        km[0])) / (2. * np.pi) + 0.5

                    energy1 = energy1.reshape(np.shape(km[0]))
                    energy2 = energy2.reshape(np.shape(km[0]))
                    # ax.scatter([0., 0.5, 1.0], [0., 0.5, 1.0], c=[0., 0.5, 1.0], edgecolor='none', cmap=cmap, alpha=1)
                    for ii in range(len(km[0])):
                        ax.scatter(km[1][ii],
                                   energy1[ii],
                                   c=b1color[ii],
                                   edgecolor='none',
                                   cmap=cmap,
                                   alpha=0.1,
                                   vmin=vmin,
                                   vmax=vmax)
                        ax.scatter(km[1][ii],
                                   energy2[ii],
                                   c=b2color[ii],
                                   edgecolor='none',
                                   cmap=cmap,
                                   alpha=0.1,
                                   vmin=vmin,
                                   vmax=vmax)
                    plt.show()
                    sys.exit()

                ax.set_ylabel(r'$\omega$',
                              labelpad=15,
                              fontsize=fontsize,
                              rotation=0)
                # title = r'$\Delta \omega =$' + '{0:0.3f}'.format(gap) + r' $t_1$'
                title = r'$t_2 =$' + '{0:0.3f}'.format(t2) + r' $t_1$,   ' + \
                        r'$\Delta_{AB} =$' + '{0:0.3f}'.format(mm) + r' $t_1$'
                ax.text(0.5,
                        1.1,
                        title,
                        ha='center',
                        va='center',
                        fontsize=fontsize,
                        transform=ax.transAxes)

            else:
                # Plot it in 3d
                fig, ax = leplt.initialize_1panel_centered_fig(
                    Wfig=180, Hfig=180, wsfrac=0.7, fontsize=fontsize)
                ax = fig.gca(projection='3d')
                # Reshape colors, energies
                b1color = cmap((berry1.reshape(np.shape(km[0])) /
                                (2. * np.pi)) / (vmax - vmin) + 0.5)
                b2color = cmap((berry2.reshape(np.shape(km[0])) /
                                (2. * np.pi)) / (vmax - vmin) + 0.5)
                energy1 = energy1.reshape(np.shape(km[0]))
                energy2 = energy2.reshape(np.shape(km[0]))
                print 'b1color = ', b1color

                # Plot surfaces
                surf = ax.plot_surface(km[0],
                                       km[1],
                                       energy1,
                                       facecolors=b1color,
                                       rstride=1,
                                       cstride=1,
                                       vmin=vmin,
                                       vmax=vmax,
                                       cmap=cmap,
                                       linewidth=1,
                                       antialiased=False)
                surf = ax.plot_surface(km[0],
                                       km[1],
                                       energy2,
                                       facecolors=b2color,
                                       rstride=1,
                                       cstride=1,
                                       vmin=vmin,
                                       vmax=vmax,
                                       cmap=cmap,
                                       linewidth=1,
                                       antialiased=False)
                ax.set_ylabel(r'$k_y$', labelpad=15, fontsize=fontsize)
                ax.yaxis.set_ticks([-np.pi, 0, np.pi])
                ax.yaxis.set_ticklabels([r'-$\pi$', 0, r'$\pi$'],
                                        fontsize=tick_fontsize)
                for tick in ax.xaxis.get_major_ticks():
                    tick.label.set_fontsize(tick_fontsize)
                ax.set_zlabel(r'$\omega$',
                              labelpad=15,
                              fontsize=fontsize,
                              rotation=90)
                # ax.zaxis.set_ticks([-np.pi, 0, np.pi])
                # ax.zaxis.set_ticklabels([r'-$\pi$', 0, r'$\pi$'], fontsize=tick_fontsize)
                for tick in ax.zaxis.get_major_ticks():
                    tick.label.set_fontsize(tick_fontsize)
                ax.axis('scaled')
                ax.set_zlim(-np.pi, np.pi)

            ax.set_xlabel(r'$k_x$', labelpad=15, fontsize=fontsize)
            ax.xaxis.set_ticks([-np.pi, 0, np.pi])
            ax.xaxis.set_ticklabels([r'-$\pi$', 0, r'$\pi$'],
                                    fontsize=tick_fontsize)
            for tick in ax.yaxis.get_major_ticks():
                tick.label.set_fontsize(tick_fontsize)
            ax.axis('scaled')
            ax.set_xlim(-np.pi, np.pi)
            ax.set_ylim(-np.pi, np.pi)

            # Save it
            plt.savefig(outdir + 'dispersion_{0:04d}'.format(kk) +
                        '.png'.format(t2),
                        dpi=140)
            plt.close('all')
            kk += 1
            print 'dirac = ', 2. * np.pi / 3., ', ', -2. * np.pi / (
                3. * np.sqrt(3.))
            ind = np.argmin(energy1)
            dirac = kv[ind]
            print 'dirac where = ', dirac

        # print the fitting
        print 'dabs = ', dabs
        print 'gaps = ', gaps
        zz = np.polyfit(np.array(dabs), np.array(gaps), 1)
        pp = np.poly1d(zz)
        print 'pp = ', pp
        print 'zz[0] = ', zz[0]
        print 'zz[1] = ', zz[1]

    imgname = outdir + 'dispersion_'
    movname = maindir + 'dispersion_varyDeltaAB_{0:0.3f}'.format(t2).replace(
        '.', 'p')
    movname += '_nkx{0:06d}'.format(nx) + '_nky{0:06d}'.format(ny)
    lemov.make_movie(imgname, movname, indexsz='04', framerate=15)
Пример #5
0
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)