Exemplo n.º 1
0
def olr_r():
	n_colors=36
	olr_map =[cm.gist_yarg(cc) for cc in range(5*n_colors,0,-5)]
	olr_coltbl = ListedColormap(olr_map,name = 'orl_coltbl',N=n_colors)
	#olr_coltbl.set_bad(color='gray')
	olr_coltbl.set_bad(color= olr_coltbl.colors[0])
	return olr_coltbl
Exemplo n.º 2
0
def olr_r():
    n_colors = 36
    olr_map = [cm.gist_yarg(cc) for cc in range(5 * n_colors, 0, -5)]
    olr_coltbl = ListedColormap(olr_map, name='orl_coltbl', N=n_colors)
    #olr_coltbl.set_bad(color='gray')
    olr_coltbl.set_bad(color=olr_coltbl.colors[0])
    return olr_coltbl
Exemplo n.º 3
0
def load_colormap(filename):
    """Load a colormap defined in a text file

    filename is the .txt file name located in the
    data/ path, not the full path.
    list_available_colormaps() lists the available color tables
    """
    try:
        if rank == 0:
            vals = np.loadtxt(os.path.join(DATA_PATH, filename))/255.0
            n_vals = len(vals)
        else:
            vals = None
        if par.use_mpi:
           vals = mpi.COMM_WORLD.bcast(vals, root=0)
        colormap = ListedColormap(vals)
    except exceptions.IOError:
        print("Cannot load colormap, available colormaps: \n* " + "\n* ".join(list_available_colormaps()))
        raise
    # color of missing pixels
    colormap.set_bad("gray")
    # color of background, necessary if you want to use
    # this colormap directly with hp.mollview(m, cmap=colormap)
    colormap.set_under("white")
    return colormap
Exemplo n.º 4
0
def beta_plot(fig, ax, data, params, direction, depth=None, cax=None, fontsize=None, mccomas=False, limits=None, refinement=0, titlesize=25, labelsize=20, ticklabelsize=15, skip_labeling=False, cbar_orientation='vertical'):
    X, Y, dslice = plot_setup(ax, data, params, direction, depth, fontsize=fontsize, mccomas=mccomas, titlesize=titlesize, labelsize=labelsize, ticklabelsize=ticklabelsize, skip_labeling=skip_labeling)

    if limits is None:
        limits = (-1,2)

    # Setup custom colorbar
    levels = np.logspace(limits[0] - .5,limits[1] + .5, (limits[1]-limits[0]+1)*(refinement+1)+1)
    ticks = np.logspace(limits[0],limits[1],limits[1]-limits[0]+1)
    viridis = cm.get_cmap('viridis', len(levels)+2)
    cmap = ListedColormap(viridis.colors[1:-1],'beta_cmap')
    cmap.set_over(viridis.colors[-1])
    cmap.set_bad(viridis.colors[0])

    # Catch the stupid warnings I don't care about
    with warnings.catch_warnings():
        warnings.simplefilter('ignore')

        mappable = ax.contourf(X.T, Y.T, dslice, levels=levels, norm=MyLogNorm(),
                                cmap=cmap, extend='both',
                                vmin=levels[0], vmax=levels[-1])

    if cax != 'None':
        cb = fig.colorbar(mappable, ax=ax, cax=cax, orientation=cbar_orientation)
        cb.set_ticks(ticks)
        cb.set_ticklabels(ticks)

    return mappable, X, Y, dslice
Exemplo n.º 5
0
    def planck_color_map(self):

        '''

        Itab = [   0,  13,  26,  39,  52,  65,  76,  77,  88, 
                   101, 114, 127,   140, 153, 166, 179,   192, 
                   205, 218, 231, 255]
        Rtab = [   0,  10,  30,  80, 191, 228, 241, 241, 245, 
                   248, 249.9, 242.25,204, 165, 114, 127.5, 178.5, 
                   204, 229.5, 242.25, 252.45]
        Gtab = [   0,  20, 184, 235, 239, 240, 241, 241, 240, 
                   235, 204,   153,  76.5,  32,   0, 127.5, 178.5, 
                   204, 229.5, 242.25, 252.45]
        Btab = [ 255, 255, 255, 255, 250, 245, 212, 212, 175, 
                 130, 38.25, 12.75,  0,   32,  32, 153,   204,   
                 229.5, 242.25, 249.9, 255]

        ncolors = 256
        ii = np.arange(ncolors, dtype=np.float32)

        R = np.interp(ii, Itab, Rtab)
        G = np.interp(ii, Itab, Rtab)
        B = np.interp(ii, Itab, Rtab)

        '''

        cmap = ListedColormap(np.loadtxt("Planck_FreqMap_RGB.txt")/255.)
        cmap.set_bad("darkgray")
        cmap.set_under("white")

        return cmap
Exemplo n.º 6
0
def planck_color_map(self):

    cmap = ListedColormap(np.loadtxt("Planck_FreqMap_RGB.txt")/255.)
    cmap.set_bad("darkgray")
    cmap.set_under("white")

    return cmap
		def get_planck_cmap():
			from matplotlib.colors import ListedColormap
			colombi1_cmap = ListedColormap(np.loadtxt("Planck_Parchment_RGB.txt")/255.)
			colombi1_cmap.set_bad("gray") # color of missing pixels
			colombi1_cmap.set_under("white") # color of background, necessary if you want to use
			# this colormap directly with hp.mollview(m, cmap=colombi1_cmap)
			return colombi1_cmap
 def get_planck_cmap():
     from matplotlib.colors import ListedColormap
     colombi1_cmap = ListedColormap(
         np.loadtxt("Planck_Parchment_RGB.txt") / 255.)
     colombi1_cmap.set_bad("gray")  # color of missing pixels
     colombi1_cmap.set_under(
         "white")  # color of background, necessary if you want to use
     # this colormap directly with hp.mollview(m, cmap=colombi1_cmap)
     return colombi1_cmap
Exemplo n.º 9
0
def plot_skymap(skymap, smooth=None, decmax=None, scale=None, color_bins=40,
                color_palette='viridis', symmetric=False, cbar_min=None,
                cbar_max=None, cbar_title='Skymap', llabel=None, polar=False,
                fig=None, sub=None):

    cpalette = sns.color_palette(color_palette, color_bins)
    cmap = ListedColormap(cpalette.as_hex())
    cmap.set_under('white')
    cmap.set_bad('gray')

    # if cbar_max and cbar_max and symmetric and (cbar_max != -cbar_min):
    #     raise ValueError('The max/min colorbar values can\'t be symmetric')
    # elif cbar_max and cbar_max:
    #     pass
    # elif:
    #     skymap_min = skymap.min()
    #     skymap_max = skymap.max()
    #     maximum = np.max(np.abs([skymap_min, skymap_max]))
    #     cbar_min = np.sign(skymap_min) * maximum
    #     cbar_max = np.sign(skymap_max) * maximum
    # else:
    #     cbar_min = cbar_min if cbar_min else skymap.min()
    #     cbar_max = cbar_max if cbar_max else skymap.max()

    if polar:
        shrink = 0.6
        rot = [0,-90,180]
        hp.orthview(skymap, half_sky=True, rot=rot, coord='C', title='',
                    min=cbar_min, max=cbar_max, cbar=False, cmap=cmap,
                    fig=fig, sub=sub)
    else:
        shrink = 1.0
        hp.mollview(skymap, rot=180, coord='C', title='', min=cbar_min,
                    max=cbar_max, cbar=False, cmap=cmap, fig=fig, sub=sub)
    hp.graticule(verbose=False)

    fig = plt.gcf()
    ax = plt.gca()
    image = ax.get_images()[0]
    cbar = fig.colorbar(image, orientation='horizontal', aspect=50,
                        pad=0.01, fraction=0.1, ax=ax,
                        format=FormatStrFormatter('%g'),
                        shrink=shrink)
    if cbar_title:
        cbar.set_label(cbar_title, size=14)

    if not polar:
        ax.set_ylim(-1, 0.005)
        ax.annotate('0$^\circ$', xy=(1.8, -0.75), size=14)
        ax.annotate('360$^\circ$', xy=(-1.99, -0.75), size=14)

    if llabel:
        ax.annotate(llabel, xy=(-1.85,-0.24), size=20, color='white')

    return fig, ax
def planck_cmap():
    """
    Generates the Planck CMB colormap from an input file, which stores the color values
    for the complete gradient. The colormap values was obtained from the following link:
    - https://github.com/zonca/paperplots/raw/master/data/Planck_Parchment_RGB.txt
    """
    cmap = ListedColormap(np.loadtxt(data + 'Planck_Parchment_RGB.txt') / 255.)
    cmap.set_bad('black')  # color of missing pixels
    cmap.set_under('white')  # color of background

    return cmap
Exemplo n.º 11
0
def pycmap(gacmap):
  from matplotlib.colors import ListedColormap
  from numpy import vstack
  r = gacmap.table['r']
  g = gacmap.table['g']
  b = gacmap.table['b']
  rt = ListedColormap(vstack((r, g, b)).T)
  rt.set_over((r[-1], g[-1], b[-1]))
  rt.set_under((r[0], g[0], b[0]))
  rt.set_bad(color='k', alpha=0)
  return rt
