def plot_nugrid_chern(chern, hlat, xyvec, nugrids, repi, outdir=None, name_exten='', ax=None, fontsize=8):
    """Plot a pcolormesh of the spatially-resolved chern calcs on ax and plot the lattice on top of this.

    Parameters
    ----------
    chern : HaldaneChern instance
    hlat : haldaneLattice instance
    xyvec :
    nugrids :
    nugsum :
    repi :
    outdir : str or None
    name_exten

    """
    leplt.plot_pcolormesh(xyvec[:, 0], xyvec[:, 1], nugrids[repi].T.ravel(), 100, ax=ax,
                          method='nearest', cmap='rwb0',
                          vmin=-1.0, vmax=1.0, xlabel='x', ylabel='y',  cax_label=r'$\nu$', fontsize=fontsize)
    netvis.movie_plot_2D(hlat.lattice.xy, hlat.lattice.BL, 0 * hlat.lattice.BL[:, 0],
                         None, None, ax=plt.gca(), axcb=None, bondcolor='k',
                         colorz=False, ptcolor=None, figsize='auto',
                         colormap='BlueBlackRed', bgcolor='#ffffff', axis_off=False, axis_equal=True,
                         lw=0.2)
    kpfns.add_kitaev_regions_to_plot(chern=chern, ksize_ind=repi, offsetxy=np.array([15, 0]))
    plt.title(r'$\nu$')
    plt.ylabel(r'$y$')
    plt.xlabel(r'$x$')
    if outdir is not None:
        plt.savefig(outdir + '_nugrid' + name_exten + '.png')
def plot_gradnusum_chern(chern, hlat, xyvec, nugsum, repi, outdir=None, name_exten='', ax=None, fontsize=8):
    """Plot the gradient of the computed chern number -- plots the sum of abs(del_i nu) where the sum is taken over
    the two directions (x and y).

    Parameters
    ----------
    chern : HaldaneChern instance
    hlat : HaldaneLattice instance
    xyvec :
    nugrids :
    nugsum :
    repi :
    outdir : str or None
    name_exten

    """
    leplt.plot_pcolormesh(xyvec[:, 0], xyvec[:, 1], nugsum[repi].T.ravel(), 100, ax=ax,
                          method='nearest', cmap='viridis',
                          vmin=None, vmax=None, xlabel='x', ylabel='y',  cax_label=r'$\sum_j |\nabla_j \nu|$',
                          fontsize=fontsize)
    netvis.movie_plot_2D(hlat.lattice.xy, hlat.lattice.BL, 0 * hlat.lattice.BL[:, 0],
                         None, None, ax=plt.gca(), axcb=None, bondcolor='k',
                         colorz=False, ptcolor=None, figsize='auto',
                         colormap='BlueBlackRed', bgcolor='#ffffff', axis_off=False, axis_equal=True,
                         lw=0.2)
    kpfns.add_kitaev_regions_to_plot(chern=chern, ksize_ind=repi, offsetxy=np.array([15, 0]))
    plt.title(r'$|\sum_j \nabla_j \nu|$')
    plt.ylabel(r'$y$')
    plt.xlabel(r'$x$')
    if outdir is None:
        plt.show()
    else:
        plt.savefig(outdir + '_nugradsumabs' + name_exten + '.png')
def expo(args):
    def filename_fn(args):
        rs = 'N({}, {})'.format(args.radius, args.sigma)
        return rs

    def fpath(fname):
        _fpath = os.path.join(args.output_dir, fname)
        return _fpath

    length = 5 * args.radius
    linspace, data = SyntheticDataset.grid_data(args.num_points, length=length)

    #    loader = dataset[args.dataset](args)
    #    trainData = loader.train
    #    for batch_idx, samples in enumerate(trainData):
    #        data,labels = samples[DatasetType.InD]

    plt.xlim(-1 * length, length)
    plt.ylim(-1 * length, length)

    for scale in tqdm([1, 2, 3, 4]):
        sigma = scale * args.sigma

        scale_args = deepcopy(args)
        scale_args.sigma = sigma
        fname = filename_fn(scale_args)

        checkpoint_dir = os.path.join(args.work_dir, 'checkpoints')
        saver = Saver(checkpoint_dir)  # makes directory if already not present
        payload = saver.load(hash_args(
            scale_args))  #hash_args(scale_args) generates the hex string

        def run_and_save(scale_args):
            export = main(scale_args)  #Model creation??

            payload = export['model']
            saver.save(hash_args(scale_args), payload)
            return payload

        export = payload or run_and_save(scale_args)

        with torch.no_grad():
            scores = inference(export, data)
            np_x = data.cpu().numpy()
            for key in scores:
                score = scores[key].cpu().numpy()
                plot_pcolormesh(np_x, linspace, score)
                score_fname = '{}_{}'.format(fname, key)
                plt.title(score_fname)
                flush_plot(plt, fpath(score_fname) + '.png')
