Exemple #1
0
def proc_scans(*args):

    hagis = smps.SMPS(dma.NoaaWide())

    scan_folder = args[0]  #"C:/Users/mrichardson/Documents/HAGIS/SMPS/Scans"
    main_dir = args[
        1]  #'C:/Users/mrichardson/Documents/HAGIS/SMPS/ProcessedData'
    range_low = args[2]
    range_high = args[3]
    darg = args[4]

    # If the directory does not exist, make it...
    if not os.path.exists(main_dir):
        os.mkdir(main_dir)

    # Change to the directory containing the scan data
    os.chdir(scan_folder)

    # All we care about is the time from the date...
    xfmt = dates.DateFormatter('%H:%M:%S')

    # Begin looping through the dates in the scan directory...
    for i in range(range_low, range_high):
        if i < 10:
            day = "0" + str(i)
        else:
            day = str(i)

        # This will define the year and month through which we scan.
        pattern = darg + day

        get_files(pattern, hagis)

        # This lag is consistent with the the 5 minute scans.
        hagis.lag = 12
        hagis.proc_files()

        # Remove empty values in the lists
        try:
            n_index = hagis.date.index(None)
        except ValueError:
            print("No NONEs found.")
        else:
            print("Index is: " + str(n_index))
            hagis.date = hagis.date[0:n_index]
            hagis.dn_interp = hagis.dn_interp[0:n_index, :]

        xi = date2num(hagis.date)
        XI, YI = meshgrid(xi, hagis.diam_interp)
        Z = hagis.dn_interp.transpose()
        Z[np.where(Z <= 0)] = np.nan
        dataframe = pd.DataFrame(hagis.dn_interp)
        dataframe.index = hagis.date

        # Alot space to store data
        file_name = "hagis_" + pattern
        file = open(main_dir + '/' + file_name + '.csv', 'w')

        dataframe.to_csv(file,
                         mode='a',
                         encoding='utf-8',
                         na_rep="NaN",
                         header=False,
                         line_terminator='\r',
                         index=False)

        dx = np.empty([len(hagis.date)], dtype="str")
        file = open(main_dir + '/' + file_name + '_index.csv', "w+")
        fwriter = csv.writer(file, delimiter='\r')
        dx = [""] * len(hagis.date)
        for e, d in enumerate(hagis.date):
            dx[e] = d.strftime("%m/%d/%y %M:%H:%S")

        fwriter.writerow(dx)
        file.close()

        file = open(main_dir + '/' + 'd.csv', "w+")
        fwriter = csv.writer(file, delimiter='\r')
        fwriter.writerow(hagis.diam_interp)
        file.close()

        np.savetxt(main_dir + '/' + file_name + '_index.csv', dx, fmt="%s")

        pmax = 10**np.ceil(np.log10(np.amax(Z[np.where(Z > 0)])))
        pmin = 1  # 10**np.floor(np.log10(np.amin(Z[np.where(Z > 0)])))

        rc('text', usetex=True)
        rc('font', family='serif')

        fig, ax = plt.subplots()
        pc = ax.pcolor(XI,
                       YI,
                       Z,
                       cmap=plt.cm.jet,
                       norm=colors.LogNorm(pmin, pmax, clip=False),
                       alpha=0.8)

        plt.colorbar(pc)
        plt.yscale('log')
        plt.ylim(5, 1000)
        plt.ylabel(r"\textbf{$D_p$} (nm)")
        plt.xlabel("Time")
        ax.xaxis.set_major_formatter(xfmt)
        plt.title(r"$\frac{dN}{d\log{D_p}}$ for " + pattern)
        fig.autofmt_xdate()
        fig.tight_layout()
        img_name = main_dir + "/Images/" + pattern + ".png"
        #plt.show()
        plt.savefig(img_name)
        print("DAY COMPLETE!!")

    return None
def main(plot_u_dist=False,
         plot_array_matrix=False,
         plot_inverse_matrix=False,
         plot_weights=False,
         grid_weights=True,
         binned_weights=True):
    plot_blaah = True
    show_plot = True
    save_plot = False

    path = "./Data/MWA_Compact_Coordinates.txt"
    plot_folder = "../Plots/Analytic_Covariance/"

    telescope = RadioTelescope(load=True, path=path)

    if plot_u_dist:
        make_plot_uv_distribution(telescope,
                                  show_plot=show_plot,
                                  save_plot=save_plot,
                                  plot_folder=plot_folder)

    sky_matrix = sky_matrix_constructor(telescope)
    inverse_redundant_matrix = redundant_matrix_constructor_alt(telescope)

    # print(redundant_matrix.shape)
    print(sky_matrix.shape)
    print(f"Sky Calibration uses {len(sky_matrix[:, 3])/2} baselines")
    # print(f"Redundant Calibration uses {len(redundant_matrix[:, 3])/2} baselines")

    if plot_array_matrix:
        make_plot_array_matrix(sky_matrix,
                               show_plot=show_plot,
                               save_plot=save_plot,
                               plot_folder=plot_folder)
        make_plot_array_matrix(redundant_matrix,
                               show_plot=show_plot,
                               save_plot=save_plot,
                               plot_folder=plot_folder)

    print(numpy.linalg.cond(sky_matrix))
    # print(numpy.linalg.cond(redundant_matrix))

    inverse_sky_matrix = numpy.linalg.pinv(sky_matrix)
    print("MAXIMUM", numpy.abs(inverse_redundant_matrix).max())
    # inverse_redundant_matrix = numpy.linalg.pinv(redundant_matrix)

    if plot_inverse_matrix:
        make_plot_array_matrix(inverse_sky_matrix.T,
                               show_plot=show_plot,
                               save_plot=save_plot,
                               plot_folder=plot_folder)
        make_plot_array_matrix(inverse_redundant_matrix.T,
                               show_plot=show_plot,
                               save_plot=save_plot,
                               plot_folder=plot_folder)

    sky_weights = numpy.sqrt((numpy.abs(inverse_sky_matrix[::2, ::2])**2 +
                              numpy.abs(inverse_sky_matrix[1::2, 1::2])**2))

    redundant_weights = numpy.sqrt(
        (numpy.abs(inverse_redundant_matrix[::2, ::2])**2 +
         numpy.abs(inverse_redundant_matrix[1::2, 1::2])**2))

    print(
        f"Every Sky calibrated Tile sees {len(sky_weights[0,:][sky_weights[0, :] > 1e-4])}"
    )
    print(
        f"Every redundant Tile sees {len(redundant_weights[0,:][redundant_weights[0, :] > 1e-4])}"
    )

    u_bins_sky = numpy.linspace(0, 375, 50)
    u_bins_red = numpy.linspace(0, 100, 50)
    redundant_bins, redundant_uu_weights, red_counts = compute_binned_weights(
        redundant_baseline_finder(telescope.baseline_table),
        redundant_weights,
        binned=True,
        u_bins=u_bins_red)
    sky_bins, sky_uu_weights, sky_counts = compute_binned_weights(
        telescope.baseline_table, sky_weights, binned=True, u_bins=u_bins_sky)
    if plot_blaah:
        figure, axes = pyplot.subplots(2, 3, figsize=(6, 4))

        sky_bins, sky_approx = baseline_hist(sky_bins,
                                             telescope.baseline_table)
        redundant_bins, redundant_approx = baseline_hist(
            redundant_bins,
            redundant_baseline_finder(telescope.baseline_table))

        norm = colors.LogNorm()
        redplot = axes[1, 0].pcolor(redundant_bins,
                                    redundant_bins,
                                    redundant_uu_weights,
                                    norm=norm)
        # redplot = axes[1, 0].semilogy(redundant_bins[:len(redundant_bins)-1],redundant_uu_weights, 'k', alpha = 0.3)

        norm = colors.LogNorm()

        skyplot = axes[0, 0].pcolor(sky_bins,
                                    sky_bins,
                                    sky_uu_weights,
                                    norm=norm)
        # skyplot = axes[0, 0].semilogy(sky_bins[:len(sky_bins)-1],sky_uu_weights, 'k', alpha = 0.3)

        norm = colors.LogNorm()
        countsredplot = axes[1, 1].pcolor(redundant_bins,
                                          redundant_bins,
                                          red_counts,
                                          norm=norm)
        # countsredplot = axes[1, 1].semilogy(redundant_bins[:len(redundant_bins)-1],red_counts, 'k', alpha = 0.3)

        norm = colors.LogNorm()

        countskyplot = axes[0, 1].pcolor(sky_bins,
                                         sky_bins,
                                         sky_counts,
                                         norm=norm)
        # countskyplot = axes[0, 1].semilogy(sky_bins[:len(sky_bins)-1], sky_counts, 'k', alpha = 0.3)

        norm = colors.LogNorm()
        # normredplot = axes[1, 2].pcolor(redundant_bins, redundant_bins, redundant_uu_weights/red_counts,
        #                                  norm = norm)
        normredplot = axes[1, 2].semilogy(
            redundant_bins[:len(redundant_bins) - 1],
            (redundant_uu_weights / red_counts).T,
            'k',
            alpha=0.3)
        # normredplot = axes[1, 2].semilogy(redundant_bins[:len(redundant_bins)-1], redundant_approx, 'C0')
        normredplot = axes[1, 2].semilogy(
            redundant_bins[:len(redundant_bins) - 1],
            redundant_approx * (245 / 2018), 'C1')

        # normskyplot = axes[0, 2].pcolor(sky_bins, sky_bins, sky_uu_weights/sky_counts, norm = norm)
        normskyplot = axes[0, 2].semilogy(sky_bins[:len(sky_bins) - 1],
                                          (sky_uu_weights / sky_counts).T,
                                          'k',
                                          alpha=0.3)
        # normskyplot = axes[0, 2].semilogy(sky_bins[:len(sky_bins)-1], sky_approx, 'C0')
        normskyplot = axes[0, 2].semilogy(sky_bins[:len(sky_bins) - 1],
                                          sky_approx * (127 / 8128), 'C1')

        axes[1, 0].set_xlabel(r"$u\,[\lambda]$")
        axes[1, 1].set_xlabel(r"$u\,[\lambda]$")
        axes[1, 2].set_xlabel(r"$u\,[\lambda]$")

        axes[0, 0].set_ylabel(r"$u^{\prime}\,[\lambda]$")
        axes[1, 0].set_ylabel(r"$u^{\prime}\,[\lambda]$")

        axes[0, 2].set_ylabel(r"weight")
        axes[1, 2].set_ylabel(r"weight")

        axes[0, 0].set_title("Sky Weights")
        axes[1, 0].set_title("Redundant Weights")

        axes[0, 1].set_title("Sky Normalisation")
        axes[1, 1].set_title("Redundant Normalisation")

        axes[0, 2].set_title("Sky Normalised Weights")
        axes[1, 2].set_title("Redundant Normalised Weights")

        # colorbar(redplot)
        # colorbar(skyplot)
        # colorbar(countsredplot)
        # colorbar(countskyplot)
        # colorbar(normredplot)
        # colorbar(normskyplot)

        pyplot.tight_layout()
        if show_plot:
            pyplot.show()

    return