Exemplo n.º 12
0
def pycmap(gacmap):
    from matplotlib.colors import ListedColormap
    from numpy import vstack
    r = gacmap.table['r']
    g = gacmap.table['g']
    b = gacmap.table['b']
    rt = ListedColormap(vstack((r, g, b)).T)
    rt.set_over((r[-1], g[-1], b[-1]))
    rt.set_under((r[0], g[0], b[0]))
    rt.set_bad(color='k', alpha=0)
    return rt
Exemplo n.º 13
0
def load_planck_cmap(cmap_fname="../misc/Planck_Parchment_RGB.txt"):
    '''
    https://zonca.github.io/2013/09/Planck-CMB-map-at-high-resolution.html
    '''
    from matplotlib.colors import ListedColormap
    import numpy as np
    colombi1_cmap = ListedColormap(np.loadtxt(cmap_fname)/255.)
    colombi1_cmap.set_bad("gray") # color of missing pixels
    colombi1_cmap.set_under("white") # color of background, necessary if you want to use

    cmap = colombi1_cmap
    return cmap
Exemplo n.º 14
0
Arquivo: colors.py Projeto: caiw/pyrsa
def rdm_colormap(n_cols=256, monitor=None):
    """this function provides a convenient colormap for visualizing
    dissimilarity matrices. it goes from blue to yellow and has grey for
    intermediate values.

    Args:
        n_cols (int, optional): precision of the colormap.
        Defaults to 256.

    Returns:
        [matplotlib ListedColormap]: this matplotlib color object can be
        used as a cmap in any plot.

    Example:
        .. code-block:: python

            import numpy as np
            import matplotlib.pyplot as plt
            from rsatoolbox.vis.colors import rdm_colormap
            plt.imshow(np.random.rand(10,10),cmap=rdm_colormap())
            plt.colorbar()
            plt.show()

    (ported from Niko Kriegeskorte's RDMcolormap.m)
    """

    # blue-cyan-gray-red-yellow with increasing V (BCGRYincV)
    anchor_cols = np.array([
        [0, 0, 1],
        [0, 1, 1],
        [.5, .5, .5],
        [1, 0, 0],
        [1, 1, 0],
    ])

    # skimage rgb2hsv is intended for 3d images (RGB)
    # here we add a new axis to our 2d anchorCols to satisfy
    # skimage, and then squeeze
    anchor_cols_hsv = rgb2hsv(anchor_cols[np.newaxis, :]).squeeze()

    inc_v_weight = 1
    anchor_cols_hsv[:, 2] = (1 - inc_v_weight) * anchor_cols_hsv[:, 2] + \
        inc_v_weight * np.linspace(0.5, 1, anchor_cols.shape[0]).T

    # anchorCols = brightness(anchorCols)
    anchor_cols = hsv2rgb(anchor_cols_hsv[np.newaxis, :]).squeeze()

    cols = color_scale(n_cols, anchor_cols, monitor)

    cmap = ListedColormap(cols)
    cmap.set_bad('white')

    return cmap
Exemplo n.º 15
0
def fplanckparchmentcmap():
    '''
    Creates the Planck matplotlib colormap.
    '''

    planck_cmap = ListedColormap(
        np.loadtxt(
            "/Users/campbell/Documents/PhD/data/functions/Planck_Parchment_RGB.txt"
        ) / 255.)
    planck_cmap.set_bad("gray")  # color of missing pixels
    planck_cmap.set_under(
        "white"
    )  # color of background, necessary if you want to use with mollview

    return planck_cmap
Exemplo n.º 16
0
def plot_mwd(RA,
             Dec,
             Color,
             ifFillRect,
             org=0,
             title='Mollweide projection',
             projection='mollweide'):
    ''' RA, Dec are arrays of the same length.
    RA takes values in [0,360), Dec in [-90,90],
    which represent angles in degrees.
    org is the origin of the plot, 0 or a multiple of 30 degrees in [0,360).
    title is the title of the figure.
    projection is the kind of projection: 'mollweide', 'aitoff', 'hammer', 'lambert'
    '''
    x = [np.remainder(n + 360 - org, 360) for n in RA]  # shift RA values
    for i in range(len(x)):
        if x[i] > 180:
            x[i] -= 360  # scale conversion to [-180, 180]
        x[i] = -x[i]  # reverse the scale: East to the left
    colombi1_cmap = ListedColormap(np.loadtxt("CMBColorMap.txt") / 255.)
    colombi1_cmap.set_bad("gray")  # color of missing pixels
    colombi1_cmap.set_under(
        "white")  # color of background, necessary if you want to use
    tick_labels = np.array([150, 120, 90, 60, 30, 0, 330, 300, 270, 240, 210])
    tick_labels = np.remainder(tick_labels + 360 + org, 360)
    fig = plt.figure(figsize=(10, 5))
    ax = fig.add_subplot(111, projection=projection, facecolor='darkgray')
    rand = np.random.random_sample((8651, ))
    ax.scatter(np.radians(x),
               np.radians(Dec),
               c=Color,
               s=1,
               alpha=1,
               cmap=colombi1_cmap)  # convert degrees to radians
    #fig.colorbar(ax, orientation='horizontal', fraction=.1)
    #ax.scatter(0, 0, c='red', s = 10)
    if ifFillRect:
        fillRect(x, Dec, Color, 6, 3, ax)

    ax.set_xticklabels(tick_labels)  # we add the scale on the x axis
    ax.set_title(title)
    ax.title.set_fontsize(15)
    ax.set_xlabel("RA")
    ax.xaxis.label.set_fontsize(12)
    ax.set_ylabel("Dec")
    ax.yaxis.label.set_fontsize(12)
    ax.grid(True)
    plt.show()
Exemplo n.º 17
0
def load_colormap(filename):
    """Load a colormap defined in a text file

    filename is the .txt file name located in the
    data/ path, not the full path.
    list_available_colormaps() lists the available color tables
    """
    try:
        colormap = ListedColormap(np.loadtxt(os.path.join(DATA_PATH, filename))/255.)
    except IOError:
        print("Cannot load colormap, available colormaps: \n* " + "\n* ".join(list_available_colormaps()))
        raise
    colormap.set_bad("gray") # color of missing pixels
    colormap.set_under("white") # color of background, necessary if you want to use
    # this colormap directly with hp.mollview(m, cmap=colormap)
    return colormap
Exemplo n.º 18
0
def load_colormap(filename):
    """Load a colormap defined in a text file

    filename is the .txt file name located in the
    data/ path, not the full path.
    list_available_colormaps() lists the available color tables
    """
    try:
        colormap = ListedColormap(
            np.loadtxt(os.path.join(DATA_PATH, filename)) / 255.)
    except IOError:
        print("Cannot load colormap, available colormaps: \n* " +
              "\n* ".join(list_available_colormaps()))
        raise
    colormap.set_bad("gray")  # color of missing pixels
    colormap.set_under(
        "white")  # color of background, necessary if you want to use
    # this colormap directly with hp.mollview(m, cmap=colormap)
    return colormap
Exemplo n.º 19
0
import numpy as np
import healpy as hp
import matplotlib.pyplot as plt
from glob import glob

def GetMapName(freq):
    indir = '/data/NEVERCOMMIT/'
    f = np.int(freq)
    filename = glob('/data/NEVERCOMMIT/*_%d_*fits' % f)[0]
    return filename

############### Universal colormap
# setup linear colormap
from matplotlib.colors import ListedColormap
planck_freqmap_cmap = ListedColormap(np.loadtxt("Planck_FreqMap_RGB.txt")/255.)
planck_freqmap_cmap.set_bad("gray") # color of missing pixels
planck_freqmap_cmap.set_under("white") # color of background, necessary if you want to use

# Graticule spacing in degrees
grat_spacing = 10.0
imgsize = 750
imgresolution = 5.

faces_to_do = np.arange(32)
freq = sys.argv[1]
# load a map
mapfname = GetMapName(freq)

I = hp.ma(hp.read_map(mapfname,field=0,verbose=True))
if np.int(freq)<500:
    I = I * 1e6
Exemplo n.º 20
0
plt.close('all')
fig,ax=plt.subplots(1,1)
ax.hist(phase_rot.ravel())
ax.set_title('Gridded: Mask - 0 = Cloud,1 = 66% prob.\n Clear,2 = 95% prob. Clear,3 = 99% prob. Clear')


# In[112]:

plt.close('all')
from matplotlib.colors import Normalize
from numpy import ma
fig,ax=plt.subplots(1,1,figsize=(12,12))
colors=sns.color_palette('coolwarm')
pal=LinearSegmentedColormap.from_list('test',colors)
pal.set_bad('0.75') #75% grey
pal.set_over('r')
pal.set_under('k')
vmin= -5.
vmax= 5.
ch29 = np.rot90(file_dict['ch29'],2)
ch31 = np.rot90(file_dict['ch31'],2)
the_norm=Normalize(vmin=vmin,vmax=vmax,clip=False)
tdiff= ch31 - ch29
tdiff=ma.array(tdiff,mask=np.isnan(tdiff))
CS= ax.imshow(tdiff,cmap=pal,norm=the_norm)
cax=plt.colorbar(CS,  ax = ax,extend='both')
cax.set_label('ch31 - ch29 brightnes temp (K)')
ax.set_title('TB 11 micron - TB 8 micron')

Exemplo n.º 21
0
    [231,255,0,255],
    [231, 66, 0, 255],
    [226,143,122,255],
    [228,0,145,255],
    [226,164,43,255],
    [255,0,0,255],
    [255,151,0,255],
    [206,73,255,255],
    [142,5,10,255],
    [18,95,0,255],
    [8,212,125,255],
    [0,255,59,255],
    ])/255.1
from matplotlib.colors import ListedColormap
mycmap = ListedColormap(colorlist[:,:3], 'segmentation')
mycmap.set_bad(color=(0,0,0,0))

vols = config.vols.keys()

class GetDices(object):
    def __init__(self, dir, title):
        self.dir = dir
        self.title = title
        self.dices = {'title': self.title}
        self.nsample = 0
    def __call__(self, args, dirnames, fnames):
        dir = self.dir
        file_dice = args #args.pop('file_dice','dice_labels.txt')
        if file_dice in fnames:
            path = os.path.normpath(dirnames).split(os.sep)
            if dir in path:
Exemplo n.º 22
0
print(a)
a.loc["one", 5:7]
b = make_tuple(a)
a.one


# In[40]:

plt.close("all")
from matplotlib.colors import Normalize
from numpy import ma

fig, ax = plt.subplots(1, 1, figsize=(12, 12))
colors = sns.color_palette("coolwarm")
pal = LinearSegmentedColormap.from_list("test", colors)
pal.set_bad("0.75")  # 75% grey
pal.set_over("r")
pal.set_under("k")
vmin = -5.0
vmax = 5.0
ch29 = np.rot90(file_dict["ch29"], 2)
ch31 = np.rot90(file_dict["ch31"], 2)
the_norm = Normalize(vmin=vmin, vmax=vmax, clip=False)
tdiff = ch29 - ch31
tdiff = ma.array(tdiff, mask=np.isnan(tdiff))
CS = ax.imshow(tdiff, cmap=pal, norm=the_norm)
cax = plt.colorbar(CS, ax=ax, extend="both")
cax.set_label("ch29 - ch31 brightnes temp (K)")
ax.set_title("TB 8 micron - TB 11 micron")

Exemplo n.º 23
0
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import ListedColormap

#
colors = [(), (), (), ()]

N = 256
blu_vals = np.ones((N, 4))
blu_vals[:, 0] = np.linspace(39 / 256, 1, N)
blu_vals[:, 1] = np.linspace(102 / 256, 1, N)
blu_vals[:, 2] = np.linspace(199 / 256, 1, N)
bluecmp = ListedColormap(blu_vals)
bluecmp.set_bad(color='w')


def colorFader(
        c1,
        c2,
        mix=0
):  #fade (linear interpolate) from color c1 (at mix=0) to c2 (mix=1)
    c1 = np.array(mpl.colors.to_rgb(c1))
    c2 = np.array(mpl.colors.to_rgb(c2))
    return (1 - mix) * c1 + mix * c2  #mpl.colors.to_hex()#


north = '#1f77b4'  #blue "#50a2d5"
east = "#4bb900"  #"#76bb4b" #green
south = '#ffe200'  # yellow
west = "#eb3920"  # red
def publication_plot_old(save=False):
    from matplotlib.gridspec import GridSpec

    freqs = get_freqs(gag=True)
    N_samples, L, _ = freqs.shape

    #freqs_rm = get_freqs(gag=True, remove_rm=True)
    freqs_rm = freqs.copy()
    #for i in range(L):
    #    if i in GAG_RESISTANCE: continue
    #    freqs_rm[:, i-1] = 0.
    for i in range(L):
        for xi, ch in enumerate(ALPHABET[:20]):
            if str(i+1) + ch in GAG_RESISTANCE_MUTS_SIMP: continue
            freqs_rm[:, i, xi] = 0.
    freqs = freqs.sum(axis=2)
    freqs.sort(axis=0)
    freqs = freqs[::-1]
    freqs_rm = freqs_rm.sum(axis=2)
    freqs_rm.sort(axis=0)
    freqs_rm = freqs_rm[::-1]


    #lanl_freqs = np.genfromtxt('lanl/gag_freqs_nowt_experienced.txt')
    lanl_freqs = np.genfromtxt('lanl/gag_freqs_nowt_naive.txt')
    lanl_freqs = lanl_freqs.reshape(-1,500,20)
    lanl_rm = lanl_freqs.copy()
    for i in range(L):
        for xi, ch in enumerate(ALPHABET[:20]):
            if str(i+1) + ch in GAG_RESISTANCE_MUTS_SIMP: continue
            lanl_rm[:, i, xi] = 0.
    lanl_freqs = lanl_freqs.sum(axis=2)
    lanl_rm = lanl_rm.sum(axis=2)
    print lanl_freqs.shape, lanl_rm.shape
    print freqs.shape


    #fig = plt.figure(figsize=(24, 12))
    fig = plt.figure(figsize=(7.5, 4))
    fig.suptitle('Variant Frequencies in Gag', size=20)
    gs = GridSpec(3, 2, height_ratios=[10,1,10], width_ratios=[100, 1])
    ax1 = plt.subplot(gs[0, :-1])
    ax3 = plt.subplot(gs[1, :-1])
    ax2 = plt.subplot(gs[2, :-1])
    matplotlib.rc('font', size=24)
    matplotlib.rc('axes', linewidth=5)
    [ax.set_xlabel('Sequence Position') for ax in (ax1, ax2)]
    ax1.set_ylabel('Samples with variants')
    ax2.set_ylabel('LANL PI-naive\nsequences with variants')


    red_cmap = ListedColormap(['red'])
    black_cmap = ListedColormap(['black'])
    red_cmap.set_bad((0,0,0,0))
    freqs_ma = np.ma.masked_where(freqs < 0.01, freqs)
    freqs_rm_ma = np.ma.masked_where(freqs_rm < 0.01, freqs_rm)
    plt1 = ax1.pcolor(freqs_ma, cmap=black_cmap, edgecolors='none')
    plt2 = ax1.pcolor(freqs_rm_ma, cmap=red_cmap, alpha=0.75, edgecolors='none')
    plt3 = ax2.bar(np.arange(L), lanl_freqs.sum(axis=0), width=1, fc='0.5', ec='0.5')
    plt4 = ax2.bar(np.arange(L), lanl_rm.sum(axis=0), width=1, fc='r', ec='none', alpha=0.75)

    plt.setp(ax1.get_xticklabels(), visible=False)
    quart1 = N_samples / 4.
    quart2 = lanl_freqs.shape[0] / 4.
    ax1.set_yticks(np.arange(0, N_samples+quart1, quart1))
    ax2.set_yticks(np.arange(0, N_samples+quart1, quart1))
    ax2.set_yticks(np.arange(0, lanl_freqs.shape[0]+quart2, quart2))
    quarter = N_samples / 4.
    #[ax.set_yticks(np.arange(0, N_samples + quarter, quarter)) for ax in (ax1, ax2)]
    [ax.set_yticklabels(['0%', '25%', '50%', '75%', '100%']) for ax in (ax1, ax2)]
    ax1.set_ylim(0, 1.5*N_samples)
    #ax2.set_ylim(0, 0.8*N_samples)
    ax2.set_ylim(0, 0.9*lanl_freqs.shape[0])

    locs = [(132, 'MA'), (363, 'CA'), (377, 'p2'), (432, 'NC'), (448, 'p1'), (500, 'p6')]
    x_start = 0
    colors = ('#AAAAAA', '#EEEEEE')
    for i, (junc, name) in enumerate(locs):
        color = colors[i%2]
        width = junc - x_start
        rect = Rectangle((x_start, 0), width, 1, edgecolor='None', color=color)
        ax3.add_patch(rect)
        ax3.text(x_start + width/2., 1/2., name, ha='center', va='center')
        ax1.axvline(x_start, color='k', ls='--', lw=1.0)
        ax2.axvline(x_start, color='k', ls='--', lw=1.0)
        x_start = junc
    ax3.set_xlim(0, L)
    plt.setp(ax3.get_xticklabels(), visible=False)
    plt.setp(ax3.get_yticklabels(), visible=False)
    [ax.tick_params(top=False, left=False, right=False, bottom=False) for ax in (ax1, ax2, ax3)]

    ax2.invert_yaxis()

    fig.subplots_adjust(hspace=0., wspace=0.02, left=0.08, right=0.95, top=0.95, bottom=0.06)
    if not save:
        plt.show()
    else:
        fig.savefig('PUB_VARIANTS_PLOT.tiff', dpi=600)
