Example #1
0
    def subplot(self, go=DEFAULT_GRAPHIC_OPTS, **nx_opts):

        clr = get_cmap('tab10')

        nl_tot = set([b.id for b in self.downloaded_buildings])
        ccs = [nx.subgraph(self.g, n) for n in nx.connected_components(self.g)]

        for idx, sgee in enumerate(ccs):
            eggos = list(sgee.edges)
            color_component = clr(idx / 10 + 0.02)

            nl_this = list(nl_tot.intersection(set(sgee.nodes)))

            nxo = dict(pos=nx.get_node_attributes(sgee, 'pos'),
                       node_size=go['node_size'],
                       font_size=go['font_size'],
                       edgelist=eggos,
                       nodelist=[],
                       edge_color=[color_component] * len(sgee.edges),
                       cmap=colors.Colormap('hot'))
            nxo.update(nx_opts)

            nx.draw_networkx(sgee, **nxo, with_labels=False)

            # bigger building nodes
            nx.draw_networkx_nodes(sgee, nx.get_node_attributes(sgee, 'pos'), nl_this, go['bnode_size'],
                                   node_color=[color_component] * len(nl_this), **nx_opts)

            # white center
            nx.draw_networkx_nodes(sgee, nx.get_node_attributes(sgee, 'pos'), nl_this, go['bnode_size']*0.5,
                                   node_color='#ffffff', **nx_opts)

        _paint_map(self.box, plt, go, self.logger)
        plt.axis('equal')
        plt.show()
Example #2
0
def clust(elect_coords, n_clusts, iters, init_clusts):

    # Load resultant coordinates from Hough circles transform
    #coords = scipy.io.loadmat(elect_coords);
    #dat = coords.get('elect_coords');
    dat = elect_coords

    # Configure Kmeans
    cluster = sklearn.cluster.KMeans()
    cluster.n_clusters = n_clusts
    cluster.init = 'k-means++'
    cluster.max_iter = iters
    cluster.verbose = 0
    cluster.n_init = init_clusts
    cluster.fit(dat)

    # Grab vector for plotting each dimension
    x = list(cluster.cluster_centers_[:, 0])
    y = list(cluster.cluster_centers_[:, 1])
    z = list(cluster.cluster_centers_[:, 2])
    c = list(cluster.labels_)

    scipy.io.savemat('k_labels.mat', {'labels': cluster.labels_})
    scipy.io.savemat('k_coords.mat', {'coords': cluster.cluster_centers_})

    # plot the results of kmeans
    cmap = colors.Colormap('hot')
    norm = colors.Normalize(vmin=1, vmax=10)
    s = 64
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    Axes3D.scatter3D(ax, x, y, z, s=s)
    plt.show(fig)

    return cluster.cluster_centers_, cluster.labels_
Example #3
0
 def _measure_noise(self):
     filepointer = self._gen_filepointer()
     try:
         depth_im_table = np.load(self.data_path + 'depth_ims_tf_table_' +
                                  filepointer + '.npz')['arr_0'][self.array]
     except:
         print("File not available.")
         return None, None
     self.coords = []
     orig_data = depth_im_table[:, :, 0]
     data = self._fix_tilt(orig_data)
     im = Image.fromarray(self._scale(data))
     self.fig, ax = plt.subplots(1)
     ax.imshow(im, cmap=col.Colormap('Greens'))
     self.cid = self.fig.canvas.mpl_connect('button_press_event',
                                            self._onclick)
     plt.show()
     try:
         x_1 = self.coords[0][0]
         x_2 = self.coords[1][0]
         y_1 = self.coords[0][1]
         y_2 = self.coords[1][1]
     except:
         print("Not enough values to get rectangle")
         return None, None
     if self.testing:
         fig, ax = plt.subplots(1)
         ax.imshow(im, cmap=col.Colormap('Greens'))
         rect = patches.Rectangle((x_1, y_1), x_2 - x_1, y_2 - y_1)
         ax.add_patch(rect)
         plt.show()
     removed = np.array([])
     removed_without_tilt = np.array([])
     for x_cnt, row in enumerate(data):
         for y_cnt, point in enumerate(row):
             if x_1 <= y_cnt <= x_2 and y_1 <= x_cnt <= y_2:
                 continue
             else:
                 removed = np.append(removed, point)
                 removed_without_tilt = np.append(removed_without_tilt,
                                                  orig_data[x_cnt, y_cnt])
     print("Picture background std:", removed.std())
     return [removed.mean(), removed_without_tilt.mean()
             ], [removed.std(), removed_without_tilt.std()]
Example #4
0
    def draw_weight(self,
                    neuron_list=None,
                    pre_list=None,
                    post_list=None,
                    flag=None,
                    title=None,
                    xlabel=None,
                    ylabel=None,
                    vmin=None,
                    vmax=None,
                    color_bar=True,
                    color_bar_label=None,
                    x_stick_labels=None):
        X = []
        if neuron_list is not None:
            pre_list = neuron_list
            post_list = neuron_list
        if flag is not None:
            pre_list = self.neuron_flag_dict[flag]
            post_list = self.neuron_flag_dict[flag]

        for neuron_id1 in post_list:
            temp = []
            for neuron_id2 in pre_list:
                if neuron_id2 == neuron_id1:
                    n = 0
                else:
                    try:
                        n = min(
                            self.neuron_list[neuron_id1].
                            get_synaps_correspondence()
                            [neuron_id2].get_weight(), 30)
                    except KeyError:
                        n = 0
                temp.append(n)
            X.append(temp)
        fig = plt.figure()
        ax = fig.add_subplot(111)
        cmap = clr.Colormap("lo", 100)
        img = ax.imshow(X, interpolation="nearest", vmax=vmax, vmin=vmin)
        if color_bar:
            color_bar = plt.colorbar(img)
            if color_bar_label is not None:
                color_bar.set_label(color_bar_label)
        if title is not None:
            ax.set_title(title)
        if xlabel is not None:
            ax.set_xlabel(xlabel)
        if ylabel is not None:
            ax.set_ylabel(ylabel)
        if x_stick_labels is not None:
            ax.xaxis.set_ticklabels(x_stick_labels)
        plt.show()
