Esempio n. 1
0
def save_gxy(xgrid,
             ygrid,
             gxy_grid,
             xc,
             yc,
             gxy,
             infodir,
             ax=None,
             title=r'$g(x,y)$',
             maxgxy='auto',
             cbar_orientation='vertical',
             cbar_nticks=2,
             check=False):
    """Save 2-pt correlation function g(x,y) into infodir"""
    print 'Saving g(x,y) heatmaps...'
    # Save heatmap of g(x,y)
    if ax is None:
        fig, ax, cbar_ax = leplt.initialize_1panel_cbar_fig(wsfrac=0.5)

    if maxgxy == 'auto':
        sca = ax.pcolormesh(xgrid, ygrid, gxy_grid, cmap='viridis', vmin=0.0)
        vmax = np.max(gxy_grid.ravel())
    else:
        vmax = maxgxy
        sca = ax.pcolormesh(xgrid,
                            ygrid,
                            gxy_grid,
                            cmap='viridis',
                            vmin=0.0,
                            vmax=maxgxy)

    cbar = plt.colorbar(sca, cax=cbar_ax, orientation=cbar_orientation)
    cbar.set_ticks([0., vmax * 0.5, vmax])
    cbar.set_label(r'$ g(x,y)$', rotation=90)
    ax.axis('equal')
    # print 'title = ', titlestr
    plt.suptitle(title)
    print 'saving figure: ', infodir + 'gxy.png'
    plt.savefig(infodir + 'gxy.png', dpi=600)

    ax.set_xlim(-5, 5)
    ax.set_ylim(-5, 5)
    plt.savefig(infodir + 'gxy_zoom.png', dpi=600)
    if check:
        plt.show()

    # Save g(xy) as txt file
    print 'Saving g(x,y) text file...'
    MM = np.dstack((xc, yc, gxy))[0]
    np.savetxt(infodir + 'gxy.txt',
               MM,
               delimiter=',',
               header='r, g(xy) : correlation function for point set')
Esempio n. 2
0
def projector_site_vs_dist_glatparam(gcoll,
                                     omegac,
                                     proj_XY,
                                     plot_mag=True,
                                     plot_diff=False,
                                     save_plt=True,
                                     alpha=1.0,
                                     maxdistlines=True,
                                     reverse_order=False,
                                     check=True):
    """THIS HAS NOT BEEN UPDATED FOR BOTT INDEX SPECIFIC CALC
    Compare the projector values at distances relative to a particular site (gyro at location proj_XY).

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

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

    sat = 1
    light = 0.6
    colors = lecmaps.husl_palette(n_colors=len(gcoll.gyro_lattices),
                                  s=sat,
                                  l=light)
    if reverse_order:
        glat_list = gcoll.gyro_lattices[::-1]
    else:
        glat_list = gcoll.gyro_lattices

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

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

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

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

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

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

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

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

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

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

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

        kk += 1

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

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

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

    return dist_list, proj_list
Esempio n. 3
0
def plot_berryband(kchern,
                   cbar_ticks=None,
                   title=None,
                   ax=None,
                   vmin=None,
                   vmax=None,
                   alpha=1.0):
    """Plot the berry curvature of an indicated band on the axis, ax

    Parameters
    ----------
    kchern : KChernGyro instance

    Returns
    -------
    fig, ax, cax
    """
    if ax is None:
        fig, ax, cax = leplt.initialize_1panel_cbar_fig(Wfig=180,
                                                        wsfrac=0.5,
                                                        tspace=10,
                                                        y0frac=0.08,
                                                        x0frac=0.15)

    vertex_points = kchern.chern['bzvtcs']
    kkx = kchern.chern['kx']
    kky = kchern.chern['ky']
    bands = kchern.chern['bands']
    cherns = kchern.chern['chern']
    berry = kchern.chern['traces']
    # b = ((1j / (2 * np.pi)) * np.mean(traces[:, i]) * bzarea)

    # Get index and parameter value of this glat
    paramval = retrieve_param_value(kchern.gyro_lattice.lp[param])
    index = np.where(paramval == params)[0][0]

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

    # Create int array indexing bands to plot, but start halfway up and only do positive eigval bands
    todo = np.arange(int(0.5 * len(bands[0, :])), len(bands[0, :]))
    for kk in todo:
        berrykk = berry[:, kk]

        # Plot berry curvature as heatmap
        xx, yy, zz = dh.interpol_meshgrid(kkx,
                                          kky,
                                          np.imag(berrykk),
                                          ngrid,
                                          method='nearest')
        ax.pcolormesh(xx, yy, zz, cmap=cmap, vmin=vmin, vmax=vmax, alpha=alpha)

        # Also draw the BZ
        patch_handle = mask_ax_to_bz(ax, vertex_points)
        # poly = Polygon(vertex_points, closed=True, fill=True, lw=1, alpha=1.0, facecolor='none', edgecolor='k')
        # ax.add_artist(poly)

        # Add title
        ax.set_xlabel('wavenumber, $k_x$')
        ax.set_ylabel('wavenumber, $k_y$')
        if not titlelock:
            title = r'Berry curvature, $\nu = $' + \
                    '{0:0.1f}'.format(float(np.real(cherns[kk]))) + ' ' + \
                    paramlabel + '=' + '{0:0.2f}'.format(float(paramval))
        ax.text(0.5,
                1.04,
                title,
                transform=ax.transAxes,
                ha='center',
                va='center')

        # Do colorbar
        if cbar_ticks is None:
            cbar_ticks = [vmin, vmax]

        sm = leplt.empty_scalar_mappable(cmap=cmap, vmin=vmin, vmax=vmax)
        plt.colorbar(sm,
                     cax=cax,
                     ticks=cbar_ticks,
                     label=r'Berry curvature, $\mathcal{F}$',
                     alpha=alpha)

        # xy limits
        vpr = vertex_points.ravel()
        ax.set_xlim(np.min(vpr), np.max(vpr))
        ax.set_ylim(np.min(vpr), np.max(vpr))

    return fig, ax, cax
Esempio n. 4
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