Exemplo n.º 25
0
        for i, r in enumerate(greens_half + [1] + list(reversed(greens_half)))
    ]),
    'blue':
    tuple([(0.1 * i, r, r) for i, r in enumerate(reversed(reds))])
}
CMAP_ASSOCIATION = LinearSegmentedColormap('association', colordict)
CMAP_ASSOCIATION.set_bad(C_BAD)

# Categorical
CMAP_CATEGORICAL = Paired
CMAP_CATEGORICAL_2 = Dark2
CMAP_CATEGORICAL.set_bad(C_BAD)

# Binary
CMAP_BINARY = ListedColormap(['#cdcdcd', '#404040'])
CMAP_BINARY.set_bad(C_BAD)

DPI = 100


# ======================================================================================================================
# Functions
# ======================================================================================================================
def plot_points(*args,
                title='',
                xlabel='',
                ylabel='',
                filepath=None,
                **kwargs):
    """
from astropy.wcs import WCS
wcs = WCS(hdu_npeaks.header)

dxlist = np.array([20, 25, -60, 35, -45])
dylist = np.array([5, -25, -40, 35, 30])
ra_list, dec_list = wcs.all_pix2world(xlist, ylist, 0)
ra_list_text, dec_list_text = wcs.all_pix2world(xlist + dxlist, ylist + dylist,
                                                0)
dra_list = ra_list - ra_list_text
ddec_list = dec_list - dec_list_text

fig = plt.figure(figsize=(4, 6))
ax = plt.subplot(projection=wcs)
cmaplst = ['#f1f7d2', '#7fcdbb', '#2c7fb8']  # stolen from colorbrewer2
lcmap = ListedColormap(cmaplst)
lcmap.set_bad('#f0f0f0')
plt.imshow(hdu_npeaks.data, vmin=-0.5, vmax=2.5, origin='lower', cmap=lcmap)

for (x, y) in zip(xlist, ylist):
    r = Circle((x, y), radius=.75, zorder=1, fc="0.8", ec="k", lw=0.2)
    ax.add_patch(r)
for i in range(len(labels)):
    plt.annotate(
        labels[i],
        xy=(xlist[i], ylist[i]),
        xycoords='data',
        xytext=(xlist[i] + dxlist[i],
                ylist[i] + dylist[i]),  #textcoords='data',
        bbox=dict(boxstyle="circle", fc="0.8", alpha=0.8),
        arrowprops=dict(arrowstyle="-",
                        shrinkA=0,
Exemplo n.º 27
0
    [233,150,122], [165, 42, 42],  # Label 8-19 (T1-12)
    [255,250,250], [147,112,219], [218,112,214], [ 75,  0,130], [255,182,193],
    [ 60,179,113], [255,235,205],  # Label 20-26 (L1-6, sacrum)
    [255,235,205], [255,228,196],  # Label 27 cocc, 28 T13,
    [218,165, 32], [  0,128,128], [188,143,143], [255,105,180],  
    [255,  0,  0], [  0,255,  0], [  0,  0,255], [255,255,  0], [  0,255,255],
    [255,  0,255], [255,239,213],  # 29-39 unused
    [  0,  0,205], [205,133, 63], [210,180,140], [102,205,170], [  0,  0,128],
    [  0,139,139], [ 46,139, 87], [255,228,225], [106, 90,205], [221,160,221],
    [233,150,122],   # Label 40-50 (subregions)
    [255,250,250], [147,112,219], [218,112,214], [ 75,  0,130], [255,182,193],
    [ 60,179,113], [255,235,205], [255,105,180], [165, 42, 42], [188,143,143],
    [255,235,205], [255,228,196], [218,165, 32], [  0,128,128] # rest unused     
    ])
cm_itk = ListedColormap(colors_itk)
cm_itk.set_bad(color='w', alpha=0)  # set NaN to full opacity for overlay

# define HU windows
wdw_sbone = Normalize(vmin=-500, vmax=1300, clip=True)
wdw_hbone = Normalize(vmin=-200, vmax=1000, clip=True)

#########################
# Resample and reorient #


def reorient_to(img, axcodes_to=('P', 'I', 'R'), verb=False):
    """Reorients the nifti from its original orientation to another specified orientation
    
    Parameters:
    ----------
    img: nibabel image
Exemplo n.º 28
0
def olr():
    olr_map = [cm.gist_yarg(cc) for cc in range(0, 255, 5)]
    olr_coltbl = ListedColormap(olr_map, name='orl_coltbl', N=36)
    olr_coltbl.set_bad(color=olr_coltbl.colors[-1])
    return olr_coltbl
Exemplo n.º 29
0
def olr():
	olr_map =[cm.gist_yarg(cc) for cc in range(0,255,5)]
	olr_coltbl = ListedColormap(olr_map,name = 'orl_coltbl',N=36)
	olr_coltbl.set_bad(color= olr_coltbl.colors[-1])
	return olr_coltbl
Exemplo n.º 30
0
"""This file contains GUI related variables."""

import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap

# Colormap for mask overlays
# palette = plt.cm.Reds
palette = ListedColormap([[0, 0, 0, 0], [1, 0, 1, 1]])  # white and magenta improve the visibility
palette.set_over('r', 1.0)
palette.set_under('w', 0)
palette.set_bad('m', 1.0)

# Slider colors
axcolor = '0.875'
hovcolor = '0.975'
Exemplo n.º 31
0
]
grids = get_grids(envs_to_plot)

color_map = {
    'place_cell': LINCLAB_COLS['red'],
    'sr': LINCLAB_COLS['red'],
    'unstructured': LINCLAB_COLS['blue']
}

N = 256
blu_vals = np.ones((N, 4))
blu_vals[:, 0] = np.linspace(39 / 256, 1, N)
blu_vals[:, 1] = np.linspace(102 / 256, 1, N)
blu_vals[:, 2] = np.linspace(199 / 256, 1, N)
bluecmp = ListedColormap(blu_vals)
bluecmp.set_bad(color='w')

red_vals = np.ones((N, 4))
red_vals[:, 0] = np.linspace(235 / 256, 1, N)
red_vals[:, 1] = np.linspace(77 / 256, 1, N)
red_vals[:, 2] = np.linspace(57 / 256, 1, N)
redcmp = ListedColormap(red_vals)
redcmp.set_bad(color='w')

blu_r_vals = np.ones((N, 4))
blu_r_vals[:, 0] = np.linspace(1, 39 / 256, N)  #np.linspace(1,80/256, N)
blu_r_vals[:, 1] = np.linspace(1, 102 / 256, N)  #np.linspace(1,162/256,N)
blu_r_vals[:, 2] = np.linspace(1, 199 / 256, N)  #np.linspace(1,213/256,N)
bluecmp_r = ListedColormap(blu_r_vals)
bluecmp_r.set_bad(color='w')
Exemplo n.º 32
0
                [0.9937714286, 0.7454571429, 0.240347619], 
                [0.9990428571, 0.7653142857, 0.2164142857], 
                [0.9955333333, 0.7860571429, 0.196652381], 
                [0.988, 0.8066, 0.1793666667], 
                [0.9788571429, 0.8271428571, 0.1633142857], 
                [0.9697, 0.8481380952, 0.147452381], 
                [0.9625857143, 0.8705142857, 0.1309], 
                [0.9588714286, 0.8949, 0.1132428571], 
                [0.9598238095, 0.9218333333, 0.0948380952], 
                [0.9661, 0.9514428571, 0.0755333333], 
                [0.9763, 0.9831, 0.0538]]

parula = ListedColormap(_parula_data, name='parula')
parula_zero = _parula_data[0]
parula_0 = ListedColormap(_parula_data, name='parula_0')
parula_0.set_bad((1,1,1))
parula_r = ListedColormap(_parula_data[::-1], name='parula_r')

willi_blau = [0.0722666667, 0.4886666667, 0.8467]


# In[ ]:


debug = False