Example #5
0
def plotIndFits(params, lunarDays, cpue, sizes, error):
    fig2 = plt.figure(figsize=(10, 10))
    index = np.linspace(0, 29.5, round(29.5 * 10))
    c = 2 * np.pi / 29.5
    cov = 0
    func = params[0] * np.cos((index + params[1]) * 2 * np.pi / 29.5)
    func2 = params[0] * c * np.sin(c * (params[1] + index)) / (
        c**2 + .36) + .6 * params[0] * np.cos(c * (params[1] + index)) / (
            c**2 + .36) + params[2] * np.exp(-.6 * index)
    func3 = params[0] * c * np.sin(
        c *
        (params[1] + (index + 295))) / (c**2 + .36) + .6 * params[0] * np.cos(
            c *
            (params[1] +
             (index + 295))) / (c**2 + .36) + params[2] * np.exp(-.6 *
                                                                 (index + 295))
    print((29.5 * 10 - (np.argmax(func3) + 1)) / 10,
          ((1 + func3[np.argmax(func3)]) -
           (1 - func3[np.argmax(func3)])) / (1 - func3[np.argmax(func3)]))
    d0 = c * np.sin(c * (params[1] + index)) / (c**2 + .36) + .6 * np.cos(
        c * (params[1] + index)) / (c**2 + .36)
    d1 = params[0] * c * np.cos(
        c * (params[1] + index)) / (c**2 + .36) - .6 * params[0] * np.sin(
            c * (params[1] + index)) / (c**2 + .36)
    d2 = np.exp(-.6 * index)
    errFunc = np.sqrt(error[0]**2 * d0**2 + (error[1] / 1)**2 * d1**2 +
                      error[2]**2 * d2**2 + 2 * cov * d0 * d1 + 1.2)
    errFuncTop = func2 + errFunc
    errFuncBottom = func2 - errFunc
    plt.plot(index, func2, label='CPUE best fit model', linewidth='3')
    plt.plot(index,
             func,
             '--',
             color='black',
             label='Influx rate of spawning squid',
             linewidth='3')
    #plt.plot(index,errFuncTop)
    #plt.plot(index,errFuncBottom)
    colorful = colors.Colormap('Greys')
    plt.fill_between(index, errFuncBottom, errFuncTop, alpha=.3)
    sns.scatterplot(lunarDays, cpue, s=sizes, palette=colorful)
    plt.xlabel('Days from Lunar Peak')
    plt.ylabel('Seasonal Adjusted CPUE')
    plt.legend()
    plt.show()
    fig2.savefig("AllSquid.tiff")
"""シンプルな人工データに対する回帰問題(普通の回帰と二値分類)
"""
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm
from matplotlib import colors
from sklearn.cross_validation import train_test_split

import gbdtree as gb

color_map = colors.Colormap("Set1")


def generate_continuous_data(true_function="default",
                             x_scale=2.,
                             num_samples=100,
                             noise_scale=.2,
                             seed=71):
    """
    連続関数に対する人工データを作成
    :param () => | str true_function:
    :param float x_scale:
    :param int num_samples:
    :param float noise_scale:
    :param int seed:
    :return: 入力変数 x, その正解ラベル t の tuple
    :rtype (np.ndarray, np.ndarray)
    """
    np.random.seed(seed)
    if true_function == "default":
        true_function = np.sin
Example #7
0
        files: List[str]) -> Generator[List[List[float]], None, None]:
    streamList = _.map(lambda f: fileStream(f), files)

    for stream in streamList:
        while stream:
            s = next(stream, None)
            if s == None:
                break
            else:
                yield s

    return None


norm = colors.LogNorm(1, 500, clip=True)
cmap = colors.Colormap('gray_r').set_under(color=[0, 0, 0], alpha=None)
# color_map converts count to RGB
# color_map is very slow if used on python list
color_map = ScalarMappable(norm=norm, cmap=cmap).to_rgba


def getShapshot(shader, color_map):
    # map the count to RGB colors
    # this is necessary for imshow to work
    return _.map(lambda i: color_map(i), shader.getAgg('cnt'))


def writeImg(colorData):
    # plot the count matrix as an image
    f = imshow(colorData)
    axis('off')
Example #8
0
""" Función Gaussiana 2D moviendose en la diagonal usando contour pltos. """

import numpy as np
import matplotlib.animation as animation
import matplotlib.pyplot as plt
import matplotlib.colors as colors

# Parameters
twidth = 20
width = 20
high = 20
Nt = 50
colormap = colors.Colormap("whiteminima")
colormap.set_under(color = 'w')

def Gaussian(t,x,y,A = 1, sig = 1, c = 1):
    '''
        Computes Gaussian function
    
    '''
    
    x2 = (x - (np.sqrt(2)/2)*c*t)
    y2 = (y - (np.sqrt(2)/2)*c*t)
    return A*np.exp(-(x2**2 + y2**2)/(sig*np.sqrt(2))**2)

t = np.linspace(-twidth/2,twidth/2, Nt)
x = np.linspace(-width/2, width/2, 60)
y = np.linspace(-high/2, high/2, 60)

