def setNorm(self): "sets the whitepoint and blackpoint (uses raw data, not scaled)" x = N.sort(self.image[:].flatten()) npts = x.shape[0] p01 = x[int(round(.01 * npts))] p99 = x[int(round(.99 * npts))] self.norm = P.normalize(vmin=p01, vmax=p99) #self.norm = P.normalize(-.1, 1.1) if hasattr(self, "overlay_img") and self.overlay_img: p01 = P.prctile(self.overlay_img[:], 1.0) p99 = P.prctile(self.overlay_img[:], 99.) self.overlay_norm = P.normalize(vmin=p01, vmax=p99)
def setNorm(self): "sets the whitepoint and blackpoint (uses raw data, not scaled)" x = N.sort(self.image[:].flatten()) npts = x.shape[0] p01 = x[int(round(.01*npts))] p99 = x[int(round(.99*npts))] self.norm = P.normalize(vmin = p01, vmax = p99) #self.norm = P.normalize(-.1, 1.1) if hasattr(self, "overlay_img") and self.overlay_img: p01 = P.prctile(self.overlay_img[:], 1.0) p99 = P.prctile(self.overlay_img[:], 99.) self.overlay_norm = P.normalize(vmin = p01, vmax = p99)
def _plot_topo_imshow(epochs, show_func, layout, decim, vmin, vmax, colorbar, cmap, layout_scale): """Helper function: plot tfr on sensor layout""" import pylab as pl if cmap is None: cmap = pl.cm.jet ch_names = _clean_names(epochs.info['ch_names']) pl.rcParams['axes.facecolor'] = 'k' fig = pl.figure(facecolor='k') pos = layout.pos.copy() if colorbar: pos[:, :2] *= layout_scale pl.rcParams['axes.edgecolor'] = 'k' sm = pl.cm.ScalarMappable(cmap=cmap, norm=pl.normalize(vmin=vmin, vmax=vmax)) sm.set_array(np.linspace(vmin, vmax)) ax = pl.axes([0.015, 0.025, 1.05, .8], axisbg='k') cb = fig.colorbar(sm, ax=ax) cb_yticks = pl.getp(cb.ax.axes, 'yticklabels') pl.setp(cb_yticks, color='w') pl.rcParams['axes.edgecolor'] = 'w' for idx, name in enumerate(_clean_names(layout.names)): if name in ch_names: ax = pl.axes(pos[idx], axisbg='k') ch_idx = ch_names.index(name) show_func(ax, ch_idx, 1e3 * epochs.times[0], 1e3 * epochs.times[-1], vmin, vmax) pl.xticks([], ()) pl.yticks([], ()) # Revert global pylab config pl.rcParams['axes.facecolor'] = 'w' pl.rcParams['axes.edgecolor'] = 'k' return fig
def resetFig(): """ Clears the last figure and redefines the axes correctly. """ pl.clf() pl.figure(figsize=(8, 6)) pl.rcParams.update({'font.size': 9.5}) pl.subplots_adjust(left=0.1, right=1.0, top=0.9, bottom=0.1) pl.tick_params(axis='both', which='major', labelsize=9) pl.tick_params(axis='both', which='minor', labelsize=9) sm1 = pl.cm.ScalarMappable(cmap=c1, norm=pl.normalize(vmin=0.0, vmax=1.0)) sm1._A = [] sm2 = pl.cm.ScalarMappable(cmap=c2, norm=pl.normalize(vmin=0.0, vmax=1.0)) sm2._A = [] sm3 = pl.cm.ScalarMappable(cmap=c3, norm=pl.normalize(vmin=0.0, vmax=1.0)) sm3._A = [] return sm1, sm2, sm3
def resetFig(): """ Clears the last figure and redefines the axes correctly. """ pl.clf() pl.figure(figsize=(8,6)) pl.rcParams.update({'font.size': 9.5}) pl.subplots_adjust(left=0.1, right=1.0, top=0.9, bottom=0.1) pl.tick_params(axis='both', which='major', labelsize=9) pl.tick_params(axis='both', which='minor', labelsize=9) sm1 = pl.cm.ScalarMappable(cmap=c1,norm=pl.normalize(vmin=0.0, vmax=1.0)) sm1._A = [] sm2 = pl.cm.ScalarMappable(cmap=c2,norm=pl.normalize(vmin=0.0, vmax=1.0)) sm2._A = [] sm3 = pl.cm.ScalarMappable(cmap=c3,norm=pl.normalize(vmin=0.0, vmax=1.0)) sm3._A = [] return sm1,sm2,sm3
def _plotter(self, func, colorscale='linear', **fargs): """Plot func for all MCMCsamplers in the collection. _plotter('<functionname>',colorscale='linear'|'log',**fargs) '<functionname>' string, names a plotting method such as 'plot_correl' colorscale scale color based on the parameter value ('linear' or 'log'; note that 'log' can only be used with numerical data > 0) **fargs additional arguments that the function may need """ import pylab # currently, pvalues must be numerical; if not then one should use the enumeration # instead of the pvalues list if numpy.all(numpy.isreal(self.pvalues)): p_dict = dict(zip(self.pvalues, map(float, self.pvalues))) else: p_dict = dict([(p, n) for n, p in enumerate(self.pvalues)]) _scalings = {'linear': lambda x: x, 'log': lambda x: numpy.log(x)} try: scale = _scalings[colorscale] except KeyError: raise ValueError("<colorscale> must be one of " + str(_scalings.keys())) pnormalize = pylab.normalize(vmin=numpy.min(scale(p_dict.values())), vmax=numpy.max(scale(p_dict.values()))) pylab.clf() ax = pylab.axes(frameon=False) lines = [] descriptions = [] for p in sorted(self.MCMCsamplers): p_num = p_dict[p] plot_func = self.MCMCsamplers[p].__getattribute__(func) (line, correl_legend) = plot_func(color=pylab.cm.jet( pnormalize(scale(p_num))), legend=False, **fargs) descr = r'$%s\ %s$' % (str(p), correl_legend.replace(r'$', '') ) # minimalistic legend lines.append(line) descriptions.append(descr) pylab.legend( lines, descriptions, numpoints=1, shadow=True, prop=pylab.matplotlib.font_manager.FontProperties(size='smaller'))
def generate_table(table_data, rows, columns): df = DataFrame(table_data, index=rows, columns=columns) base = 0 colorings = [] #colorings.append([base]*(len(rows)+1)) for column in columns: vals = df[column].values normal = normalize(vals.min() - 1, vals.max() + 1) m = cm.ScalarMappable( norm=matplotlib.colors.Normalize(vmin=vals.min(), vmax=vals.max())) m.set_cmap("YlGn") col_colors = m.to_rgba(vals) print col_colors colorings.append(col_colors) #colorings.append(list(np.transpose(cm.hot(normal(vals)))[1])) colorings = np.transpose(colorings, (1, 0, 2)) print colorings.shape fig = figure(figsize=(15, 8)) ax = fig.add_subplot(111, frameon=True, xticks=[], yticks=[]) #print colorings vals = df.values the_table = table(cellText=vals, rowLabels=df.index, colLabels=df.columns, colWidths=[0.13] * vals.shape[1], loc='center', cellColours=colorings, fontsize=15) #nrows, ncols = len(rows)+1, len(columns)+1 #hcell, wcell = 1, 1 #hpad, wpad = .5, 0 #fig = figure(figsize=(ncols*wcell+wpad, nrows*hcell+hpad)) #fig = figure() #ax = fig.add_subplot(111) #ax.axis('off') #ax.table(cellText=table_data, # rowLabels=rows, # colLabels=columns, # loc='center') show() close()
def _plotter(self,func,colorscale='linear',**fargs): """Plot func for all MCMCsamplers in the collection. _plotter('<functionname>',colorscale='linear'|'log',**fargs) '<functionname>' string, names a plotting method such as 'plot_correl' colorscale scale color based on the parameter value ('linear' or 'log'; note that 'log' can only be used with numerical data > 0) **fargs additional arguments that the function may need """ import pylab # currently, pvalues must be numerical; if not then one should use the enumeration # instead of the pvalues list if numpy.all(numpy.isreal(self.pvalues)): p_dict = dict( zip(self.pvalues, map(float,self.pvalues)) ) else: p_dict = dict( [(p,n) for n,p in enumerate(self.pvalues)] ) _scalings = {'linear': lambda x:x, 'log': lambda x:numpy.log(x)} try: scale = _scalings[colorscale] except KeyError: raise ValueError("<colorscale> must be one of "+str(_scalings.keys())) pnormalize = pylab.normalize(vmin=numpy.min(scale(p_dict.values())), vmax=numpy.max(scale(p_dict.values()))) pylab.clf() ax = pylab.axes(frameon=False) lines = [] descriptions = [] for p in sorted(self.MCMCsamplers): p_num = p_dict[p] plot_func = self.MCMCsamplers[p].__getattribute__(func) (line,correl_legend) = plot_func(color=pylab.cm.jet(pnormalize(scale(p_num))), legend=False, **fargs) descr = r'$%s\ %s$' % (str(p), correl_legend.replace(r'$','')) # minimalistic legend lines.append(line) descriptions.append(descr) pylab.legend(lines,descriptions,numpoints=1,shadow=True, prop=pylab.matplotlib.font_manager.FontProperties(size='smaller'))
def generate_table(table_data,rows,columns): df = DataFrame(table_data, index=rows, columns=columns) base = 0 colorings = [] #colorings.append([base]*(len(rows)+1)) for column in columns: vals = df[column].values normal = normalize(vals.min()-1, vals.max()+1) m = cm.ScalarMappable(norm=matplotlib.colors.Normalize(vmin=vals.min(), vmax=vals.max())) m.set_cmap("YlGn") col_colors = m.to_rgba(vals) print col_colors colorings.append(col_colors) #colorings.append(list(np.transpose(cm.hot(normal(vals)))[1])) colorings = np.transpose(colorings,(1,0,2)) print colorings.shape fig = figure(figsize=(15,8)) ax = fig.add_subplot(111, frameon=True, xticks=[], yticks=[]) #print colorings vals = df.values the_table=table(cellText=vals, rowLabels=df.index, colLabels=df.columns, colWidths = [0.13]*vals.shape[1], loc='center', cellColours=colorings, fontsize=15) #nrows, ncols = len(rows)+1, len(columns)+1 #hcell, wcell = 1, 1 #hpad, wpad = .5, 0 #fig = figure(figsize=(ncols*wcell+wpad, nrows*hcell+hpad)) #fig = figure() #ax = fig.add_subplot(111) #ax.axis('off') #ax.table(cellText=table_data, # rowLabels=rows, # colLabels=columns, # loc='center') show() close()
def show(self): """ A quick triple plot for a sanity check on the convolution.""" import pylab as P marker = float(self.npix) / 2 P.subplot(131) P.imshow(self.psf_vals, interpolation='nearest') norm = P.normalize(np.log10(self.bg_vals.min()), np.log10(self.bg_vals.max())) P.subplot(132) P.imshow(np.log10(self.bg_vals).transpose()[::-1], norm=norm, interpolation='nearest') P.axvline(marker, color='k') P.axhline(marker, color='k') P.subplot(133) P.imshow(np.log10(self.cvals).transpose()[::-1], norm=norm, interpolation='nearest') P.axvline(marker, color='k') P.axhline(marker, color='k')
def colorbar(cs=None,vmin=None,vmax=None, **kwargs): ''' Create a colorbar with the vmin,vmax if vmin and vmax are user-defined, rescale the filled contour as well. ''' fig = pylab.gcf() if cs is not None: if vmin is not None and vmax is not None: cs.set_clim(vmin,vmax) if vmin is None: vmin = cs.get_clim()[0] if vmax is None: vmax = cs.get_clim()[1] mappable = pylab.cm.ScalarMappable( cmap=cs.get_cmap(), norm=pylab.normalize(vmin=vmin,vmax=vmax)) mappable.set_array([]) cbar = fig.colorbar(mappable,**kwargs) else: cbar = pylab.colorbar(**kwargs) tick_formatter(cbar) return cbar
def plot_Kcolors_vs_temp_sample(filename='syn_nir_d06500_a619.dat'): temp, AKs, J, H, K, Kp, Ks, Lp, m, logg, logL = load_nearIR(filename) Kp_Ks = Kp - Ks cnorm = py.normalize(Kp_Ks.min(), Kp_Ks.max()) # Plot in 1D, pick out specific extinctions and temperatures # as examples. plotAKs = [0, 10, 20, 30] py.clf() py.subplots_adjust(hspace=0.001, bottom=0.1) sharedAxis = None for ii in range(len(plotAKs)): aa = plotAKs[ii] color = py.cm.jet(cnorm(Kp_Ks[0, aa])) idx = np.where(Kp_Ks[:,aa] != 0)[0] tmpAx = py.subplot(len(plotAKs), 1, ii+1, sharex=sharedAxis) if sharedAxis == None: sharedAxis = tmpAx foo = py.plot(temp[idx], Kp_Ks[idx, aa], 'k-', color=color, linewidth=2) py.setp(py.gca().get_xticklabels(), visible=False) minVal = Kp_Ks[idx, aa].min() py.ylim(minVal, minVal + 0.018) py.xlim(5000, 32000) py.ylabel('Kp - Ks') py.text(25000, minVal + 0.012, 'AKs = %.1f' % AKs[aa], color=color, weight='bold') py.setp(py.gca().get_xticklabels(), visible=True) py.xlabel('T_eff (K)') py.savefig('plots/syn_nir_Kp-Ks_T_sample.png') # Kp - K Kp_K = Kp - K cnorm = py.normalize(Kp_K.min(), Kp_K.max()) # Plot in 1D, pick out specific extinctions and temperatures # as examples. plotAKs = [0, 10, 20, 30] py.clf() py.subplots_adjust(hspace=0.001, bottom=0.1) sharedAxis = None for ii in range(len(plotAKs)): aa = plotAKs[ii] color = py.cm.jet(cnorm(Kp_K[0, aa])) idx = np.where(Kp_K[:,aa] != 0)[0] tmpAx = py.subplot(len(plotAKs), 1, ii+1, sharex=sharedAxis) if sharedAxis == None: sharedAxis = tmpAx foo = py.plot(temp[idx], Kp_K[idx, aa], 'k-', color=color, linewidth=2) py.setp(py.gca().get_xticklabels(), visible=False) minVal = Kp_K[idx, aa].min() py.ylim(minVal, minVal + 0.018) py.xlim(5000, 32000) py.ylabel('Kp - K') py.text(25000, minVal + 0.012, 'AKs = %.1f' % AKs[aa], color=color, weight='bold') py.setp(py.gca().get_xticklabels(), visible=True) py.xlabel('T_eff (K)') py.savefig('plots/syn_nir_Kp-K_T_sample.png')
pp(ln) ln=[a[2]+','+a[4] for a in ln] pp(ln) for i, trace in enumerate(l): x=numpy.linspace(0,1000,len(trace)) # norm=sum(trace)*(x[-1]-x[0])/len(x) # norm=numpy.mean(x) ax.plot(x, (numpy.array(trace)-trace[0]), color=colors[i]) ax.set_xlim([0,1000]) sm = pylab.cm.ScalarMappable(cmap='copper', norm=pylab.normalize(vmin=2.5, vmax=20)) sm._A = [] box = ax.get_position() pos=[box.x0+1.03*box.width, box.y0+box.height*0.1, 0.01, box.height*0.8] axColor=pylab.axes(pos) cbar=pylab.colorbar(sm, cax=axColor) tick_locator = ticker.MaxNLocator(nbins=7) cbar.locator = tick_locator cbar.update_ticks() cbar.ax.tick_params( length=1, ) cbar.ax.set_yticklabels(ln, fontsize=5*scale) ax.text(1.3, 0.5, r'$g^{TA\to FS}$, $g_{TI\to FS}$', transform=ax.transAxes, va='center', rotation=270)
def plot_Kcolors_vs_temp_sample(filename='syn_nir_d06500_a619.dat'): temp, AKs, J, H, K, Kp, Ks, Lp, m, logg, logL = load_nearIR(filename) Kp_Ks = Kp - Ks cnorm = py.normalize(Kp_Ks.min(), Kp_Ks.max()) # Plot in 1D, pick out specific extinctions and temperatures # as examples. plotAKs = [0, 10, 20, 30] py.clf() py.subplots_adjust(hspace=0.001, bottom=0.1) sharedAxis = None for ii in range(len(plotAKs)): aa = plotAKs[ii] color = py.cm.jet(cnorm(Kp_Ks[0, aa])) idx = np.where(Kp_Ks[:, aa] != 0)[0] tmpAx = py.subplot(len(plotAKs), 1, ii + 1, sharex=sharedAxis) if sharedAxis == None: sharedAxis = tmpAx foo = py.plot(temp[idx], Kp_Ks[idx, aa], 'k-', color=color, linewidth=2) py.setp(py.gca().get_xticklabels(), visible=False) minVal = Kp_Ks[idx, aa].min() py.ylim(minVal, minVal + 0.018) py.xlim(5000, 32000) py.ylabel('Kp - Ks') py.text(25000, minVal + 0.012, 'AKs = %.1f' % AKs[aa], color=color, weight='bold') py.setp(py.gca().get_xticklabels(), visible=True) py.xlabel('T_eff (K)') py.savefig('plots/syn_nir_Kp-Ks_T_sample.png') # Kp - K Kp_K = Kp - K cnorm = py.normalize(Kp_K.min(), Kp_K.max()) # Plot in 1D, pick out specific extinctions and temperatures # as examples. plotAKs = [0, 10, 20, 30] py.clf() py.subplots_adjust(hspace=0.001, bottom=0.1) sharedAxis = None for ii in range(len(plotAKs)): aa = plotAKs[ii] color = py.cm.jet(cnorm(Kp_K[0, aa])) idx = np.where(Kp_K[:, aa] != 0)[0] tmpAx = py.subplot(len(plotAKs), 1, ii + 1, sharex=sharedAxis) if sharedAxis == None: sharedAxis = tmpAx foo = py.plot(temp[idx], Kp_K[idx, aa], 'k-', color=color, linewidth=2) py.setp(py.gca().get_xticklabels(), visible=False) minVal = Kp_K[idx, aa].min() py.ylim(minVal, minVal + 0.018) py.xlim(5000, 32000) py.ylabel('Kp - K') py.text(25000, minVal + 0.012, 'AKs = %.1f' % AKs[aa], color=color, weight='bold') py.setp(py.gca().get_xticklabels(), visible=True) py.xlabel('T_eff (K)') py.savefig('plots/syn_nir_Kp-K_T_sample.png')
def make_tec_screen_plots(pp, tec_screen, residuals, station_positions, source_names, times, height, order, beta_val, r_0, prefix = 'frame_', remove_gradient=True, show_source_names=False, min_tec=None, max_tec=None): """Makes plots of TEC screens Keyword arguments: pp -- array of piercepoint locations tec_screen -- array of TEC screen values at the piercepoints residuals -- array of TEC screen residuals at the piercepoints source_names -- array of source names times -- array of times height -- height of screen (m) order -- order of screen (e.g., number of KL base vectors to keep) r_0 -- scale size of phase fluctuations (m) beta_val -- power-law index for phase structure function (5/3 => pure Kolmogorov turbulence) prefix -- prefix for output file names remove_gradient -- fit and remove a gradient from each screen show_source_names -- label sources on screen plots min_tec -- minimum TEC value for plot range max_tec -- maximum TEC value for plot range """ from pylab import kron, concatenate, pinv, norm, newaxis, normalize import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1.inset_locator import inset_axes import numpy as np import os from operations.tecscreen import calc_piercepoint import progressbar root_dir = os.path.dirname(prefix) if root_dir == '': root_dir = './' prestr = os.path.basename(prefix) + 'screen_' try: os.makedirs(root_dir) except OSError: pass N_stations = station_positions.shape[0] N_sources = len(source_names) N_times = len(times) A = concatenate([kron(np.eye(N_sources), np.ones((N_stations,1))), kron(np.ones((N_sources,1)), np.eye(N_stations))], axis=1) N_piercepoints = N_sources * N_stations P = np.eye(N_piercepoints) - np.dot(np.dot(A, pinv(np.dot(A.T, A))), A.T) x, y, z = station_positions[0, :] east = np.array([-y, x, 0]) east = east / norm(east) north = np.array([ -x, -y, (x*x + y*y)/z]) north = north / norm(north) up = np.array([x ,y, z]) up = up / norm(up) T = concatenate([east[:, newaxis], north[:, newaxis]], axis=1) pp1 = np.dot(pp[0, :, :], T) lower = np.amin(pp1, axis=0) upper = np.amax(pp1, axis=0) extent = upper - lower lower = lower - 0.05 * extent upper = upper + 0.05 * extent extent = upper - lower Nx = 25 Ny = int(extent[1] / extent[0] * np.float(Nx)) xr = np.arange(lower[0], upper[0], extent[0]/Nx) yr = np.arange(lower[1], upper[1], extent[1]/Ny) screen = np.zeros((Nx, Ny, N_times)) gradient = np.zeros((Nx, Ny, N_times)) residuals = residuals.transpose([0, 2, 1]).reshape(N_piercepoints, N_times) fitted_tec1 = tec_screen.transpose([0, 2, 1]).reshape(N_piercepoints, N_times) + residuals logging.info('Calculating TEC screen images...') pbar = progressbar.ProgressBar(maxval=N_times).start() ipbar = 0 for k in range(N_times): D = np.resize(pp[k, :, :], (N_piercepoints, N_piercepoints, 3)) D = np.transpose(D, (1, 0, 2)) - D D2 = np.sum(D**2, axis=2) C = -(D2 / r_0**2)**(beta_val / 2.0) / 2.0 f = np.dot(pinv(C), tec_screen[:, k, :].reshape(N_piercepoints)) for i, x in enumerate(xr[0: Nx]): for j, y in enumerate(yr[0: Ny]): p = calc_piercepoint(np.dot(np.array([x, y]), np.array([east, north])), up, height) d2 = np.sum(np.square(pp[k, :, :] - p[0]), axis=1) c = -(d2 / ( r_0**2 ))**(beta_val / 2.0) / 2.0 screen[i, j, k] = np.dot(c, f) # Fit and remove a gradient. # Plot gradient in lower-left corner with its own color bar? if remove_gradient: xs, ys = np.indices(screen.shape[0:2]) zs = screen[:, :, k] XYZ = [] for xf, yf in zip(xs.flatten().tolist(), ys.flatten().tolist()): XYZ.append([xf, yf, zs[xf, yf]]) XYZ = np.array(XYZ) a, b, c = fitPLaneLTSQ(XYZ) grad_plane = a * xs + b * ys + c gradient[:, :, k] = grad_plane screen[:, :, k] = screen[:, :, k] - grad_plane screen[:, :, k] = screen[:, :, k] - np.mean(screen[:, :, k]) for t in range(fitted_tec1.shape[0]): xs_pt = np.where(np.array(xr) > pp1[t, 0])[0][0] ys_pt = np.where(np.array(yr) > pp1[t, 1])[0][0] grad_plane_pt = a * xs_pt + b * ys_pt + c fitted_tec1[t, k] = fitted_tec1[t, k] - grad_plane_pt fitted_tec1[:, k] = fitted_tec1[:, k] - np.mean(fitted_tec1[:, k]) pbar.update(ipbar) ipbar += 1 pbar.finish() if min_tec is None: vmin = np.min([np.amin(screen), np.amin(fitted_tec1)]) else: vmin = min_tec if max_tec is None: vmax = np.max([np.amax(screen), np.amax(fitted_tec1)]) else: vmax = max_tec logging.info('Plotting TEC screens...') fig, ax = plt.subplots(figsize=[7, 7]) pbar = progressbar.ProgressBar(maxval=N_times).start() ipbar = 0 for k in range(N_times): plt.clf() im = plt.imshow(screen.transpose([1, 0, 2])[:, :, k], cmap = plt.cm.jet, origin = 'lower', interpolation = 'nearest', extent = (xr[0]/1000.0, xr[-1]/1000.0, yr[0]/1000.0, yr[-1]/1000.0), vmin=vmin, vmax=vmax) sm = plt.cm.ScalarMappable(cmap=plt.cm.jet, norm=normalize(vmin=vmin, vmax=vmax)) sm._A = [] cbar = plt.colorbar(im) cbar.set_label('TECU', rotation=270) x = [] y = [] s = [] c = [] for j in range(fitted_tec1.shape[0]): x.append(pp1[j, 0] / 1000.0) y.append(pp1[j, 1] / 1000.0) xs = np.where(np.array(xr) > pp1[j, 0])[0][0] ys = np.where(np.array(yr) > pp1[j, 1])[0][0] fit_screen_diff = abs(fitted_tec1[j, k] - screen[xs, ys, k]) s.append(max(20*fit_screen_diff/0.01, 10)) c.append(sm.to_rgba(fitted_tec1[j, k])) plt.scatter(x, y, s=s, c=c) if show_source_names: labels = source_names for label, xl, yl in zip(labels, x[0::N_stations], y[0::N_stations]): plt.annotate( label, xy = (xl, yl), xytext = (-2, 2), textcoords = 'offset points', ha = 'right', va = 'bottom') plt.title('Screen {0}'.format(k)) plt.xlim(xr[-1]/1000.0, xr[0]/1000.0) plt.ylim(yr[0]/1000.0, yr[-1]/1000.0) plt.xlabel('Projected Distance along RA (km)') plt.ylabel('Projected Distance along Dec (km)') if remove_gradient: axins = inset_axes(ax, width="15%", height="10%", loc=2) axins.imshow(gradient.transpose([1, 0, 2])[:, : ,k], cmap = plt.cm.jet, origin = 'lower', interpolation = 'nearest', extent = (xr[0]/1000.0, xr[-1]/1000.0, yr[0]/1000.0, yr[-1]/1000.0), vmin=vmin, vmax=vmax) plt.xticks(visible=False) plt.yticks(visible=False) axins.set_xlim(xr[-1]/1000.0, xr[0]/1000.0) axins.set_ylim(yr[0]/1000.0, yr[-1]/1000.0) plt.savefig(root_dir+'/'+prestr+'frame%0.3i.png' % k) pbar.update(ipbar) ipbar += 1 pbar.finish() plt.close(fig)
plt.gray() plt.grid() plt.pause(0.001) clusters = CLUBSclustering(DS,2) print clusters xc, yc, wc = [],[],[] for i in xrange(len(clusters)): xc.append(clusters[i][0][0]) yc.append(clusters[i][0][1]) wc.append(clusters[i][1]) #area = [200*np.sqrt(w) for w in wc] #area = [np.sqrt(w) for w in wc] area = wc normal = pylab.normalize(min(wc), max(wc)) colors = pylab.cm.jet(normal(wc)) rectangles = [] for c,cl in zip(colors,pq.listOfClusters): bottomleft = cl.limitsLow extendright = cl.limitsHigh[0]-cl.limitsLow[0] extendtop = cl.limitsHigh[1]-cl.limitsLow[1] rectangles.append(matplotlib.patches.Rectangle(bottomleft,extendright,extendtop, color=c, alpha = 0.3)) for r in rectangles: plt.gca().add_patch(r) plt.axis([0,dim,0,dim]) plt.pause(0.001) plt.scatter(xc,yc,c='red',s=area,alpha=0.9) plt.pause(0.001)
rbf = Rbf(x, y) fi = rbf(xi) p.subplot(2, 1, 2) p.plot(x, y, "bo", xi, fi, "g", xi, s.sin(xi), "r") p.title("RBF interpolation - multiquadrics") p.savefig("rbf1d.png") p.close() # 2-d tests - setup scattered data x = s.rand(100) * 4.0 - 2.0 y = s.rand(100) * 4.0 - 2.0 z = x * s.exp(-x ** 2 - y ** 2) ti = s.linspace(-2.0, 2.0, 100) (XI, YI) = s.meshgrid(ti, ti) # use RBF rbf = Rbf(x, y, z, epsilon=2) ZI = rbf(XI, YI) # plot the result n = p.normalize(-2.0, 2.0) p.subplot(1, 1, 1) p.pcolor(XI, YI, ZI, cmap=p.cm.jet) p.scatter(x, y, 100, z, cmap=p.cm.jet) p.title("RBF interpolation - multiquadrics") p.xlim(-2, 2) p.ylim(-2, 2) p.colorbar() p.savefig("rbf2d.png") p.close()
def plot_connectivity_circle_cvu(con, nodes_numberless, indices=None, n_lines=10000, node_colors=None, colormap='YlOrRd', fig=None, reqrois=[], suppress_extra_rois=False, node_angles=None, node_width=None, facecolor='black', textcolor='white', node_edgecolor='black', linewidth=1.5, vmin=None, vmax=None, colorbar=False, title=None, fontsize_names='auto', bilateral_symmetry=True): """Visualize connectivity as a circular graph. Note: This code is originally taken from public open-source examples in matplotlib by Nicolas P. Rougier. It was adapted for use in MNE python, primarily by Martin Luessi, but also by all the other contributors to MNE python. There are some differences between the current version and the MNE python version. Most importantly, the current version offers less flexibility of the layout of the plot and has algorithms to determine this layout automatically given the ordering of the CVU dataset. Each hemisphere takes up roughly half the space and the left hemisphere is always on the left side of the plot. Then there is a very complex and poorly documented algorithm to randomly suppress extra label names so that all of the label names that result are readable. Note that the suppression of label names can be overwritten in the GUI although it is quite effortful, typically it is recommended to do image postprocessing instead. Parameters ---------- con : array Connectivity scores. Can be a square matrix, or a 1D array. If a 1D array is provided, "indices" has to be used to define the connection indices. nodes_numberless : list of str Node names. The order corresponds to the order in con. indices : tuple of arrays | None Two arrays with indices of connections for which the connections strenghts are defined in con. Only needed if con is a 1D array. n_lines : int | None If not None, only the n_lines strongest connections (strenght=abs(con)) are drawn. node_angles : array, shape=(len(nodes_numberless,)) | None Array with node positions in degrees. If None, the nodes are equally spaced on the circle. See mne.viz.circular_layout. node_width : float | None Width of each node in degrees. If None, "360. / len(nodes_numberless)" is used. node_colors : list of tuples | list of str List with the color to use for each node. If fewer colors than nodes are provided, the colors will be repeated. Any color supported by matplotlib can be used, e.g., RGBA tuples, named colors. facecolor : str Color to use for background. See matplotlib.colors. textcolor : str Color to use for text. See matplotlib.colors. node_edgecolor : str Color to use for lines around nodes. See matplotlib.colors. linewidth : float Line width to use for connections. colormap : str Colormap to use for coloring the connections. vmin : float | None Minimum value for colormap. If None, it is determined automatically. vmax : float | None Maximum value for colormap. If None, it is determined automatically. colorbar : bool Display a colorbar or not. title : str The figure title. fontsize_names : int | str The fontsize for the node labels. If 'auto', the program attempts to determine a reasonable size. 'auto' is the default value. Returns ------- fig : instance of pyplot.Figure The figure handle. """ n_nodes = len(nodes_numberless) #reverse the lower hemisphere so that the circle is bilaterally symmetric start_hemi = 'l' first_hemi = nodes_numberless[0][0] def find_pivot(ls, item): for i, l in enumerate(ls): if l[0] != item: return i hemi_pivot = find_pivot(nodes_numberless, first_hemi) if bilateral_symmetry: if start_hemi == first_hemi: nodes_numberless = (nodes_numberless[:hemi_pivot] + nodes_numberless[:hemi_pivot - 1:-1]) node_colors = (node_colors[:hemi_pivot] + node_colors[:hemi_pivot - 1:-1]) if indices.size > 0: indices = indices.copy() indices[np.where(indices >= hemi_pivot)] = ( n_nodes - 1 + hemi_pivot - indices[np.where(indices >= hemi_pivot)]) else: nodes_numberless = (nodes_numberless[hemi_pivot:] + nodes_numberless[hemi_pivot - 1::-1]) node_colors = (node_colors[hemi_pivot:] + node_colors[hemi_pivot - 1::-1]) if indices.size > 0: indices_x = indices.copy() indices_x[np.where(indices < hemi_pivot)] = ( n_nodes - 1 - indices[np.where(indices < hemi_pivot)]) indices_x[np.where(indices >= hemi_pivot)] = ( -hemi_pivot + indices[np.where(indices >= hemi_pivot)]) indices = indices_x del indices_x #if bilateral symmetry is turned off, then still put the #left hemisphere on the left side else: if start_hemi != first_hemi: nodes_numberless = (nodes_numberless[hemi_pivot:] + nodes_numberless[:hemi_pivot]) node_colors = (node_colors[hemi_pivot:] + node_colors[:hemi_pivot]) if indices.size > 0: indices_x = indices.copy() indices_x[np.where(indices < hemi_pivot)] = ( hemi_pivot + indices[np.where(indices < hemi_pivot)]) indices_x[np.where(indices >= hemi_pivot)] = ( -hemi_pivot + indices[np.where(indices >= hemi_pivot)]) indices = indices_x del indices_x if node_angles is not None: if len(node_angles) != n_nodes: raise ValueError('node_angles has to be the same length ' 'as nodes_numberless') # convert it to radians node_angles = node_angles * np.pi / 180 else: # uniform layout on unit circle node_angles = np.linspace(0, 2 * np.pi, n_nodes, endpoint=False) node_angles += np.pi / 2 if node_width is None: node_width = 2 * np.pi / n_nodes else: node_width = node_width * np.pi / 180 # handle 1D and 2D connectivity information if con.ndim == 1: if indices is None: raise ValueError('indices has to be provided if con.ndim == 1') #we use 1D indices elif con.ndim == 2: if con.shape[0] != n_nodes or con.shape[1] != n_nodes: raise ValueError('con has to be 1D or a square matrix') # we use the lower-triangular part indices = tril_indices(n_nodes, -1) con = con[indices] else: raise ValueError('con has to be 1D or a square matrix') # get the colormap if isinstance(colormap, CustomColormap): colormap = colormap._get__pl() elif isinstance(colormap, basestring): colormap = pl.get_cmap(colormap) # Make figure background the same colors as axes if fig == None: fig = pl.figure(figsize=(5, 5), facecolor=facecolor) else: fig = pl.figure(num=fig.number) # Use a polar axes axes = pl.subplot(111, polar=True, axisbg=facecolor) #else: # Use the first axis already in the figure #axes = fig.get_axes()[0] # No ticks, we'll put our own pl.xticks([]) pl.yticks([]) # Set y axes limit pl.ylim(0, 10) #pl.ylim(ymin=0) axes.spines['polar'].set_visible(False) # Draw lines between connected nodes, only draw the strongest connections if n_lines is not None and len(con) > n_lines: con_thresh = np.sort(np.abs(con).ravel())[-n_lines] else: con_thresh = 0. # get the connections which we are drawing and sort by connection strength # this will allow us to draw the strongest connections first con_abs = np.abs(con) con_draw_idx = np.where(con_abs >= con_thresh)[0] con = con[con_draw_idx] con_abs = con_abs[con_draw_idx] indices = [ind[con_draw_idx] for ind in indices] # input is already sorted #sort_idx = np.argsort(con_abs) #con_abs = con_abs[sort_idx] #con = con[sort_idx] #indices = [ind[sort_idx] for ind in indices] # Get vmin vmax for color scaling if np.size(con) > 0: if vmin is None: vmin = np.min(con[np.abs(con) >= con_thresh]) if vmax is None: vmax = np.max(con) vrange = vmax - vmin # We want o add some "noise" to the start and end position of the # edges: We modulate the noise with the number of connections of the # node and the connection strength, such that the strongest connections # are closer to the node center nodes_n_con = np.zeros((n_nodes), dtype=np.int) for i, j in zip(indices[0], indices[1]): nodes_n_con[i] += 1 nodes_n_con[j] += 1 # initalize random number generator so plot is reproducible rng = np.random.mtrand.RandomState(seed=0) n_con = len(indices[0]) noise_max = 0.25 * node_width start_noise = rng.uniform(-noise_max, noise_max, n_con) end_noise = rng.uniform(-noise_max, noise_max, n_con) nodes_n_con_seen = np.zeros_like(nodes_n_con) for i, (start, end) in enumerate(zip(indices[0], indices[1])): nodes_n_con_seen[start] += 1 nodes_n_con_seen[end] += 1 start_noise[i] *= ((nodes_n_con[start] - nodes_n_con_seen[start]) / nodes_n_con[start]) end_noise[i] *= ((nodes_n_con[end] - nodes_n_con_seen[end]) / nodes_n_con[end]) # scale connectivity for colormap (vmin<=>0, vmax<=>1) if np.size(con) > 0: con_val_scaled = (con - vmin) / vrange # Finally, we draw the connections for pos, (i, j) in enumerate(zip(indices[0], indices[1])): # Start point t0, r0 = node_angles[i], 7 # End point t1, r1 = node_angles[j], 7 # Some noise in start and end point t0 += start_noise[pos] t1 += end_noise[pos] verts = [(t0, r0), (t0, 5), (t1, 5), (t1, r1)] codes = [ m_path.Path.MOVETO, m_path.Path.CURVE4, m_path.Path.CURVE4, m_path.Path.LINETO ] path = m_path.Path(verts, codes) color = colormap(con_val_scaled[pos]) # Actual line patch = m_patches.PathPatch(path, fill=False, edgecolor=color, linewidth=linewidth, alpha=1.) axes.add_patch(patch) # Draw ring with colored nodes #radii = np.ones(n_nodes) * 8 radii = np.ones(n_nodes) - .2 bars = axes.bar(node_angles, radii, width=node_width, bottom=7.2, edgecolor=node_edgecolor, linewidth=0, facecolor='.9', align='center', zorder=10) for bar, color in zip(bars, node_colors): bar.set_facecolor(color) # Draw node labels #basic idea -- check for "too close" pairs. too close is pi/50 #remove smallest "too close" pairs. if multiple tied within a segment, #remove pairs at equal spacing. #calculate each segment individually and find the extent of the segment. #TODO this parameter, too_close, could be modified and adjusted for #a variety of sizes if ever the circle could be panned (or if it were #merely made bigger). determining the proper value is a matter of #userspace testing too_close = np.pi / 50 # get angles for text placement text_angles = get_labels_avg_idx(nodes_numberless, n_nodes, frac=1, pad=np.pi / 400) #print reqrois segments = get_tooclose_segments(text_angles, too_close, reqrois) for segment in segments: prune_segment(text_angles, segment, too_close) #print suppress_extra_rois, len(reqrois) if suppress_extra_rois and len(reqrois) > 0: for name in text_angles.keys(): if name not in reqrois: del text_angles[name] if fontsize_names == 'auto': fontsize_names = 10 #TODO segments with many guaranteed ROIs are potentially spatially skewed #this is probably not worth fixing #now calculate how many pairs must be removed and remove them at equal #spacing. there should be no more than theta/(n-1) >= pi/50 pairs where #theta is the extent and n is the number of pairs. #n-1 is used because each segment holds one item by default #for angles,hemi in [(text_angles_sh,start_hemi),(text_angles_eh,end_hemi)]: # for name in angles: if fontsize_names == 'auto': fontsize_names = 8 for name in text_angles: angle_rad = text_angles[name] + np.pi / 2 #if hemi is end_hemi: # angle_rad+=np.pi angle_deg = 180 * angle_rad / np.pi if angle_deg >= 270 or angle_deg < 90: ha = 'left' else: # Flip the label, so text is always upright angle_deg += 180 ha = 'right' name_nonum = name.strip('1234567890') hemi = '' axes.text(angle_rad, 8.2, hemi + name_nonum, size=fontsize_names, rotation=angle_deg, rotation_mode='anchor', horizontalalignment=ha, verticalalignment='center', color=textcolor) if title is not None: pl.subplots_adjust(left=0.2, bottom=0.2, right=0.8, top=0.75) pl.figtext(0.03, 0.95, title, color=textcolor, fontsize=14) else: pl.subplots_adjust(left=0.2, bottom=0.2, right=0.8, top=0.8) if colorbar: sm = pl.cm.ScalarMappable(cmap=colormap, norm=pl.normalize(vmin=vmin, vmax=vmax)) sm.set_array(np.linspace(vmin, vmax)) ax = fig.add_axes([.92, 0.03, .015, .25]) cb = fig.colorbar(sm, cax=ax) cb_yticks = pl.getp(cb.ax.axes, 'yticklabels') pl.setp(cb_yticks, color=textcolor) return fig, node_angles
ln=[str(int(float(a[-1]))) for a in ln0] # ln0=list_names[organize['CSdelay']][1::2] # ln+=['2.5, ' + str(int(float(a[-1]))) for a in ln0] colors=misc.make_N_colors('copper', len(l)) for i, trace in enumerate(l): x=numpy.linspace(-numpy.pi*3,numpy.pi*3,len(trace)) norm=sum(trace)*(x[-1]-x[0])/len(x) ax.plot(x, trace/norm, color=colors[i]) ax.set_xlim([-numpy.pi,numpy.pi]) sm = pylab.cm.ScalarMappable(cmap='copper', norm=pylab.normalize(vmin=0, vmax=len(ln)-1)) sm._A = [] box = ax.get_position() pos=[box.x0+1.03*box.width, box.y0+box.height*0.1, 0.01, box.height*0.8] axColor=pylab.axes(pos) cbar=pylab.colorbar(sm, cax=axColor, ticks=range(len(ln))) cbar.ax.tick_params( length=1, ) cbar.ax.set_yticklabels(ln, fontsize=5*scale) # cbar.ax.set_yticklabels(ln, fontsize=5*scale) # ax.text(1.3, 0.5, r'$t_{delay}^{CTX\to str}$ (ms)', # transform=ax.transAxes, va='center', rotation=270)
def truth_nd(*args): "a gausian sphere" x = asarray(list(args), "float64") return exp(-sqrt((x ** 2).sum(axis=0))) # 2D example N = 300 xi = random.rand(N) yi = random.rand(N) di = truth_2d(xi, yi) xa, ya = mgrid[0:1:50j, 0:1:50j] s = Rbf(xi, yi, di) da = s(xa, ya) pl.figure() n = pl.normalize(-1.0, 1.0) pl.pcolor(xa, ya, da, norm=n, cmap=pl.cm.jet) pl.scatter(xi, yi, 100, di, norm=n, cmap=pl.cm.jet) pl.axis([0.0, 1.0, 0.0, 1.0]) pl.colorbar() pl.draw() # 3d example N = 300 xi = 2.0 * random.randn(N) yi = 2.0 * random.randn(N) zi = 2.0 * random.randn(N) di = truth_nd(xi, yi, zi) zas = [-0.25, 0.0, 0.25, 0.75] xa, ya = mgrid[-1:1:50j, -1:1:50j] s = Rbf(xi, yi, zi, di) fig = pl.figure(figsize=(12, 3))
def make_tec_screen_plots(pp, rr, tec_fit_white, tec_fit, station_positions, source_names, times, height, order, beta_val, r_0, prefix = 'frame_', remove_gradient=True): """Makes plots of TEC screens""" import pylab import numpy as np import os from operations.tecscreen import calc_piercepoint import progressbar root_dir = os.path.dirname(prefix) if root_dir == '': root_dir = './' prestr = os.path.basename(prefix) try: os.makedirs(root_dir) except OSError: pass N_stations = station_positions.shape[0] N_sources = len(source_names) N_times = len(times) A = pylab.concatenate([pylab.kron(np.eye(N_sources), np.ones((N_stations,1))), pylab.kron(np.ones((N_sources,1)), np.eye(N_stations))], axis=1) N_piercepoints = N_sources * N_stations P = np.eye(N_piercepoints) - np.dot(np.dot(A, pylab.pinv(np.dot(A.T, A))), A.T) x,y,z = station_positions[0, :] east = np.array([-y, x, 0]) east = east / pylab.norm(east) north = np.array([ -x, -y, (x*x + y*y)/z]) north = north / pylab.norm(north) up = np.array([x,y,z]) up = up / pylab.norm(up) T = pylab.concatenate([east[:, pylab.newaxis], north[:, pylab.newaxis]], axis=1) pp1 = np.dot(pp[0, :, :], T) lower = np.amin(pp1, axis=0) upper = np.amax(pp1, axis=0) extent = upper - lower lower = lower - 0.05 * extent upper = upper + 0.05 * extent extent = upper - lower N = 50 xr = np.arange(lower[0], upper[0], extent[0]/N) yr = np.arange(lower[1], upper[1], extent[1]/N) screen = np.zeros((N, N, N_times)) fitted_tec1 = tec_fit.transpose([0, 2, 1]).reshape(N_piercepoints, N_times) + np.dot(P, rr-tec_fit.transpose([0, 2, 1]).reshape(N_piercepoints, N_times)) logging.info('Calculating TEC screen images...') pbar = progressbar.ProgressBar(maxval=N_times).start() ipbar = 0 for k in range(N_times): f = tec_fit_white[:, k, :] for i, x in enumerate(xr[0: N]): for j, y in enumerate(yr[0: N]): p = calc_piercepoint(np.dot(np.array([x, y]), np.array([east, north])), up, height) d2 = np.sum(np.square(pp[k, :, :] - p[0]), axis=1) c = -(d2 / ( r_0**2 ) )**( beta_val / 2.0 ) / 2.0 screen[j, i, k] = np.dot(c, f.reshape(N_piercepoints)) # Fit and remove a gradient if remove_gradient: xs, ys = np.indices(screen.shape[0:2]) zs = screen[:, :, k] XYZ = [] for xf, yf in zip(xs.flatten().tolist(), ys.flatten().tolist()): XYZ.append([xf, yf, zs[xf, yf]]) XYZ = np.array(XYZ) a, b, c = fitPLaneLTSQ(XYZ) grad_plane = a * xs + b * ys + c screen[:, :, k] = screen[:, :, k] - grad_plane for t in range(fitted_tec1.shape[0]): xs_pt = np.where(np.array(xr) > pp1[t, 0])[0][0] ys_pt = np.where(np.array(yr) > pp1[t, 1])[0][0] grad_plane_pt = a * ys_pt + b * xs_pt + c fitted_tec1[t, k] = fitted_tec1[t, k] - grad_plane_pt pbar.update(ipbar) ipbar += 1 pbar.finish() vmin = np.min([np.amin(screen), np.amin(fitted_tec1)]) vmax = np.max([np.amax(screen), np.amax(fitted_tec1)]) logging.info('Plotting TEC screens...') fig1 = pylab.figure(figsize = (7, 7)) pbar = progressbar.ProgressBar(maxval=N_times).start() ipbar = 0 for k in range(N_times): pylab.clf() im = pylab.imshow(screen[:, :, k], cmap = pylab.cm.jet, origin = 'lower', interpolation = 'nearest', extent = (xr[0], xr[-1], yr[0], yr[-1]), vmin = vmin, vmax = vmax) sm = pylab.cm.ScalarMappable(cmap = pylab.cm.jet, norm = pylab.normalize(vmin = vmin, vmax=vmax)) sm._A = [] pylab.title(str(i)) cbar = pylab.colorbar() cbar.set_label('TECU', rotation=270) x = [] y = [] s = [] c = [] for j in range(fitted_tec1.shape[0]): x.append(pp1[j,0]) y.append(pp1[j,1]) xs = np.where(np.array(xr) > pp1[j,0])[0][0] ys = np.where(np.array(yr) > pp1[j,1])[0][0] s.append(max(2400*abs(fitted_tec1[j, k] - screen[ys, xs, k]), 10)) c.append(sm.to_rgba(fitted_tec1[j, k])) pylab.scatter(x, y, s=s, c=c) labels = source_names for label, xl, yl in zip(labels, x[0::N_stations], y[0::N_stations]): pylab.annotate( label, xy = (xl, yl), xytext = (-20, 20), textcoords = 'offset points', ha = 'right', va = 'bottom', bbox = dict(boxstyle = 'round,pad=0.5', fc = 'gray', alpha = 0.5), arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0')) pylab.title('Time {0}'.format(k)) pylab.xlim(xr[-1], xr[0]) pylab.ylim(yr[0], yr[-1]) pylab.xlabel('Projected Distance (m)') pylab.ylabel('Projected Distance (m)') pylab.savefig(root_dir+'/'+prestr+'frame%0.3i.png' % k) pbar.update(ipbar) ipbar += 1 pbar.finish() pylab.close(fig1)
def make_tec_screen_plots(pp, tec_screen, residuals, station_positions, source_names, times, height, order, beta_val, r_0, prefix='frame_', remove_gradient=True, show_source_names=False, min_tec=None, max_tec=None): """Makes plots of TEC screens Keyword arguments: pp -- array of piercepoint locations tec_screen -- array of TEC screen values at the piercepoints residuals -- array of TEC screen residuals at the piercepoints source_names -- array of source names times -- array of times height -- height of screen (m) order -- order of screen (e.g., number of KL base vectors to keep) r_0 -- scale size of phase fluctuations (m) beta_val -- power-law index for phase structure function (5/3 => pure Kolmogorov turbulence) prefix -- prefix for output file names remove_gradient -- fit and remove a gradient from each screen show_source_names -- label sources on screen plots min_tec -- minimum TEC value for plot range max_tec -- maximum TEC value for plot range """ from pylab import kron, concatenate, pinv, norm, newaxis, normalize import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1.inset_locator import inset_axes import numpy as np import os from operations.tecscreen import calc_piercepoint import progressbar root_dir = os.path.dirname(prefix) if root_dir == '': root_dir = './' prestr = os.path.basename(prefix) + 'screen_' try: os.makedirs(root_dir) except OSError: pass N_stations = station_positions.shape[0] N_sources = len(source_names) N_times = len(times) A = concatenate([ kron(np.eye(N_sources), np.ones((N_stations, 1))), kron(np.ones((N_sources, 1)), np.eye(N_stations)) ], axis=1) N_piercepoints = N_sources * N_stations P = np.eye(N_piercepoints) - np.dot(np.dot(A, pinv(np.dot(A.T, A))), A.T) x, y, z = station_positions[0, :] east = np.array([-y, x, 0]) east = east / norm(east) north = np.array([-x, -y, (x * x + y * y) / z]) north = north / norm(north) up = np.array([x, y, z]) up = up / norm(up) T = concatenate([east[:, newaxis], north[:, newaxis]], axis=1) pp1 = np.dot(pp[0, :, :], T) lower = np.amin(pp1, axis=0) upper = np.amax(pp1, axis=0) extent = upper - lower lower = lower - 0.05 * extent upper = upper + 0.05 * extent extent = upper - lower Nx = 25 Ny = int(extent[1] / extent[0] * np.float(Nx)) xr = np.arange(lower[0], upper[0], extent[0] / Nx) yr = np.arange(lower[1], upper[1], extent[1] / Ny) screen = np.zeros((Nx, Ny, N_times)) gradient = np.zeros((Nx, Ny, N_times)) residuals = residuals.transpose([0, 2, 1]).reshape(N_piercepoints, N_times) fitted_tec1 = tec_screen.transpose([0, 2, 1]).reshape( N_piercepoints, N_times) + residuals logging.info('Calculating TEC screen images...') pbar = progressbar.ProgressBar(maxval=N_times).start() ipbar = 0 for k in range(N_times): D = np.resize(pp[k, :, :], (N_piercepoints, N_piercepoints, 3)) D = np.transpose(D, (1, 0, 2)) - D D2 = np.sum(D**2, axis=2) C = -(D2 / r_0**2)**(beta_val / 2.0) / 2.0 f = np.dot(pinv(C), tec_screen[:, k, :].reshape(N_piercepoints)) for i, x in enumerate(xr[0:Nx]): for j, y in enumerate(yr[0:Ny]): p = calc_piercepoint( np.dot(np.array([x, y]), np.array([east, north])), up, height) d2 = np.sum(np.square(pp[k, :, :] - p[0]), axis=1) c = -(d2 / (r_0**2))**(beta_val / 2.0) / 2.0 screen[i, j, k] = np.dot(c, f) # Fit and remove a gradient. # Plot gradient in lower-left corner with its own color bar? if remove_gradient: xs, ys = np.indices(screen.shape[0:2]) zs = screen[:, :, k] XYZ = [] for xf, yf in zip(xs.flatten().tolist(), ys.flatten().tolist()): XYZ.append([xf, yf, zs[xf, yf]]) XYZ = np.array(XYZ) a, b, c = fitPLaneLTSQ(XYZ) grad_plane = a * xs + b * ys + c gradient[:, :, k] = grad_plane screen[:, :, k] = screen[:, :, k] - grad_plane screen[:, :, k] = screen[:, :, k] - np.mean(screen[:, :, k]) for t in range(fitted_tec1.shape[0]): xs_pt = np.where(np.array(xr) > pp1[t, 0])[0][0] ys_pt = np.where(np.array(yr) > pp1[t, 1])[0][0] grad_plane_pt = a * xs_pt + b * ys_pt + c fitted_tec1[t, k] = fitted_tec1[t, k] - grad_plane_pt fitted_tec1[:, k] = fitted_tec1[:, k] - np.mean(fitted_tec1[:, k]) pbar.update(ipbar) ipbar += 1 pbar.finish() if min_tec is None: vmin = np.min([np.amin(screen), np.amin(fitted_tec1)]) else: vmin = min_tec if max_tec is None: vmax = np.max([np.amax(screen), np.amax(fitted_tec1)]) else: vmax = max_tec logging.info('Plotting TEC screens...') fig, ax = plt.subplots(figsize=[7, 7]) pbar = progressbar.ProgressBar(maxval=N_times).start() ipbar = 0 for k in range(N_times): plt.clf() im = plt.imshow(screen.transpose([1, 0, 2])[:, :, k], cmap=plt.cm.jet, origin='lower', interpolation='nearest', extent=(xr[0] / 1000.0, xr[-1] / 1000.0, yr[0] / 1000.0, yr[-1] / 1000.0), vmin=vmin, vmax=vmax) sm = plt.cm.ScalarMappable(cmap=plt.cm.jet, norm=normalize(vmin=vmin, vmax=vmax)) sm._A = [] cbar = plt.colorbar(im) cbar.set_label('TECU', rotation=270) x = [] y = [] s = [] c = [] for j in range(fitted_tec1.shape[0]): x.append(pp1[j, 0] / 1000.0) y.append(pp1[j, 1] / 1000.0) xs = np.where(np.array(xr) > pp1[j, 0])[0][0] ys = np.where(np.array(yr) > pp1[j, 1])[0][0] fit_screen_diff = abs(fitted_tec1[j, k] - screen[xs, ys, k]) s.append(max(20 * fit_screen_diff / 0.01, 10)) c.append(sm.to_rgba(fitted_tec1[j, k])) plt.scatter(x, y, s=s, c=c) if show_source_names: labels = source_names for label, xl, yl in zip(labels, x[0::N_stations], y[0::N_stations]): plt.annotate(label, xy=(xl, yl), xytext=(-2, 2), textcoords='offset points', ha='right', va='bottom') plt.title('Screen {0}'.format(k)) plt.xlim(xr[-1] / 1000.0, xr[0] / 1000.0) plt.ylim(yr[0] / 1000.0, yr[-1] / 1000.0) plt.xlabel('Projected Distance along RA (km)') plt.ylabel('Projected Distance along Dec (km)') if remove_gradient: axins = inset_axes(ax, width="15%", height="10%", loc=2) axins.imshow(gradient.transpose([1, 0, 2])[:, :, k], cmap=plt.cm.jet, origin='lower', interpolation='nearest', extent=(xr[0] / 1000.0, xr[-1] / 1000.0, yr[0] / 1000.0, yr[-1] / 1000.0), vmin=vmin, vmax=vmax) plt.xticks(visible=False) plt.yticks(visible=False) axins.set_xlim(xr[-1] / 1000.0, xr[0] / 1000.0) axins.set_ylim(yr[0] / 1000.0, yr[-1] / 1000.0) plt.savefig(root_dir + '/' + prestr + 'frame%0.3i.png' % k) pbar.update(ipbar) ipbar += 1 pbar.finish() plt.close(fig)
def plot_connectivity_circle_cvu(con, nodes_numberless, indices=None, n_lines=10000, node_colors=None, colormap='YlOrRd', fig=None, reqrois=[], suppress_extra_rois=False, node_angles=None, node_width=None, facecolor='black', textcolor='white', node_edgecolor='black',linewidth=1.5, vmin=None,vmax=None, colorbar=False, title=None, fontsize_names='auto'): """Visualize connectivity as a circular graph. Note: This code is based on the circle graph example by Nicolas P. Rougier http://www.loria.fr/~rougier/coding/recipes.html This function replicates functionality from MNE python, by Martin Luessi and others. Many changes are made from the MNE python version. Parameters ---------- con : array Connectivity scores. Can be a square matrix, or a 1D array. If a 1D array is provided, "indices" has to be used to define the connection indices. nodes_numberless : list of str Node names. The order corresponds to the order in con. indices : tuple of arrays | None Two arrays with indices of connections for which the connections strenghts are defined in con. Only needed if con is a 1D array. n_lines : int | None If not None, only the n_lines strongest connections (strenght=abs(con)) are drawn. node_angles : array, shape=(len(nodes_numberless,)) | None Array with node positions in degrees. If None, the nodes are equally spaced on the circle. See mne.viz.circular_layout. node_width : float | None Width of each node in degrees. If None, "360. / len(nodes_numberless)" is used. node_colors : list of tuples | list of str List with the color to use for each node. If fewer colors than nodes are provided, the colors will be repeated. Any color supported by matplotlib can be used, e.g., RGBA tuples, named colors. facecolor : str Color to use for background. See matplotlib.colors. textcolor : str Color to use for text. See matplotlib.colors. node_edgecolor : str Color to use for lines around nodes. See matplotlib.colors. linewidth : float Line width to use for connections. colormap : str Colormap to use for coloring the connections. vmin : float | None Minimum value for colormap. If None, it is determined automatically. vmax : float | None Maximum value for colormap. If None, it is determined automatically. colorbar : bool Display a colorbar or not. title : str The figure title. fontsize_names : int | str The fontsize for the node labels. If 'auto', the program attempts to determine a reasonable size. 'auto' is the default value. Returns ------- fig : instance of pyplot.Figure The figure handle. """ n_nodes = len(nodes_numberless) #start_hemi = nodes_numberless[0][:3] #end_hemi = nodes_numberless[-1][:3] #n_starthemi = sum(map(lambda lb:lb[:3]==start_hemi,nodes_numberless)) #n_endhemi = sum(map(lambda lb:lb[:3]==end_hemi,nodes_numberless)) if node_angles is not None: if len(node_angles) != n_nodes: raise ValueError('node_angles has to be the same length ' 'as nodes_numberless') # convert it to radians node_angles = node_angles * np.pi / 180 else: # uniform layout on unit circle node_angles = np.linspace(0, 2 * np.pi, n_nodes, endpoint=False) if node_width is None: node_width = 2 * np.pi / n_nodes else: node_width = node_width * np.pi / 180 # handle 1D and 2D connectivity information if con.ndim == 1: if indices is None: raise ValueError('indices has to be provided if con.ndim == 1') #we use 1D indices elif con.ndim == 2: if con.shape[0] != n_nodes or con.shape[1] != n_nodes: raise ValueError('con has to be 1D or a square matrix') # we use the lower-triangular part indices = tril_indices(n_nodes, -1) con = con[indices] else: raise ValueError('con has to be 1D or a square matrix') # get the colormap if isinstance(colormap, basestring): colormap = pl.get_cmap(colormap) # Make figure background the same colors as axes if fig==None: fig = pl.figure(figsize=(5, 5), facecolor=facecolor) else: fig = pl.figure(num=fig.number) # Use a polar axes axes = pl.subplot(111, polar=True, axisbg=facecolor) #else: # Use the first axis already in the figure #axes = fig.get_axes()[0] # No ticks, we'll put our own pl.xticks([]) pl.yticks([]) # Set y axes limit pl.ylim(0, 10) #pl.ylim(ymin=0) # Draw lines between connected nodes, only draw the strongest connections if n_lines is not None and len(con) > n_lines: con_thresh = np.sort(np.abs(con).ravel())[-n_lines] else: con_thresh = 0. # get the connections which we are drawing and sort by connection strength # this will allow us to draw the strongest connections first con_abs = np.abs(con) con_draw_idx = np.where(con_abs >= con_thresh)[0] con = con[con_draw_idx] con_abs = con_abs[con_draw_idx] indices = [ind[con_draw_idx] for ind in indices] # input is already sorted #sort_idx = np.argsort(con_abs) #con_abs = con_abs[sort_idx] #con = con[sort_idx] #indices = [ind[sort_idx] for ind in indices] # Get vmin vmax for color scaling if np.size(con)>0: if vmin is None: vmin = np.min(con[np.abs(con) >= con_thresh]) if vmax is None: vmax = np.max(con) vrange = vmax - vmin # We want o add some "noise" to the start and end position of the # edges: We modulate the noise with the number of connections of the # node and the connection strength, such that the strongest connections # are closer to the node center nodes_n_con = np.zeros((n_nodes), dtype=np.int) for i, j in zip(indices[0], indices[1]): nodes_n_con[i] += 1 nodes_n_con[j] += 1 # initalize random number generator so plot is reproducible rng = np.random.mtrand.RandomState(seed=0) n_con = len(indices[0]) noise_max = 0.25 * node_width start_noise = rng.uniform(-noise_max, noise_max, n_con) end_noise = rng.uniform(-noise_max, noise_max, n_con) nodes_n_con_seen = np.zeros_like(nodes_n_con) for i, (start, end) in enumerate(zip(indices[0], indices[1])): nodes_n_con_seen[start] += 1 nodes_n_con_seen[end] += 1 start_noise[i] *= ((nodes_n_con[start] - nodes_n_con_seen[start]) / nodes_n_con[start]) end_noise[i] *= ((nodes_n_con[end] - nodes_n_con_seen[end]) / nodes_n_con[end]) # scale connectivity for colormap (vmin<=>0, vmax<=>1) if np.size(con)>0: con_val_scaled = (con - vmin) / vrange # Finally, we draw the connections for pos, (i, j) in enumerate(zip(indices[0], indices[1])): # Start point t0, r0 = node_angles[i], 7 # End point t1, r1 = node_angles[j], 7 # Some noise in start and end point t0 += start_noise[pos] t1 += end_noise[pos] verts = [(t0, r0), (t0, 5), (t1, 5), (t1, r1)] codes = [m_path.Path.MOVETO, m_path.Path.CURVE4, m_path.Path.CURVE4, m_path.Path.LINETO] path = m_path.Path(verts, codes) color = colormap(con_val_scaled[pos]) # Actual line patch = m_patches.PathPatch(path, fill=False, edgecolor=color, linewidth=linewidth, alpha=1.) axes.add_patch(patch) # Draw ring with colored nodes #radii = np.ones(n_nodes) * 8 radii=np.ones(n_nodes)-.2 bars = axes.bar(node_angles, radii, width=node_width, bottom=7.2, edgecolor=node_edgecolor, linewidth=0, facecolor='.9', align='center',zorder=10) for bar, color in zip(bars, node_colors): bar.set_facecolor(color) # Draw node labels #basic idea -- check for "too close" pairs. too close is pi/50 #remove smallest "too close" pairs. if multiple tied within a segment, #remove pairs at equal spacing. #calculate each segment individually and find the extent of the segment. #TODO this parameter, too_close, could be modified and adjusted for #a variety of sizes if ever the circle could be panned (or if it were #merely made bigger). determining the proper value is a matter of #userspace testing too_close = np.pi/50 # get angles for text placement text_angles = get_labels_avg_idx(nodes_numberless,n_nodes,frac=1,pad=np.pi/400) #print reqrois segments = get_tooclose_segments(text_angles,too_close,reqrois) for segment in segments: prune_segment(text_angles,segment,too_close) #print suppress_extra_rois, len(reqrois) if suppress_extra_rois and len(reqrois)>0: for name in text_angles.keys(): if name not in reqrois: del text_angles[name] if fontsize_names=='auto': fontsize_names=10 #TODO segments with many guaranteed ROIs are potentially spatially skewed #this is probably not worth fixing #now calculate how many pairs must be removed and remove them at equal #spacing. there should be no more than theta/(n-1) >= pi/50 pairs where #theta is the extent and n is the number of pairs. #n-1 is used because each segment holds one item by default #for angles,hemi in [(text_angles_sh,start_hemi),(text_angles_eh,end_hemi)]: # for name in angles: if fontsize_names=='auto': fontsize_names=8 for name in text_angles: angle_rad = text_angles[name] #if hemi is end_hemi: # angle_rad+=np.pi angle_deg = 180*angle_rad/np.pi if angle_deg >= 270 or angle_deg < 90: ha = 'left' else: # Flip the label, so text is always upright angle_deg += 180 ha = 'right' name_nonum=name.strip('1234567890') hemi='' axes.text(angle_rad, 8.2, hemi+name_nonum, size=fontsize_names, rotation=angle_deg, rotation_mode='anchor', horizontalalignment=ha, verticalalignment='center', color=textcolor) if title is not None: pl.subplots_adjust(left=0.2, bottom=0.2, right=0.8, top=0.75) pl.figtext(0.03, 0.95, title, color=textcolor, fontsize=14) else: pl.subplots_adjust(left=0.2, bottom=0.2, right=0.8, top=0.8) if colorbar: sm = pl.cm.ScalarMappable(cmap=colormap, norm=pl.normalize(vmin=vmin, vmax=vmax)) sm.set_array(np.linspace(vmin, vmax)) ax = fig.add_axes([.92, 0.03, .015, .25]) cb = fig.colorbar(sm, cax=ax) cb_yticks = pl.getp(cb.ax.axes, 'yticklabels') pl.setp(cb_yticks, color=textcolor) return fig
def clickScat(array2d, array3d, xScat=None, xerror3d=None, yerror3d=None, array3d2=None, xerror3d2=None, yerror3d2=None, fn=None, xMap=None, yMap=None, modelError=False, ylimScat=None): """ figureHandles=clickScat(array2d, array3d, xScat=None, xerror3d=None, yerror3d=None, array3d2=None, xerror3d2=None, yerror3d2=None, fn=None, xMap=None, yMap=None): xScat: x-axis variables for Scatter Plot. Has to be the same length as last dimension of array3d.shape[2] xerror3d: errorbars for x-axis. two sided. fn:'annual' """ import insar dateaxis=False; if xScat is None: xScat=np.r_[0:array3d.shape[2]]; elif isinstance(xScat[0], P.matplotlib.dates.datetime.date): xScat=P.matplotlib.dates.date2num(xScat); dateaxis=True; def onclick(event): P.figure(fh.number); P.clf(); #ax = P.gca() #inv = ax.transData.inverted() #A=inv.transform((event.x, event.y)) #A[1]=np.int(np.round((1-A[1])*array2d.shape[1])) #A[0]=np.int(np.round((A[0])*array2d.shape[0])) try: y=np.round(event.xdata); except: return x=np.round(event.ydata); #ARRAY MAPPING IS first axis y(rows) and second axis is cols (x) if all(np.isnan(array3d[x, y,:])): #if there are no points to plot (all nan) then return return #Plot second scatter data. if array3d2 is not None: if isinstance(array3d2, list): if yerror3d is None: w=np.ones(array3d[x, y,:].shape); else: w=basic.rescale(1./yerror3d[x,y,:], [1,2]) markers=['*','+','s','d','x','v','<','>','^'] m=0; for arr in array3d2: print ("%d, %d, %d" % (x,y,m)) P.scatter(xScat, arr[x, y,:], marker=markers[m]); idx=~( np.isnan(arr[x, y,:]) | np.isnan(array3d[x, y,:])) #c=insar.crosscorrelate(basic.nonan(w[idx]*arr[x, y,idx]),basic.nonan(w[idx]*array3d[x, y,idx])) slope, intercept, r_value, p_value, std_err = scipy.stats.linregress(basic.nonan(w[idx]*arr[x, y,idx]), basic.nonan(w[idx]*array3d[x, y,idx])) P.annotate(str("r2[%s]: %0.2f" % (markers[m],r_value)), (0,0.9-m*0.05), xycoords='axes fraction') m=m+1; else: if xerror3d2 is None: xerr=None; else: xerr=xerror3d2[x,y,:] if yerror3d2 is None: yerr=None; else: yerr=yerror3d2[x, y,:] P.errorbar(xScat,array3d2[x, y,:], xerr=xerr, yerr=yerr, marker='*', fmt='o'); #Plot function result as scatter data. p=None if fn is not None: if fn=='linear_amplitude_annual': dataMask=~np.isnan(array3d[x, y,:]) p0=np.array([1,0,0,basic.nonan(array3d[x, y,:]).mean() ]) fitfun=lambda p: (p[0]+p[1]*xScat[dataMask]/365. )* np.cos(2*np.pi*xScat[dataMask]/365.+p[2]) + p[3] xScat2=np.linspace(xScat.min(),xScat.max()) fitfun2=lambda p: (p[0]+p[1]*xScat2/365.) * np.cos(2*np.pi*xScat2/365.+p[2]) + p[3] #errfun=lambda p: sum(abs(basic.nonan(array3d[x, y,:])-fitfun(p))); if yerror3d is None: w=np.ones(array3d[x, y,:].shape); else: w=basic.rescale(1./yerror3d[x,y,:], [1,2]) errfun=lambda p: basic.nonan(w*array3d[x, y,:])-w[dataMask]*fitfun(p); #p=scipy.optimize.fmin_powell(errfun, p0) p=scipy.optimize.leastsq(errfun, p0); p=p[0]; P.scatter(xScat[dataMask], fitfun(p), marker='^'); sortedxy= np.squeeze(np.dstack([xScat2, fitfun2(p)])); sortedxy=sortedxy[sortedxy[:,0].argsort(),:] P.plot(sortedxy[:,0], sortedxy[:,1]); slope, intercept, r_value, p_value, std_err = scipy.stats.linregress(basic.nonan(w*array3d[x, y,:]),w[dataMask]*fitfun(p)) P.annotate(str("a0:%0.2f\na1:%0.2f\npha:%0.2f\nbias:%0.2f\nr2:%0.2f" % (p[0], p[1], p[2], p[3], r_value**2.)), (0.8,0.8), xycoords='axes fraction') elif fn=='quadratic_amplitude_annual': dataMask=~np.isnan(array3d[x, y,:]) p0=np.array([1,0,0,0,basic.nonan(array3d[x, y,:]).mean() ]) fitfun=lambda p: (p[0]+p[1]*xScat[dataMask]/365.+p[2]*(xScat[dataMask]/365.)**2. )* np.cos(2*np.pi*xScat[dataMask]/365.+p[3]) + p[4] xScat2=np.linspace(xScat.min(),xScat.max()) fitfun2=lambda p: (p[0]+p[1]*xScat2/365.+p[2]*(xScat2/365.)**2.) * np.cos(2*np.pi*xScat2/365.+p[3]) + p[4] #errfun=lambda p: sum(abs(basic.nonan(array3d[x, y,:])-fitfun(p))); if yerror3d is None: w=np.ones(array3d[x, y,:].shape); else: w=basic.rescale(1./yerror3d[x,y,:], [1,2]) errfun=lambda p: basic.nonan(w*array3d[x, y,:])-w[dataMask]*fitfun(p); #p=scipy.optimize.fmin_powell(errfun, p0) p=scipy.optimize.leastsq(errfun, p0); p=p[0]; P.scatter(xScat[dataMask], fitfun(p), marker='^'); sortedxy= np.squeeze(np.dstack([xScat2, fitfun2(p)])); sortedxy=sortedxy[sortedxy[:,0].argsort(),:] P.plot(sortedxy[:,0], sortedxy[:,1]); slope, intercept, r_value, p_value, std_err = scipy.stats.linregress(basic.nonan(w*array3d[x, y,:]),w[dataMask]*fitfun(p)) P.annotate(str("a0:%0.2f\na1:%0.2f\na2:%0.2f\npha:%0.2f\nbias:%0.2f\nr2:%0.2f" % (p[0], p[1], p[2], p[3], p[4], r_value**2.)), (0.8,0.8), xycoords='axes fraction') elif fn=='annual': dataMask=~np.isnan(array3d[x, y,:]) p0=np.array([1,1,basic.nonan(array3d[x, y,:]).mean() ]) fitfun=lambda p: p[0]* np.cos(2*np.pi*xScat[dataMask]/365.+p[1]) + p[2] xScat2=np.linspace(xScat.min(),xScat.max()) fitfun2=lambda p: p[0]* np.cos(2*np.pi*xScat2/365.+p[1]) + p[2] #errfun=lambda p: sum(abs(basic.nonan(array3d[x, y,:])-fitfun(p))); if yerror3d is None: w=np.ones(array3d[x, y,:].shape); else: w=basic.rescale(1./yerror3d[x,y,:], [1,2]) errfun=lambda p: basic.nonan(w*array3d[x, y,:])-w[dataMask]*fitfun(p); #p=scipy.optimize.fmin_powell(errfun, p0) p=scipy.optimize.leastsq(errfun, p0); p=p[0]; P.scatter(xScat[dataMask], fitfun(p), marker='^'); sortedxy= np.squeeze(np.dstack([xScat2, fitfun2(p)])); sortedxy=sortedxy[sortedxy[:,0].argsort(),:] P.plot(sortedxy[:,0], sortedxy[:,1]); slope, intercept, r_value, p_value, std_err = scipy.stats.linregress(basic.nonan(w*array3d[x, y,:]),w[dataMask]*fitfun(p)) P.annotate(str("amp:%0.2f\npha:%0.2f\nbias:%0.2f\nr2:%0.2f" % (p[0], p[1], p[2], r_value**2.)), (0.8,0.8), xycoords='axes fraction') else: p=None P.scatter(xScat, fn(xScat), marker='^'); #convert axis to date... if dateaxis: try: P.figure(fh.number).axes[0].xaxis_date(tz=None) P.figure(fh.number).autofmt_xdate() except: pass #change x y to xMap, yMap if yMap is not None: xM=ya*x+yb; else: xM=x; if xMap is not None: yM=xa*(y)+xb; else: yM=y; #x and y are flipped in the try/except block above. So Flip again. #if p is not None: # P.title("x,y,[]: " + str(yM) + ", " + str(xM) + ', ' + str(p) ) #else: P.title("x,y,z,z.std: " + str(yM) + ", " + str(xM) + ', ' + str(array2d[x,y]) +', ' + str(np.std(basic.nonan(array3d[x, y,:]))) ) # rotate and align the tick labels so they look better #P.figure(fh.number).autofmt_xdate() # use a more precise date string for the x axis locations in the # toolbar #P.gca().fmt_xdata = mdates.DateFormatter('%Y-%m-%d') if xerror3d is None: xerr=None; else: xerr=xerror3d[x,y,:] if yerror3d is None: yerr=None; else: yerr=yerror3d[x, y,:] if modelError: yerr=yerror3d[x, y,:] yerr[dataMask]=errfun(p) P.errorbar(xScat,array3d[x, y,:], xerr=xerr, yerr=yerr, fmt='ro'); if ylimScat is not None: P.ylim(ylimScat); ################################## ## END OF PLOTTING ################################## s=array2d[~np.isnan(array2d)].std(); m=array2d[~np.isnan(array2d)].mean(); fig=P.figure();ax=fig.add_subplot(111);ax.matshow(array2d, vmin=m-s, vmax=m+s); #fig=P.figure();ax=fig.add_subplot(111);ax.matshow(basic.wrapToInt(array2d, s), vmin=-s, vmax=s); if xMap is not None: ticks=ax.get_xticks(); (xa,xb)=np.polyfit(np.r_[0:len(xMap)],xMap,1) ax.set_xticklabels(np.around(xa*ticks+xb,4)); if yMap is not None: ticks=ax.get_yticks(); (ya,yb)=np.polyfit(np.r_[len(yMap):0:-1],yMap,1) ax.set_yticklabels(np.around(ya*ticks+yb,4)); #P.colorbar(); cax,kw=P.matplotlib.colorbar.make_axes(ax,orientation='vertical') P.matplotlib.colorbar.ColorbarBase(cax, cmap=P.jet(), norm=P.normalize(vmin=m-s,vmax=m+s), orientation='vertical') fh=P.figure(); #should be accessible in child function? fig.canvas.mpl_connect('button_press_event', onclick); return (fig,fh)
l = [] for key in sorted(d['data'].keys()): v = d['data'][key]['Net_1']['GP_GP']['mean_coherence'] l.append(v) l = l[organize['beta']] colors = misc.make_N_colors('copper', len(l)) for i, trace in enumerate(l): x = numpy.linspace(0, 128, len(trace)) # norm=sum(trace)*(x[-1]-x[0])/len(x) ax.plot(x, trace, color=colors[i]) ax.set_xlim([0, 50]) sm = pylab.cm.ScalarMappable(cmap='copper', norm=pylab.normalize(vmin=0., vmax=20)) sm._A = [] box = ax.get_position() pos = [ box.x0 + 1.03 * box.width, box.y0 + box.height * 0.1, 0.01, box.height * 0.8 ] axColor = pylab.axes(pos) cbar = pylab.colorbar(sm, cax=axColor) tick_locator = ticker.MaxNLocator(nbins=4) cbar.locator = tick_locator cbar.update_ticks() cbar.ax.tick_params(length=1, ) ax.text(1.25,
def clickScat(array2d, array3d, xScat=None, xerror3d=None, yerror3d=None, array3d2=None, xerror3d2=None, yerror3d2=None, fn=None, xMap=None, yMap=None, modelError=False, ylimScat=None): """ figureHandles=clickScat(array2d, array3d, xScat=None, xerror3d=None, yerror3d=None, array3d2=None, xerror3d2=None, yerror3d2=None, fn=None, xMap=None, yMap=None): xScat: x-axis variables for Scatter Plot. Has to be the same length as last dimension of array3d.shape[2] xerror3d: errorbars for x-axis. two sided. fn:'annual' """ import insar dateaxis = False if xScat is None: xScat = np.r_[0:array3d.shape[2]] elif isinstance(xScat[0], P.matplotlib.dates.datetime.date): xScat = P.matplotlib.dates.date2num(xScat) dateaxis = True def onclick(event): P.figure(fh.number) P.clf() #ax = P.gca() #inv = ax.transData.inverted() #A=inv.transform((event.x, event.y)) #A[1]=np.int(np.round((1-A[1])*array2d.shape[1])) #A[0]=np.int(np.round((A[0])*array2d.shape[0])) try: y = np.round(event.xdata) except: return x = np.round(event.ydata) #ARRAY MAPPING IS first axis y(rows) and second axis is cols (x) if all(np.isnan(array3d[x, y, :])): #if there are no points to plot (all nan) then return return #Plot second scatter data. if array3d2 is not None: if isinstance(array3d2, list): if yerror3d is None: w = np.ones(array3d[x, y, :].shape) else: w = basic.rescale(1. / yerror3d[x, y, :], [1, 2]) markers = ['*', '+', 's', 'd', 'x', 'v', '<', '>', '^'] m = 0 for arr in array3d2: print("%d, %d, %d" % (x, y, m)) P.scatter(xScat, arr[x, y, :], marker=markers[m]) idx = ~(np.isnan(arr[x, y, :]) | np.isnan(array3d[x, y, :])) #c=insar.crosscorrelate(basic.nonan(w[idx]*arr[x, y,idx]),basic.nonan(w[idx]*array3d[x, y,idx])) slope, intercept, r_value, p_value, std_err = scipy.stats.linregress( basic.nonan(w[idx] * arr[x, y, idx]), basic.nonan(w[idx] * array3d[x, y, idx])) P.annotate(str("r2[%s]: %0.2f" % (markers[m], r_value)), (0, 0.9 - m * 0.05), xycoords='axes fraction') m = m + 1 else: if xerror3d2 is None: xerr = None else: xerr = xerror3d2[x, y, :] if yerror3d2 is None: yerr = None else: yerr = yerror3d2[x, y, :] P.errorbar(xScat, array3d2[x, y, :], xerr=xerr, yerr=yerr, marker='*', fmt='o') #Plot function result as scatter data. p = None if fn is not None: if fn == 'linear_amplitude_annual': dataMask = ~np.isnan(array3d[x, y, :]) p0 = np.array([1, 0, 0, basic.nonan(array3d[x, y, :]).mean()]) fitfun = lambda p: (p[0] + p[1] * xScat[dataMask] / 365. ) * np.cos(2 * np.pi * xScat[dataMask] / 365. + p[2]) + p[3] xScat2 = np.linspace(xScat.min(), xScat.max()) fitfun2 = lambda p: (p[0] + p[1] * xScat2 / 365.) * np.cos( 2 * np.pi * xScat2 / 365. + p[2]) + p[3] #errfun=lambda p: sum(abs(basic.nonan(array3d[x, y,:])-fitfun(p))); if yerror3d is None: w = np.ones(array3d[x, y, :].shape) else: w = basic.rescale(1. / yerror3d[x, y, :], [1, 2]) errfun = lambda p: basic.nonan(w * array3d[x, y, :]) - w[ dataMask] * fitfun(p) #p=scipy.optimize.fmin_powell(errfun, p0) p = scipy.optimize.leastsq(errfun, p0) p = p[0] P.scatter(xScat[dataMask], fitfun(p), marker='^') sortedxy = np.squeeze(np.dstack([xScat2, fitfun2(p)])) sortedxy = sortedxy[sortedxy[:, 0].argsort(), :] P.plot(sortedxy[:, 0], sortedxy[:, 1]) slope, intercept, r_value, p_value, std_err = scipy.stats.linregress( basic.nonan(w * array3d[x, y, :]), w[dataMask] * fitfun(p)) P.annotate( str("a0:%0.2f\na1:%0.2f\npha:%0.2f\nbias:%0.2f\nr2:%0.2f" % (p[0], p[1], p[2], p[3], r_value**2.)), (0.8, 0.8), xycoords='axes fraction') elif fn == 'quadratic_amplitude_annual': dataMask = ~np.isnan(array3d[x, y, :]) p0 = np.array( [1, 0, 0, 0, basic.nonan(array3d[x, y, :]).mean()]) fitfun = lambda p: (p[0] + p[1] * xScat[dataMask] / 365. + p[ 2] * (xScat[dataMask] / 365.)**2.) * np.cos( 2 * np.pi * xScat[dataMask] / 365. + p[3]) + p[4] xScat2 = np.linspace(xScat.min(), xScat.max()) fitfun2 = lambda p: (p[0] + p[1] * xScat2 / 365. + p[2] * ( xScat2 / 365.)**2.) * np.cos(2 * np.pi * xScat2 / 365. + p[ 3]) + p[4] #errfun=lambda p: sum(abs(basic.nonan(array3d[x, y,:])-fitfun(p))); if yerror3d is None: w = np.ones(array3d[x, y, :].shape) else: w = basic.rescale(1. / yerror3d[x, y, :], [1, 2]) errfun = lambda p: basic.nonan(w * array3d[x, y, :]) - w[ dataMask] * fitfun(p) #p=scipy.optimize.fmin_powell(errfun, p0) p = scipy.optimize.leastsq(errfun, p0) p = p[0] P.scatter(xScat[dataMask], fitfun(p), marker='^') sortedxy = np.squeeze(np.dstack([xScat2, fitfun2(p)])) sortedxy = sortedxy[sortedxy[:, 0].argsort(), :] P.plot(sortedxy[:, 0], sortedxy[:, 1]) slope, intercept, r_value, p_value, std_err = scipy.stats.linregress( basic.nonan(w * array3d[x, y, :]), w[dataMask] * fitfun(p)) P.annotate(str( "a0:%0.2f\na1:%0.2f\na2:%0.2f\npha:%0.2f\nbias:%0.2f\nr2:%0.2f" % (p[0], p[1], p[2], p[3], p[4], r_value**2.)), (0.8, 0.8), xycoords='axes fraction') elif fn == 'annual': dataMask = ~np.isnan(array3d[x, y, :]) p0 = np.array([1, 1, basic.nonan(array3d[x, y, :]).mean()]) fitfun = lambda p: p[0] * np.cos(2 * np.pi * xScat[dataMask] / 365. + p[1]) + p[2] xScat2 = np.linspace(xScat.min(), xScat.max()) fitfun2 = lambda p: p[0] * np.cos(2 * np.pi * xScat2 / 365. + p[1]) + p[2] #errfun=lambda p: sum(abs(basic.nonan(array3d[x, y,:])-fitfun(p))); if yerror3d is None: w = np.ones(array3d[x, y, :].shape) else: w = basic.rescale(1. / yerror3d[x, y, :], [1, 2]) errfun = lambda p: basic.nonan(w * array3d[x, y, :]) - w[ dataMask] * fitfun(p) #p=scipy.optimize.fmin_powell(errfun, p0) p = scipy.optimize.leastsq(errfun, p0) p = p[0] P.scatter(xScat[dataMask], fitfun(p), marker='^') sortedxy = np.squeeze(np.dstack([xScat2, fitfun2(p)])) sortedxy = sortedxy[sortedxy[:, 0].argsort(), :] P.plot(sortedxy[:, 0], sortedxy[:, 1]) slope, intercept, r_value, p_value, std_err = scipy.stats.linregress( basic.nonan(w * array3d[x, y, :]), w[dataMask] * fitfun(p)) P.annotate(str("amp:%0.2f\npha:%0.2f\nbias:%0.2f\nr2:%0.2f" % (p[0], p[1], p[2], r_value**2.)), (0.8, 0.8), xycoords='axes fraction') else: p = None P.scatter(xScat, fn(xScat), marker='^') #convert axis to date... if dateaxis: try: P.figure(fh.number).axes[0].xaxis_date(tz=None) P.figure(fh.number).autofmt_xdate() except: pass #change x y to xMap, yMap if yMap is not None: xM = ya * x + yb else: xM = x if xMap is not None: yM = xa * (y) + xb else: yM = y #x and y are flipped in the try/except block above. So Flip again. #if p is not None: # P.title("x,y,[]: " + str(yM) + ", " + str(xM) + ', ' + str(p) ) #else: P.title("x,y,z,z.std: " + str(yM) + ", " + str(xM) + ', ' + str(array2d[x, y]) + ', ' + str(np.std(basic.nonan(array3d[x, y, :])))) # rotate and align the tick labels so they look better #P.figure(fh.number).autofmt_xdate() # use a more precise date string for the x axis locations in the # toolbar #P.gca().fmt_xdata = mdates.DateFormatter('%Y-%m-%d') if xerror3d is None: xerr = None else: xerr = xerror3d[x, y, :] if yerror3d is None: yerr = None else: yerr = yerror3d[x, y, :] if modelError: yerr = yerror3d[x, y, :] yerr[dataMask] = errfun(p) P.errorbar(xScat, array3d[x, y, :], xerr=xerr, yerr=yerr, fmt='ro') if ylimScat is not None: P.ylim(ylimScat) ################################## ## END OF PLOTTING ################################## s = array2d[~np.isnan(array2d)].std() m = array2d[~np.isnan(array2d)].mean() fig = P.figure() ax = fig.add_subplot(111) ax.matshow(array2d, vmin=m - s, vmax=m + s) #fig=P.figure();ax=fig.add_subplot(111);ax.matshow(basic.wrapToInt(array2d, s), vmin=-s, vmax=s); if xMap is not None: ticks = ax.get_xticks() (xa, xb) = np.polyfit(np.r_[0:len(xMap)], xMap, 1) ax.set_xticklabels(np.around(xa * ticks + xb, 4)) if yMap is not None: ticks = ax.get_yticks() (ya, yb) = np.polyfit(np.r_[len(yMap):0:-1], yMap, 1) ax.set_yticklabels(np.around(ya * ticks + yb, 4)) #P.colorbar(); cax, kw = P.matplotlib.colorbar.make_axes(ax, orientation='vertical') P.matplotlib.colorbar.ColorbarBase(cax, cmap=P.jet(), norm=P.normalize(vmin=m - s, vmax=m + s), orientation='vertical') fh = P.figure() #should be accessible in child function? fig.canvas.mpl_connect('button_press_event', onclick) return (fig, fh)
l=[] for key in sorted(d['data'].keys()): v=d['data'][key]['Net_1']['GP_GP']['mean_coherence'] l.append(v) l=l[organize['beta']] colors=misc.make_N_colors('copper', len(l)) for i, trace in enumerate(l): x=numpy.linspace(0,128,len(trace)) # norm=sum(trace)*(x[-1]-x[0])/len(x) ax.plot(x, trace, color=colors[i]) ax.set_xlim([0,50]) sm = pylab.cm.ScalarMappable(cmap='copper', norm=pylab.normalize(vmin=0., vmax=20)) sm._A = [] box = ax.get_position() pos=[box.x0+1.03*box.width, box.y0+box.height*0.1, 0.01, box.height*0.8] axColor=pylab.axes(pos) cbar=pylab.colorbar(sm, cax=axColor) tick_locator = ticker.MaxNLocator(nbins=4) cbar.locator = tick_locator cbar.update_ticks() cbar.ax.tick_params( length=1, ) ax.text(1.25, 0.5, r'Beta amplitude (Hz)', transform=ax.transAxes, va='center', rotation=270) ax.set_xlabel(r'Frequency (Hz)')