# ### Galpy initialization
# 
# We are using the McMillan17 potential from McMillan, 2017, MNRAS, 465, 76.  
# Contrary to galpy, its normalisation parameters are:  
Exemplo n.º 33
0
def makeMap(timegrid,method,datadir,popfile,popcolormap,stationdict,citylist,elats,elons):
    figwidth = 8.0
    bounds = timegrid.getRange()
    bounds = list(bounds)
    if bounds[1] < 0 and bounds[0] > bounds[1]:
        bounds[1] = bounds[1] + 360

    clat = bounds[2] + (bounds[3] - bounds[2])/2
    clon = bounds[0] + (bounds[1] - bounds[0])/2
    dx = (bounds[1] - bounds[0])*111191 * np.cos(np.degrees(clat))
    dy = (bounds[3] - bounds[2])*111191
    aspect = np.abs(dy/dx)
    figheight = aspect * figwidth
    fig = plt.figure(figsize=(figwidth,figheight),edgecolor='g',facecolor='g')
    ax1 = fig.add_axes([0,0,1.0,1.0])
    m = Basemap(llcrnrlon=bounds[0],llcrnrlat=bounds[2],
                urcrnrlon=bounds[1],urcrnrlat=bounds[3],
                resolution='h',projection='merc',lat_ts=clat)
    
    #get the population grid
    popgrid = EsriGrid(popfile)
    popgrid.load(bounds=bounds)
    popdata = np.flipud(popgrid.griddata)

    cmap = GMTColormap(popcolormap)
    clist = cmap.getColorList()
    boundaries = cmap.getZValues()
    palette = ListedColormap(clist,'my_colormap')
 
    i = np.where(np.isnan(popdata))
    popdata[i] = -1
    popdatam = np.ma.masked_values(popdata, -1)
    palette.set_bad(WATER_COLOR,1.0)
    
    ncolors = len(boundaries)
    am = m.imshow(popdatam,cmap=palette,norm=BoundaryNorm(boundaries,ncolors),interpolation='nearest')

    statgrid = np.flipud(timegrid.griddata)
    (lons,lats) = getLatLonGrids(timegrid)
    (x,y) = m(lons,lats)
    clevels = np.arange(MINTIME,MAXTIME+DTIME,DTIME)
    cs = m.contour(x,y,statgrid,clevels)
    #plt.clabel(cs, inline=1, fontsize=10)
    proxy = [plt.Rectangle((0,0),1,1,fc = pc.get_color()[0]) for pc in cs.collections]
    labels = [str(c)+' sec' for c in clevels]

    sx,sy = m(stationdict['lon'],stationdict['lat'])
    m.plot(sx,sy,'rD')
    plt.text(sx,sy,stationdict['code'])

    #plot the various epicenters
    for elat,elon in zip(elats,elons):
        ex,ey = m(elon,elat)
        m.plot(ex,ey,'k*')

    #plot the cities
    for city in citylist:
        cx,cy = m(city['lon'],city['lat'])
        m.plot(cx,cy,'.',color=CITY_COLOR)
        plt.text(cx,cy,city['name'],color=CITY_COLOR)
    
    m.drawrivers(color=WATER_COLOR)
    m.drawcountries(color='k',linewidth=2.0)
    mer = getMapLines(bounds[0],bounds[1])
    par = getMapLines(bounds[2],bounds[3])
    
    xmap_range = m.xmax-m.xmin
    ymap_range = m.ymax-m.ymin
    xoff = -0.09*(xmap_range)
    yoff = -0.04*(ymap_range)

    m.drawmeridians(mer,labels=[0,0,1,0],fontsize=8,
                             linewidth=0.5,color='black',yoffset=yoff,xoffset=xoff,dashes=[1,0.01])
    m.drawparallels(par,labels=[0,1,0,0],fontsize=8,
                             linewidth=0.5,color='black',yoffset=yoff,xoffset=xoff,dashes=[1,0.01])
    m.drawmapboundary(color='k',linewidth=2.0)

    plt.legend(proxy,labels)
    
    outfile = os.path.join(datadir,method+'.pdf')
    plt.savefig(outfile)
    plt.close()
Exemplo n.º 34
0
import numpy as np

############### CMB colormap
from matplotlib.colors import ListedColormap
colombi1_cmap = ListedColormap(np.loadtxt("../../data/Planck_Parchment_RGB.txt")/255.)
colombi1_cmap.set_bad("gray") # color of missing pixels
colombi1_cmap.set_under("white") # color of background, necessary if you want to use
# this colormap directly with hp.mollview(m, cmap=colombi1_cmap)

############### Universal colormap
# setup linear colormap
from matplotlib.colors import ListedColormap
planck_freqmap_cmap = ListedColormap(np.loadtxt("../../data/Planck_FreqMap_RGB.txt")/255.)
planck_freqmap_cmap.set_bad("gray") # color of missing pixels
planck_freqmap_cmap.set_under("white") # color of background, necessary if you want to use

# setup nonlinear colormap
from matplotlib.colors import LinearSegmentedColormap
class PlanckUniversalColormap(LinearSegmentedColormap):
    name = "planckuniv"
    def __init__(self, cmap):
        self.cmap = cmap
        self.N = self.cmap.N

    def is_gray(self):
        return False

    def __call__(self, xi, alpha=1.0, **kw):
        x = xi * (1e7+1e3) - 1e3
        yi = self.modsinh(x)
        # range 0-1
Exemplo n.º 35
0
import numpy as np
import healpy as hp
import matplotlib.pyplot as plt
from scipy import special
from matplotlib.colors import ListedColormap
#matplotlib.use("agg")
colombi1_cmap = ListedColormap(np.loadtxt("Planck_Parchment_RGB.txt") / 255.)
colombi1_cmap.set_bad("gray")  # color of missing pixels
colombi1_cmap.set_under(
    "white")  # color of background, necessary if you want to use
# this colormap directly with hp.mollview(m, cmap=colombi1_cmap)
cmap_planck = colombi1_cmap

import matplotlib
matplotlib.use("Agg")
Nside = 512

cl = hp.fitsfunc.read_cl("cl.fits")

gauss_map = hp.synfast(cl[0],
                       512,
                       lmax=3 * Nside - 1,
                       fwhm=0,
                       pixwin=True,
                       verbose=False,
                       pol=False)

dpi = 800
fig_size_inch = 6, 4.5
fig = plt.figure(1, figsize=(6, 4.5))
Exemplo n.º 36
0
# M = np.sum(hits)
# print("total time samples: {}".format(M))

# Load input map
from s4cmb.input_sky import HealpixFitsMap
#Sky in
nside_out = 512
path_to_in = "/global/homes/e/elbouha/toast/examples/data/ffp10_lensed_scl_100_nside0512.fits"
sky_in = 1e6 * hp.fitsfunc.read_map(path_to_in, field=None, nest=True)

# Define Planck color map
from matplotlib.colors import ListedColormap

planck_cmap = ListedColormap(np.loadtxt("Planck_Parchment_RGB.txt") / 255.)
planck_cmap.set_bad("gray")
planck_cmap.set_under("white")
cmap = planck_cmap