def plot_spectrum_with_dos(hlat,
                           ksys_fracM,
                           omegacM,
                           nuM,
                           ngrid,
                           Wfig=90,
                           Hfig=None,
                           x0frac=0.15,
                           y0frac=0.1,
                           wsfrac=0.4,
                           hs=None,
                           wsdosfrac=0.3,
                           vspace=8,
                           hspace=8,
                           tspace=10,
                           FSFS=8,
                           xlabel=None,
                           ylabel=None,
                           title=None):
    """Plot chern spectrum vs ksize (or other variable on x axis), with corresponding DOS plot aligned with y axis
    (increasing in frequency).

    Parameters
    ----------
    hlat : haldane_lattice
    Wfig : int or float
        width of the figure in mm
    Hfig : int or float or None
        Height of the figure in mm
    x0frac : fraction of Wfig to leave blank left of plot
    y0frac : fraction of Wfig to leave blank below plot
    wsfrac : fraction of Wfig to make width of subplot
    hs : height of subplot in mm. If none, uses ws = wsfrac * Wfig
    vspace : vertical space between subplots
    hspace : horizontal space btwn subplots
    tspace : space above top figure
    fontsize : size of text labels, title

    Returns
    -------
    fig : matplotlib.pyplot figure instance
    ax : matplotlib.pyplot axis instance
    """
    # Make figure
    fig, ax = initialize_spectrum_with_dos_plot(Wfig=Wfig,
                                                Hfig=Hfig,
                                                x0frac=x0frac,
                                                y0frac=y0frac,
                                                wsfrac=wsfrac,
                                                hs=hs,
                                                wsdosfrac=wsdosfrac,
                                                vspace=vspace,
                                                hspace=hspace,
                                                tspace=tspace,
                                                fontsize=FSFS)

    # ax[2].xaxis.set_major_locator( MaxNLocator(nbins = 3) ) #, prune = 'lower') )
    # ax[3].xaxis.set_major_locator( MaxNLocator(nbins = 3) )

    # Plot sideways DOS colored by PR: http://matplotlib.org/examples/pylab_examples/scatter_hist.html
    print 'kpfns: adding ipr to axis...'
    hlat.add_ipr_to_ax(ax[0],
                       ipr=None,
                       alpha=1.0,
                       inverse_PR=False,
                       norm=None,
                       nbins=75,
                       fontsize=FSFS,
                       cbar_ax=ax[2],
                       vmin=None,
                       vmax=None,
                       linewidth=0,
                       cax_label=r'$p$',
                       make_cbar=True,
                       climbars=True,
                       cbar_labelpad=3,
                       orientation='horizontal',
                       cbar_orientation='horizontal',
                       invert_xaxis=True,
                       ylabel=r'$D(\omega)$',
                       xlabel='Oscillation frequency $\omega$',
                       cbar_nticks=3,
                       cbar_tickfmt='%0.1f')
    leplt.plot_pcolormesh(ksys_fracM,
                          omegacM,
                          nuM,
                          ngrid,
                          ax=ax[1],
                          cax=ax[3],
                          method='nearest',
                          cmap=cmaps.diverging_cmap(250, 10, l=30),
                          vmin=-1.0,
                          vmax=1.0,
                          title=title,
                          xlabel=xlabel,
                          ylabel=ylabel,
                          cax_label=r'$\nu$',
                          cbar_labelpad=3,
                          cbar_orientation='horizontal',
                          ticks=[-1, 0, 1],
                          fontsize=FSFS)
    # plt.show()
    # sys.exit()

    # Add title
    ax[0].annotate(title,
                   xy=(0.5, .95),
                   xycoords='figure fraction',
                   horizontalalignment='center',
                   verticalalignment='center')
    # Match axes
    ax[0].set_ylim(ax[1].get_ylim())
    ax[0].xaxis.set_major_locator(MaxNLocator(nbins=2))  # , prune = 'upper') )
    ax[1].yaxis.set_label_position("right")
    ax[1].yaxis.set_ticks_position('both')
    plt.setp(ax[1].get_yticklabels(), visible=False)
    ax[2].xaxis.set_label_position("top")
    ax[3].xaxis.set_label_position("top")

    return fig, ax