X, Y = np.meshgrid(x,y)
Example #9
0
def triangle_plot( chain, axis_labels=None, fname = None, nbins=40, filled=True, cmap="Blues", norm = None, truths = None,\
                         burnin=None, fontsize=20 , tickfontsize=15, nticks=4, linewidth=1.,wspace=0.5,hspace=0.5):
    """Plot a corner plot from an MCMC chain. the shape of the chain array should be (nwalkers*nsamples, ndim + 1). The extra column is for the walker ID 
    number (i.e. if you have 20 walkers the id numbers are np.arange(20)). Note the walker ID's are never used, theyre only assumed to be there because 
    of the way I write MCMC chains to file."""

    major_formatter = FuncFormatter(my_formatter)
    nwalkers = len(np.unique(chain[:, 0]))

    if burnin is not None:
        traces = chain[nwalkers * burnin:, 1:].T
    else:
        traces = chain[:, 1:].T

    if axis_labels is None:
        axis_labels = [''] * len(traces)

    #Defines the widths of the plots in inches
    plot_width = 15.
    plot_height = 15.
    axis_space = 0.05

    if truths != None and (len(truths) != len(traces)):
        print >> stderr, "ERROR: There must be the same number of true values as traces"

    num_samples = min([len(trace) for trace in traces])
    n_traces = len(traces)

    #Set up the figure
    fig = plt.figure(num=None, figsize=(plot_height, plot_width))

    dim = 2 * n_traces - 1

    gs = gridspec.GridSpec(dim + 1, dim + 1)
    gs.update(wspace=wspace, hspace=hspace)

    hist_2d_axes = {}

    #Create axes for 2D histograms
    for x_pos in xrange(n_traces - 1):
        for y_pos in range(n_traces - 1 - x_pos):
            x_var = x_pos
            y_var = n_traces - 1 - y_pos

            hist_2d_axes[(x_var, y_var)] = fig.add_subplot( \
                                           gs[ -1-(2*y_pos):-1-(2*y_pos), \
                                               2*x_pos:(2*x_pos+2) ] )
            hist_2d_axes[(x_var,
                          y_var)].xaxis.set_major_formatter(major_formatter)
            hist_2d_axes[(x_var,
                          y_var)].yaxis.set_major_formatter(major_formatter)

    #Create axes for 1D histograms
    hist_1d_axes = {}
    for var in xrange(n_traces - 1):
        hist_1d_axes[var] = fig.add_subplot(gs[(2 * var):(2 * var + 2),
                                               2 * var:(2 * var + 2)])
        hist_1d_axes[var].xaxis.set_major_formatter(major_formatter)
        hist_1d_axes[var].yaxis.set_major_formatter(major_formatter)
    hist_1d_axes[n_traces - 1] = fig.add_subplot(gs[-2:, -2:])
    hist_1d_axes[n_traces - 1].xaxis.set_major_formatter(major_formatter)
    hist_1d_axes[n_traces - 1].yaxis.set_major_formatter(major_formatter)

    #Remove the ticks from the axes which don't need them
    for x_var in xrange(n_traces - 1):
        for y_var in xrange(1, n_traces - 1):
            try:
                hist_2d_axes[(x_var, y_var)].xaxis.set_visible(False)
            except KeyError:
                continue
    for var in xrange(n_traces - 1):
        hist_1d_axes[var].set_xticklabels([])
        hist_1d_axes[var].xaxis.set_major_locator(MaxNLocator(nticks))
        hist_1d_axes[var].yaxis.set_visible(False)

    for y_var in xrange(1, n_traces):
        for x_var in xrange(1, n_traces - 1):
            try:
                hist_2d_axes[(x_var, y_var)].yaxis.set_visible(False)
            except KeyError:
                continue

    #Do the plotting
    #Firstly make the 1D histograms
    vals, walls = np.histogram(traces[-1][:num_samples],
                               bins=nbins,
                               normed=True)

    xplot = np.zeros(nbins * 2 + 2)
    yplot = np.zeros(nbins * 2 + 2)
    for i in xrange(1, nbins * 2 + 1):
        xplot[i] = walls[(i - 1) / 2]
        yplot[i] = vals[(i - 2) / 2]

    xplot[0] = walls[0]
    xplot[-1] = walls[-1]
    yplot[0] = yplot[1]
    yplot[-1] = yplot[-2]

    Cmap = colors.Colormap(cmap)
    cNorm = colors.Normalize(vmin=0., vmax=1.)
    scalarMap = cm.ScalarMappable(norm=cNorm, cmap=cmap)
    cVal = scalarMap.to_rgba(0.65)

    #this one's special, so do it on it's own
    hist_1d_axes[n_traces - 1].plot(xplot, yplot, color='k', lw=linewidth)
    if filled:
        hist_1d_axes[n_traces - 1].fill_between(xplot, yplot, color=cVal)
    hist_1d_axes[n_traces - 1].set_xlim(walls[0], walls[-1])
    hist_1d_axes[n_traces - 1].set_xlabel(axis_labels[-1], fontsize=fontsize)
    hist_1d_axes[n_traces - 1].tick_params(labelsize=tickfontsize)
    hist_1d_axes[n_traces - 1].xaxis.set_major_locator(MaxNLocator(nticks))
    hist_1d_axes[n_traces - 1].yaxis.set_visible(False)
    plt.setp(hist_1d_axes[n_traces - 1].xaxis.get_majorticklabels(),
             rotation=45)
    if truths is not None:
        xlo, xhi = hist_1d_axes[n_traces - 1].get_xlim()
        if truths[n_traces - 1] < xlo:
            dx = xlo - truths[n_traces - 1]
            hist_1d_axes[n_traces - 1].set_xlim(
                (xlo - dx - 0.05 * (xhi - xlo), xhi))
        elif truths[n_traces - 1] > xhi:
            dx = truths[n_traces - 1] - xhi
            hist_1d_axes[n_traces - 1].set_xlim(
                (xlo, xhi + dx + 0.05 * (xhi - xlo)))
        hist_1d_axes[n_traces - 1].axvline(truths[n_traces - 1],
                                           ls='--',
                                           c='k')

    #Now Make the 2D histograms
    for x_var in xrange(n_traces):
        for y_var in xrange(n_traces):
            try:
                if norm == 'log':
                    H, y_edges, x_edges = np.histogram2d( traces[y_var][:num_samples], traces[x_var][:num_samples],\
                                                           bins = nbins, norm = LogNorm() )
                else:
                    H, y_edges, x_edges = np.histogram2d( traces[y_var][:num_samples], traces[x_var][:num_samples],\
                                                           bins = nbins )
                confidence_2d(traces[x_var][:num_samples],traces[y_var][:num_samples],ax=hist_2d_axes[(x_var,y_var)],\
                    nbins=nbins,intervals=None,linecolor='0.5',filled=filled,cmap=cmap,linewidth=linewidth)
                if truths is not None:
                    xlo, xhi = hist_2d_axes[(x_var, y_var)].get_xlim()
                    ylo, yhi = hist_2d_axes[(x_var, y_var)].get_ylim()
                    if truths[x_var] < xlo:
                        dx = xlo - truths[x_var]
                        hist_2d_axes[(x_var, y_var)].set_xlim(
                            (xlo - dx - 0.05 * (xhi - xlo), xhi))
                    elif truths[x_var] > xhi:
                        dx = truths[x_var] - xhi
                        hist_2d_axes[(x_var, y_var)].set_xlim(
                            (xlo, xhi + dx + 0.05 * (xhi - xlo)))
                    if truths[y_var] < ylo:
                        dy = ylo - truths[y_var]
                        hist_2d_axes[(x_var, y_var)].set_ylim(
                            (ylo - dy - 0.05 * (yhi - ylo), yhi))
                    elif truths[y_var] < ylo:
                        dy = truths[y_var] - yhi
                        hist_2d_axes[(x_var, y_var)].set_ylim(
                            (ylo, yhi + dy + 0.05 * (yhi - ylo)))
                    #TODO: deal with the pesky case of a prior edge
                    hist_2d_axes[(x_var, y_var)].plot(truths[x_var],
                                                      truths[y_var],
                                                      '*',
                                                      color='k',
                                                      markersize=10)
            except KeyError:
                pass
        if x_var < n_traces - 1:
            vals, walls = np.histogram(traces[x_var][:num_samples],
                                       bins=nbins,
                                       normed=True)

            xplot = np.zeros(nbins * 2 + 2)
            yplot = np.zeros(nbins * 2 + 2)
            for i in xrange(1, nbins * 2 + 1):
                xplot[i] = walls[(i - 1) / 2]
                yplot[i] = vals[(i - 2) / 2]

            xplot[0] = walls[0]
            xplot[-1] = walls[-1]
            yplot[0] = yplot[1]
            yplot[-1] = yplot[-2]

            hist_1d_axes[x_var].plot(xplot, yplot, color='k', lw=linewidth)
            if filled:
                hist_1d_axes[x_var].fill_between(xplot, yplot, color=cVal)
            hist_1d_axes[x_var].set_xlim(x_edges[0], x_edges[-1])
            if truths is not None:
                xlo, xhi = hist_1d_axes[x_var].get_xlim()
                if truths[x_var] < xlo:
                    dx = xlo - truths[x_var]
                    hist_1d_axes[x_var].set_xlim(
                        (xlo - dx - 0.05 * (xhi - xlo), xhi))
                elif truths[x_var] > xhi:
                    dx = truths[x_var] - xhi
                    hist_1d_axes[x_var].set_xlim(
                        (xlo, xhi + dx + 0.05 * (xhi - xlo)))
                hist_1d_axes[x_var].axvline(truths[x_var], ls='--', c='k')

    #Finally Add the Axis Labels
    for x_var in xrange(n_traces - 1):
        hist_2d_axes[(x_var, n_traces - 1)].set_xlabel(axis_labels[x_var],
                                                       fontsize=fontsize)
        hist_2d_axes[(x_var, n_traces - 1)].tick_params(labelsize=tickfontsize)
        hist_2d_axes[(x_var, n_traces - 1)].xaxis.set_major_locator(
            MaxNLocator(nticks))
        plt.setp(hist_2d_axes[(x_var,
                               n_traces - 1)].xaxis.get_majorticklabels(),
                 rotation=45)
    for y_var in xrange(1, n_traces):
        hist_2d_axes[(0, y_var)].set_ylabel(axis_labels[y_var],
                                            fontsize=fontsize)
        hist_2d_axes[(0, y_var)].tick_params(labelsize=tickfontsize)
        plt.setp(hist_2d_axes[(0, y_var)].yaxis.get_majorticklabels(),
                 rotation=45)
        hist_2d_axes[(0, y_var)].yaxis.set_major_locator(MaxNLocator(nticks))

    if fname != None:
        if len(fname.split('.')) == 1:
            fname += '.pdf'
        plt.savefig(fname, transparent=True, bbox_inches="tight")

    return None