# Plot the maps
# pl.figure(2,figsize=(8, 8))
xsize = 700
# hp.gnomview(np.log10(hits+1), rot=[0, -30], xsize=xsize, reso=6.9,
#             title='nhits', notext=True, cmap=cmap)
# hp.gnomview(1e-1*hits, rot=[0, -30], xsize=xsize, reso = 1,
#             title='hits', notext=True, cmap=cmap, nest=True)
# pl.show()
# hp.gnomview(cond, rot=[0, -30], xsize=xsize, reso = 1.5,
#             title='rcond', notext=True, cmap=cmap, nest=True)
# pl.show()
Exemplo n.º 37
0
def get_cmap_planck():
    """
    Function to get Planck colormap
    https://zonca.github.io/2013/09/Planck-CMB-map-at-high-resolution.html
    """

    cm_data = [[0., 0., 255.], [0., 2., 255.], [0., 5., 255.], [0., 8., 255.],
               [0., 10., 255.], [0., 13., 255.], [0., 16., 255.],
               [0., 18., 255.], [0., 21., 255.], [0., 24., 255.],
               [0., 26., 255.], [0., 29., 255.], [0., 32., 255.],
               [0., 34., 255.], [0., 37., 255.], [0., 40., 255.],
               [0., 42., 255.], [0., 45., 255.], [0., 48., 255.],
               [0., 50., 255.], [0., 53., 255.], [0., 56., 255.],
               [0., 58., 255.], [0., 61., 255.], [0., 64., 255.],
               [0., 66., 255.], [0., 69., 255.], [0., 72., 255.],
               [0., 74., 255.], [0., 77., 255.], [0., 80., 255.],
               [0., 82., 255.], [0., 85., 255.], [0., 88., 255.],
               [0., 90., 255.], [0., 93., 255.], [0., 96., 255.],
               [0., 98., 255.], [0., 101., 255.], [0., 104., 255.],
               [0., 106., 255.], [0., 109., 255.], [0., 112., 255.],
               [0., 114., 255.], [0., 117., 255.], [0., 119., 255.],
               [0., 122., 255.], [0., 124., 255.], [0., 127., 255.],
               [0., 129., 255.], [0., 132., 255.], [0., 134., 255.],
               [0., 137., 255.], [0., 139., 255.], [0., 142., 255.],
               [0., 144., 255.], [0., 147., 255.], [0., 150., 255.],
               [0., 152., 255.], [0., 155., 255.], [0., 157., 255.],
               [0., 160., 255.], [0., 162., 255.], [0., 165., 255.],
               [0., 167., 255.], [0., 170., 255.], [0., 172., 255.],
               [0., 175., 255.], [0., 177., 255.], [0., 180., 255.],
               [0., 182., 255.], [0., 185., 255.], [0., 188., 255.],
               [0., 190., 255.], [0., 193., 255.], [0., 195., 255.],
               [0., 198., 255.], [0., 200., 255.], [0., 203., 255.],
               [0., 205., 255.], [0., 208., 255.], [0., 210., 255.],
               [0., 213., 255.], [0., 215., 255.], [0., 218., 255.],
               [0., 221., 255.], [6., 221., 254.], [12., 221., 253.],
               [18., 222., 252.], [24., 222., 251.], [30., 222., 250.],
               [36., 223., 249.], [42., 223., 248.], [48., 224., 247.],
               [54., 224., 246.], [60., 224., 245.], [66., 225., 245.],
               [72., 225., 244.], [78., 225., 243.], [85., 226., 242.],
               [91., 226., 241.], [97., 227., 240.], [103., 227., 239.],
               [109., 227., 238.], [115., 228., 237.], [121., 228., 236.],
               [127., 229., 236.], [133., 229., 235.], [139., 229., 234.],
               [145., 230., 233.], [151., 230., 232.], [157., 230., 231.],
               [163., 231., 230.], [170., 231., 229.], [176., 232., 228.],
               [182., 232., 227.], [188., 232., 226.], [194., 233., 226.],
               [200., 233., 225.], [206., 233., 224.], [212., 234., 223.],
               [218., 234., 222.], [224., 235., 221.], [230., 235., 220.],
               [236., 235., 219.], [242., 236., 218.], [248., 236., 217.],
               [255., 237., 217.], [255., 235., 211.], [255., 234., 206.],
               [255., 233., 201.], [255., 231., 196.], [255., 230., 191.],
               [255., 229., 186.], [255., 227., 181.], [255., 226., 176.],
               [255., 225., 171.], [255., 223., 166.], [255., 222., 161.],
               [255., 221., 156.], [255., 219., 151.], [255., 218., 146.],
               [255., 217., 141.], [255., 215., 136.], [255., 214., 131.],
               [255., 213., 126.], [255., 211., 121.], [255., 210., 116.],
               [255., 209., 111.], [255., 207., 105.], [255., 206., 100.],
               [255., 205., 95.], [255., 203., 90.], [255., 202., 85.],
               [255., 201., 80.], [255., 199., 75.], [255., 198., 70.],
               [255., 197., 65.], [255., 195., 60.], [255., 194., 55.],
               [255., 193., 50.], [255., 191., 45.], [255., 190., 40.],
               [255., 189., 35.], [255., 187., 30.], [255., 186., 25.],
               [255., 185., 20.], [255., 183., 15.], [255., 182., 10.],
               [255., 181., 5.], [255., 180., 0.], [255., 177., 0.],
               [255., 175., 0.], [255., 172., 0.], [255., 170., 0.],
               [255., 167., 0.], [255., 165., 0.], [255., 162., 0.],
               [255., 160., 0.], [255., 157., 0.], [255., 155., 0.],
               [255., 152., 0.], [255., 150., 0.], [255., 147., 0.],
               [255., 145., 0.], [255., 142., 0.], [255., 140., 0.],
               [255., 137., 0.], [255., 135., 0.], [255., 132., 0.],
               [255., 130., 0.], [255., 127., 0.], [255., 125., 0.],
               [255., 122., 0.], [255., 120., 0.], [255., 117., 0.],
               [255., 115., 0.], [255., 112., 0.], [255., 110., 0.],
               [255., 107., 0.], [255., 105., 0.], [255., 102., 0.],
               [255., 100., 0.], [255., 97., 0.], [255., 95., 0.],
               [255., 92., 0.], [255., 90., 0.], [255., 87., 0.],
               [255., 85., 0.], [255., 82., 0.], [255., 80., 0.],
               [255., 77., 0.], [255., 75., 0.], [251., 73., 0.],
               [247., 71., 0.], [244., 69., 0.], [240., 68., 0.],
               [236., 66., 0.], [233., 64., 0.], [229., 62., 0.],
               [226., 61., 0.], [222., 59., 0.], [218., 57., 0.],
               [215., 55., 0.], [211., 54., 0.], [208., 52., 0.],
               [204., 50., 0.], [200., 48., 0.], [197., 47., 0.],
               [193., 45., 0.], [190., 43., 0.], [186., 41., 0.],
               [182., 40., 0.], [179., 38., 0.], [175., 36., 0.],
               [172., 34., 0.], [168., 33., 0.], [164., 31., 0.],
               [161., 29., 0.], [157., 27., 0.], [154., 26., 0.],
               [150., 24., 0.], [146., 22., 0.], [143., 20., 0.],
               [139., 19., 0.], [136., 17., 0.], [132., 15., 0.],
               [128., 13., 0.], [125., 12., 0.], [121., 10., 0.],
               [118., 8., 0.], [114., 6., 0.], [110., 5., 0.], [107., 3., 0.],
               [103., 1., 0.], [100., 0., 0.]]

    cmap = ListedColormap(np.array(cm_data) / 255.0, name='planck')
    # color of missing pixels
    cmap.set_bad('gray')
    # color of background, necessary if you want to use
    cmap.set_under('white')

    return cmap
Exemplo n.º 38
0
plt.close('all')
fig, ax = plt.subplots(1, 1)
ax.hist(phase_rot.ravel())
ax.set_title(
    'Gridded: Mask - 0 = Cloud,1 = 66% prob.\n Clear,2 = 95% prob. Clear,3 = 99% prob. Clear'
)

# In[112]:

plt.close('all')
from matplotlib.colors import Normalize
from numpy import ma
fig, ax = plt.subplots(1, 1, figsize=(12, 12))
colors = sns.color_palette('coolwarm')
pal = LinearSegmentedColormap.from_list('test', colors)
pal.set_bad('0.75')  #75% grey
pal.set_over('r')
pal.set_under('k')
vmin = -5.
vmax = 5.
ch29 = np.rot90(file_dict['ch29'], 2)
ch31 = np.rot90(file_dict['ch31'], 2)
the_norm = Normalize(vmin=vmin, vmax=vmax, clip=False)
tdiff = ch31 - ch29
tdiff = ma.array(tdiff, mask=np.isnan(tdiff))
CS = ax.imshow(tdiff, cmap=pal, norm=the_norm)
cax = plt.colorbar(CS, ax=ax, extend='both')
cax.set_label('ch31 - ch29 brightnes temp (K)')
ax.set_title('TB 11 micron - TB 8 micron')

# ### For next Tuesday: check in a notebook that
def publication_plot_old(save=False):
    from matplotlib.gridspec import GridSpec

    freqs = get_freqs(gag=True)
    N_samples, L, _ = freqs.shape

    #freqs_rm = get_freqs(gag=True, remove_rm=True)
    freqs_rm = freqs.copy()
    #for i in range(L):
    #    if i in GAG_RESISTANCE: continue
    #    freqs_rm[:, i-1] = 0.
    for i in range(L):
        for xi, ch in enumerate(ALPHABET[:20]):
            if str(i + 1) + ch in GAG_RESISTANCE_MUTS_SIMP: continue
            freqs_rm[:, i, xi] = 0.
    freqs = freqs.sum(axis=2)
    freqs.sort(axis=0)
    freqs = freqs[::-1]
    freqs_rm = freqs_rm.sum(axis=2)
    freqs_rm.sort(axis=0)
    freqs_rm = freqs_rm[::-1]

    #lanl_freqs = np.genfromtxt('lanl/gag_freqs_nowt_experienced.txt')
    lanl_freqs = np.genfromtxt('lanl/gag_freqs_nowt_naive.txt')
    lanl_freqs = lanl_freqs.reshape(-1, 500, 20)
    lanl_rm = lanl_freqs.copy()
    for i in range(L):
        for xi, ch in enumerate(ALPHABET[:20]):
            if str(i + 1) + ch in GAG_RESISTANCE_MUTS_SIMP: continue
            lanl_rm[:, i, xi] = 0.
    lanl_freqs = lanl_freqs.sum(axis=2)
    lanl_rm = lanl_rm.sum(axis=2)
    print lanl_freqs.shape, lanl_rm.shape
    print freqs.shape

    #fig = plt.figure(figsize=(24, 12))
    fig = plt.figure(figsize=(7.5, 4))
    fig.suptitle('Variant Frequencies in Gag', size=20)
    gs = GridSpec(3, 2, height_ratios=[10, 1, 10], width_ratios=[100, 1])
    ax1 = plt.subplot(gs[0, :-1])
    ax3 = plt.subplot(gs[1, :-1])
    ax2 = plt.subplot(gs[2, :-1])
    matplotlib.rc('font', size=24)
    matplotlib.rc('axes', linewidth=5)
    [ax.set_xlabel('Sequence Position') for ax in (ax1, ax2)]
    ax1.set_ylabel('Samples with variants')
    ax2.set_ylabel('LANL PI-naive\nsequences with variants')

    red_cmap = ListedColormap(['red'])
    black_cmap = ListedColormap(['black'])
    red_cmap.set_bad((0, 0, 0, 0))
    freqs_ma = np.ma.masked_where(freqs < 0.01, freqs)
    freqs_rm_ma = np.ma.masked_where(freqs_rm < 0.01, freqs_rm)
    plt1 = ax1.pcolor(freqs_ma, cmap=black_cmap, edgecolors='none')
    plt2 = ax1.pcolor(freqs_rm_ma,
                      cmap=red_cmap,
                      alpha=0.75,
                      edgecolors='none')
    plt3 = ax2.bar(np.arange(L),
                   lanl_freqs.sum(axis=0),
                   width=1,
                   fc='0.5',
                   ec='0.5')
    plt4 = ax2.bar(np.arange(L),
                   lanl_rm.sum(axis=0),
                   width=1,
                   fc='r',
                   ec='none',
                   alpha=0.75)

    plt.setp(ax1.get_xticklabels(), visible=False)
    quart1 = N_samples / 4.
    quart2 = lanl_freqs.shape[0] / 4.
    ax1.set_yticks(np.arange(0, N_samples + quart1, quart1))
    ax2.set_yticks(np.arange(0, N_samples + quart1, quart1))
    ax2.set_yticks(np.arange(0, lanl_freqs.shape[0] + quart2, quart2))
    quarter = N_samples / 4.
    #[ax.set_yticks(np.arange(0, N_samples + quarter, quarter)) for ax in (ax1, ax2)]
    [
        ax.set_yticklabels(['0%', '25%', '50%', '75%', '100%'])
        for ax in (ax1, ax2)
    ]
    ax1.set_ylim(0, 1.5 * N_samples)
    #ax2.set_ylim(0, 0.8*N_samples)
    ax2.set_ylim(0, 0.9 * lanl_freqs.shape[0])

    locs = [(132, 'MA'), (363, 'CA'), (377, 'p2'), (432, 'NC'), (448, 'p1'),
            (500, 'p6')]
    x_start = 0
    colors = ('#AAAAAA', '#EEEEEE')
    for i, (junc, name) in enumerate(locs):
        color = colors[i % 2]
        width = junc - x_start
        rect = Rectangle((x_start, 0), width, 1, edgecolor='None', color=color)
        ax3.add_patch(rect)
        ax3.text(x_start + width / 2., 1 / 2., name, ha='center', va='center')
        ax1.axvline(x_start, color='k', ls='--', lw=1.0)
        ax2.axvline(x_start, color='k', ls='--', lw=1.0)
        x_start = junc
    ax3.set_xlim(0, L)
    plt.setp(ax3.get_xticklabels(), visible=False)
    plt.setp(ax3.get_yticklabels(), visible=False)
    [
        ax.tick_params(top=False, left=False, right=False, bottom=False)
        for ax in (ax1, ax2, ax3)
    ]

    ax2.invert_yaxis()

    fig.subplots_adjust(hspace=0.,
                        wspace=0.02,
                        left=0.08,
                        right=0.95,
                        top=0.95,
                        bottom=0.06)
    if not save:
        plt.show()
    else:
        fig.savefig('PUB_VARIANTS_PLOT.tiff', dpi=600)