Exemple #3
0
# numu_nc_mask = numu_inttypes < 2

do_event_dist = False
if do_event_dist:
    fig = plt.figure(figsize=(18, 7))
    # bins = [np.linspace(0,500,100), np.linspace(4,8,40)]
    bins = 100
    numu_nc_mask = numu_inttypes < 2

    # top down
    ax = fig.add_subplot(121)
    counts, xedges, yedges, im = ax.hist2d(numu_xx,
                                           numu_yy,
                                           bins=bins,
                                           cmap=cmap,
                                           norm=colors.LogNorm(),
                                           cmin=1)
    cbar = plt.colorbar(im, ax=ax)
    cbar.set_label('Events', fontsize=sizer)
    ax.set_ylabel(r'Y', fontsize=sizer)
    ax.set_xlabel(r'X', fontsize=sizer)
    ax.tick_params(labelsize=sizer)
    ax.set_title('Top-Down View')

    # side view
    ax2 = fig.add_subplot(122)
    counts, xedges, yedges, im = ax2.hist2d(numu_xx,
                                            numu_zz,
                                            bins=bins,
                                            cmap=cmap,
                                            norm=colors.LogNorm(),
def filter_edge(file,
                plot=False,
                isfile=True,
                edgecontrast=4,
                edge_threshold=0,
                cut=False):
    if isfile:
        img = fits.open(file)[0].data
    else:
        img = file
    centre = peak_local_max(img, threshold_rel=peak_threshold)
    if cut:
        if len(centre) > 1:
            #is there one peak or are there two?
            kmeans = KMeans(n_clusters=1)
            kmeans.fit(centre)
            ccentres = kmeans.cluster_centers_
            wss1 = np.mean(np.linalg.norm(centre - ccentres, axis=1))

            kmeans = KMeans(n_clusters=2)
            kmeans.fit(centre)
            cid = kmeans.predict(centre)
            ccentres = kmeans.cluster_centers_
            wss2 = np.mean(
                np.linalg.norm(centre[cid == 0] - ccentres[0], axis=1))
            +np.mean(np.linalg.norm(centre[cid == 1] - ccentres[1], axis=1))

            if wss2 < wss1:  #i.e. 2 clusters better fit
                print("2 bright peaks")
                bigger_cluster = np.argmax(np.bincount(cid))
                centre = centre[
                    cid ==
                    bigger_cluster]  #subselect points around main cluster
            centre = np.mean(centre, axis=0)
            centre = (int(centre[0]), int(centre[1]))

        if type(centre[0]) != int:
            centre = centre[0]
        if (centre[0] - halfwidth) < 0:
            left = 0
            right = 2 * halfwidth
        elif (centre[0] + halfwidth) > img.shape[0]:
            right = img.shape[0]
            left = right - 2 * halfwidth
        else:
            left, right = centre[0] - halfwidth, centre[0] + halfwidth
        if (centre[1] - halfwidth) < 0:
            bottom = 0
            top = 2 * halfwidth
        elif (centre[1] + halfwidth) > img.shape[0]:
            top = img.shape[0]
            bottom = right - 2 * halfwidth
        else:
            bottom, top = centre[1] - halfwidth, centre[1] + halfwidth

        imcut = img[left:right, bottom:top]
    else:
        dim = img.shape[0]
        imcut = img[int(dim / 4):int(3 * dim / 4),
                    int(dim / 4):int(3 * dim / 4)]

    edge1 = canny(np.log10(imcut),
                  sigma=edgecontrast,
                  high_threshold=edge_threshold)

    if plot:
        plt.imshow(imcut,
                   cmap=cm.viridis,
                   norm=colors.LogNorm(imcut.max() / 1e4, imcut.max()))
        plt.imshow(np.ma.masked_less(edge1 * imcut,
                                     imcut.max() * peak_threshold),
                   cmap=cm.gray_r,
                   norm=colors.LogNorm(imcut.max() / 1e4, imcut.max()))

        time = float(file.split('proj_')[1].split('.')[0]) / 10.
        plt.title('%0.2f Gyr' % time)
        plt.savefig('featuremaps/sq_weighted_%0.2f.png' % time)
    print("Edges found!")
    return edge1, imcut
Exemple #5
0
 def norm(self, vmin=None,vmax=None):
     if self.GetPlotParam('cnorm_type') == 'Log':
         return  mcolors.LogNorm(vmin, vmax)
     else:
         return mcolors.Normalize(vmin, vmax)
lw_exp_0 = 2.5
lw_exp_er = 2.
op = 1.
c_exp = 'dodgerblue'
#c_exp = 'b'
ax.plot(obs0[0], obs0[1], lw=lw_exp_0, ls='-', c=c_exp, alpha=op)
ax.plot(obsup[0], obsup[1], lw=lw_exp_er, ls='--', c=c_exp, alpha=op)
ax.plot(obsdw[0], obsdw[1], lw=lw_exp_er, ls='--', c=c_exp, alpha=op)



# scatter plot
vmin = 1**-3
vmax = 1
sc = ax.scatter(xar, yar, s=30, c=zar, norm=cls.LogNorm(), vmin = vmin, vmax = vmax, lw=1, marker='o', alpha=0.7, rasterized=False)    
# color bar
cb = plt.colorbar(sc)        

# chi2 = 0.05 contour
lw_0 = 3.5
lw_er = 2.5

levels = [0.05]
ax.tricontour(xar,yar,zar,  levels, linewidths=lw_0, colors='r', linestyles='-')
ax.tricontour(xar,yar,zp,  levels, linewidths=lw_er, colors='r', linestyles='--')
ax.tricontour(xar,yar,zn,  levels, linewidths=lw_er, colors='r', linestyles='--')

# texting chi2 values 
## for i in xrange(len(xar)):
##     ax.text(xar[i], yar[i], '{zval}'.format(zval=zar[i]), fontsize=3, rotation=20)
Exemple #7
0
def main(args):

    t = time.perf_counter()

    # Constants:
    resolution = 3500.  # lambda/dlambda
    fiber_diameter = 0.8  # Arcsec
    rn = 2.  # Detector readnoise (e-)
    dark = 0.0  # Detector dark-current (e-/s)

    # Temporary numbers that assume a given spectrograph PSF and LSF.
    # Assume 3 pixels per spectral and spatial FWHM.
    spatial_fwhm = 3.0
    spectral_fwhm = 3.0

    mags = numpy.arange(args.mag[0], args.mag[1] + args.mag[2], args.mag[2])
    times = numpy.arange(args.time[0], args.time[1] + args.time[2],
                         args.time[2])

    # Get source spectrum in 1e-17 erg/s/cm^2/angstrom. Currently, the
    # source spectrum is assumed to be
    #   - normalized by the total integral of the source flux
    #   - independent of position within the source
    wave = get_wavelength_vector(args.wavelengths[0], args.wavelengths[1],
                                 args.wavelengths[2])
    spec = get_spectrum(wave, mags[0], resolution=resolution)

    # Get the source distribution.  If the source is uniform, onsky is None.
    onsky = None

    # Get the sky spectrum
    sky_spectrum = spectrum.MaunakeaSkySpectrum()

    # Overplot the source and sky spectrum
    #    ax = spec.plot()
    #    ax = sky_spectrum.plot(ax=ax, show=True)

    # Get the atmospheric throughput
    atmospheric_throughput = efficiency.AtmosphericThroughput(
        airmass=args.airmass)

    # Set the telescope. Defines the aperture area and throughput
    # (nominally 3 aluminum reflections for Keck)
    telescope = telescopes.KeckTelescope()

    # Define the observing aperture; fiber diameter is in arcseconds,
    # center is 0,0 to put the fiber on the target center. "resolution"
    # sets the resolution of the fiber rendering; it has nothing to do
    # with spatial or spectral resolution of the instrument
    fiber = aperture.FiberAperture(0, 0, fiber_diameter, resolution=100)

    # Get the spectrograph throughput (circa June 2018; TODO: needs to
    # be updated). Includes fibers + foreoptics + FRD + spectrograph +
    # detector QE (not sure about ADC). Because this is the total
    # throughput, define a generic efficiency object.
    thru_db = numpy.genfromtxt(
        os.path.join(os.environ['SYNOSPEC_DIR'], 'data/efficiency',
                     'fobos_throughput.db'))
    spectrograph_throughput = efficiency.Efficiency(thru_db[:, 1],
                                                    wave=thru_db[:, 0])

    # System efficiency combines the spectrograph and the telescope
    system_throughput = efficiency.SystemThroughput(
        wave=spec.wave,
        spectrograph=spectrograph_throughput,
        telescope=telescope.throughput)

    # Instantiate the detector; really just a container for the rn and
    # dark current for now. QE is included in fobos_throughput.db file,
    # so I set it to 1 here.
    det = detector.Detector(rn=rn, dark=dark, qe=1.0)

    # Extraction: makes simple assumptions about the detector PSF for
    # each fiber spectrum and mimics a "perfect" extraction, including
    # an assumption of no cross-talk between fibers. Ignore the
    # "spectral extraction".
    extraction = extract.Extraction(det,
                                    spatial_fwhm=spatial_fwhm,
                                    spatial_width=1.5 * spatial_fwhm,
                                    spectral_fwhm=spectral_fwhm,
                                    spectral_width=spectral_fwhm)

    snr_label = 'S/N per {0}'.format('R element' if args.snr_units ==
                                     'resolution' else args.snr_units)

    # SNR
    g = efficiency.FilterResponse()
    r = efficiency.FilterResponse(band='r')
    snr_g = numpy.empty((mags.size, times.size), dtype=float)
    snr_r = numpy.empty((mags.size, times.size), dtype=float)
    for i in range(mags.size):
        spec.rescale_magnitude(mags[i], band=g)
        for j in range(times.size):
            print('{0}/{1} ; {2}/{3}'.format(i + 1, mags.size, j + 1,
                                             times.size),
                  end='\r')
            # Perform the observation
            obs = Observation(telescope,
                              sky_spectrum,
                              fiber,
                              times[j],
                              det,
                              system_throughput=system_throughput,
                              atmospheric_throughput=atmospheric_throughput,
                              airmass=args.airmass,
                              onsky_source_distribution=onsky,
                              source_spectrum=spec,
                              extraction=extraction,
                              snr_units=args.snr_units)

            # Construct the S/N spectrum
            snr_spec = obs.snr(sky_sub=True)
            snr_g[i,
                  j] = numpy.sum(g(snr_spec.wave) * snr_spec.flux) / numpy.sum(
                      g(snr_spec.wave))
            snr_r[i,
                  j] = numpy.sum(r(snr_spec.wave) * snr_spec.flux) / numpy.sum(
                      r(snr_spec.wave))
    print('{0}/{1} ; {2}/{3}'.format(i + 1, mags.size, j + 1, times.size))

    extent = [
        args.time[0] - args.time[2] / 2, args.time[1] + args.time[2] / 2,
        args.mag[0] - args.mag[2] / 2, args.mag[1] + args.mag[2] / 2
    ]

    w, h = pyplot.figaspect(1)
    fig = pyplot.figure(figsize=(1.5 * w, 1.5 * h))
    ax = fig.add_axes([0.15, 0.2, 0.7, 0.7])
    img = ax.imshow(snr_g,
                    origin='lower',
                    interpolation='nearest',
                    extent=extent,
                    aspect='auto',
                    norm=colors.LogNorm(vmin=snr_g.min(), vmax=snr_g.max()))
    cax = fig.add_axes([0.86, 0.2, 0.02, 0.7])
    pyplot.colorbar(img, cax=cax)
    cax.text(4,
             0.5,
             snr_label,
             ha='center',
             va='center',
             transform=cax.transAxes,
             rotation='vertical')
    ax.text(0.5,
            -0.08,
            'Exposure Time [s]',
            ha='center',
            va='center',
            transform=ax.transAxes)
    ax.text(-0.12,
            0.5,
            r'Surface Brightness [AB mag/arcsec$^2$]',
            ha='center',
            va='center',
            transform=ax.transAxes,
            rotation='vertical')
    ax.text(0.5,
            1.03,
            r'$g$-band S/N',
            ha='center',
            va='center',
            transform=ax.transAxes,
            fontsize=12)
    pyplot.show()
def plotter2(arrays,
             fname,
             norm=None,
             labels=['Q', 'U', 'E', 'B'],
             axis_labels=None,
             npx=2,
             share=True,
             zmin=None,
             **args):
    print('WA', labels)
    np = len(arrays)
    npy = np // npx
    if np % npx: npy += 1
    fig, axes = plt.subplots(npx,
                             npy,
                             sharex=share,
                             sharey=share,
                             figsize=(12, 12))
    print("NPX %d NPY %d" % (npx, npy))
    max_val = max([arr.max() for arr in arrays])
    min_all = min([arr.min() for arr in arrays])
    if zmin is not None:
        min_all = zmin
    if norm is 'positive':
        min_val = min([arr[arr > 0].min() for arr in arrays])
        args['norm'] = colors.LogNorm(vmin=min_val, vmax=max_val)
        print("WTF", min_val)
    elif norm is 'symlog':
        min_val = min_all
        args['norm'] = colors.SymLogNorm(linthresh=1e-10,
                                         vmin=min_val,
                                         vmax=max_val)
    elif norm is 'ind':
        args['norm'] = None
    else:
        min_val = min_all
        args['norm'] = colors.Normalize(vmin=min_val, vmax=max_val)

    args['interpolation'] = 'nearest'
    args['origin'] = 'lower'
    oot = []
    for n, arr in enumerate(arrays):
        ipy = n // npx
        ipx = n % npx
        if npx == 1:
            this_ax = axes
        elif npy == 1:
            this_ax = axes[ipx]
        else:
            this_ax = axes[ipx][ipy]
        oot.append(this_ax.imshow(arr, **args))
        if norm is 'ind': cb = fig.colorbar(oot[-1], ax=this_ax)
        this_ax.set_title(labels[n])


#   oot.append(axes[1][0].imshow(U,**args))
#   if norm is 'ind': cb=fig.colorbar(oot[-1],ax=axes[1][0])
#   axes[1][0].set_title(labels[1])
#   oot.append(axes[0][1].imshow(E,**args))
#   if norm is 'ind': cb=fig.colorbar(oot[-1],ax=axes[0][1])

#   axes[0][1].set_title(labels[2])
#   oot.append(axes[1][1].imshow(B,**args))
#   if norm is 'ind': cb=fig.colorbar(oot[-1],ax=axes[1][1])
#   axes[1][1].set_title(labels[3])
    if norm is not 'ind':
        cb = fig.colorbar(oot[-1], ax=axes)
        if norm is 'positive':
            cb.cmap.set_under('w')
    if axis_labels:
        for n in range(np):
            axes[n // 2][n % 2].set_xlabel(axis_labels[0])
            axes[n // 2][n % 2].set_ylabel(axis_labels[1])
    fig.savefig(fname)
    print(fname)
    plt.close(fig)
Exemple #9
0
nrow = len(in_x)
fig, axs = plt.subplots(nrows=nrow,
                        ncols=1,
                        squeeze=0,
                        sharex=True,
                        figsize=(17, 3 * nrow))
for i in range(0, nrow):
    x = in_x[i]
    y = in_y[i]
    bins = in_bounds[i]
    name = in_names[i]
    cs = axs[i][0].pcolormesh(x,
                              np.arange(0,
                                        len(bins) - 1, 1),
                              np.transpose(y),
                              norm=colors.LogNorm(vmin=1, vmax=10),
                              cmap='viridis')
    axs[i][0].xaxis_date()
    axs[i][0].set_title(
        '%s, %s to %s' % (name, dt.datetime.strftime(
            d1, '%Y-%m-%d'), dt.datetime.strftime(d2, '%Y-%m-%d')))
    axs[i][0].set_yticks(np.arange(0, len(bins) - 1, 1))
    axs[i][0].tick_params(axis='y', which='major', labelsize=10)
    for label in axs[i][0].yaxis.get_ticklabels()[::2]:
        label.set_visible(False)
    axs[i][0].set_yticklabels(bins)
    axs[i][0].set_ylabel('Particle Diameter ($\mu$m)')
    if i == nrow - 1:
        axs[i][0].set_xlabel('Hours UTC')
    axs[i][0].set_xlim(d1, d2)
    axs[i][0].xaxis.set_major_formatter(myFmt)
Exemple #10
0
    nbins_enu = IntInput("Number of points in neutrino energy",
                         "Invalid input", 10, 100000)
    edetmin = 0.001 * FloatInput("Min detected energy (MeV)", "Invalid input",
                                 0, 100000)
    edetmax = 0.001 * FloatInput("Max detected energy (MeV)", "Invalid input",
                                 edetmin, 100000)
    nbins_edet = IntInput("Number of bins in detected energy", "Invalid input",
                          10, 100000)

if z_mesh.shape != (nbins_enu, nbins_edet):
    print "Problem with dimensions!"

# Do we plot logarithmic color scale?
if logopt[0] == "T" or logopt[0] == "t" or logopt[0] == "1" or logopt[
        0] == "Y" or logopt[0] == "y":
    normpar = colors.LogNorm()
elif logopt[0] == "F" or logopt[0] == "f" or logopt[0] == "0" or logopt[
        0] == "N" or logopt[0] == "n":
    normpar = None
else:
    print "Are you sure you properly set a logarithm bool?"
    normpar = None

smearplot = plt.imshow(
    z_mesh,  # plot the smearing values as an image, because python
    cmap="CMRmap",  # nice colormap 
    interpolation="nearest",  # avoid smoothing
    origin="lower",  # (0,0) is in the bottom left corner
    extent=(enumin, enumax, edetmin, edetmax),  # set axis ranges
    norm=normpar)  # log scale
plt.title("Smearing matrix")
Exemple #11
0
#ax.set_xlabel(r'$m_{\tilde \chi_1^{\pm}} [\rm GeV]$', fontsize=23)
ax.set_ylabel(r'$m_{\tilde \chi_1^0} [\rm GeV]$', fontsize=23)
# axes ranges
ax.set_xlim([min(xar) * 0.5, max(xar) * 1.05])
ax.set_ylim([min(yar) * 0.5, max(yar) * 1.05])

# ticks font
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)

# scatter plot
sc = ax.scatter(xar,
                yar,
                s=30,
                c=zar,
                norm=cls.LogNorm(),
                lw=1,
                marker='o',
                alpha=0.7,
                rasterized=False)
# color bar
cb = plt.colorbar(sc)

# chi2 = 0.05 contour
levels = [0.05]
ax.tricontour(xar,
              yar,
              zar,
              levels,
              linewidths=2.5,
              colors='r',
fig1 = PLT.figure(figsize=(17.5, 14))
# fig1.clf()
ax11 = fig1.add_subplot(111,
                        xlim=(NP.amin(holimg.lf_P1[:, 0]),
                              NP.amax(holimg.lf_P1[:, 0])),
                        ylim=(NP.amin(holimg.mf_P1[:, 0]),
                              NP.amax(holimg.mf_P1[:, 0])))
# imgplot = ax11.imshow(NP.mean(NP.abs(holimg.holograph_P1)**2, axis=2), aspect='equal', extent=(NP.amin(holimg.lf_P1[:,0]), NP.amax(holimg.lf_P1[:,0]), NP.amin(holimg.mf_P1[:,0]), NP.amax(holimg.mf_P1[:,0])), origin='lower', norm=PLTC.LogNorm())
imgplot = ax11.imshow(NP.mean(avg_img, axis=2),
                      aspect='equal',
                      extent=(NP.amin(holimg.lf_P1[:, 0]),
                              NP.amax(holimg.lf_P1[:, 0]),
                              NP.amin(holimg.mf_P1[:, 0]),
                              NP.amax(holimg.mf_P1[:, 0])),
                      origin='lower',
                      norm=PLTC.LogNorm())
l, = ax11.plot(skypos[:, 0],
               skypos[:, 1],
               'o',
               mfc='none',
               mec='white',
               mew=1,
               ms=10)
PLT.grid(True, which='both', ls='-', color='g')
cbaxes = fig1.add_axes([0.1, 0.05, 0.8, 0.05])
cbar = fig1.colorbar(imgplot, cax=cbaxes, orientation='horizontal')
# PLT.colorbar(imgplot)
PLT.savefig(
    '/data3/t_nithyanandan/project_MOFF/simulated/MWA/figures/random_source_positions_{0:0d}_iterations.png'
    .format(itr),
    bbox_inches=0)
Exemple #13
0
    def densityPlot(self,
                    x,
                    y,
                    title,
                    xlabel,
                    ylabel,
                    binx,
                    biny,
                    pyMisc,
                    xmin=None,
                    xmax=None,
                    ymin=None,
                    ymax=None,
                    cuts=None,
                    figure=None,
                    ax=None,
                    layered=True):
        if cuts:
            xcut = self.applyCuts(x, cuts)
            ycut = self.applyCuts(y, cuts)
        else:
            xcut = x
            ycut = y
        if ax or figure:
            print("")
        else:
            fig, ax = plt.subplots(tight_layout=True, figsize=(11.69, 8.27))
        if (xmin or xmax or ymin or ymax):
            # norm=colors.LogNorm() makes colorbar normed and logarithmic
            hist = ax.hist2d(xcut,
                             ycut,
                             bins=(pyMisc.setbin(x, binx, xmin, xmax),
                                   pyMisc.setbin(y, biny, ymin, ymax)),
                             norm=colors.LogNorm())
        else:
            # norm=colors.LogNorm() makes colorbar normed and logarithmic
            hist = ax.hist2d(xcut,
                             ycut,
                             bins=(pyMisc.setbin(x,
                                                 binx), pyMisc.setbin(y,
                                                                      biny)),
                             norm=colors.LogNorm())
        if layered is True:
            plt.colorbar(hist[3],
                         ax=ax,
                         spacing='proportional',
                         label='Number of Events')

        plt.title(title)
        plt.xlabel(xlabel)
        plt.ylabel(ylabel)

        inputVal = [x, y]

        if (xmin or xmax or ymin or ymax):
            binVal = [
                pyMisc.setbin(x, binx, xmin, xmax),
                pyMisc.setbin(y, biny, ymin, ymax)
            ]
        else:
            binVal = [pyMisc.setbin(x, binx), pyMisc.setbin(y, biny)]
        return [binVal, fig]
Exemple #14
0
print("size =",size)
print("limit =",limit)

np.set_printoptions(threshold=np.inf)

x = np.linspace(-2, 1, size)
y = np.linspace(-1.5, 1.5, size)
xl=len(x)
yl=len(y)

a=np.zeros((xl,yl),dtype = np.int)
# Generate Datas
for i in range(xl):
    for j in range(yl):
        a[j][i]=f.mand(x[i]+y[j]*1j,limit)
    #print(i)
    f.progress(i+1,size)

np.savetxt("mand results/2/mand_"+str(size)+"_"+str(limit)+".txt", a, delimiter=',', fmt="%d")

#-------------------------------------

ax = plt.figure()
plt.xticks(())
plt.yticks(())
plt.xlim((-0.5, size-0.5))
plt.ylim((0, size))
plt.imshow(a, interpolation='nearest', norm=colors.LogNorm(), cmap="autumn", origin='lower')
#plt.colorbar()
plt.savefig("mand results/pics/mand_"+str(size)+"_"+str(limit)+".png")
plt.show()
Exemple #15
0
    def add_colorbar(self, mappable=None, ax=None, location='right',
                     width=0.2, pad=0.1, log=None, label="", clim=None,
                     cmap=None, clip=None, visible=True, axes_class=axes.Axes,
                     **kwargs):
        """Add a colorbar to the current `Axes`

        Parameters
        ----------
        mappable : matplotlib data collection
            collection against which to map the colouring
        ax : :class:`~matplotlib.axes.Axes`
            axes from which to steal space for the colour-bar
        location : `str`, optional, default: 'right'
            position of the colorbar
        width : `float`, optional default: 0.2
            width of the colorbar as a fraction of the axes
        pad : `float`, optional, default: 0.1
            gap between the axes and the colorbar as a fraction of the axes
        log : `bool`, optional, default: `False`
            display the colorbar with a logarithmic scale
        label : `str`, optional, default: '' (no label)
            label for the colorbar
        clim : pair of floats, optional
            (lower, upper) limits for the colorbar scale, values outside
            of these limits will be clipped to the edges
        visible : `bool`, optional, default: `True`
            make the colobar visible on the figure, this is useful to
            make two plots, each with and without a colorbar, but
            guarantee that the axes will be the same size
        **kwargs
            other keyword arguments to be passed to the
            :meth:`~matplotlib.figure.Figure.colorbar` generator

        Returns
        -------
        Colorbar
            the :class:`~matplotlib.colorbar.Colorbar` added to this plot
        """
        # find default layer
        if mappable is None and ax is not None and len(ax.collections):
            mappable = ax.collections[-1]
        elif mappable is None and ax is not None and len(ax.images):
            mappable = ax.images[-1]
        elif (visible is False and mappable is None and
              ax is not None and len(ax.lines)):
            mappable = ax.lines[-1]
        elif mappable is None and ax is None:
            for ax in self.axes[::-1]:
                if hasattr(ax, 'collections') and len(ax.collections):
                    mappable = ax.collections[-1]
                    break
                elif hasattr(ax, 'images') and len(ax.images):
                    mappable = ax.images[-1]
                    break
                elif visible is False and len(ax.lines):
                    mappable = ax.lines[-1]
                    break
        if visible and mappable is None:
            raise ValueError("Cannot determine mappable layer for this "
                             "colorbar")
        elif ax is None:
            raise ValueError("Cannot determine an anchor Axes for this "
                             "colorbar")

        # find default axes
        if not ax:
            ax = mappable.axes

        mappables = ax.collections + ax.images

        # get new colour axis
        divider = make_axes_locatable(ax)
        if location not in ['right', 'top']:
            raise ValueError("'left' and 'bottom' colorbars have not "
                             "been implemented")
        cax = divider.append_axes(location, width, pad=pad,
                                  add_to_figure=visible, axes_class=axes_class)
        self._coloraxes.append(cax)
        if visible:
            self.sca(ax)
        else:
            return

        # set limits
        if not clim:
            clim = mappable.get_clim()
        if log is None:
            log = isinstance(mappable.norm, mcolors.LogNorm)
        if log and clim[0] <= 0.0:
            cdata = mappable.get_array()
            try:
                clim = (cdata[cdata > 0.0].min(), clim[1])
            except ValueError:
                pass
        for m in mappables:
            m.set_clim(clim)

        # set map
        if cmap is not None:
            mappable.set_cmap(cmap)

        # set normalisation
        norm = mappable.norm
        if clip is None:
            clip = norm.clip
        for m in mappables:
            if log and not isinstance(norm, mcolors.LogNorm):
                m.set_norm(mcolors.LogNorm(*mappable.get_clim()))
            elif not log:
                m.set_norm(mcolors.Normalize(*mappable.get_clim()))
            m.norm.clip = clip

        # set log ticks
        if log:
            kwargs.setdefault('ticks', LogLocator(subs=numpy.arange(1, 11)))
            kwargs.setdefault('format', CombinedLogFormatterMathtext())

        # make colour bar
        colorbar = self.colorbar(mappable, cax=cax, ax=ax, **kwargs)

        # set label
        if label:
            colorbar.set_label(label)
        colorbar.draw_all()

        self.colorbars.append(colorbar)
        return colorbar
Exemple #16
0
    # Generate a global grid
    lon_bnd = np.linspace(
        param['lon_range'][0], param['lon_range'][1],
        int((param['lon_range'][1] - param['lon_range'][0]) /
            param['grid_res']) + 1)

    lat_bnd = np.linspace(
        param['lat_range'][0], param['lat_range'][1],
        int((param['lat_range'][1] - param['lat_range'][0]) /
            param['grid_res']) + 1)

    print('Gridding trajectories...')
    inv_grid = grid_traj(lon_bnd, lat_bnd, param, fh)
    print('Calculation complete')
    plt.figure()
    plt.pcolormesh(inv_grid, norm=colors.LogNorm(vmin=0.001, vmax=1))
    plt.colorbar()

##############################################################################
# Binning ####################################################################
##############################################################################

# def binModel(lon_bnd, lat_bnd, param, fh):
#     @njit
#     def update_min_time_model(lon_full, lat_full, time_full, grid, data):
#         lat_bnd = grid[0]
#         lon_bnd = grid[1]

#         ntraj = lon_full.shape[0]
#         for i in range(ntraj):
#             # Load positions and times for this trajectory
Exemple #17
0
# B.C.s are observations, so a PISM output file contains everything we need
u_bc = floating(get('u_bc'))
v_bc = floating(get('v_bc'))

plt.clf()

f, (a0, a1) = plt.subplots(1,
                           2,
                           gridspec_kw={'width_ratios': [1.2, 1]},
                           figsize=(16, 8))

# mark the grounding line
a0.contour(x, y, mask, [2.5], colors="black", lw=2)

# plot velsurf_mag using log color scale
p = a0.pcolormesh(x, y, velsurf_mag, norm=colors.LogNorm(vmin=1, vmax=1.5e3))
# add a colorbar:
f.colorbar(p, ax=a0, extend='both', ticks=[1, 10, 100, 500, 1000], format="%d")

# quiver plot of velocities
s = 10  # stride in grid points
a0.quiver(x[::s], y[::s], u_bc[::s, ::s], v_bc[::s, ::s], color='white')
a0.quiver(x[::s], y[::s], u[::s, ::s], v[::s, ::s], color='black')
a0.set_xticks([])
a0.set_yticks([])
a0.set_title("Ross ice velocity (m/year)\nwhite=observed, black=model")

# do the scatter plot
magnitude = np.sqrt(np.abs(u[::s, ::s])**2 + np.abs(v[::s, ::s])**2)
bc_magnitude = np.sqrt(np.abs(u_bc[::s, ::s])**2 + np.abs(v_bc[::s, ::s])**2)
max_velocity = np.maximum(magnitude.max(), bc_magnitude.max())
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as colors
from matplotlib.mlab import bivariate_normal
'''
Lognorm: Instead of pcolor log10(Z1) you can have colorbars that have
the exponential labels using a norm.
'''
N = 100
X, Y = np.mgrid[-3:3:complex(0, N), -2:2:complex(0, N)]

# A low hump with a spike coming out of the top right.  Needs to have
# z/colour axis on a log scale so we see both hump and spike.  linear
# scale only shows the spike.
Z1 = bivariate_normal(X, Y, 0.1, 0.2, 1.0, 1.0) +  \
    0.1 * bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)

fig, ax = plt.subplots(2, 1)

pcm = ax[0].pcolor(X,
                   Y,
                   Z1,
                   norm=colors.LogNorm(vmin=Z1.min(), vmax=Z1.max()),
                   cmap='PuBu_r')
fig.colorbar(pcm, ax=ax[0], extend='max')

pcm = ax[1].pcolor(X, Y, Z1, cmap='PuBu_r')
fig.colorbar(pcm, ax=ax[1], extend='max')
fig.show()
Exemple #19
0
from astropy.io import fits

hdu = fits.open( sys.argv[1] )[0]
dd = hdu.data

fig, axs = plt.subplots( 1, 3,  figsize=(3*5,5) )

d = dd
vmin = d.min()
vmax = d.max()
norm = mplc.SymLogNorm( 1e-9, vmin=vmin, vmax=vmax  )
ax = axs[0]
img = ax.imshow( d, norm=norm, cmap=cm.jet  )
ax.set_title( "all value" )
plt.colorbar( img, ax=ax, shrink=0.8 )

d = dd.copy()
ax = axs[1]
ax.set_title( "postive value" )
img = ax.imshow( d, norm=mplc.LogNorm(), cmap=cm.jet  )
plt.colorbar( img, ax=ax, shrink=0.8 )

d = -dd.copy()
ax = axs[2]
ax.set_title( "negtive value" )
img = ax.imshow( d, norm=mplc.LogNorm(), cmap=cm.jet  )
plt.colorbar( img, ax=ax, shrink=0.8 )

fig.savefig( sys.argv[1][:-5] + '_value.png', dpi=300 )

                for case in np.arange(0,ncases):
                    zi_agl[case,ii,jj] = zloc[T[case,ii,jj,:]>=zi_cut][0]
                zloc -= zloc[0]
                for case in np.arange(0,ncases):
                    zi[case,ii,jj] = zloc[T[case,ii,jj,:]>=zi_cut][0]
                    norm_z[case,ii,jj,:] = zloc/zi[case,ii,jj]

        if saveFigs:
            print('Saving Figures')
            yloc = int(ny/2)
            fig  = plt.figure(figsize=(16,4))

            for case in np.arange(0,ncases):
                pltnum = 231 + case
                plt1 = plt.subplot(pltnum)#,aspect='equal')
                cont = plt1.pcolormesh(x[:,yloc,:],z[:,yloc,:],tke[int(case),:,yloc,:],norm=colors.LogNorm(vmin=1e-1,vmax=1e1))#,cmap=plt.cm.RdBu)
                pltnum = 234 + case
                plt2 = plt.subplot(pltnum,sharex=plt1)#,aspect='equal')
                plt2.pcolormesh(x[:,yloc,:],z[:,yloc,:],T[case,:,yloc,:])#,norm=Normalize(0,3))#,cmap=plt.cm.RdBu)
                plt2.scatter(x[:,yloc,0],zi_agl[case,:,yloc],s=4,c='k',alpha=0.4)

            cax1 = fig.add_axes([0.92, 0.15, 0.01, 0.7])
            plt.colorbar(cont,cax1)
            figname1 = '{}_{}_PBLHeight'.format(simstr[ss],terr_str)
            print('{}{}.png'.format(savedir,figname1))
            plt.savefig('{}{}.png'.format(savedir,figname1))
            plt.clf()

#            plt.figure(figsize=(9,6))
#            plt.pcolormesh(x[:,yloc,:],norm_z[:,yloc,:],T[:,yloc,:])#,norm=Normalize(0,1.1))
#            plt.colorbar()
Exemple #21
0
    'rg2': np.squeeze(rg2)
}

np.save('derivatives.npy', Data)

num = np.sum(id_suit)
print(num)

X = (np.arange(7) + 1)[np.newaxis, :] * np.ones([gd0.shape[0], 1])
import matplotlib.colors as mcolors

plt.figure()
plt.hist2d(X.ravel(), (gd0 * rs).ravel(),
           bins=[0.5 + np.arange(8), 200],
           cmap='Reds',
           norm=mcolors.LogNorm(vmin=10, vmax=None, clip=True))
plt.plot(np.arange(8) + 0.5, np.zeros(8), '-k', linewidth=3)
plt.xlabel('index')
plt.ylabel('derivative')
plt.colorbar()
plt.show()

plt.figure()
plt.hist2d(X.ravel(), (gd1 * rs).ravel(),
           bins=[0.5 + np.arange(8), 200],
           cmap='Blues',
           norm=mcolors.LogNorm(vmin=10, vmax=None, clip=True))
plt.xlabel('index')
plt.ylabel('derivative')
plt.colorbar()
plt.show()
Exemple #22
0
def plot_detected_planet_contrasts(planet_table,
                                   wv_index,
                                   detected,
                                   flux_ratios,
                                   instrument,
                                   telescope,
                                   show=True,
                                   save=False,
                                   ymin=1e-9,
                                   ymax=1e-4,
                                   xmin=0.,
                                   xmax=1.,
                                   alt_data=None,
                                   alt_label=""):
    '''
    Make a plot of the planets detected at a given wavelenth_index

    Inputs: 
        planet_table    - a Universe.planets table
        wv_index        - the index from the instrument.current_wvs 
                            wavelength array to consider
        detected        - a boolean array of shape [n_planets,n_wvs] 
                        that indicates whether or not a planet was detected 
                        at a given wavelength
        flux_ratios     - an array of flux ratios between the planet and the star
                        at the given wavelength. sape [n_planets,n_wvs]
        instuemnt       - an instance of the psisim.instrument class
        telescope       - an instance of the psisim.telescope class

    Keyword Arguments: 
        show            - do you want to show the plot? Boolean
        save            - do you want to save the plot? Boolean
        ymin,ymax,xmin,xmax - the limits on the plot
        alt_data        - An optional argument to pass to show a secondary set of data.
                        This could be e.g. detection limits, or another set of atmospheric models
        alt_label       - This sets the legend label for the alt_data
    '''

    fig, ax = plt.subplots(1, 1, figsize=(7, 5))

    seps = np.array([
        planet_table_entry['AngSep'] / 1000
        for planet_table_entry in planet_table
    ])

    # import pdb; pdb.set_trace()
    #Plot the non-detections
    ax.scatter(seps[~detected[:, wv_index]],
               flux_ratios[:, wv_index][~detected[:, wv_index]],
               marker='.',
               label="Full Sample",
               s=20)

    # print(seps[~detected[:,wv_index]],flux_ratios[:,wv_index][~detected[:,wv_index]])
    masses = np.array([
        float(planet_table_entry['PlanetMass'])
        for planet_table_entry in planet_table
    ])
    # import pdb; pdb.set_trace()

    # import pdb; pdb.set_trace()
    #Plot the detections
    scat = ax.scatter(seps[detected[:, wv_index]],
                      flux_ratios[:, wv_index][detected[:, wv_index]],
                      marker='o',
                      label="Detected",
                      c=masses[detected[:, wv_index]],
                      cmap='gist_heat',
                      edgecolors='k',
                      norm=colors.LogNorm(vmin=1, vmax=1000))
    fig.colorbar(scat, label=r"Planet Mass [$M_{\oplus}$]", ax=ax)

    #Plot 1 and 2 lambda/d
    ax.plot([
        instrument.current_wvs[wv_index] * 1e-6 / telescope.diameter * 206265,
        instrument.current_wvs[wv_index] * 1e-6 / telescope.diameter * 206265
    ], [0, 1.],
            label=r"$\lambda/D$ at $\lambda=${:.3f}$\mu m$".format(
                instrument.current_wvs[wv_index]),
            color='k')
    ax.plot([
        2 * instrument.current_wvs[wv_index] * 1e-6 / telescope.diameter *
        206265, 2 * instrument.current_wvs[wv_index] * 1e-6 /
        telescope.diameter * 206265
    ], [0, 1.],
            '-.',
            label=r"$2\lambda/D$ at $\lambda=${:.3f}$\mu m$".format(
                instrument.current_wvs[wv_index]),
            color='k')

    #If detection_limits is passed, then plot the 5-sigma detection limits for each source
    if alt_data is not None:
        ax.scatter(seps,
                   alt_data[:, wv_index],
                   marker='.',
                   label=alt_label,
                   color='darkviolet',
                   s=20)
        for i, sep in enumerate(seps):
            ax.plot([sep, sep],
                    [flux_ratios[i, wv_index], alt_data[i, wv_index]],
                    color='k',
                    alpha=0.1,
                    linewidth=1)

    #Axis title
    ax.set_title("Planet Detection Yield at {:.3}um".format(
        instrument.current_wvs[wv_index]),
                 fontsize=18)

    #Legend
    legend = ax.legend(loc='upper right', fontsize=13)
    legend.legendHandles[-1].set_color('orangered')
    legend.legendHandles[-1].set_edgecolor('k')

    #Plot setup
    ax.set_ylabel("Total Intensity Flux Ratio", fontsize=16)
    ax.set_xlabel("Separation ['']", fontsize=16)
    # ax.set_xlim(xmin,xmax)
    ax.set_ylim(ymin, ymax)
    ax.set_yscale('log')
    ax.set_xscale('log')

    #Do we show it?
    if show:
        plt.show()

    plt.tight_layout()

    #Do we save it?
    if save:
        plt.savefig("Detected_Planets_flux_v_sma.png", bbox_inches="tight")

    #Return the figure so that the user can manipulate it more if they so please
    return fig, ax
Exemple #23
0
def __make_plots__(cube_list,
                   save_filepath,
                   figsize=(16, 9),
                   terrain=cimgt.StamenTerrain(),
                   logscaled=True,
                   vmin=None,
                   vmax=None,
                   colourmap='viridis',
                   colourbarticks=None,
                   colourbarticklabels=None,
                   colourbar_label=None,
                   markerpoint=None,
                   markercolor='#B9DC0C',
                   timestamp=None,
                   time_box_position=None,
                   plottitle=None,
                   box_colour='#FFFFFF',
                   textcolour='#000000',
                   coastlines=False,
                   scheduler_address=None):

    cubenumber, cube = cube_list

    if type(figsize) == tuple:
        fig, ax = plt.subplots(figsize=figsize)

    Terrain = terrain
    fig = plt.axes(projection=Terrain.crs)
    fig.add_image(terrain, 4)

    if logscaled == True and vmin == None and vmax == None and colourmap == 'viridis':
        data = iplt.pcolormesh(cube,
                               alpha=1,
                               norm=colors.LogNorm(),
                               cmap='viridis')

    if logscaled == True and type(vmin) == float and type(
            vmax) == float and colourmap == 'viridis':
        data = iplt.pcolormesh(cube,
                               alpha=1,
                               norm=colors.LogNorm(vmin=vmin, vmax=vmax),
                               cmap='viridis')

    if logscaled == True and vmin == None and vmax == None and type(
            colourmap) == str:
        data = iplt.pcolormesh(cube,
                               alpha=1,
                               norm=colors.LogNorm(),
                               cmap=colourmap)

    if logscaled == True and type(vmin) == float and type(
            vmax) == float and type(colourmap) == str:
        data = iplt.pcolormesh(cube,
                               alpha=1,
                               norm=colors.LogNorm(vmin=vmin, vmax=vmax),
                               cmap=colourmap)

    if logscaled == False and vmin == None and vmax == None and colourmap == 'viridis':
        data = iplt.pcolormesh(cube,
                               alpha=1,
                               norm=colors.LogNorm(),
                               cmap='viridis')

    if logscaled == False and type(vmin) == float and type(
            vmax) == float and colourmap == 'viridis':
        data = iplt.pcolormesh(cube,
                               alpha=1,
                               vmin=vmin,
                               vmax=vmax,
                               cmap='viridis')

    if logscaled == False and vmin == None and vmax == None and type(
            colourmap) == str:
        data = iplt.pcolormesh(cube, alpha=1, cmap=colourmap)

    if logscaled == False and type(vmin) == float and type(
            vmax) == float and type(colourmap) == str:
        data = iplt.pcolormesh(cube,
                               alpha=1,
                               vmin=vmin,
                               vmax=vmax,
                               cmap=colourmap)

    if coastlines == True:
        plt.gca().coastlines('50m')

    cbaxes = plt.axes([0.2, 0.25, 0.65, 0.03])
    colorbar = plt.colorbar(data, cax=cbaxes, orientation='horizontal')
    colorbar.set_ticks(colourbarticks)
    colorbar.set_ticklabels(colourbarticklabels)

    if colourbar_label is not None:
        colorbar.set_label(colourbar_label,
                           fontproperties='FT2Font',
                           color=box_colour,
                           fontsize=8,
                           bbox=dict(facecolor=box_colour,
                                     edgecolor='#2A2A2A',
                                     boxstyle='square'))

    if markerpoint is not None and markercolor is not None:
        longitude, latitude, name_of_place = markerpoint
        fig.plot(longitude,
                 latitude,
                 marker='^',
                 color=markercolor,
                 markersize=12,
                 transform=ccrs.Geodetic())
        geodetic_transform = ccrs.Geodetic()._as_mpl_transform(fig)
        text_transform = offset_copy(geodetic_transform, units='dots', y=+75)
        fig.text(longitude,
                 latitude,
                 u + name_of_place,
                 fontproperties='FT2Font',
                 alpha=1,
                 fontsize=8,
                 verticalalignment='center',
                 horizontalalignment='right',
                 transform=text_transform,
                 bbox=dict(facecolor=markercolor,
                           edgecolor='#2A2A2A',
                           boxstyle='round'))

    if timestamp is not None:
        attributedict = subset.attributes
        datetime = attributedict.get(timestamp)
        timetransform = offset_copy(geodetic_transform, units='dots', y=0)
        longitude_of_time_box, latitude_of_time_box = time_box_position
        fig.text(longitude_of_time_box,
                 latitude_of_time_box,
                 "Time, date: " + datetime,
                 fontproperties='FT2Font',
                 alpha=0.7,
                 fontsize=8,
                 transform=timetransform,
                 bbox=dict(facecolor=markercolor,
                           edgecolor='#2A2A2A',
                           boxstyle='round'))

    if plottitle is not None:
        titleaxes = plt.axes([0.2, 0.8, 0.65, 0.04], facecolor=box_colour)
        titleaxes.text(0.5,
                       0.25,
                       plottitle,
                       horizontalalignment='center',
                       fontproperties='FT2Font',
                       fontsize=10,
                       weight=600,
                       color=textcolour)
        titleaxes.set_yticks([])
        titleaxes.set_xticks([])

    picturename = save_filepath + "%04i.png" % cubenumber
    plt.savefig(picturename, dpi=200, bbox_inches="tight")
Exemple #24
0
def plot_detected_planet_magnitudes(planet_table,
                                    wv_index,
                                    detected,
                                    flux_ratios,
                                    instrument,
                                    telescope,
                                    show=True,
                                    save=False,
                                    ymin=1,
                                    ymax=30,
                                    xmin=0.,
                                    xmax=1.,
                                    alt_data=None,
                                    alt_label=""):
    '''
    Make a plot of the planets detected at a given wavelenth_index

    Inputs: 
        planet_table    - a Universe.planets table
        wv_index        - the index from the instrument.current_wvs 
                            wavelength array to consider
        detected        - a boolean array of shape [n_planets,n_wvs] 
                        that indicates whether or not a planet was detected 
                        at a given wavelength
        flux_ratios     - an array of flux ratios between the planet and the star
                        at the given wavelength. sape [n_planets,n_wvs]
        instuemnt       - an instance of the psisim.instrument class
        telescope       - an instance of the psisim.telescope class

    Keyword Arguments: 
        show            - do you want to show the plot? Boolean
        save            - do you want to save the plot? Boolean
        ymin,ymax,xmin,xmax - the limits on the plot
        alt_data        - An optional argument to pass to show a secondary set of data.
                        This could be e.g. detection limits, or another set of atmospheric models
        alt_label       - This sets the legend label for the alt_data
    '''

    fig, ax = plt.subplots(1, 1, figsize=(7, 5))

    #convert flux ratios to delta_mags
    dMags = -2.5 * np.log10(flux_ratios[:, wv_index])

    band = instrument.current_filter
    if band == 'R':
        bexlabel = 'CousinsR'
        starlabel = 'StarRmag'
    elif band == 'I':
        bexlabel = 'CousinsI'
        starlabel = 'StarImag'
    elif band == 'J':
        bexlabel = 'SPHEREJ'
        starlabel = 'StarJmag'
    elif band == 'H':
        bexlabel = 'SPHEREH'
        starlabel = 'StarHmag'
    elif band == 'K':
        bexlabel = 'SPHEREKs'
        starlabel = 'StarKmag'
    elif band == 'L':
        bexlabel = 'NACOLp'
        starlabel = 'StarKmag'
    elif band == 'M':
        bexlabel = 'NACOMp'
        starlabel = 'StarKmag'
    else:
        raise ValueError(
            "Band needs to be 'R', 'I', 'J', 'H', 'K', 'L', 'M'. Got {0}.".
            format(band))

    stellar_mags = planet_table[starlabel]
    stellar_mags = np.array(stellar_mags)

    planet_mag = stellar_mags + dMags
    # import pdb;pdb.set_trace()

    seps = np.array([
        planet_table_entry['AngSep'] / 1000
        for planet_table_entry in planet_table
    ])

    # import pdb; pdb.set_trace()
    #Plot the non-detections
    ax.scatter(seps[~detected[:, wv_index]],
               planet_mag[:][~detected[:, wv_index]],
               marker='.',
               label="Full Sample",
               s=20)

    # print(seps[~detected[:,wv_index]],flux_ratios[:,wv_index][~detected[:,wv_index]])
    masses = np.array([
        float(planet_table_entry['PlanetMass'])
        for planet_table_entry in planet_table
    ])
    # import pdb; pdb.set_trace()

    # import pdb; pdb.set_trace()
    #Plot the detections
    scat = ax.scatter(seps[detected[:, wv_index]],
                      planet_mag[:][detected[:, wv_index]],
                      marker='o',
                      label="Detected",
                      c=masses[detected[:, wv_index]],
                      cmap='gist_heat',
                      edgecolors='k',
                      norm=colors.LogNorm(vmin=1, vmax=1000))
    fig.colorbar(scat, label=r"Planet Mass [$M_{\oplus}$]", ax=ax)

    import pdb
    pdb.set_trace()

    #Plot 1 and 2 lambda/d
    ax.axvline(
        instrument.current_wvs[wv_index] * 1e-6 / telescope.diameter * 206265,
        color='k',
    )
    ax.axvline(2 * instrument.current_wvs[wv_index] * 1e-6 /
               telescope.diameter * 206265,
               color='k',
               linestyle='--')

    ax.axhline(18.7 + 0.4, color='r', linestyle='-.', label="")

    #If detection_limits is passed, then plot the 5-sigma detection limits for each source
    if alt_data is not None:
        ax.scatter(seps,
                   alt_data[:, wv_index],
                   marker='.',
                   label=alt_label,
                   color='darkviolet',
                   s=20)
        for i, sep in enumerate(seps):
            ax.plot([sep, sep],
                    [flux_ratios[i, wv_index], alt_data[i, wv_index]],
                    color='k',
                    alpha=0.1,
                    linewidth=1)

    #Axis title
    ax.set_title("Planet Detection Yield at {:.3}um".format(
        instrument.current_wvs[wv_index]),
                 fontsize=18)

    #Legend
    legend = ax.legend(loc='upper right', fontsize=13)
    legend.legendHandles[-1].set_color('orangered')
    legend.legendHandles[-1].set_edgecolor('k')

    #Plot setup
    ax.set_ylabel(r"Planet Magnitude at {:.1f}$\mu m$".format(
        instrument.current_wvs[wv_index]),
                  fontsize=16)
    ax.set_xlabel("Separation ['']", fontsize=16)
    # ax.set_xlim(xmin,xmax)
    ax.set_ylim(ymin, ymax)
    # ax.set_yscale('log')
    ax.set_xscale('log')

    #Do we show it?
    if show:
        plt.show()

    plt.tight_layout()

    #Do we save it?
    if save:
        plt.savefig("Detected_Planets_flux_v_sma.png", bbox_inches="tight")

    #Return the figure so that the user can manipulate it more if they so please
    return fig, ax
Exemple #25
0
 def color_normalizer(self,
                      value,
                      cmap,
                      base_opacity,
                      norm_method,
                      gamma=None,
                      initial=True,
                      coordinates=None):
     # Get Colormap
     if initial:
         self.color_map_value = cmx.get_cmap(cmap)
         # Data normalize
         if norm_method == 'linear':
             self.norm = cm.Normalize(vmin=self.value_min,
                                      vmax=self.value_max)
             self.values_norm = self.norm(value)
             self.color_values_norm = self.color_map_value(self.values_norm)
         elif norm_method == 'power':
             self.norm = cm.PowerNorm(gamma=gamma,
                                      vmin=value.min(),
                                      vmax=value.max())
             self.values_norm = self.norm(value)
             self.color_values_norm = self.color_map_value(self.values_norm)
         elif norm_method == 'lognormal':
             val_modify = (-1.0) * value
             value_lognorm = val_modify + abs(val_modify.min()) + 1e-40
             self.norm = cm.LogNorm(vmin=value_lognorm.min(),
                                    vmax=value_lognorm.max())
             self.values_norm = self.norm(val_modify)
             self.color_values_norm = self.color_map_value(self.values_norm)
         elif norm_method == 'relative':
             self.prev_value = value
             self.values_norm = np.zeros(value.shape)
             self.color_values_norm = self.color_map_value(self.values_norm)
             self.relative_init = False
         else:
             raise Exception("Invalid normalization method")
     else:
         if norm_method == 'relative':
             if self.relative_init:
                 self.prev_value = value
                 self.values_norm = np.zeros(value.shape)
                 self.color_values_norm = self.color_map_value(
                     self.values_norm)
                 self.relative_init = False
             else:
                 # Distance normalizer
                 dist_inv = 1 / np.sqrt(
                     np.sum((coordinates * coordinates), axis=1))
                 dist_inv_normalizer = cm.LogNorm(vmin=dist_inv.min(),
                                                  vmax=dist_inv.max())
                 dist_inv_norm = dist_inv_normalizer(dist_inv)
                 scale = dist_inv_norm.reshape((dist_inv_norm.size, 1))
                 #
                 self.values_norm += scale * (
                     value - self.prev_value) / self.prev_value
                 self.values_norm = np.clip(self.values_norm, 0.0, 1.0)
                 self.color_values_norm = self.color_map_value(
                     self.values_norm)
                 self.prev_value = value
         else:
             self.color_values_norm = self.color_map_value(self.norm(value))
     # Assign opacity
     self.color_values_norm[:, :, -1] *= base_opacity
     # Reshape normalized color values
     self.color_values_norm = self.color_values_norm.reshape(
         (value.size, 4))
     return (self.values_norm, self.color_values_norm)
Exemple #26
0
    def cplot(self,
              title='potential energy landscape',
              cmap='RdYlBu_r',
              n_bins=10,
              show_plot=True,
              grid=True,
              **kwargs):
        # get X, Y, and Z coords
        X = self.x1_coords
        Y = self.x2_coords
        Z = self.values
        # setup figure
        fig = plt.figure(title,
                         figsize=(self.x1_coords.max() / self.x2_coords.max() *
                                  10, 8))
        ax = fig.add_subplot(1, 1, 1)
        # get appropriate levels
        try:
            levels = kwargs['levels']
            kwargs = removekey(kwargs, 'levels')
            try:
                norm = kwargs['norm']
                if type(norm) is type(colors.LogNorm()):
                    tick_values = np.logspace(start=np.log10(np.min(levels)),
                                              stop=np.log10(np.max(levels)),
                                              num=len(levels),
                                              base=10.0)
                else:
                    raise
            except:
                tick_values = np.linspace(start=np.min(levels),
                                          stop=np.max(levels),
                                          num=len(levels))
        except:
            try:
                # test if norm exists
                norm = kwargs['norm']
                if type(norm) is type(colors.LogNorm()):
                    levels = np.logspace(
                        #Z.min(), Z.max(), nbins, endpoint=True)
                        start=np.log10(Z.min()),
                        stop=np.log10(Z.max()),
                        num=n_bins,
                        base=10.0)
                else:
                    levels = mpl.ticker.MaxNLocator(n_bins=n_bins).tick_values(
                        Z.min(), Z.max())
            except:
                levels = mpl.ticker.MaxNLocator(n_bins=n_bins).tick_values(
                    Z.min(), Z.max())
            tick_values = np.linspace(Z.min(), Z.max(), len(levels))

        CS = ax.contourf(X,
                         Y,
                         Z,
                         cmap=cmap,
                         levels=levels,
                         origin='lower',
                         zorder=0,
                         **kwargs)
        if grid:
            # set grid
            intervals = 1
            loc = plticker.MultipleLocator(base=intervals)
            ax.yaxis.set_major_locator(loc)
            ax.xaxis.set_major_locator(loc)
            plt.grid('on', linestyle='-', linewidth=1, color='black', zorder=1)
        # make colorbar
        fig.subplots_adjust(right=0.8)
        cbar_ax = fig.add_axes([0.82, 0.15, 0.02, 0.7])
        cb = fig.colorbar(CS, cax=cbar_ax, ticks=levels)
        cb.ax.set_yticklabels([str(i) for i in tick_values])
        if show_plot:
            plt.show()
        return fig, ax
def plot_model_set(
    cluster_snapshot,
    uncertainty_snapshot,
    mask,
    params,
    id,
    r_eff,
    cut_radius,
    estimated_bg,
    bg_scatter,
    old_center,
    final_center_oversampled,
    make_plot,
):
    model_image, model_psf_image, model_psf_bin_image = fit_utils.create_model_image(
        *params, psf, snapshot_size_oversampled, oversampling_factor)

    diff_image = cluster_snapshot - model_psf_bin_image
    sigma_image = diff_image / uncertainty_snapshot
    # have zeros in the sigma image where the mask has zeros, but leave it unmodified
    # otherwise
    sigma_image *= np.minimum(mask, 1.0)
    # do the radial weighting. Need to get the data coordinates of the center
    weights_snapshot = fit_utils.radial_weighting(
        cluster_snapshot,
        fit_utils.oversampled_to_image(params[1], oversampling_factor),
        fit_utils.oversampled_to_image(params[2], oversampling_factor),
        style=radial_weighting,
    )
    sigma_image *= weights_snapshot

    if make_plot:
        # set up the normalizations and colormaps
        # Use the data image to get the normalization that will be used in all plots. Base
        # it on the data so that it is the same in all bootstrap iterations
        vmax = 2 * np.max(cluster_snapshot)
        linthresh = 3 * np.min(uncertainty_snapshot)
        data_norm = colors.SymLogNorm(vmin=-vmax,
                                      vmax=vmax,
                                      linthresh=linthresh,
                                      base=10)
        sigma_norm = colors.Normalize(vmin=-10, vmax=10)
        u_norm = colors.Normalize(0, vmax=1.2 * np.max(uncertainty_snapshot))
        m_norm = colors.Normalize(0, vmax=np.max(mask))
        w_norm = colors.LogNorm(0.01, np.max(weights_snapshot))

        data_cmap = bpl.cm.lisbon
        sigma_cmap = cmocean.cm.tarn  # "bwr_r" also works
        u_cmap = cmocean.cm.deep_r
        m_cmap = cmocean.cm.gray_r
        w_cmap = cmocean.cm.dense_r

        # create the figure and add all the subplots
        fig = plt.figure(figsize=[20, 20])
        gs = gridspec.GridSpec(
            nrows=4,
            ncols=4,
            width_ratios=[10, 10, 1, 15],  # have a dummy spacer column
            wspace=0.1,
            hspace=0.3,
            left=0.01,
            right=0.98,
            bottom=0.06,
            top=0.94,
        )
        ax_r = fig.add_subplot(gs[0, 0], projection="bpl")  # raw model
        ax_f = fig.add_subplot(gs[0, 1],
                               projection="bpl")  # full model (f for fit)
        ax_d = fig.add_subplot(gs[1, 1], projection="bpl")  # data
        ax_s = fig.add_subplot(gs[1, 0], projection="bpl")  # sigma difference
        ax_u = fig.add_subplot(gs[2, 1], projection="bpl")  # uncertainty
        ax_m = fig.add_subplot(gs[2, 0], projection="bpl")  # mask
        ax_w = fig.add_subplot(gs[3, 0], projection="bpl")  # weights
        ax_pd = fig.add_subplot(
            gs[0:2, 3], projection="bpl")  # radial profile differential
        ax_pc = fig.add_subplot(gs[2:, 3],
                                projection="bpl")  # radial profile cumulative

        # show the images in their respective panels
        common_data = {"norm": data_norm, "cmap": data_cmap}
        r_im = ax_r.imshow(model_image, **common_data, origin="lower")
        f_im = ax_f.imshow(model_psf_bin_image, **common_data, origin="lower")
        d_im = ax_d.imshow(cluster_snapshot, **common_data, origin="lower")
        s_im = ax_s.imshow(sigma_image,
                           norm=sigma_norm,
                           cmap=sigma_cmap,
                           origin="lower")
        u_im = ax_u.imshow(uncertainty_snapshot,
                           norm=u_norm,
                           cmap=u_cmap,
                           origin="lower")
        m_im = ax_m.imshow(mask, norm=m_norm, cmap=m_cmap, origin="lower")
        w_im = ax_w.imshow(weights_snapshot,
                           norm=w_norm,
                           cmap=w_cmap,
                           origin="lower")

        fig.colorbar(r_im, ax=ax_r)
        fig.colorbar(f_im, ax=ax_f)
        fig.colorbar(d_im, ax=ax_d)
        fig.colorbar(s_im, ax=ax_s)
        fig.colorbar(u_im, ax=ax_u)
        fig.colorbar(m_im, ax=ax_m)
        fig.colorbar(w_im, ax=ax_w)

        ax_r.set_title("Raw Cluster Model")
        ax_f.set_title("Model Convolved\nwith PSF and Binned")
        ax_d.set_title("Data")
        ax_s.set_title("(Data - Model)/Uncertainty")
        ax_u.set_title("Uncertainty")
        ax_m.set_title("Mask")
        ax_w.set_title("Weights")

        for ax in [ax_r, ax_f, ax_d, ax_s, ax_u, ax_m, ax_w]:
            ax.remove_labels("both")
            ax.remove_spines(["all"])

        # add an X marker to the location of the center
        # the rest are image coords
        x_image = fit_utils.oversampled_to_image(params[1],
                                                 oversampling_factor)
        y_image = fit_utils.oversampled_to_image(params[2],
                                                 oversampling_factor)
        for ax in [ax_d, ax_s, ax_u, ax_w]:
            ax.scatter([x_image], [y_image], marker="x", c=bpl.almost_black)
        # make the marker white in the mask plot
        ax_m.scatter([x_image], [y_image], marker="x", c="w")
        # then add LEGUS's center to the data and mask plot
        for ax in [ax_d, ax_m]:
            ax.scatter([old_center[0]], [old_center[1]], marker="x", c="0.5")

    # Then make the radial plots. first background subtract
    cluster_snapshot -= params[7]
    model_image -= params[7]
    model_psf_image -= params[7]
    model_psf_bin_image -= params[7]

    c_d = bpl.color_cycle[0]
    c_m = bpl.color_cycle[1]
    # the center is in oversampled coords, fix that
    x_c = fit_utils.oversampled_to_image(params[1], oversampling_factor)
    y_c = fit_utils.oversampled_to_image(params[2], oversampling_factor)

    radii, model_ys, data_ys = create_radial_profile(model_psf_bin_image,
                                                     cluster_snapshot, mask,
                                                     x_c, y_c)

    if make_plot:
        ax_pd.scatter(radii, data_ys, c=c_d, s=5, alpha=1.0, label="Data")
        ax_pd.scatter(radii, model_ys, c=c_m, s=5, alpha=1.0, label="Model")
        ax_pd.axhline(0, ls=":", c=bpl.almost_black)
        ax_pd.axvline(r_eff, ls=":", c=bpl.almost_black)

        # then bin this data to make the binned plot
        ax_pd.plot(*bin_profile(radii, data_ys, 1.0),
                   c=c_d,
                   lw=5,
                   label="Binned Data")
        ax_pd.plot(*bin_profile(radii, model_ys, 1.0),
                   c=c_m,
                   lw=5,
                   label="Binned Model")

        ax_pd.legend(loc="upper right")
        ax_pd.add_labels("Radius (pixels)",
                         "Background Subtracted Pixel Value [$e^{-}$]")
        # set min and max values so it's easier to flip through bootstrapping plots
        y_min = np.min(cluster_snapshot)
        y_max = np.max(cluster_snapshot)
        # give them a bit of padding
        diff = y_max - y_min
        y_min -= 0.1 * diff
        y_max += 0.1 * diff
        ax_pd.set_limits(0, np.ceil(max(radii)), y_min, y_max)

    # then make the cumulative one. The radii are already in order so this is easy
    model_ys_cumulative = np.cumsum(model_ys)
    data_ys_cumulative = np.cumsum(data_ys)

    if make_plot:
        ax_pc.plot(radii, data_ys_cumulative, c=c_d, label="Data")
        ax_pc.plot(radii, model_ys_cumulative, c=c_m, label="Model")
        ax_pc.set_limits(0, np.ceil(max(radii)), 0,
                         1.2 * np.max(data_ys_cumulative))
        ax_pc.legend(loc="upper left")
        ax_pc.axvline(r_eff, ls=":", c=bpl.almost_black)
        ax_pc.add_labels(
            "Radius (pixels)",
            "Cumulative Background Subtracted Pixel Values [$e^{-}$]")

    # calculate different quality metrics of cumulative profile and the RMS
    median_diff = mad_of_cumulative(radii, model_ys_cumulative,
                                    data_ys_cumulative, cut_radius)
    max_diff = max_diff_cumulative(radii, model_ys_cumulative,
                                   data_ys_cumulative, cut_radius)
    last_diff = diff_cumulative_at_radius(radii, model_ys_cumulative,
                                          data_ys_cumulative, cut_radius)
    r_eff_diff = diff_cumulative_at_reff_data(radii, model_ys_cumulative,
                                              data_ys_cumulative)
    this_rms = rms(sigma_image, snapshot_x_cen, snapshot_y_cen, cut_radius)

    if make_plot:
        # the last one just has the list of parameters
        ax_pc.easy_add_text(
            "$R_{eff}$" + f" = {r_eff:.2f} pixels\n"
            f"log(peak brightness) = {params[0]:.2f}\n"
            f"x center = {final_center_oversampled[0]:.2f}\n"
            f"y center = {final_center_oversampled[1]:.2f}\n"
            f"scale radius [pixels] = {params[3]:.2g}\n"
            f"q (axis ratio) = {params[4]:.2f}\n"
            f"position angle = {params[5]:.2f}\n"
            f"$\eta$ (power law slope) = {params[6]:.2f}\n"
            f"background = {params[7]:.2f}\n\n"
            f"cut radius = {cut_radius:.2f} pixels\n"
            f"estimated background = {estimated_bg:.2f}$\pm${bg_scatter:.2f}\n"
            f"RMS = {this_rms:,.2f}\n"
            f"MAD of cumulative profile = {100 * median_diff:.2f}%\n"
            f"Max diff of cumulative profile = {100 * max_diff:.2f}%\n"
            f"Diff of cumulative profile at cut radius = {100 * last_diff:.2f}%\n"
            f"Diff of cumulative profile at data $R_{eff}$ = {100 * last_diff:.2f}%\n",
            "lower right",
            fontsize=15,
        )

        fig.savefig(size_dir / "cluster_fit_plots" / create_plot_name(id),
                    dpi=100)
        plt.close(fig)
        del fig

    return median_diff, max_diff, last_diff, r_eff_diff, this_rms
#print (result.errormap.mean(axis=2))
print("data in heatmap:")
#print(heatmap.mean(axis=2))
fig, ax = plt.subplots()
print("heatmap:")
#np.set_printoptions(threshold='nan')
for line in heatmap:
    print(list(line))
#print(heatmap)

#mask = heatmap.isnan()
map = ax.imshow(heatmap,
                interpolation='nearest',
                origin='lower',
                cmap=cm.viridis,
                norm=colors.LogNorm(vmin=heatmap.min(), vmax=heatmap.max()))
#plt.colorbar(heatmap,orientation = 'horizontal')
cbar = fig.colorbar(map, orientation='horizontal')
#cbar.ax.set_yticklabels(['0.0','0.025','0.05','0.075','>0.01'])
cbar.set_label('Error scale / %', rotation=0, **fig_font)
ax.set_title('Prediction error with different MLP topologies', **fig_font)
plt.xlabel('Neurons per hidden layer', **fig_font)
plt.ylabel('Hidden layers', **fig_font)

CONST = 1
#x = np.arange(-9, 150, 10)
#y = np.arange(0, 20, 1)
#labels_x = [1,20,40,60,80,100,120,140]#[i+CONST for i in x]
#labels_y = [20,10,1]#[i+CONST for i in y]
## set custom tick labels
#ax.set_xticklabels(labels_x)
                       dtype=float,
                       usecols=(3, 4),
                       skip_header=1,
                       unpack=True)