def plot_chern_spectrum_on_axis(kcoll, ax, dos_ax, cbar_ipr_ax, cbar_nu_ax, fontsize=8, alpha=1.0,
                                ipr_vmin=None, ipr_vmax=None, cbar_labelpad=3, invert_xaxis=True,
                                ipr_cax_label='participation\nratio,' + r' $p$',
                                chern_cax_label='Chern\nnumber, ' + r'$\nu$'):
    """
    Parameters
    ----------
    kcoll : HaldaneCollection instance
        The chern collection to add to the plot
    ax : matplotlib axis instance
        the axis on which to add the spectrum
    dos_ax : matplotlib axis instance
        the axis on which to add
    alpha : float
        opacity of the spectrum and DOS added to the plot

    Returns
    -------
    ax, dos_ax
    """
    dmyi = 0
    for hlat_name in kcoll.cherns:
        # Grab a pointer to the haldane_lattice
        hlat = kcoll.cherns[hlat_name][0].haldane_lattice
        dmyi += 1
    if dmyi > 1:
        raise RuntimeError('This function takes a HaldaneCollection which is allowed only ONE haldane_lattice-- ' +
                           'ie, a chern spectrum for a single haldaneLattice instance')

    print 'Opening hlat_name = ', hlat_name
    ngrid = len(kcoll.cherns[hlat_name][0].chern_finsize)

    # Assume all ksize elements are the same size for now
    ksys_frac = kcoll.cherns[hlat_name][0].chern_finsize[:, -2]*0.5
    ksys_fracM = np.array([ksys_frac for i in range(len(kcoll.cherns[hlat_name]))])

    # Build omegacV
    omegacV = np.zeros(len(kcoll.cherns[hlat_name]))
    nuM = np.zeros((len(kcoll.cherns[hlat_name]), len(ksys_frac)))

    for ind in range(len(kcoll.cherns[hlat_name])):
        print 'ind = ', ind
        cp_ii = kcoll.cherns[hlat_name][ind].cp
        omegacV[ind] = cp_ii['omegac']
        nuM[ind, :] = kcoll.cherns[hlat_name][ind].chern_finsize[:, -1]

    omegacM = omegacV.reshape(len(nuM), 1) * np.ones_like(nuM)
    print 'omegacM = ', omegacM

    print 'kpfns: adding ipr and chern spectrum to axes...'
    print 'Adding chern spectrum to axis: ax = ', ax
    leplt.plot_pcolormesh(ksys_fracM, omegacM, nuM, ngrid, ax=ax, cax=cbar_nu_ax, method='nearest',
                          cmap=cmaps.diverging_cmap(250, 10, l=30),
                          vmin=-1.0, vmax=1.0, title=None, xlabel=None, ylabel=None,  cax_label=chern_cax_label,
                          cbar_labelpad=cbar_labelpad, cbar_orientation='horizontal', ticks=[-1, 0, 1],
                          fontsize=fontsize, alpha=alpha)

    if dos_ax is not None and dos_ax != 'none':
        print 'Adding ipr to DOS axis: dos_ax = ', dos_ax
        hlat.add_ipr_to_ax(dos_ax, ipr=None, alpha=alpha, inverse_PR=False,
                           norm=None, nbins=75, fontsize=fontsize, cbar_ax=cbar_ipr_ax,
                           vmin=ipr_vmin, vmax=ipr_vmax, linewidth=0, cax_label=ipr_cax_label,
                           make_cbar=True, climbars=True,
                           cbar_labelpad=cbar_labelpad, orientation='horizontal', cbar_orientation='horizontal',
                           invert_xaxis=invert_xaxis, ylabel=None, xlabel=None,
                           cbar_nticks=2, cbar_tickfmt='%0.1f')
        ax.set_ylim(dos_ax.get_ylim())

    return ax, dos_ax, cbar_ipr_ax, cbar_nu_ax