Exemplo n.º 40
0
import numpy as np
import matplotlib.cm as cm
from matplotlib.colors import ListedColormap

############### CMB colormap
from matplotlib.colors import ListedColormap
colombi1_cmap = ListedColormap(np.loadtxt("Planck_Parchment_RGB.txt") / 255.)
colombi1_cmap.set_bad("gray")  # color of missing pixels
colombi1_cmap.set_under(
    "gray")  # color of background, necessary if you want to use
# this colormap directly with hp.mollview(m, cmap=colombi1_cmap)

############### CMB colormap
planck_parchment_cmap = ListedColormap(
    np.loadtxt("Planck_Parchment_RGB.txt") / 255.)
#planck_parchment_cmap.set_bad("gray") # color of missing pixels
planck_parchment_cmap.set_bad("lightslategray")  # color of missing pixels
#planck_parchment_cmap.set_under("white") # color of background, necessary if you want to use
# this colormap directly with hp.mollview(m, cmap=planck_parchment_cmap)

planck_grey_cmap = cm.get_cmap('gray')

############### Universal colormap
# setup linear colormap
planck_freqmap_cmap = ListedColormap(
    np.loadtxt("Planck_FreqMap_RGB.txt") / 255.)
planck_freqmap_cmap.set_bad("gray")  # color of missing pixels
planck_freqmap_cmap.set_under(
    "white")  # color of background, necessary if you want to use

# setup nonlinear colormap
Exemplo n.º 41
0
mag_1 = mag.format(band_1.upper())
mag_2 = mag.format(band_2.upper())
mag_err_1 = mag_err.format(band_1.upper())
mag_err_2 = mag_err.format(band_2.upper())
mag_dered_1 = mag_dered.format(band_1.upper())
mag_dered_2 = mag_dered.format(band_2.upper())

################################################################################

# Set colors
cmap_gray = matplotlib.cm.Greys
cmap_color = matplotlib.cm.viridis
c_color = cmap_color(0.25)
p_color = cmap_color(1.0)
cmap_gray_mask = ListedColormap(cmap_gray(np.linspace(0.1, 1.0, 100)))
cmap_gray_mask.set_bad('white')

################################################################################


def analysis(ra, dec, mod, mc_source_id):
    """Analyze a candidate"""

    pix_nside_select = ugali.utils.healpix.angToPix(nside, ra, dec)
    ra_select, dec_select = ugali.utils.healpix.pixToAng(
        nside, pix_nside_select)
    pix_nside_neighbors = np.concatenate([[pix_nside_select],
                                          healpy.get_all_neighbours(
                                              nside, pix_nside_select)])

    # Construct data
Exemplo n.º 42
0
    [231, 255, 0, 255],
    [231, 66, 0, 255],
    [226, 143, 122, 255],
    [228, 0, 145, 255],
    [226, 164, 43, 255],
    [255, 0, 0, 255],
    [255, 151, 0, 255],
    [206, 73, 255, 255],
    [142, 5, 10, 255],
    [18, 95, 0, 255],
    [8, 212, 125, 255],
    [0, 255, 59, 255],
]) / 255.1
from matplotlib.colors import ListedColormap
mycmap = ListedColormap(colorlist[:, :3], 'segmentation')
mycmap.set_bad(color=(0, 0, 0, 0))

vols = config.vols.keys()


class GetDices(object):
    def __init__(self, dir, title):
        self.dir = dir
        self.title = title
        self.dices = {'title': self.title}
        self.nsample = 0

    def __call__(self, args, dirnames, fnames):
        dir = self.dir
        file_dice = args  #args.pop('file_dice','dice_labels.txt')
        if file_dice in fnames:
Exemplo n.º 43
0
from setup_matplotlib import *
import healpy as hp

m = hp.ma(hp.read_map("../../data/wmap_band_iqumap_r9_7yr_W_v4.fits", 0)) * 1e3 # muK
nside = hp.npix2nside(len(m))

# setup colormap
from matplotlib.colors import ListedColormap
colombi1_cmap = ListedColormap(np.loadtxt("../../data/parchment1.dat")/255.)
colombi1_cmap.set_bad("gray") # color of missing pixels

# using directly matplotlib instead of mollview has higher
# quality output, I plan to merge this into healpy

# ratio is always 1/2
xsize = 2000
ysize = xsize/2.

unit = r"$\mathrm{\mu K}$"

# this is the mollview min and max
vmin = -1e3; vmax = 1e3

theta = np.linspace(np.pi, 0, ysize)
phi   = np.linspace(-np.pi, np.pi, xsize)
longitude = np.radians(np.linspace(-180, 180, xsize))
latitude = np.radians(np.linspace(-90, 90, ysize))

# project the map to a rectangular matrix xsize x ysize
PHI, THETA = np.meshgrid(phi, theta)
grid_pix = hp.ang2pix(nside, THETA, PHI)
Exemplo n.º 44
0
        for i, r in enumerate(greens_half + [1] + list(reversed(greens_half)))
    ]),
    'blue':
    tuple([(0.1 * i, r, r) for i, r in enumerate(reversed(reds))])
}
CMAP_CONTINUOUS_ASSOCIATION = LinearSegmentedColormap('association', colordict)
CMAP_CONTINUOUS_ASSOCIATION.set_bad(C_BAD)

# Categorical colormap
CMAP_CATEGORICAL_PAIRED = Paired
CMAP_CATEGORICAL_PAIRED.set_bad(C_BAD)

CMAP_CATEGORICAL_SET3 = Set3
CMAP_CATEGORICAL_SET3.set_bad(C_BAD)

CMAP_CATEGORICAL_TAB20 = tab20
CMAP_CATEGORICAL_TAB20.set_bad(C_BAD)

CMAP_CATEGORICAL_TAB20B = tab20b
CMAP_CATEGORICAL_TAB20B.set_bad(C_BAD)

CMAP_CATEGORICAL_TAB20C = tab20c
CMAP_CATEGORICAL_TAB20C.set_bad(C_BAD)

# Binary colormap
CMAP_BINARY_WB = ListedColormap(['#E8E8E8', '#080808'])
CMAP_BINARY_WB.set_bad(C_BAD)