plt.scatter(m1, m2, s=0.1, color="red", label="dataset")
plt.legend()
plt.tight_layout()
plt.show()

tol = 1e-2
for i in range(int(len(m1))):
    if (m1[i] < tol):
        m1[i] = tol
    if (m2[i] < tol):
        m2[i] = tol

min1 = min(m1)
max1 = max(m1)

if (min1 < tol):
    min1 = tol

logbins = np.logspace(np.log10(min1), np.log10(max1), 50)
plt.hist2d(m1, m2, bins=logbins, norm=colors.LogNorm())
plt.xlabel("$M_1$ [$M_{\odot}$]")
plt.ylabel("$M_2$ [$M_{\odot}$]")
cbar = plt.colorbar()
cbar.set_label("N of BHS per cell")
plt.tight_layout()
plt.show()
    def draw(self, x_ray_image):
        self.x_ray_image = np.copy(x_ray_image)

        if not self.has_been_drawn:
            self.fig = Figure(figsize=(5, 8), dpi=100)

        #self.x_ray_image = np.multiply(np.divide(np.subtract(x_ray_image, self.x_ray_image.min()),
        #        self.x_ray_image.max() - self.x_ray_image.min()), 255);
        if self.has_been_drawn:
            print("redraw")
            self.fig.clear()

        norm = colors.Normalize(vmin=self.x_ray_image.min(),
                                vmax=self.x_ray_image.max())
        log_norm = colors.LogNorm(vmin=self.x_ray_image.min(),
                                  vmax=self.x_ray_image.max())

        ax = self.fig.add_subplot(211)
        self.im_plot1 = ax.imshow(self.x_ray_image, norm=norm, cmap="PuBu_r")
        self.fig.colorbar(self.im_plot1, ax=ax, extend='max')
        ax.set_title("X-ray image")
        '''ax = self.fig.add_subplot(311)
        self.im_plot2 = ax.imshow(self.x_ray_image, cmap="PuBu_r", norm=log_norm);
        self.fig.colorbar(self.im_plot2, ax=ax, extend='max');
        ax.set_title("X-ray image (in log scale)");'''

        ax = self.fig.add_subplot(212)
        n, bins, patches = ax.hist(self.x_ray_image.ravel(),
                                   bins=256,
                                   density=True,
                                   facecolor='g',
                                   alpha=0.75)
        ax.set_yscale("log")
        ax.set_title("Intensity histogram")
        ax.set_xlabel("Intensity")
        ax.set_ylabel("Frequency")

        if not self.has_been_drawn:

            #ax.title("Intensity histogram of X-ray image");

            # a tk.DrawingArea
            self.canvas = FigureCanvasTkAgg(self.fig, master=self.root)

            self.toolbar = NavigationToolbar2Tk(self.canvas, self.root)
            self.toolbar.update()

            self.canvas.mpl_connect('key_press_event', self.on_key_event)

            self.button = Tk.Button(master=self.root,
                                    text='Quit',
                                    command=self._quit)

            self.has_been_drawn = True
        #else:

        #self.im_plot.set_data(self.x_ray_image)
        self.canvas.draw()
        self.canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
        self.canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
        self.button.pack(side=Tk.BOTTOM)