Example #10
0
	#for i in range(len(xs)):
		
	for i in range(len(xs)):
		ax.plot(xs[i:i+2],ys[i:i+2],zs[i:i+2],color=[0.2, 0.0, 0.9])
		ax.plot(xs2[i:i+2],ys2[i:i+2],zs2[i:i+2],color=[1, 0.7, 0])
	"""
	for angle in range(0, 360):
	    ax.view_init(30, angle)
	    plt.draw()
	    plt.pause(.00001)
"""
X = np.arange(min(xs[0] - 0.2,-0.5), max(0.5, xs[0] + 0.2), 0.015)
Y = np.arange(min(ys[0] - 0.2,-0.5), max(0.5, ys[0] + 0.2), 0.015)
X, Y = np.meshgrid(X, Y)
Z = ((v[None,None,:,0] * X[:,:,None] + v[None,None,:,1] * Y[:,:,None])**2 * d[None,None,:]).sum(axis=2)
cmap = clrs.Colormap('cool', N=len(xs))
#surf = ax.plot_surface(X, Y, Z, linewidth=0, antialiased=False)
ax.plot_wireframe(X, Y, Z, color=[0.2,0.8,0.5])

for k in [0,200,400,600,900]:
	startx = xs2[k]
	starty = ys2[k]
	startz = d.dot(v.dot([startx,starty])**2)
	b = 2*(((-v.dot([startx,starty]))[:,np.newaxis] * v) * d[:,np.newaxis] ).sum(axis=0)
	b = b / np.abs(b).sum()
	c = 0.1
	endx = startx - b[0] * c
	endy = starty - b[1] * c
	endz = startz + b.dot(b) * c

	startx = startx + b[0] * c
Example #11
0
# for category in enumerate(categories)
# col1 = midwest.category()
# data1 = midwest.loc[midwest.category==category, :]

# In[22]:

# Using Colormaps to set color of line in matplotlib
# https://stackoverflow.com/questions/8931268/using-colormaps-to-set-color-of-line-in-matplotlib
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.cm as cmx
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111)
jet = colors.Colormap('jet')
cNorm = colors.Normalize(vmin=0, vmax=values[-1])
scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet)
lines = []
for idx in range(len(curves)):
    line = curves[idx]
    colorVal = scalarMap.to_rgba(values[idx])
    retLine, = ax.plot(line, color=colorVal)
    #retLine.set_color()
    lines.append(retLine)
ax.legend(lines, labels, loc='upper right')
ax.grid()
plt.show()