CMAP_BINARY_RE = ListedColormap(['#F80088', '#20D9BA'])
CMAP_BINARY_RE.set_bad(C_BAD)
Exemplo n.º 45
0
    def full_scan(self):
        '''
        creates a heat map of detection efficiency for every
        point in MIDAS test stand scan
        '''
        # magma_r.colors gives us the colormap values below
        reversed_magma = np.array(
            [[0.987053, 0.991438, 0.749504, 1.00000],
             [0.995131, 0.827052, 0.585701, 1.00000],
             [0.996341, 0.660969, 0.451160, 1.00000],
             [0.979645, 0.491014, 0.367783, 1.00000],
             [0.913354, 0.330052, 0.382563, 1.00000],
             [0.786212, 0.241514, 0.450184, 1.00000],
             [0.639216, 0.189921, 0.494150, 1.00000],
             [0.494258, 0.141462, 0.507988, 1.00000],
             [0.347636, 0.0829460, 0.494121, 1.00000],
             [0.198177, 0.0638620, 0.404009, 1.00000],
             [0.0697640, 0.0497260, 0.193735, 1.00000],
             [0.00146200, 0.000466000, 0.013866, 1.00000]])

        # using the magma_r.color values we are able to create the
        # whole color map using ListedColormap()
        newcmp = ListedColormap(reversed_magma)

        # we then set nan values to show up as 'white'
        # which we will use to help us see errors
        newcmp.set_bad(color='w')

        def calc_cutoff(lst):
            '''
            calculates the single PE ADC cutoff value from the minimum pulse
            histogram bar values. specifically, it picks the ADC value
            directly between the pedastal and single PE peak.
            '''
            # assumes pedestal is tallest point on minimum
            # pulse histogram
            pedastal = max(lst)

            # assumes single PE peak is second tallest
            # point on minimum pulse historgam
            ind = lst.index(pedastal)
            lst.pop(ind)
            pe_peak = max(lst)

            # if the single PE peak is too close to the
            # pedestal it recalculates the single PE peak
            while pe_peak > pedastal * 0.98:
                ind = lst.index(pe_peak)
                lst.pop(ind)  #loop this?
                pe_peak = max(lst)

            # calculates the cutoff to be the point between
            # the single PE peak and the pedastal
            cutoff = (pedastal + pe_peak) / 2
            return cutoff

        def position_vals():
            '''
            creates a list of the xy position values
            at each event # using MOTO bank if motors
            are running, and the SCAN bank if not

            '''
            # open the hdf5 file for reading
            hdf5_file = h5py.File(
                ''.join([self.file_name, 'ScanEvents', '.hdf5']), 'r')

            # save the name of all the groups (events)
            # stored in the hdf5 file
            keys = hdf5_file.keys()

            # since the groups are python dictorinary
            # keys they are not sorted in the order that they
            # were stored so they need to be formatted
            # and then properly stored
            keys = list(map(int, list(keys)))
            keys.sort()

            # make a list containing all the groups in the file
            groups = []
            for key in keys:
                groups.append(hdf5_file[str(key)])

            # initialize the list to store all the
            # position values from the scan
            scan_vals = []

            # loop through each group and store the
            # position data in scan_vals
            #
            # when the motors are not running this code
            # uses the SCAN bank to simulate xy data that
            # would normally come from the MOTO bank
            for group in groups:
                for data_set_name in group.keys():
                    if data_set_name == "ch0":
                        data_set = group[data_set_name].value
                        dset = group[data_set_name]

                        moto_exists = dset.attrs["motors running"]

                        if moto_exists:
                            pos = dset.attrs["moto position"]
                        else:
                            pos = dset.attrs["scan position"]

                        scan_vals.append(pos)

            return moto_exists, scan_vals

        def detection_eff(scan_vals):
            '''
            calculates the detection efficiency at each xy position
            and creates a list of all the xy positions without duplicates
            '''

            # initialize counter
            i = 0

            # initialize list to store xy positions
            x_pos = []
            y_pos = []

            # initialize list to save xy position and
            # minimum pulse values associated with that position
            collective = []

            # initialize list to use as temporary storage in loop
            temp_lst = []

            # if the motors are running use real xy position values
            #
            # for each position, associate a list of all the
            # minimum pulse values at that position
            if moto_exists:
                old_pos = [0, 0]
                for pos in scan_vals:
                    if pos[0] == old_pos[0] and pos[1] == old_pos[1]:
                        temp_lst.append(min_pulses[i])

                    else:
                        x_pos.append(old_pos[0])
                        y_pos.append(old_pos[1])

                        collective.append([old_pos, temp_lst])
                        temp_lst = []
                        temp_lst.append(min_pulses[i])

                    i += 1
                    old_pos = pos

            # if motos aren't running, use simulated xy data from SCAN bank
            #
            # for each position, associate a list of all the
            # minimum pulse values at that position
            else:
                old_pos = 0
                for pos in scan_vals:
                    if pos == old_pos:
                        temp_lst.append(min_pulses[i])
                    else:
                        x_pos.append(old_pos)
                        y_pos.append(old_pos)
                        collective.append([old_pos, temp_lst])
                        temp_lst = []
                        temp_lst.append(min_pulses[i])

                    i += 1
                    old_pos = pos

                x_pos = list(map(lambda x: x // 10, x_pos))
                y_pos = list(map(lambda y: y % 10, y_pos))

            # initilize list of detection efficiency at each point
            d_eff_list = []

            # for each xy position, calculate the pourcentage of
            # associated minimum pulse values which lie below
            # the cutoff ADC val (which mean a PE was seen by the PMT)
            # then save these pourcentages in d_eff_list
            for i in range(len(collective)):
                loc = collective[i][0]
                pulse_list = collective[i][1]
                hits = 0
                numof_pulses = len(pulse_list)
                for pulse in pulse_list:
                    if pulse < cutoff:
                        hits += 1

                hits1 = float(hits)
                pulses = float(numof_pulses)
                if pulses > 0:
                    d_eff = hits1 / pulses
                else:
                    d_eff = 0.0
                d_eff_list.append(d_eff)

            return d_eff_list, x_pos, y_pos

        def plotting():
            '''
            using the list of detection efficincies and the xy positions
            this function plots a heat map of the detection efficiencies
            on the xy positions of the scan
            '''
            side = int(np.sqrt(len(d_eff_l)))
            Z = np.resize(d_eff_l, (side, side))

            # plots heat map for detection efficiency and saves photo of it
            # under the midas2hdf5 folder
            plt.figure(figsize=(5, 5))
            plt.imshow(Z,
                       cmap=newcmp,
                       interpolation='nearest',
                       extent=[min(x), max(x), min(y),
                               max(y)])
            plt.colorbar()
            plt.xlabel('X positon [m]')
            plt.ylabel('Y positon [m]')
            plt.title(''.join([self.file_name, ' detection efficency']))
            plt.savefig(''.join([self.file_name, '_detectionEfficency']))

        # opens the hdf5 file for reading
        hdf5_file = h5py.File(''.join([self.file_name, 'ScanEvents', '.hdf5']),
                              'r')

        # print the progress of the program
        print("progress:")

        y_hist, min_pulses = self.min_vals_histo(False)
        cutoff = calc_cutoff(list(y_hist))
        print("1/4")

        moto_exists, scan_lst = position_vals()
        print("2/4")

        d_eff_l, x, y = detection_eff(scan_lst)
        # closes the hdf5 file for reading
        hdf5_file.close()
        print("3/4")

        # setting values of exactly zero equal to nan
        # so they show up as white on the plot
        for i in range(len(d_eff_l)):
            if d_eff_l[i] == 0.0:
                d_eff_l[i] = np.nan

        plotting()
        print("4/4 \nplot saved in midas2hdf5 folder")
Exemplo n.º 46
0
import numpy as np
import matplotlib.cm as cm
from matplotlib.colors import ListedColormap

############### CMB colormap
from matplotlib.colors import ListedColormap
colombi1_cmap = ListedColormap(np.loadtxt("Planck_Parchment_RGB.txt")/255.)
colombi1_cmap.set_bad("gray") # color of missing pixels
colombi1_cmap.set_under("gray") # color of background, necessary if you want to use
# this colormap directly with hp.mollview(m, cmap=colombi1_cmap)


############### CMB colormap
planck_parchment_cmap = ListedColormap(np.loadtxt("Planck_Parchment_RGB.txt")/255.)
#planck_parchment_cmap.set_bad("gray") # color of missing pixels
planck_parchment_cmap.set_bad("lightslategray") # color of missing pixels
#planck_parchment_cmap.set_under("white") # color of background, necessary if you want to use
# this colormap directly with hp.mollview(m, cmap=planck_parchment_cmap)

planck_grey_cmap = cm.get_cmap('gray')

############### Universal colormap
# setup linear colormap
planck_freqmap_cmap = ListedColormap(np.loadtxt("Planck_FreqMap_RGB.txt")/255.)
planck_freqmap_cmap.set_bad("gray") # color of missing pixels
planck_freqmap_cmap.set_under("white") # color of background, necessary if you want to use

# setup nonlinear colormap
from matplotlib.colors import LinearSegmentedColormap
class PlanckUniversalColormap(LinearSegmentedColormap):
    name = "planckuniv"