# In[24]:
Example #12
0
widget.addItem(grid)

# m1 = gl.GLMeshItem(vertexes=vertices, faces=faces,
#                    drawFaces=False, color=pg.mkColor('k'),
#                    drawEdges=True, edgeColor=pg.mkColor('g'),
#                    #faceColors=colors,
#                    smooth=False)
mesh = gl.GLMeshItem(meshdata=cortex_mesh_data)
# m1.translate(5, 5, 0)
# m1.setGLOptions('additive')
widget.addItem(mesh)

# stc is from the plot_compute_mne_inverse_raw_in_label.py example
sources = stc.data.squeeze()
cmapper = cm.ScalarMappable(cmap='viridis')
cmap = mcolors.Colormap(name='viridis')
cmap.to_
colors = cmapper.to_rgba(sources)

lastTime = ptime.time()
fps = None


def update():
    # Update colors
    colors = np.concatenate((np.random.random(
        (vertex_cnt, 3)), np.ones((vertex_cnt, 1))),
                            axis=1)
    cortex_mesh_data._vertexColors[vertex_idx] = colors
    cortex_mesh_data._vertexColorsIndexedByFaces = None
    # colors = np.concatenate((np.random.random((vertexes.shape[0], 3)),
Example #13
0
from netCDF4 import Dataset
from mpl_toolkits.basemap import Basemap
from matplotlib import colors
import numpy as np
import matplotlib.pyplot as plt

#hint
#from left to right -> 90 until 150 longitude
#from bottom to top -> -20 until 20 latitude
#llcrnrlon	longitude of lower left hand corner of the desired map domain (degrees).
#llcrnrlat	latitude of lower left hand corner of the desired map domain (degrees).
#urcrnrlon	longitude of upper right hand corner of the desired map domain (degrees).
#urcrnrlat	latitude of upper right hand corner of the desired map domain (degrees).


contoh = colors.Colormap('r', N=1)

#all matrix here is list object
def createbinermat(rightmat, leftmat, treshold):
	right = np.asarray(rightmat)
	left = np.asarray(leftmat)
	y, x = np.shape(right)
	out = np.zeros((y,x), dtype=np.int)
	for i in xrange(y):
		for j in xrange(x):
			if (rightmat[i][j]-leftmat[i][j]) <= treshold:
				out[i][j] = 1
			else:
				out[i][j] = 0
	return out 
Example #14
0
def corner_plot( chain, weights=None, axis_labels=None,  print_values=True, fname = None, nbins=40, \
                 figsize = (7.,7.), filled=True, gradient=False, cmap="Blues", truths = None,\
                 fontsize=20 , tickfontsize=15, nticks=4, linewidth=1., truthlinewidth=2., linecolor = 'k', \
                 markercolor = 'k', markersize = 10, wspace=0.5, hspace=0.5, scatter=False, scatter_size=2., \
                 scatter_color='k', scatter_alpha=0.5):
    """
    Make a corner plot from MCMC output.
    Parameters
    ----------
    chain : array_like[nsamples, ndim]
        Samples from an MCMC chain. ndim should be >= 2.
    weights: array_like[nsamples]
        Weights to be applied to the samples (if e.g. nested sampling has been used to obtain the samples)
    axis_labels : array_like[ndim]
        Strings corresponding to axis labels.
    print_values:
        If True, print median values from 1D posteriors and +/- uncertainties 
        from the 84th and 16th percentiles above the 1D histograms.
    fname : str 
        The name of the file to save the figure to.
    nbins : int 
        The number of bins to use in each dimension for the histograms.
    figsize : tuple
        The height and width of the plot in inches.
    filled : bool
        If True, the histograms and contours will be filled.
    gradient: bool
        If True, then instead of filled contours, bicubic interpolation is applied to the 2D histograms (appropriate 
            when your posterior is densely sampled).
    cmap : str
        Name of the colormap to use.
    truths : array_like[ndim]
        A list of true values. These are marked on the 2D and 1D histograms. If None, none are added.
    fontsize : float
        The size font to use for axis labels.
    tickfontsize : float
        The size font to use for tick labels.
    nticks : int
        The number of ticks to use on each axis.
    linewidth: float
        The width of the lines surrounding the contours and histograms.
    truthlinewidth:
        The width of the dashed lines in 1D histograms at 'true' values.
    linecolor: str
        The color of the lines surrounding the contours and histograms.
    markercolor: str
        The color of the marker at the 'true' values in the 2D subplots.
    markersize: float
        The size of the marker to put on the 2D subplots.
    wspace : float
        The amount of whitespace to place vertically between subplots.
    hspace : float
        The amount of whitespace to place horizontally between subplots.
    scatter: bool
        If true, do scatter plots instead of contour plots in the 2D projections.
    scatter_size: float
        The size of the points in the scatter plot.
    scatter_color: str 
        The color of the points in the scatter plot. 
    scatter_alpha: float 
        The alpha value for the scatter points. 
    """

    major_formatter = FuncFormatter(my_formatter)

    if weights is not None:
        print_values = False  #current method for extracting results won't work for that

    if print_values is True:
        res = chain_results(chain)

    traces = chain.T

    if axis_labels is None:
        axis_labels = [''] * len(traces)

    if len(traces) != len(axis_labels):
        print("There must be the same number of axis labels as traces",
              file=sys.stderr)

    if truths != None and (len(truths) != len(traces)):
        print("There must be the same number of true values as traces",
              file=sys.stderr)

    num_samples = min([len(trace) for trace in traces])
    n_traces = len(traces)

    #Set up the figure
    fig = plt.figure(num=None, figsize=figsize)

    dim = 2 * n_traces - 1

    gs = gridspec.GridSpec(dim + 1, dim + 1)
    gs.update(wspace=wspace, hspace=hspace)

    hist_2d_axes = {}

    #Create axes for 2D histograms
    for x_pos in xrange(n_traces - 1):
        for y_pos in range(n_traces - 1 - x_pos):
            x_var = x_pos
            y_var = n_traces - 1 - y_pos

            hist_2d_axes[(x_var, y_var)] = fig.add_subplot( \
                                           gs[ -1-(2*y_pos):-1-(2*y_pos), \
                                               2*x_pos:(2*x_pos+2) ] )
            hist_2d_axes[(x_var,
                          y_var)].xaxis.set_major_formatter(major_formatter)
            hist_2d_axes[(x_var,
                          y_var)].yaxis.set_major_formatter(major_formatter)

    #Create axes for 1D histograms
    hist_1d_axes = {}
    for var in xrange(n_traces - 1):
        hist_1d_axes[var] = fig.add_subplot(gs[(2 * var):(2 * var + 2),
                                               2 * var:(2 * var + 2)])
        hist_1d_axes[var].xaxis.set_major_formatter(major_formatter)
        hist_1d_axes[var].yaxis.set_major_formatter(major_formatter)
    hist_1d_axes[n_traces - 1] = fig.add_subplot(gs[-2:, -2:])
    hist_1d_axes[n_traces - 1].xaxis.set_major_formatter(major_formatter)
    hist_1d_axes[n_traces - 1].yaxis.set_major_formatter(major_formatter)

    #Remove the ticks from the axes which don't need them
    for x_var in xrange(n_traces - 1):
        for y_var in xrange(1, n_traces - 1):
            try:
                hist_2d_axes[(x_var, y_var)].xaxis.set_visible(False)
            except KeyError:
                continue
    for var in xrange(n_traces - 1):
        hist_1d_axes[var].set_xticklabels([])
        hist_1d_axes[var].xaxis.set_major_locator(MaxNLocator(nticks))
        hist_1d_axes[var].yaxis.set_visible(False)

    for y_var in xrange(1, n_traces):
        for x_var in xrange(1, n_traces - 1):
            try:
                hist_2d_axes[(x_var, y_var)].yaxis.set_visible(False)
            except KeyError:
                continue

    #Do the plotting
    #Firstly make the 1D histograms
    vals, walls = np.histogram(traces[-1][:num_samples],
                               bins=nbins,
                               weights=weights,
                               normed=True)

    xplot = np.zeros(nbins * 2 + 2)
    yplot = np.zeros(nbins * 2 + 2)
    for i in xrange(1, nbins * 2 + 1):
        xplot[i] = walls[int((i - 1) / 2)]
        yplot[i] = vals[int((i - 2) / 2)]

    xplot[0] = walls[0]
    xplot[-1] = walls[-1]
    yplot[0] = yplot[1]
    yplot[-1] = yplot[-2]

    if not scatter:
        Cmap = colors.Colormap(cmap)
        cNorm = colors.Normalize(vmin=0., vmax=1.)
        scalarMap = cm.ScalarMappable(norm=cNorm, cmap=cmap)
        cVal = scalarMap.to_rgba(0.65)
    else:
        cVal = scatter_color

    #this one's special, so do it on it's own
    if print_values is True:
        hist_1d_axes[n_traces - 1].set_title("${0:.2f}^{{ +{1:.2f} }}_{{ -{2:.2f} }}$".\
            format(res[n_traces - 1][0],res[n_traces - 1][1],res[n_traces - 1][2]),fontsize=fontsize)
    hist_1d_axes[n_traces - 1].plot(xplot,
                                    yplot,
                                    color=linecolor,
                                    lw=linewidth)
    if filled:
        hist_1d_axes[n_traces - 1].fill_between(xplot, yplot, color=cVal)
    hist_1d_axes[n_traces - 1].set_xlim(walls[0], walls[-1])
    hist_1d_axes[n_traces - 1].set_xlabel(axis_labels[-1], fontsize=fontsize)
    hist_1d_axes[n_traces - 1].tick_params(labelsize=tickfontsize)
    hist_1d_axes[n_traces - 1].xaxis.set_major_locator(MaxNLocator(nticks))
    hist_1d_axes[n_traces - 1].yaxis.set_visible(False)
    plt.setp(hist_1d_axes[n_traces - 1].xaxis.get_majorticklabels(),
             rotation=45)
    if truths is not None:
        xlo, xhi = hist_1d_axes[n_traces - 1].get_xlim()
        if truths[n_traces - 1] < xlo:
            dx = xlo - truths[n_traces - 1]
            hist_1d_axes[n_traces - 1].set_xlim(
                (xlo - dx - 0.05 * (xhi - xlo), xhi))
        elif truths[n_traces - 1] > xhi:
            dx = truths[n_traces - 1] - xhi
            hist_1d_axes[n_traces - 1].set_xlim(
                (xlo, xhi + dx + 0.05 * (xhi - xlo)))
        hist_1d_axes[n_traces - 1].axvline(truths[n_traces - 1],
                                           ls='--',
                                           c='k',
                                           lw=truthlinewidth)

    #Now Make the 2D histograms
    for x_var in xrange(n_traces):
        for y_var in xrange(n_traces):
            try:
                H, y_edges, x_edges = np.histogram2d( traces[y_var][:num_samples], traces[x_var][:num_samples],\
                                                           weights=weights, bins = nbins )
                confidence_2d(traces[x_var][:num_samples],traces[y_var][:num_samples],weights=weights,\
                    ax=hist_2d_axes[(x_var,y_var)],nbins=nbins,intervals=None,linecolor=linecolor,\
                    filled=filled,cmap=cmap,linewidth=linewidth, gradient=gradient,scatter=scatter,\
                    scatter_color=scatter_color, scatter_alpha=scatter_alpha, scatter_size=scatter_size)
                hist_2d_axes[(x_var, y_var)].set_xlim(x_edges[0], x_edges[-1])
                hist_2d_axes[(x_var, y_var)].set_ylim(y_edges[0], y_edges[-1])
                if truths is not None:
                    xlo, xhi = hist_2d_axes[(x_var, y_var)].get_xlim()
                    ylo, yhi = hist_2d_axes[(x_var, y_var)].get_ylim()
                    if truths[x_var] < xlo:
                        dx = xlo - truths[x_var]
                        hist_2d_axes[(x_var, y_var)].set_xlim(
                            (xlo - dx - 0.05 * (xhi - xlo), xhi))
                    elif truths[x_var] > xhi:
                        dx = truths[x_var] - xhi
                        hist_2d_axes[(x_var, y_var)].set_xlim(
                            (xlo, xhi + dx + 0.05 * (xhi - xlo)))
                    if truths[y_var] < ylo:
                        dy = ylo - truths[y_var]
                        hist_2d_axes[(x_var, y_var)].set_ylim(
                            (ylo - dy - 0.05 * (yhi - ylo), yhi))
                    elif truths[y_var] > yhi:
                        dy = truths[y_var] - yhi
                        hist_2d_axes[(x_var, y_var)].set_ylim(
                            (ylo, yhi + dy + 0.05 * (yhi - ylo)))
                    #TODO: deal with the pesky case of a prior edge
                    hist_2d_axes[(x_var, y_var)].set_axis_bgcolor(
                        scalarMap.to_rgba(0.))  #so that the contours blend
                    hist_2d_axes[(x_var,y_var)].plot( truths[x_var], truths[y_var], '*',\
                                 color = markercolor, markersize = markersize, \
                                 markeredgecolor = 'none')
            except KeyError:
                pass
        if x_var < n_traces - 1:
            vals, walls = np.histogram(traces[x_var][:num_samples],
                                       bins=nbins,
                                       weights=weights,
                                       normed=True)

            xplot = np.zeros(nbins * 2 + 2)
            yplot = np.zeros(nbins * 2 + 2)
            for i in xrange(1, nbins * 2 + 1):
                xplot[i] = walls[int((i - 1) / 2)]
                yplot[i] = vals[int((i - 2) / 2)]

            xplot[0] = walls[0]
            xplot[-1] = walls[-1]
            yplot[0] = yplot[1]
            yplot[-1] = yplot[-2]

            if print_values is True:
                hist_1d_axes[x_var].set_title("${0:.2f}^{{ +{1:.2f} }}_{{ -{2:.2f} }}$".\
                                format(res[x_var][0],res[x_var][1],res[x_var][2]),fontsize=fontsize)
            hist_1d_axes[x_var].plot(xplot,
                                     yplot,
                                     color=linecolor,
                                     lw=linewidth)
            if filled:
                hist_1d_axes[x_var].fill_between(xplot, yplot, color=cVal)
            hist_1d_axes[x_var].set_xlim(x_edges[0], x_edges[-1])
            if truths is not None:
                xlo, xhi = hist_1d_axes[x_var].get_xlim()
                if truths[x_var] < xlo:
                    dx = xlo - truths[x_var]
                    hist_1d_axes[x_var].set_xlim(
                        (xlo - dx - 0.05 * (xhi - xlo), xhi))
                elif truths[x_var] > xhi:
                    dx = truths[x_var] - xhi
                    hist_1d_axes[x_var].set_xlim(
                        (xlo, xhi + dx + 0.05 * (xhi - xlo)))
                hist_1d_axes[x_var].axvline(truths[x_var],
                                            ls='--',
                                            c='k',
                                            lw=truthlinewidth)

    #Finally Add the Axis Labels
    for x_var in xrange(n_traces - 1):
        hist_2d_axes[(x_var, n_traces - 1)].set_xlabel(axis_labels[x_var],
                                                       fontsize=fontsize)
        hist_2d_axes[(x_var, n_traces - 1)].tick_params(labelsize=tickfontsize)
        hist_2d_axes[(x_var, n_traces - 1)].xaxis.set_major_locator(
            MaxNLocator(nticks))
        plt.setp(hist_2d_axes[(x_var,
                               n_traces - 1)].xaxis.get_majorticklabels(),
                 rotation=45)
    for y_var in xrange(1, n_traces):
        hist_2d_axes[(0, y_var)].set_ylabel(axis_labels[y_var],
                                            fontsize=fontsize)
        hist_2d_axes[(0, y_var)].tick_params(labelsize=tickfontsize)
        plt.setp(hist_2d_axes[(0, y_var)].yaxis.get_majorticklabels(),
                 rotation=45)
        hist_2d_axes[(0, y_var)].yaxis.set_major_locator(MaxNLocator(nticks))

    plt.gcf().subplots_adjust(
        bottom=0.15)  #make sure nothing is getting chopped off

    if fname != None:
        if len(fname.split('.')) == 1:
            fname += '.pdf'
        plt.savefig(fname, transparent=True)

    return None
Example #15
0
def corner_plot(chain,
                axis_labels=None,
                fname=None,
                nbins=40,
                figsize=(15., 15.),
                filled=True,
                gradient=False,
                cmap="Blues",
                fontsize=20,
                tickfontsize=15,
                nticks=4,
                linewidth=1.,
                linecolor='k',
                markercolor='k',
                markersize=10,
                wspace=0.5,
                hspace=0.5):
    """
    Make a corner plot to show histograms / correlations
    """

    major_formatter = FuncFormatter(my_formatter)

    traces = chain.T

    if axis_labels is None:
        axis_labels = [''] * len(traces)

    num_samples = min([len(trace) for trace in traces])
    n_traces = len(traces)

    #Set up the figure
    fig = plt.figure(num=None, figsize=figsize)

    fig.subplots_adjust(bottom=0.15)

    dim = 2 * n_traces - 1

    gs = gridspec.GridSpec(dim + 1, dim + 1)
    gs.update(wspace=wspace, hspace=hspace)

    hist_2d_axes = {}

    #Create axes for 2D histograms
    for x_pos in xrange(n_traces - 1):
        for y_pos in range(n_traces - 1 - x_pos):
            x_var = x_pos
            y_var = n_traces - 1 - y_pos

            hist_2d_axes[(x_var, y_var)] = fig.add_subplot( \
                                           gs[ -1-(2*y_pos):-1-(2*y_pos), \
                                               2*x_pos:(2*x_pos+2) ] )
            hist_2d_axes[(x_var,
                          y_var)].xaxis.set_major_formatter(major_formatter)
            hist_2d_axes[(x_var,
                          y_var)].yaxis.set_major_formatter(major_formatter)

    #Create axes for 1D histograms
    hist_1d_axes = {}
    for var in xrange(n_traces - 1):
        hist_1d_axes[var] = fig.add_subplot(gs[(2 * var):(2 * var + 2),
                                               2 * var:(2 * var + 2)])
        hist_1d_axes[var].xaxis.set_major_formatter(major_formatter)
        hist_1d_axes[var].yaxis.set_major_formatter(major_formatter)
    hist_1d_axes[n_traces - 1] = fig.add_subplot(gs[-2:, -2:])
    hist_1d_axes[n_traces - 1].xaxis.set_major_formatter(major_formatter)
    hist_1d_axes[n_traces - 1].yaxis.set_major_formatter(major_formatter)

    #Remove the ticks from the axes which don't need them
    for x_var in xrange(n_traces - 1):
        for y_var in xrange(1, n_traces - 1):
            try:
                hist_2d_axes[(x_var, y_var)].xaxis.set_visible(False)
            except KeyError:
                continue
    for var in xrange(n_traces - 1):
        hist_1d_axes[var].set_xticklabels([])
        hist_1d_axes[var].xaxis.set_major_locator(MaxNLocator(nticks))
        hist_1d_axes[var].yaxis.set_visible(False)

    for y_var in xrange(1, n_traces):
        for x_var in xrange(1, n_traces - 1):
            try:
                hist_2d_axes[(x_var, y_var)].yaxis.set_visible(False)
            except KeyError:
                continue

    #Do the plotting
    #Firstly make the 1D histograms
    vals, walls = np.histogram(traces[-1][:num_samples],
                               bins=nbins,
                               normed=True)

    xplot = np.zeros(nbins * 2 + 2)
    yplot = np.zeros(nbins * 2 + 2)
    for i in xrange(1, nbins * 2 + 1):
        xplot[i] = walls[int((i - 1) / 2)]
        yplot[i] = vals[int((i - 2) / 2)]

    xplot[0] = walls[0]
    xplot[-1] = walls[-1]
    yplot[0] = yplot[1]
    yplot[-1] = yplot[-2]

    Cmap = colors.Colormap(cmap)
    cNorm = colors.Normalize(vmin=0., vmax=1.)
    scalarMap = cm.ScalarMappable(norm=cNorm, cmap=cmap)
    cVal = scalarMap.to_rgba(0.65)

    #this one's special, so do it on it's own
    hist_1d_axes[n_traces - 1].plot(xplot,
                                    yplot,
                                    color=linecolor,
                                    lw=linewidth)
    if filled:
        hist_1d_axes[n_traces - 1].fill_between(xplot, yplot, color=cVal)
    hist_1d_axes[n_traces - 1].set_xlim(walls[0], walls[-1])
    hist_1d_axes[n_traces - 1].set_xlabel(axis_labels[-1], fontsize=fontsize)
    hist_1d_axes[n_traces - 1].tick_params(labelsize=tickfontsize)
    hist_1d_axes[n_traces - 1].xaxis.set_major_locator(MaxNLocator(nticks))
    hist_1d_axes[n_traces - 1].yaxis.set_visible(False)
    plt.setp(hist_1d_axes[n_traces - 1].xaxis.get_majorticklabels(),
             rotation=45)
    hist_1d_axes[n_traces - 1].xaxis.set_label_coords(0.5, -0.3)

    #Now Make the 2D histograms
    for x_var in xrange(n_traces):
        for y_var in xrange(n_traces):
            try:
                H, y_edges, x_edges = np.histogram2d(
                    traces[y_var][:num_samples],
                    traces[x_var][:num_samples],
                    bins=nbins)

                hist_2d_axes[(x_var,
                              y_var)].scatter(traces[x_var][:num_samples],
                                              traces[y_var][:num_samples],
                                              edgecolor='None',
                                              facecolor=cVal,
                                              s=10)

                hist_2d_axes[(x_var, y_var)].set_xlim(x_edges.min(),
                                                      x_edges.max())
                hist_2d_axes[(x_var, y_var)].set_ylim(y_edges.min(),
                                                      y_edges.max())

            except KeyError:
                pass
        if x_var < n_traces - 1:
            vals, walls = np.histogram(traces[x_var][:num_samples],
                                       bins=nbins,
                                       normed=True)

            xplot = np.zeros(nbins * 2 + 2)
            yplot = np.zeros(nbins * 2 + 2)
            for i in xrange(1, nbins * 2 + 1):
                xplot[i] = walls[int((i - 1) / 2)]
                yplot[i] = vals[int((i - 2) / 2)]

            xplot[0] = walls[0]
            xplot[-1] = walls[-1]
            yplot[0] = yplot[1]
            yplot[-1] = yplot[-2]

            hist_1d_axes[x_var].plot(xplot,
                                     yplot,
                                     color=linecolor,
                                     lw=linewidth)
            if filled:
                hist_1d_axes[x_var].fill_between(xplot, yplot, color=cVal)
            hist_1d_axes[x_var].set_xlim(x_edges[0], x_edges[-1])

    #Finally Add the Axis Labels
    for x_var in xrange(n_traces - 1):
        hist_2d_axes[(x_var, n_traces - 1)].set_xlabel(axis_labels[x_var],
                                                       fontsize=fontsize)
        hist_2d_axes[(x_var, n_traces - 1)].tick_params(labelsize=tickfontsize)
        hist_2d_axes[(x_var, n_traces - 1)].xaxis.set_major_locator(
            MaxNLocator(nticks))
        plt.setp(hist_2d_axes[(x_var,
                               n_traces - 1)].xaxis.get_majorticklabels(),
                 rotation=45)
        hist_2d_axes[(x_var, n_traces - 1)].xaxis.set_label_coords(0.5, -0.3)
    for y_var in xrange(1, n_traces):
        hist_2d_axes[(0, y_var)].set_ylabel(axis_labels[y_var],
                                            fontsize=fontsize)
        hist_2d_axes[(0, y_var)].tick_params(labelsize=tickfontsize)
        plt.setp(hist_2d_axes[(0, y_var)].yaxis.get_majorticklabels(),
                 rotation=45)
        hist_2d_axes[(0, y_var)].yaxis.set_major_locator(MaxNLocator(nticks))
        hist_2d_axes[(0, y_var)].yaxis.set_label_coords(-0.25, 0.5)

    # hist_2d_axes[(1, 2)].xaxis.labelpad = 15
    # hist_2d_axes[(0, 1)].yaxis.labelpad = 12

    if fname != None:
        if len(fname.split('.')) == 1:
            fname += '.pdf'
        plt.savefig(fname, transparent=True)

    return None