def plot(objVectors, centroidIDs, clusterIDs, generation, run, params): """ plots 'objVectors' and emphasizes the solutions indicated by 'centroidIDs'. In case of 2 objectives, the clusters, given by clusterIDs, are plotted by connecting every point with the centroid of its cluster as well. The return parameter is an objective of type 'onClick' which allows to later on ask which objective vector the user has picked. """ if (len(objVectors > 0)) and (len(objVectors[0, :]) == 2): # plot all points h, = plt.plot(objVectors[:, 0], objVectors[:, 1], 'x') # plot centroids differently plt.plot(objVectors[centroidIDs, 0], objVectors[centroidIDs, 1], 'o' + plt.get(h, 'color')) s = plt.axis() # get size of plot for annotations # plot the centroids's ids as well for i in centroidIDs: plt.text(objVectors[i, 0] + (0.1 / (s[1] - s[0])), objVectors[i, 1] + (0.1 / (s[3] - s[2])), i, color=plt.get(h, 'color')) # connect all points with the centroids of their cluster for i in range(len(objVectors[:, 0])): x = [objVectors[i, 0], objVectors[centroidIDs[clusterIDs[i]], 0]] y = [objVectors[i, 1], objVectors[centroidIDs[clusterIDs[i]], 1]] plt.plot(x, y, ':' + plt.get(h, 'color'), linewidth=0.25) beautify2DPlot(generation, run) # allow for interactive clicking: if params.interaction == 1: # 1) add possibility to get objective vector and ids by clicking right: #annotes = range(len(objVectors)) #af = AnnoteFinder.AnnoteFinder(objVectors[:,0],objVectors[:,1], annotes) #connect('button_press_event', af) # 2) choose best solution by clicking left: oc = onClick.onClick(objVectors) connect('button_press_event', oc) return oc else: parallelCoordinatesPlot(objVectors, generation, run, params) # allow for interactive clicking: if params.interaction == 1: # 1) add possibility to get objective vector and ids by clicking right: annotes = range(len(objVectors)) af = AnnoteFinder.AnnoteFinder(objVectors[:, 0], objVectors[:, 1], annotes) connect('button_press_event', af) # 2) choose best solution by clicking left: oc = onClick.onClick(objVectors) connect('button_press_event', oc) return oc
def align_axes(axis_name='xyzc', axes=None): """Make sure that the given axes are aligned along the given axis_name ('x', 'y', 'c', or any combination thereof (e.g. 'xy' which is the default)). If no axis handles are specified, all axes in the current figure are used. """ if axes is None: axes = plt.findobj(match=plt.Axes) for name in axis_name: prop = '%clim' % name all_lim = [] all_axes = [] for ax in axes: if ax is None: continue try: all_lim.append(plt.get(ax, prop)) all_axes.append(ax) except AttributeError: for childax in plt.get(ax, 'children'): try: all_lim.append(plt.get(childax, prop)) all_axes.append(childax) except: pass if all_lim: all_lim = np.asarray(all_lim) aligned_lim = (all_lim[:,0].min(), all_lim[:,1].max()) plt.setp(all_axes, prop, aligned_lim)
def align_axes(axis_name='xyzc', axes=None): """Make sure that the given axes are aligned along the given axis_name ('x', 'y', 'c', or any combination thereof (e.g. 'xy' which is the default)). If no axis handles are specified, all axes in the current figure are used. """ if axes is None: axes = plt.findobj(match=plt.Axes) for name in axis_name: prop = '%clim' % name all_lim = [] all_axes = [] for ax in axes: try: all_lim.append(plt.get(ax, prop)) all_axes.append(ax) except AttributeError: for childax in plt.get(ax, 'children'): try: all_lim.append(plt.get(childax, prop)) all_axes.append(childax) except: pass if all_lim: all_lim = np.asarray(all_lim) aligned_lim = (all_lim[:,0].min(), all_lim[:,1].max()) plt.setp(all_axes, prop, aligned_lim)
def plot(objVectors, centroidIDs, clusterIDs, generation, run, params): """ plots 'objVectors' and emphasizes the solutions indicated by 'centroidIDs'. In case of 2 objectives, the clusters, given by clusterIDs, are plotted by connecting every point with the centroid of its cluster as well. The return parameter is an objective of type 'onClick' which allows to later on ask which objective vector the user has picked. """ if (len(objVectors > 0)) and (len(objVectors[0,:]) == 2): # plot all points h, = plt.plot(objVectors[:,0],objVectors[:,1], 'x') # plot centroids differently plt.plot(objVectors[centroidIDs,0], objVectors[centroidIDs, 1], 'o' + plt.get(h, 'color')) s = plt.axis() # get size of plot for annotations # plot the centroids's ids as well for i in centroidIDs: plt.text(objVectors[i,0] + (0.1/(s[1]-s[0])), objVectors[i,1] + (0.1/(s[3]-s[2])), i, color=plt.get(h, 'color')) # connect all points with the centroids of their cluster for i in range(len(objVectors[:,0])): x = [objVectors[i,0], objVectors[centroidIDs[clusterIDs[i]],0]] y = [objVectors[i,1], objVectors[centroidIDs[clusterIDs[i]],1]] plt.plot(x, y, ':' + plt.get(h, 'color'), linewidth=0.25) beautify2DPlot(generation, run) # allow for interactive clicking: if params.interaction == 1: # 1) add possibility to get objective vector and ids by clicking right: #annotes = range(len(objVectors)) #af = AnnoteFinder.AnnoteFinder(objVectors[:,0],objVectors[:,1], annotes) #connect('button_press_event', af) # 2) choose best solution by clicking left: oc = onClick.onClick(objVectors) connect('button_press_event', oc) return oc else: parallelCoordinatesPlot(objVectors, generation, run, params) # allow for interactive clicking: if params.interaction == 1: # 1) add possibility to get objective vector and ids by clicking right: annotes = range(len(objVectors)) af = AnnoteFinder.AnnoteFinder(objVectors[:,0],objVectors[:,1], annotes) connect('button_press_event', af) # 2) choose best solution by clicking left: oc = onClick.onClick(objVectors) connect('button_press_event', oc) return oc
def main(): if len(sys.argv) < 2: logfilename = 'log.out' # use default filename print('No input filename specified: using %s' % logfilename) else: logfilename = sys.argv[1] if not os.path.exists(logfilename): print('%s does not exist!' % logfilename) sys.exit() else: print('Reading file %s' % logfilename) if len(sys.argv) < 3: pngfilename = None print( 'No output filename specified: will not write output file for plot' ) else: pngfilename = sys.argv[2] print('Plot will be saved as %s' % pngfilename) data = np.genfromtxt(logfilename, usecols=(1, 2)) t = data[:, 0] w = data[:, 1] # i = data[:, 3] pyplot.figure(0) pyplot.plot(t, w) ax = pyplot.gca() ax.set_xlabel('Time (second)') ax.set_ylabel('Power (W)') ax2 = ax.twinx() clim = pyplot.get(ax, 'ylim') ax2.set_ylim(clim[0] * 1000 / 120, clim[1] * 1000 / 120) ax2.set_ylabel('Current (mA)') # generate a PNG file if pngfilename: pyplot.savefig(pngfilename + '-power.png') # show the plot pyplot.show() pyplot.figure(1) # cumulative plot pyplot.plot(t / 60, np.cumsum(w) / 1000) ax = pyplot.gca() ax.set_xlabel('Time (minutes)') ax.set_ylabel('Energy (kJ)') ax2 = ax.twinx() clim = pyplot.get(ax, 'ylim') ax2.set_ylim(clim[0] / 3.6, clim[1] / 3.6) ax2.set_ylabel('Energy (Wh)') if pngfilename: pyplot.savefig(pngfilename + '-energy.png') # show the plot pyplot.show()
def plot_iteration_stats(itstats, figNum=None, pretitle=None): if (figNum is None): fig = pyplot.figure() else: fig = pyplot.figure(figNum) pyplot.clf() pyplot.hold(True) pyplot.plot(itstats, 'k-', linewidth=2) yl = pyplot.get(pyplot.gca(), 'ylim') dyl = yl[1] - yl[0] yoff = yl[1] - 0.1 * dyl str = 'min iterations : %d' % (np.min(itstats[1:])) pyplot.text(0.05 * len(itstats), yoff, str, fontsize=10) yoff = yoff - dyl / 20 str = 'mean iterations : %d' % (np.int(np.mean(itstats[1:]))) pyplot.text(0.05 * len(itstats), yoff, str, fontsize=10) yoff = yoff - dyl / 20 str = 'max iterations : %d' % (np.max(itstats[1:])) pyplot.text(0.05 * len(itstats), yoff, str, fontsize=10) pyplot.xlabel('Assimilation Step', fontweight='bold', fontsize=12) pyplot.ylabel('# Iterations', fontweight='bold', fontsize=12) title = '# Iterations for cost function' if (not (pretitle is None)): title = pretitle + ' - ' + title pyplot.title(title, fontweight='bold', fontsize=14) fig.canvas.set_window_title(title) pyplot.hold(False) return fig
def setshowticklabs(h, ticklabs='all'): "find the set of plots which get tick-info" showticklabs = np.ndarray((len(h)), dtype=bool) showticklabs[:] = False # default to show all if ticklabs == 'all': showticklabs[:] = True else: # get the dir to search for extreem plot if ticklabs == 'sw': sline = np.array((-1, -1)) elif ticklabs == 'se': sline = np.array((1, -1)) elif ticklabs == 'nw': sline = np.array((1, 1)) elif ticklabs == 'ne': sline = np.array((1, -1)) # find the most extreem plot d = None tickpi = None for pi, ax in enumerate(h): pltpos = plt.get(ax, 'position').get_points().mean( 0) # get axis center dpi = np.dot(sline, pltpos) if d is None or dpi > d: d = dpi tickpi = pi # set to show tick info showticklabs[tickpi] = True return showticklabs
def plot_iteration_stats(itstats, figNum=None, pretitle=None): if ( figNum is None ): fig = pyplot.figure() else: fig = pyplot.figure(figNum) pyplot.clf() pyplot.hold(True) pyplot.plot(itstats,'k-',linewidth=2) yl = pyplot.get(pyplot.gca(),'ylim') dyl = yl[1] - yl[0] yoff = yl[1] - 0.1 * dyl str = 'min iterations : %d' % (np.min(itstats[1:])) pyplot.text(0.05*len(itstats),yoff,str,fontsize=10) yoff = yoff - dyl / 20 str = 'mean iterations : %d' % (np.int(np.mean(itstats[1:]))) pyplot.text(0.05*len(itstats),yoff,str,fontsize=10) yoff = yoff - dyl / 20 str = 'max iterations : %d' % (np.max(itstats[1:])) pyplot.text(0.05*len(itstats),yoff,str,fontsize=10) pyplot.xlabel('Assimilation Step',fontweight='bold',fontsize=12) pyplot.ylabel('# Iterations', fontweight='bold',fontsize=12) title = '# Iterations for cost function' if ( not (pretitle is None) ): title = pretitle + ' - ' + title pyplot.title(title,fontweight='bold',fontsize=14) fig.canvas.set_window_title(title) pyplot.hold(False) return fig
def axis_range(ax): # gets subplot coordinates on a figure in "normalized" # coordinates pos = plt.get(ax, 'position') bottom_left = pos.p0 top_right = pos.p1 xmin, xmax = bottom_left[0], top_right[0] ymin, ymax = bottom_left[1], top_right[1] return xmin, xmax, ymin, ymax
def Spy(A, P1, symb, ttl, ax, parts=2, printperm=0): m, n = A.shape colors = numpy.zeros((parts + 1, 3)) for cnt in numpy.arange(parts + 1): colors[cnt, :] = plotcolors(cnt) part_ids = numpy.zeros(m, dtype=numpy.int32) part_ids[P1] = 1 perm = part_ids.argsort() A_perm = A[perm, :][:, perm] A_perm = A_perm.tocoo() part_ids = part_ids[perm] nnz = A.nnz xlab = 'nnz = %d\n' % nnz for i in range(nnz): if part_ids[A_perm.row[i]] == part_ids[A_perm.col[i]]: A_perm.data[i] = part_ids[A_perm.col[i]] else: A_perm.data[i] = parts plt.hold(True) plt.title(ttl, fontsize=14) bbox = plt.get(plt.gca(), 'position') pos = [bbox.x1, bbox.y1] markersize = max(6, min(14, round(6 * min(pos[:]) / max(m + 1, n + 1)))) sy = symb for cnt in numpy.arange(parts + 1): ii, = numpy.where(A_perm.data == cnt) #print 'part %d has %d entries'%(cnt, len(ii)) c = colors[cnt, :] plt.plot(A_perm.col[ii], A_perm.row[ii], marker=sy, markersize=markersize, color=c, linestyle='.') plt.axis('tight') plt.xlim(xmin=-2) plt.ylim(ymin=-2) plt.xlim(xmax=m + 2) plt.ylim(ymax=n + 2) ax.set_ylim(ax.get_ylim()[::-1]) ax.set_aspect((m + 1) / (n + 1), adjustable='box') plt.hold(False) plt.show()
def plot_abs_error_var(xbev, xaev, label=['x'], N=1, yscale='semilog', figNum=None): if ((yscale != 'linear') and (yscale != 'semilog')): yscale = 'semilog' if (figNum is None): fig = pyplot.figure() else: fig = pyplot.figure(figNum) pyplot.clf() for k in range(0, N): pyplot.subplot(N, 1, k + 1) pyplot.hold(True) if (yscale == 'linear'): pyplot.plot(xbev[k, 2:], 'b-', label='background', linewidth=2) pyplot.plot(xaev[k, 2:], 'r-', label='analysis', linewidth=2) elif (yscale == 'semilog'): pyplot.semilogy(np.abs(xbev[k, 2:]), 'b-', label='background', linewidth=2) pyplot.semilogy(np.abs(xaev[k, 2:]), 'r-', label='analysis', linewidth=2) pyplot.ylabel(label[k], fontweight='bold', fontsize=12) strb = 'mean background : %5.4f +/- %5.4f' % (np.mean( xbev[k, 2:]), np.std(xbev[k, 2:], ddof=1)) stra = 'mean analysis : %5.4f +/- %5.4f' % (np.mean( xaev[k, 2:]), np.std(xaev[k, 2:], ddof=1)) yl = pyplot.get(pyplot.gca(), 'ylim') if (yscale == 'linear'): yoffb = 0.9 * yl[1] yoffa = 0.8 * yl[1] elif (yscale == 'semilog'): yoffb = 0.5e1 * yl[0] yoffa = 0.2e1 * yl[0] pyplot.text(0, yoffb, strb, fontsize=10) pyplot.text(0, yoffa, stra, fontsize=10) pyplot.hold(False) if (k == 0): title = 'Ensemble Kalman Filter Error Variance' pyplot.title(title, fontweight='bold', fontsize=14) if (k == 1): pyplot.legend(loc=1) if (k == N - 1): pyplot.xlabel('Assimilation Step', fontweight='bold', fontsize=12) fig.canvas.set_window_title(title) return fig
def plot_ObImpact(dJa, dJe, sOI=None, eOI=None, title=None, xlabel=None, ylabel=None): color_adj = 'c' color_ens = 'm' width = 0.45 if ( title is None ): title = '' if ( xlabel is None ): xlabel = '' if ( ylabel is None ): ylabel = '' if ( (sOI is None) ): sOI = 0 if ( (eOI is None) or (eOI == -1) ): eOI = len(dJa) index = np.arange(eOI-sOI) if ( len(index) > 1000 ): inc = 1000 elif ( len(index) > 100 ): inc = 100 elif ( len(index) > 10 ): inc = 10 else: inc = 1 fig = pyplot.figure() pyplot.hold(True) r0 = pyplot.plot(np.zeros(eOI-sOI+1),'k-') r1 = pyplot.bar(index, dJa, width, color=color_adj, edgecolor=color_adj, linewidth=0.0) r2 = pyplot.bar(index+width, dJe, width, color=color_ens, edgecolor=color_ens, linewidth=0.0) stra = r'mean $\delta J_a$ : %5.4f +/- %5.4f' % (np.mean(dJa), np.std(dJa,ddof=1)) stre = r'mean $\delta J_e$ : %5.4f +/- %5.4f' % (np.mean(dJe), np.std(dJe,ddof=1)) locs, labels = pyplot.xticks() newlocs = np.arange(sOI,sOI+len(index)+1,inc) - sOI newlabels = np.arange(sOI,sOI+len(index)+1,inc) pyplot.xticks(newlocs, newlabels) yl = pyplot.get(pyplot.gca(),'ylim') dyl = yl[1] - yl[0] yoff = yl[0] + 0.1 * dyl pyplot.text(5,yoff,stra,fontsize=10,color=color_adj) yoff = yl[0] + 0.2 * dyl pyplot.text(5,yoff,stre,fontsize=10,color=color_ens) pyplot.xlabel(xlabel, fontsize=12) pyplot.ylabel(ylabel, fontsize=12) pyplot.title(title, fontsize=14) fig.canvas.set_window_title(title) pyplot.hold(False) return fig
def plot_log_likelihood_learning_curves(training_curves, static_lines, save_dir, x_lim=None, y_lim=None, file_name='train', title=None, logx=False, ax=None): """plot log-likelihood training curves :param training_curves: list of lists each inner list is of the form: [times, log-likelihoods, label, color] where times & log-likelihoods are arrays for plotting :param static_lines: list of lists each inner list is of the form [log-likelihood, label] where log-likelihood is a single value that will plotted as a horizontal line """ create_fig = False if ax is None: fig, ax = plt.subplots(1, 1, figsize=(5.5, 5.5)) create_fig = True for triple in training_curves: if logx: ax.semilogx(triple[0], triple[1], label=triple[2], color=triple[3]) else: ax.plot(triple[0], triple[1], label=triple[2]) ax.annotate(r"{}".format(round(triple[1][-1], 2)), xy=(triple[1][-1], triple[1][-1] + 1), fontsize=5, color=triple[3]) for pair in static_lines: ax.plot(plt.get(ax, 'xlim'), (pair[0], pair[0]), label=pair[1]) if title: ax.set_title(title) ax.set_xlabel('time (seconds)') ax.set_ylabel('log likelihood') ax.legend(loc='lower right') if x_lim: ax.set_xlim(x_lim) if y_lim: ax.set_ylim(y_lim) if create_fig: save_fig(fig, save_dir, '{}_likelihood_optimisation_curve'.format(file_name))
def add_number(fig, ax, order=1, offset=None): # offset = [-175,50] if offset is None else offset offset = [-75, 25] if offset is None else offset pos = fig.transFigure.transform(plt.get(ax, 'position')) x = pos[0, 0] + offset[0] y = pos[1, 1] + offset[1] ax.text(x=x, y=y, s='%s)' % chr(96 + order), ha='center', va='center', transform=None, weight='bold', fontsize=14)
def Spy(A, P1, symb, ttl, ax, parts=2, printperm=0): m, n = A.shape colors = numpy.zeros((parts + 1, 3)) for cnt in numpy.arange(parts + 1): colors[cnt, :] = plotcolors(cnt) part_ids = numpy.zeros(m, dtype=numpy.int32) part_ids[P1] = 1 perm = part_ids.argsort() A_perm = A[perm, :][:, perm] A_perm = A_perm.tocoo() part_ids = part_ids[perm] nnz = A.nnz xlab = "nnz = %d\n" % nnz for i in range(nnz): if part_ids[A_perm.row[i]] == part_ids[A_perm.col[i]]: A_perm.data[i] = part_ids[A_perm.col[i]] else: A_perm.data[i] = parts plt.hold(True) plt.title(ttl, fontsize=14) bbox = plt.get(plt.gca(), "position") pos = [bbox.x1, bbox.y1] markersize = max(6, min(14, round(6 * min(pos[:]) / max(m + 1, n + 1)))) sy = symb for cnt in numpy.arange(parts + 1): ii, = numpy.where(A_perm.data == cnt) # print 'part %d has %d entries'%(cnt, len(ii)) c = colors[cnt, :] plt.plot(A_perm.col[ii], A_perm.row[ii], marker=sy, markersize=markersize, color=c, linestyle=".") plt.axis("tight") plt.xlim(xmin=-2) plt.ylim(ymin=-2) plt.xlim(xmax=m + 2) plt.ylim(ymax=n + 2) ax.set_ylim(ax.get_ylim()[::-1]) ax.set_aspect((m + 1) / (n + 1), adjustable="box") plt.hold(False) plt.show()
def plot_rmse(xbrmse=None, xarmse=None, xyrmse=None, yscale='semilog', figNum=None, pretitle=None, sStat=100): if ( (yscale != 'linear') and (yscale != 'semilog') ): yscale = 'semilog' if ( figNum is None ): fig = pyplot.figure() else: fig = pyplot.figure(figNum) pyplot.clf() pyplot.hold(True) if ( yscale == 'linear' ): if ( xbrmse is not None ): pyplot.plot(xbrmse[1:],'b-',label='prior', linewidth=2, alpha=0.90) if ( xarmse is not None ): pyplot.plot(xarmse[:],'r-',label='posterior', linewidth=2, alpha=0.65) if ( xyrmse is not None ): pyplot.plot(xyrmse, 'k-',label='observation',linewidth=2, alpha=0.40) elif ( yscale == 'semilog' ): if ( xbrmse is not None ): pyplot.semilogy(xbrmse[1: ],'b-',label='prior', linewidth=2, alpha=0.90) if ( xarmse is not None ): pyplot.semilogy(xarmse[:-1],'r-',label='posterior', linewidth=2, alpha=0.65) if ( xyrmse is not None ): pyplot.semilogy(xyrmse, 'k-',label='observation',linewidth=2, alpha=0.40) yl = pyplot.get(pyplot.gca(),'ylim') pyplot.ylim(0.0, yl[1]) dyl = yl[1] if ( xbrmse is not None ): strb = 'mean prior rmse : %5.4f +/- %5.4f' % (np.mean(xbrmse[sStat+1:]),np.std(xbrmse[sStat+1:],ddof=1)) pyplot.text(0.05*len(xbrmse),yl[1]-0.1*dyl,strb,fontsize=10) if ( xarmse is not None ): stra = 'mean posterior rmse : %5.4f +/- %5.4f' % (np.mean(xarmse[sStat:-1]),np.std(xarmse[sStat:-1],ddof=1)) pyplot.text(0.05*len(xarmse),yl[1]-0.15*dyl,stra,fontsize=10) if ( xyrmse is not None ): stro = 'mean observation rmse : %5.4f +/- %5.4f' % (np.mean(xyrmse[sStat:]), np.std(xyrmse[sStat:],ddof=1)) pyplot.text(0.05*len(xyrmse),yl[1]-0.2*dyl,stro,fontsize=10) pyplot.xlabel('Assimilation Cycle',fontweight='bold',fontsize=12) pyplot.ylabel('RMSE',fontweight='bold',fontsize=12) title = 'Root Mean Squared Error' if ( not (pretitle is None) ): title = pretitle + ' - ' + title pyplot.title(title,fontweight='bold',fontsize=14) pyplot.legend(loc='lower right',ncol=2) pyplot.hold(False) fig.canvas.set_window_title(title) return fig
def view_scatterplots(df, list_plots): ''' Gets scatterplots of different columns (usually target versus feature of interest), with the option to colorcode by other feature. Inputs: - df: a Pandas Dataframe. - list_plots: list of dicts, where each dictionary represents a scatterploof to get, which should have for keys: - 'xcol': target or other columns of interest) - 'ycol': other feature of interests. - 'colorcol': feature to colorcode by. optional. Output: Scatterplot(s) ''' for plt in list_plots: xcol = plt['xcol'] ycol = plt['ycol'] get_scatterplot(df, xcol, ycol, plt.get('colorcol', None))
def plot_abs_error_var(xbev, xaev, label=['x'], N=1, yscale='semilog', figNum=None): if ( (yscale != 'linear') and (yscale != 'semilog') ): yscale = 'semilog' if ( figNum is None ): fig = pyplot.figure() else: fig = pyplot.figure(figNum) pyplot.clf() for k in range(0,N): pyplot.subplot(N,1,k+1) pyplot.hold(True) if ( yscale == 'linear'): pyplot.plot(xbev[k,2:],'b-',label='background',linewidth=2) pyplot.plot(xaev[k,2:],'r-',label='analysis',linewidth=2) elif ( yscale == 'semilog' ): pyplot.semilogy(np.abs(xbev[k,2:]),'b-',label='background',linewidth=2) pyplot.semilogy(np.abs(xaev[k,2:]),'r-',label='analysis',linewidth=2) pyplot.ylabel(label[k],fontweight='bold',fontsize=12) strb = 'mean background : %5.4f +/- %5.4f' % (np.mean(xbev[k,2:]), np.std(xbev[k,2:],ddof=1)) stra = 'mean analysis : %5.4f +/- %5.4f' % (np.mean(xaev[k,2:]), np.std(xaev[k,2:],ddof=1)) yl = pyplot.get(pyplot.gca(),'ylim') if ( yscale == 'linear'): yoffb = 0.9 * yl[1] yoffa = 0.8 * yl[1] elif ( yscale == 'semilog' ): yoffb = 0.5e1 * yl[0] yoffa = 0.2e1 * yl[0] pyplot.text(0,yoffb,strb,fontsize=10) pyplot.text(0,yoffa,stra,fontsize=10) pyplot.hold(False) if ( k == 0 ): title = 'Ensemble Kalman Filter Error Variance' pyplot.title(title,fontweight='bold',fontsize=14) if ( k == 1 ): pyplot.legend(loc=1) if ( k == N-1 ): pyplot.xlabel('Assimilation Step',fontweight='bold',fontsize=12) fig.canvas.set_window_title(title) return fig
def draw_plot(self): self.figure.clf() self.ax = self.figure.add_subplot(111) self.canvas.mpl_connect('pick_event', self.on_pick) self.ax.grid(self.grid_cb.isChecked()) lines = [] for entry in self.final: line, = self.ax.plot(*entry, picker=True) lines.append(line) self.ax.hold(False) self.ax.set_title("Energy Data") self.ax.set_xlabel("Time (minutes)") self.ax.set_ylabel("Power (w)") self.ax2 = self.ax.twinx() clim = plt.get(self.ax, 'ylim') self.ax2.set_ylim(clim[0]*1000/120, clim[1]*1000/120) self.ax2.set_ylabel("Current (mA)") for i in range(0, len(lines)): lines[i].set_label(self.names[i]) handles, labels = self.ax.get_legend_handles_labels() self.ax.legend(handles, labels) self.canvas.draw()
def zvect(zFrom, zTo=None, arg3=None, arg4=None): """ZVECT Plot vectors in complex z-plane from zFrom to zTo common usage: zvect(Z) displays each element of Z as an arrow emanating from the origin. usage: HV = zvect(zFrom, <zTo>, <LTYPE>, <SCALE>) zFrom: is a vector of complex numbers; each one will be the starting location of an arrow. zTo: is a vector of complex numbers; each one will be the ending point of an arrow starting at zFrom. LTYPE: string containing any valid line type (see PLOT) SCALE: controls size of arrowhead (default = 1.0) (order of LTYPE and SCALE args doesn't matter) HV: output handle from graphics of vector plot ** If either zFrom or zTo is a scalar all vectors will start or end at that point. See also ZCAT. """ zFrom = np.asarray(zFrom) zTo = np.asarray(zTo) scale = 1.0 linetype = 'b-' if zTo is None: zTo = zFrom zFrom = 0 * zTo elif zTo is not None: if type(zTo) == str: linetype = zTo zTo = zFrom zFrom = 0 * zTo elif len(zTo) == 0: zTo = zFrom zFrom = 0 * zTo elif len(zTo) == 1: zTo = zTo * np.ones(zFrom.shape) elif zTo and arg3 is not None: if type(arg3) == str: linetype = arg3 else: scale = arg3 else: if type(arg3) == str: linetype = arg3 scale = arg4 else: scale = arg3 linetype = arg4 jkl = np.where(np.logical_not(np.isnan(zTo - zFrom)))[0] if len(jkl) == 0: exit('cannot plot NaNs') zTo = zTo[jkl] zFrom = zFrom[jkl] if len(zFrom) == 1: zFrom = zFrom * np.ones(zTo.shape) elif len(zTo) == 1: zTo = zTo * np.ones(zFrom.shape) if len(zFrom) != len(zTo): exit('ZVECT: zFrom and zTo must be same length.') tt = np.r_[zFrom, zTo] # zmx = max(abs(tt)) jkl = np.where(tt == max(tt))[0] figsize = max(abs(tt - tt[jkl])) arrow = scale * (np.vstack((-1, 0, -1)) + 1j * np.vstack( (1 / 4, 0, -1 / 4))) dz = zTo - zFrom dzm = abs(dz) zmax = max(dzm) zscale = np.mean(np.r_[zmax, figsize]) scz = 0.11 + 0.77 * (dzm / zscale - 1)**6 tt = np.array(np.ones((3, 1)) * zTo + arrow * (scz * dz)) h = plt.plot( np.vstack((zFrom, zTo)).real, np.vstack((zFrom, zTo)).imag, linetype, tt.real, tt.imag, linetype) num_zzz = len(zFrom) for kk in range(num_zzz): kolor = plt.get(h[kk], 'color') plt.setp(h[kk + num_zzz], 'color', kolor) plt.axis('equal') plt.show() return h
def plot_rmse(xbrmse=None, xarmse=None, xyrmse=None, yscale='semilog', figNum=None, pretitle=None, sStat=100): if ((yscale != 'linear') and (yscale != 'semilog')): yscale = 'semilog' if (figNum is None): fig = pyplot.figure() else: fig = pyplot.figure(figNum) pyplot.clf() pyplot.hold(True) if (yscale == 'linear'): if (xbrmse is not None): pyplot.plot(xbrmse[1:], 'b-', label='prior', linewidth=2, alpha=0.90) if (xarmse is not None): pyplot.plot(xarmse[:], 'r-', label='posterior', linewidth=2, alpha=0.65) if (xyrmse is not None): pyplot.plot(xyrmse, 'k-', label='observation', linewidth=2, alpha=0.40) elif (yscale == 'semilog'): if (xbrmse is not None): pyplot.semilogy(xbrmse[1:], 'b-', label='prior', linewidth=2, alpha=0.90) if (xarmse is not None): pyplot.semilogy(xarmse[:-1], 'r-', label='posterior', linewidth=2, alpha=0.65) if (xyrmse is not None): pyplot.semilogy(xyrmse, 'k-', label='observation', linewidth=2, alpha=0.40) yl = pyplot.get(pyplot.gca(), 'ylim') pyplot.ylim(0.0, yl[1]) dyl = yl[1] if (xbrmse is not None): strb = 'mean prior rmse : %5.4f +/- %5.4f' % (np.mean( xbrmse[sStat + 1:]), np.std(xbrmse[sStat + 1:], ddof=1)) pyplot.text(0.05 * len(xbrmse), yl[1] - 0.1 * dyl, strb, fontsize=10) if (xarmse is not None): stra = 'mean posterior rmse : %5.4f +/- %5.4f' % (np.mean( xarmse[sStat:-1]), np.std(xarmse[sStat:-1], ddof=1)) pyplot.text(0.05 * len(xarmse), yl[1] - 0.15 * dyl, stra, fontsize=10) if (xyrmse is not None): stro = 'mean observation rmse : %5.4f +/- %5.4f' % (np.mean( xyrmse[sStat:]), np.std(xyrmse[sStat:], ddof=1)) pyplot.text(0.05 * len(xyrmse), yl[1] - 0.2 * dyl, stro, fontsize=10) pyplot.xlabel('Assimilation Cycle', fontweight='bold', fontsize=12) pyplot.ylabel('RMSE', fontweight='bold', fontsize=12) title = 'Root Mean Squared Error' if (not (pretitle is None)): title = pretitle + ' - ' + title pyplot.title(title, fontweight='bold', fontsize=14) pyplot.legend(loc='lower right', ncol=2) pyplot.hold(False) fig.canvas.set_window_title(title) return fig
def ImagePos(source, lens1, lens2): temp = Image.new("RGBA", (640, 480), (255, 255, 255)) if (lens1.pos == lens2.pos): return else: if (lens1.pos > lens2.pos): temp = lens1 lens1 = lens2 lens2 = temp #drawlens(lens1.pos) #drawlens(lens2.pos) obj_dis1 = lens1.pos plt.hold(True) ''' temp = draw_lens.draw_lens_on(temp,lens1) plt.imshow(temp); temp = draw_lens.draw_lens_on(temp,lens2) plt.imshow(temp); ''' if (source.y == 1 and obj_dis1 == lens1.focus): #point source at focus img_dis1 = np.Inf obj_dis2 = img_dis1 img_dis2 = lens2.focus plt.plot([0, lens1.pos], [0, -2], 'b', [0, lens1.pos], [0, -1], 'b', [0, lens1.pos], [0, 0], 'b', [0, lens1.pos], [0, 1], 'b', [0, lens1.pos], [0, 2], 'b') plt.plot([lens1.pos, lens2.pos], [-2, -2], 'b', [lens1.pos, lens2.pos], [-1, -1], 'b', [lens1.pos, lens2.pos], [0, 0], 'b', [lens1.pos, lens2.pos], [1, 1], 'b', [lens1.pos, lens2.pos], [2, 2], 'b') if (img_dis2 > 0): plt.plot([lens2.pos, lens2.pos + img_dis2], [-2, 0], 'b', [lens2.pos, lens2.pos + img_dis2], [-1, 0], 'b', [lens2.pos, lens2.pos + img_dis2], [0, 0], 'b', [lens2.pos, lens2.pos + img_dis2], [1, 0], 'b', [lens2.pos, lens2.pos + img_dis2], [2, 0], 'b') else: plt.plot([lens2.pos, lens2.pos + img_dis2], [-2, 0], 'b--', [lens2.pos, lens2.pos + img_dis2], [-1, 0], 'b--', [lens2.pos, lens2.pos + img_dis2], [0, 0], 'b--', [lens2.pos, lens2.pos + img_dis2], [1, 0], 'b--', [lens2.pos, lens2.pos + img_dis2], [2, 0], 'b--') plt.plot([lens2.pos, lens2.pos - img_dis2], [-2, -4], 'b', [lens2.pos, lens2.pos - img_dis2], [-1, -2], 'b', [lens2.pos, lens2.pos - img_dis2], [0, 0], 'b', [lens2.pos, lens2.pos - img_dis2], [1, 2], 'b', [lens2.pos, lens2.pos - img_dis2], [2, 4], 'b') return if (source.y == 1): img_dis1 = 1.0 * obj_dis1 * lens1.focus / (obj_dis1 - lens1.focus) obj_dis2 = lens2.pos - (img_dis1 + lens1.pos) img_dis2 = 1.0 * obj_dis2 * lens2.focus / (obj_dis2 - lens2.focus) else: obj_dis1 = np.Inf img_dis1 = lens1.focus obj_dis2 = lens2.pos - (img_dis1 + lens1.pos) img_dis2 = obj_dis2 * lens2.focus / (obj_dis2 - lens2.focus) if (img_dis1 > 0 and obj_dis2 > 0): if (source.y == 1): plt.plot([0, lens1.pos], [0, -2], 'b', [0, lens1.pos], [0, -1], 'b', [0, lens1.pos], [0, 0], 'b', [0, lens1.pos], [0, 1], 'b', [0, lens1.pos], [0, 2], 'b') else: plt.plot([0, lens1.pos], [-2, -2], 'b', [0, lens1.pos], [-1, -1], 'b', [0, lens1.pos], [0, 0], 'b', [0, lens1.pos], [1, 1], 'b', [0, lens1.pos], [2, 2], 'b') plt.plot( [lens1.pos, lens1.pos + img_dis1, lens2.pos], [-2, 0, 2 * (lens2.pos - lens1.pos - img_dis1) / img_dis1], 'b', [lens1.pos, lens1.pos + img_dis1, lens2.pos], [-1, 0, 1 * (lens2.pos - lens1.pos - img_dis1) / img_dis1], 'b', [lens1.pos, lens1.pos + img_dis1, lens2.pos], [0, 0, 0], 'b', [lens1.pos, lens1.pos + img_dis1, lens2.pos], [1, 0, -1 * (lens2.pos - lens1.pos - img_dis1) / img_dis1], 'b', [lens1.pos, lens1.pos + img_dis1, lens2.pos], [2, 0, -2 * (lens2.pos - lens1.pos - img_dis1) / img_dis1], 'b') if (img_dis2 > 0): plt.plot( [lens2.pos + img_dis2, lens2.pos], [0, 2 * (lens2.pos - lens1.pos - img_dis1) / img_dis1], 'b', [lens2.pos + img_dis2, lens2.pos], [0, 1 * (lens2.pos - lens1.pos - img_dis1) / img_dis1], 'b', [lens2.pos + img_dis2, lens2.pos], [0, 0], 'b', [lens2.pos + img_dis2, lens2.pos], [0, -1 * (lens2.pos - lens1.pos - img_dis1) / img_dis1], 'b', [lens2.pos + img_dis2, lens2.pos], [0, -2 * (lens2.pos - lens1.pos - img_dis1) / img_dis1], 'b') else: plt.plot( [lens2.pos, lens2.pos + img_dis2], [-2 * (lens2.pos - lens1.pos - img_dis1) / img_dis1, 0], 'b--', [lens2.pos, lens2.pos + img_dis2], [-1 * (lens2.pos - lens1.pos - img_dis1) / img_dis1, 0], 'b--', [lens2.pos, lens2.pos + img_dis2], [0 * (lens2.pos - lens1.pos - img_dis1) / img_dis1, 0], 'b--', [lens2.pos, lens2.pos + img_dis2], [1 * (lens2.pos - lens1.pos - img_dis1) / img_dis1, 0], 'b--', [lens2.pos, lens2.pos + img_dis2], [2 * (lens2.pos - lens1.pos - img_dis1) / img_dis1, 0], 'b--') plt.plot([lens2.pos, lens2.pos - img_dis2], [ -2 * (lens2.pos - lens1.pos - img_dis1) / img_dis1, -4 * (lens2.pos - lens1.pos - img_dis1) / img_dis1 ], 'b', [lens2.pos, lens2.pos - img_dis2], [ -1 * (lens2.pos - lens1.pos - img_dis1) / img_dis1, -2 * (lens2.pos - lens1.pos - img_dis1) / img_dis1 ], 'b', [lens2.pos, lens2.pos - img_dis2], [0, 0], 'b', [lens2.pos, lens2.pos - img_dis2], [ 1 * (lens2.pos - lens1.pos - img_dis1) / img_dis1, 2 * (lens2.pos - lens1.pos - img_dis1) / img_dis1 ], 'b', [lens2.pos, lens2.pos - img_dis2], [ 2 * (lens2.pos - lens1.pos - img_dis1) / img_dis1, 4 * (lens2.pos - lens1.pos - img_dis1) / img_dis1 ], 'b') elif (img_dis1 > 0 and obj_dis2 < 0): plt.plot([0, lens1.pos], [0, -2], 'b', [0, lens1.pos], [0, -1], 'b', [0, lens1.pos], [0, 0], 'b', [0, lens1.pos], [0, 1], 'b', [0, lens1.pos], [0, 2], 'b') plt.plot([lens1.pos, lens2.pos], [-2, 2 * (lens2.pos - lens1.pos - img_dis1) / img_dis1], 'b', [lens1.pos, lens2.pos], [-1, 1 * (lens2.pos - lens1.pos - img_dis1) / img_dis1], 'b', [lens1.pos, lens2.pos], [0, 0], 'b', [lens1.pos, lens2.pos], [1, -1 * (lens2.pos - lens1.pos - img_dis1) / img_dis1], 'b', [lens1.pos, lens2.pos], [2, -2 * (lens2.pos - lens1.pos - img_dis1) / img_dis1], 'b') plt.plot([lens1.pos + img_dis1, lens2.pos], [0, 2 * (lens2.pos - lens1.pos - img_dis1) / img_dis1], 'b--', [lens1.pos + img_dis1, lens2.pos], [0, 1 * (lens2.pos - lens1.pos - img_dis1) / img_dis1], 'b--', [lens1.pos + img_dis1, lens2.pos], [0, 0], 'b--', [lens1.pos + img_dis1, lens2.pos], [0, -1 * (lens2.pos - lens1.pos - img_dis1) / img_dis1], 'b--', [lens1.pos + img_dis1, lens2.pos], [0, -2 * (lens2.pos - lens1.pos - img_dis1) / img_dis1], 'b--') if (img_dis2 > 0): plt.plot( [lens2.pos + img_dis2, lens2.pos], [0, 2 * (lens2.pos - lens1.pos - img_dis1) / img_dis1], 'b', [lens2.pos + img_dis2, lens2.pos], [0, 1 * (lens2.pos - lens1.pos - img_dis1) / img_dis1], 'b', [lens2.pos + img_dis2, lens2.pos], [0, 0], 'b', [lens2.pos + img_dis2, lens2.pos], [0, -1 * (lens2.pos - lens1.pos - img_dis1) / img_dis1], 'b', [lens2.pos + img_dis2, lens2.pos], [0, -2 * (lens2.pos - lens1.pos - img_dis1) / img_dis1], 'b') else: plt.plot( [lens2.pos, lens2.pos + img_dis2], [-2 * (lens2.pos - lens1.pos - img_dis1) / img_dis1, 0], 'b--', [lens2.pos, lens2.pos + img_dis2], [-1 * (lens2.pos - lens1.pos - img_dis1) / img_dis1, 0], 'b--', [lens2.pos, lens2.pos + img_dis2], [0 * (lens2.pos - lens1.pos - img_dis1) / img_dis1, 0], 'b--', [lens2.pos, lens2.pos + img_dis2], [1 * (lens2.pos - lens1.pos - img_dis1) / img_dis1, 0], 'b--', [lens2.pos, lens2.pos + img_dis2], [2 * (lens2.pos - lens1.pos - img_dis1) / img_dis1, 0], 'b--') plt.plot([lens2.pos, lens2.pos - img_dis2], [ -2 * (lens2.pos - lens1.pos - img_dis1) / img_dis1, -4 * (lens2.pos - lens1.pos - img_dis1) / img_dis1 ], 'b', [lens2.pos, lens2.pos - img_dis2], [ -1 * (lens2.pos - lens1.pos - img_dis1) / img_dis1, -2 * (lens2.pos - lens1.pos - img_dis1) / img_dis1 ], 'b', [lens2.pos, lens2.pos - img_dis2], [0, 0], 'b', [lens2.pos, lens2.pos - img_dis2], [ 1 * (lens2.pos - lens1.pos - img_dis1) / img_dis1, 2 * (lens2.pos - lens1.pos - img_dis1) / img_dis1 ], 'b', [lens2.pos, lens2.pos - img_dis2], [ 2 * (lens2.pos - lens1.pos - img_dis1) / img_dis1, 4 * (lens2.pos - lens1.pos - img_dis1) / img_dis1 ], 'b') elif (img_dis1 < 0): if (source.y == 1): plt.plot([0, lens1.pos], [ 0, 2.0 * (-img_dis1) / (lens2.pos - lens1.pos - img_dis1) ], 'b', [0, lens1.pos], [ 0, 1.0 * (-img_dis1) / (lens2.pos - lens1.pos - img_dis1) ], 'b', [0, lens1.pos], [0, 0], 'b', [0, lens1.pos], [ 0, -1.0 * (-img_dis1) / (lens2.pos - lens1.pos - img_dis1) ], 'b', [0, lens1.pos], [ 0, -2.0 * (-img_dis1) / (lens2.pos - lens1.pos - img_dis1) ], 'b') else: plt.plot([0, lens1.pos], [ 2.0 * (-img_dis1) / (lens2.pos - lens1.pos - img_dis1), 2.0 * (-img_dis1) / (lens2.pos - lens1.pos - img_dis1) ], 'b', [0, lens1.pos], [ 1.0 * (-img_dis1) / (lens2.pos - lens1.pos - img_dis1), 1.0 * (-img_dis1) / (lens2.pos - lens1.pos - img_dis1) ], 'b', [0, lens1.pos], [0, 0], 'b', [0, lens1.pos], [ -1.0 * (-img_dis1) / (lens2.pos - lens1.pos - img_dis1), -1.0 * (-img_dis1) / (lens2.pos - lens1.pos - img_dis1) ], 'b', [0, lens1.pos], [ -2.0 * (-img_dis1) / (lens2.pos - lens1.pos - img_dis1), -2.0 * (-img_dis1) / (lens2.pos - lens1.pos - img_dis1) ], 'b') plt.plot( [lens1.pos + img_dis1, lens1.pos], [0, 2.0 * (-img_dis1) / (lens2.pos - lens1.pos - img_dis1)], 'b--', [lens1.pos + img_dis1, lens1.pos], [0, 1.0 * (-img_dis1) / (lens2.pos - lens1.pos - img_dis1)], 'b--', [lens1.pos + img_dis1, lens1.pos], [0, 0], 'b--', [lens1.pos + img_dis1, lens1.pos], [0, -1.0 * (-img_dis1) / (lens2.pos - lens1.pos - img_dis1)], 'b--', [lens1.pos + img_dis1, lens1.pos], [0, -2.0 * (-img_dis1) / (lens2.pos - lens1.pos - img_dis1)], 'b--') plt.plot( [lens2.pos, lens1.pos], [2, 2.0 * (-img_dis1) / (lens2.pos - lens1.pos - img_dis1)], 'b', [lens2.pos, lens1.pos], [1, 1.0 * (-img_dis1) / (lens2.pos - lens1.pos - img_dis1)], 'b', [lens2.pos, lens1.pos], [0, 0], 'b', [lens2.pos, lens1.pos], [-1, -1.0 * (-img_dis1) / (lens2.pos - lens1.pos - img_dis1)], 'b', [lens2.pos, lens1.pos], [-2, -2.0 * (-img_dis1) / (lens2.pos - lens1.pos - img_dis1)], 'b') if (img_dis2 > 0): plt.plot([lens2.pos + img_dis2, lens2.pos], [0, 2], 'b', [lens2.pos + img_dis2, lens2.pos], [0, 1], 'b', [lens2.pos + img_dis2, lens2.pos], [0, 0], 'b', [lens2.pos + img_dis2, lens2.pos], [0, -1], 'b', [lens2.pos + img_dis2, lens2.pos], [0, -2], 'b') else: plt.plot([lens2.pos, lens2.pos + img_dis2], [-2, 0], 'b--', [lens2.pos, lens2.pos + img_dis2], [-1, 0], 'b--', [lens2.pos, lens2.pos + img_dis2], [0, 0], 'b--', [lens2.pos, lens2.pos + img_dis2], [1, 0], 'b--', [lens2.pos, lens2.pos + img_dis2], [2, 0], 'b--') plt.plot([lens2.pos, lens2.pos - img_dis2], [-2, -4], 'b', [lens2.pos, lens2.pos - img_dis2], [-1, -2], 'b', [lens2.pos, lens2.pos - img_dis2], [0, 0], 'b', [lens2.pos, lens2.pos - img_dis2], [1, 2], 'b', [lens2.pos, lens2.pos - img_dis2], [2, 4], 'b') x_axis = plt.get(plt.gca(), "xlim") plt.savefig("lens.jpg", ) temp = Image.open("lens.jpg") draw_lens_on(temp, lens1, x_axis) draw_lens_on(temp, lens2, x_axis) temp.save('./lens/static/lens/pos.jpg')
m_ls = la.solve(G, t) else: m_ls = la.lstsq(G, t)[0] # Plot the least-squares solution and confidence intervals covm_ls = (noise**2) * la.inv(np.dot(G.T, G)) conf95 = 1.96 * np.sqrt(np.diag(covm_ls)) conf95 = conf95.reshape(N, 1) dz = dobs[1] - dobs[0] dobs2 = dobs + dz / 2 fig1, ax1 = plt.subplots(1, 1) ax1.plot(dobs2, m_ls * 1000, '-', drawstyle='steps') dum = ax1.plot(dobs2, (m_ls + conf95) * 1000, '--', drawstyle='steps') color = plt.get(dum[0], 'color') ax1.plot(dobs2, (m_ls - conf95) * 1000, '--', color=color, drawstyle='steps') ax1.set_xlabel('Depth [m]') ax1.set_ylabel('Slowness [s/km]') fig1.savefig('c4fmL2.pdf') plt.close() # --- Apply first-order Tikhonov regularization --- L1 = roughmat(N, 1, full=True) U1, V1, X1, LAM1, MU1 = gsvd(G, L1) # Apply the L curve criteria to the first-order regularization problem rho1, eta1, reg_params1 = lcurve_gsvd(U1, X1, LAM1, MU1, t, G, L1, 1200)
plt.imshow(Z, origin='lower', extent=extent, cmap=cmap, norm=norm) v = plt.axis() plt.contour(Z, levels, colors='k', origin='lower', extent=extent) plt.axis(v) plt.title("Image, origin 'lower'") plt.subplot(2, 2, 4) # We will use the interpolation "nearest" here to show the actual # image pixels. # Note that the contour lines don't extend to the edge of the box. # This is intentional. The Z values are defined at the center of each # image pixel (each color block on the following subplot), so the # domain that is contoured does not extend beyond these pixel centers. im = plt.imshow(Z, interpolation='nearest', extent=extent, cmap=cmap, norm=norm) v = plt.axis() plt.contour(Z, levels, colors='k', origin='image', extent=extent) plt.axis(v) ylim = plt.get(plt.gca(), 'ylim') plt.setp(plt.gca(), ylim=ylim[::-1]) plt.title("Origin from rc, reversed y-axis") plt.colorbar(im) plt.tight_layout() plt.show()
def _plotall_plot_page(arrays, props, curr_page=0): narrays = len(arrays) nsubplots = min(narrays, np.prod(props['subplot'])) subplots = curr_page * nsubplots + np.arange(nsubplots) # Pass 1: plot everything and align axes. all_axes = [] all_image_axes = [] click_handlers = {} for n, x in enumerate(subplots): if x < 0 or x >= narrays: continue kwargs = {} if n > 0: if 'x' in props['align']: kwargs['sharex'] = all_axes[0] if 'y' in props['align']: kwargs['sharey'] = all_axes[0] curr_axes = plt.subplot(*props['subplots'][x], **kwargs) data = np.asarray(arrays[x]) if _plotall_get_prop(props['transpose'], x): data = np.transpose(data) plotfun = _plotall_get_prop(props['plotfun'], x) plotfun(data) clickfun = props['clickfun'] if clickfun: click_handlers[curr_axes] = _plotall_get_prop(clickfun, x) all_axes.append(curr_axes) if data.ndim == 2: xlim_max = data.shape[1] - 0.5 else: xlim_max = len(data) plt.setp(curr_axes, 'xlim', [-0.5, xlim_max]) if data.ndim == 2: all_image_axes.append(curr_axes) plt.setp(curr_axes, 'ylim', [-0.5, data.shape[0]-0.5]) # Draw colorbars on all subplots (even if they are not images) # to keep axis widths consistent. if props['colorbar']: plt.colorbar() if 'x' in props['align']: align_axes('x', all_axes) for ax in ('y', 'c'): if ax in props['align']: align_axes(ax, all_image_axes) fig = plt.gcf() clickfun = functools.partial(_plotall_click_handler, click_handlers=click_handlers) cid = fig.canvas.mpl_connect("button_press_event", clickfun) # Pass 2: set specified axis properties. for x in subplots: if x < 0 or x >= narrays: continue curr_axes = all_axes[x - subplots[0]] plt.axes(curr_axes) succeeded = False for name, val in props['other'].iteritems(): val = _plotall_get_prop(val, x) if isinstance(val, types.FunctionType): val = val() try: plt.setp(curr_axes, name, val) succeeded = True except AttributeError: for curr_axes_child in plt.get(curr_axes, 'children'): try: plt.setp(curr_axes_child, name, val) succeeded = True except: pass if not succeeded: print 'Unable to set "%s" property on %s' % (name, curr_axes) if props['pub']: if x <= nsubplots - props['subplot'][1]: plt.xlabel(' ') #set(curr_axes, 'XTickLabel', ' ') plt.grid(props['grid']) # add_pan_and_zoom_controls_to_figure(properties.figure, all_axes); return all_axes
xticks=[-2, -1, 0, 1, 2], ylim=[0, 1], xlim=[-2, 2], ylabel='P(choose sum)', yticks=[0, .25, .5, .75, 1], color=plt.cm.jet(cm_inds[si - 1])) #setup colorbar cmap_singplot = mpl.colors.ListedColormap(plt.cm.jet(cm_inds)) norm = mpl.colors.BoundaryNorm(boundaries=np.insert(using_flatlo, 0, .5) + .5, ncolors=cmap_singplot.N) cbar = mpl.colorbar.ColorbarBase(ax[2], cmap=cmap_singplot, norm=norm, ticks=using) bbox = plt.get(ax[0], 'position') cbpos = plt.get(ax[2], 'position') #plt.tight_layout() #ax[2].set_position([cbpos.x0,cbpos.y0+.2,cbpos.width*.1,cbpos.height*.5]) pdf.savefig() h, ax = plt.subplots(1, 2, figsize=[2 * width_per_panel, height_per_panel]) Plotter.scatter(ax[0], xdata=x_arithperf, ydata=x_threshperf, ylim=[.5, 1], xlim=[.5, 1], xlabel='Arithmetic strategy', ylabel='Singleton-Thresholding Strategy', title='Monkey X') Plotter.scatter(ax[1],
def _plotall_plot_page(arrays, props, curr_page=0): narrays = len(arrays) nsubplots = min(narrays, np.prod(props['subplot'])) subplots = curr_page * nsubplots + np.arange(nsubplots) # Pass 1: plot everything and align axes. if props['clf']: plt.clf() all_axes = [] all_image_axes = [] click_handlers = {} for n, x in enumerate(subplots): if x < 0 or x >= narrays or arrays[x] is None: all_axes.append(None) continue kwargs = {} if all_axes: if 'x' in props['align']: kwargs['sharex'] = all_axes[0] if 'y' in props['align']: kwargs['sharey'] = all_axes[0] curr_axes = plt.subplot(*props['subplots'][x], **kwargs) data = np.asarray(arrays[x]) if _plotall_get_prop(props['transpose'], x): data = np.transpose(data) plotfun = _plotall_get_prop(props['plotfun'], x) plotfun(data) clickfun = props['clickfun'] if clickfun: click_handlers[curr_axes] = _plotall_get_prop(clickfun, x) all_axes.append(curr_axes) if data.ndim == 2: xlim_max = data.shape[1] - 0.5 else: xlim_max = len(data) plt.setp(curr_axes, 'xlim', [-0.5, xlim_max]) if data.ndim == 2: all_image_axes.append(curr_axes) plt.setp(curr_axes, 'ylim', [-0.5, data.shape[0]-0.5]) # Draw colorbars on all subplots (even if they are not images) # to keep axis widths consistent. if props['colorbar']: plt.colorbar() if 'x' in props['align']: align_axes('x', all_axes) for ax in ('y', 'c'): if ax in props['align']: align_axes(ax, all_image_axes) fig = plt.gcf() clickfun = functools.partial(_plotall_click_handler, click_handlers=click_handlers) cid = fig.canvas.mpl_connect("button_press_event", clickfun) # Pass 2: set specified axis properties. for x in subplots: if x < 0 or x >= narrays or arrays[x] is None: continue curr_axes = all_axes[x] if curr_axes is None: continue plt.axes(curr_axes) succeeded = False for name, val in props['other'].iteritems(): val = _plotall_get_prop(val, x) if isinstance(val, types.FunctionType): val = val() try: plt.setp(curr_axes, name, val) succeeded = True except AttributeError: for curr_axes_child in plt.get(curr_axes, 'children'): try: plt.setp(curr_axes_child, name, val) succeeded = True except: pass if not succeeded: print 'Unable to set "%s" property on %s' % (name, curr_axes) if props['pub']: if x <= nsubplots - props['subplot'][1]: plt.xlabel(' ') #set(curr_axes, 'XTickLabel', ' ') plt.grid(props['grid']) # add_pan_and_zoom_controls_to_figure(properties.figure, all_axes); return all_axes
fig = plt.figure(facecolor='w') ax1 = fig.add_subplot(2, 1, 1) ax1.plot(trainDay, np.array(data['rewardsEarned'][mouseInd])[sortInd], 'ko') ax2 = fig.add_subplot(2, 1, 2) ax2.plot(weighDay, data['weight'][mouseInd], 'ko') for i, (ax, ylbl) in enumerate(zip((ax1, ax2), ('Rewards', 'Weight (g)'))): for j, lbl in zip((handoffReady, rig, ephys), ('handoff\nready', 'on rig', 'ephys')): x = trainDay[j] - 0.5 ax.axvline(x, color='k') if i == 0: ylim = plt.get(ax, 'ylim') ax.text(x, ylim[0] + 1.05 * (ylim[1] - ylim[0]), lbl, horizontalalignment='center', verticalalignment='bottom') for side in ('right', 'top'): ax.spines[side].set_visible(False) ax.tick_params(direction='out', top=False, right=False) ax.set_xlim([-1, max(trainDay) + 1]) if i == 1: ax.set_xlabel('Day') ax.set_ylabel(ylbl) params = (rewardsEarned, dprimeEngaged, probEngaged) labels = ('Rewards Earned', 'd prime', 'prob. engaged')
def main(): # name of starting ensDA output diagnostic file, starting index and measure [measure, fname, sOI, _] = get_input_arguments() # Ensemble sizes to compare Ne = [5, 10, 20, 30, 40, 50] # some more arguments, currently hard-coded save_figures = False # save plots as eps yscale = 'linear' # y-axis of RMSE plots (linear/semilog) yFix = None # fix the y-axis of RMSE plots ( None = automatic ) fOrient = 'portrait' # figure orientation (landscape/portrait) if ( not measure ): measure = 'truth' if ( sOI == -1 ): sOI = 0 nf = len(Ne) fnames = [] for i in range(0,nf): fnames.append(fname + '%d.nc4' % Ne[i]) for i in range(0,nf): print fnames[i] if ( len(fnames) <= 15 ): fcolor = ["#000000", "#C0C0C0", "#808080", "#800000", "#FF0000",\ "#800080", "#FF00FF", "#008000", "#00FF00", "#808000",\ "#FFFF00", "#000080", "#0000FF", "#008080", "#00FFFF"] # black, silver, gray, maroon, red # purple, fuchsia, green, lime, olive # yellow, navy, blue, teal, aqua else: fcolor = get_Ndistinct_colors(len(fnames)) # read dimensions and necessary attributes from the diagnostic file [model, DA, ensDA, _] = read_diag_info(fnames[0]) if ( ensDA.update == 1 ): estr = 'EnKF' elif ( ensDA.update == 2 ): estr = 'EnSRF' elif ( ensDA.update == 3 ): estr = 'EAKF' # allocate room for variables print 'computing RMSE against %s' % measure xbrmse = np.zeros((len(fnames),DA.nassim)) xarmse = np.zeros((len(fnames),DA.nassim)) xyrmse = np.zeros((len(fnames),DA.nassim)) flabel = [] blabel = [] mean_prior = np.zeros(len(fnames)) mean_posterior = np.zeros(len(fnames)) std_prior = np.zeros(len(fnames)) std_posterior = np.zeros(len(fnames)) mean_evratio = np.zeros(len(fnames)) std_evratio = np.zeros(len(fnames)) for fname in fnames: print 'reading ... %s' % fname f = fnames.index(fname) try: nc = Dataset(fname, mode='r', format='NETCDF4') flabel.append('Ne = %d' % len(nc.dimensions['ncopy'])) blabel.append('%d' % len(nc.dimensions['ncopy'])) nc.close() except Exception as Instance: print 'Exception occurred during read of ' + fname print type(Instance) print Instance.args print Instance sys.exit(1) # read the diagnostic file xt, Xb, Xa, y, _, _, evratio = read_diag(fname, 0, end_time=DA.nassim) # compute ensemble mean xbm = np.squeeze(np.mean(Xb, axis=1)) xam = np.squeeze(np.mean(Xa, axis=1)) # compute RMSE in prior, posterior and observations if ( measure == 'truth' ): xbrmse[f,] = np.sqrt( np.sum( (xt - xbm)**2, axis = 1) / model.Ndof ) xarmse[f,] = np.sqrt( np.sum( (xt - xam)**2, axis = 1) / model.Ndof ) else: xbrmse[f,] = np.sqrt( np.sum( (y - xbm)**2, axis = 1) / model.Ndof ) xarmse[f,] = np.sqrt( np.sum( (y - xam)**2, axis = 1) / model.Ndof ) xyrmse[f,] = np.sqrt( np.sum( (xt - y)**2 ) / model.Ndof ) # compute mean and std. dev. in the error-variance ratio mean_evratio[f] = np.mean(evratio[sOI+1:]) std_evratio[f] = np.std(evratio[sOI+1:], ddof=1) # start plotting #----------------------------------------------------------- fig = pyplot.figure() pyplot.clf() pyplot.hold(True) for fname in fnames: f = fnames.index(fname) q = np.squeeze(xbrmse[f,sOI:]) if ( yscale == 'linear' ): pyplot.plot( q,'-',color=fcolor[f],label=flabel[f],linewidth=1) elif ( yscale == 'semilog' ): pyplot.semilogy(q,'-',color=fcolor[f],label=flabel[f],linewidth=1) yl = pyplot.get(pyplot.gca(),'ylim') xl = pyplot.get(pyplot.gca(),'xlim') if ( yFix is None ): ymax = yl[1] else: ymax = yFix pyplot.ylim(0.0, ymax) pyplot.xlim(0.0, len(q)) for fname in fnames: f = fnames.index(fname) q = np.squeeze(xbrmse[f,sOI:]) mean_prior[f] = np.mean(q) std_prior[f] = np.std(q,ddof=1) str = 'mean rmse : %5.4f +/- %5.4f' % (np.mean(q), np.std(q,ddof=1)) pyplot.text(25,(1-0.05*(f+1))*ymax,str,color=fcolor[f],fontsize=10) pyplot.xlabel('Assimilation Cycle',fontweight='bold',fontsize=12) pyplot.ylabel('RMSE',fontweight='bold',fontsize=12) pyplot.title('RMSE - Prior',fontweight='bold',fontsize=14) pyplot.legend(loc=1) pyplot.hold(False) if save_figures: fig.savefig('%s_ensDA_RMSE_Prior.eps' % (model.Name),dpi=300,orientation=fOrient,format='eps') #----------------------------------------------------------- #----------------------------------------------------------- fig = pyplot.figure() pyplot.clf() pyplot.hold(True) for fname in fnames: f = fnames.index(fname) q = np.squeeze(xarmse[f,sOI:]) if ( yscale == 'linear' ): pyplot.plot( q,'-',color=fcolor[f],label=flabel[f],linewidth=1) elif ( yscale == 'semilog' ): pyplot.semilogy(q,'-',color=fcolor[f],label=flabel[f],linewidth=1) yl = pyplot.get(pyplot.gca(),'ylim') xl = pyplot.get(pyplot.gca(),'xlim') if ( yFix is None ): ymax = yl[1] else: ymax = yFix pyplot.ylim(0.0, ymax) pyplot.xlim(0.0, len(q)) for fname in fnames: f = fnames.index(fname) q = np.squeeze(xarmse[f,sOI:]) mean_posterior[f] = np.mean(q) std_posterior[f] = np.std(q,ddof=1) str = 'mean rmse : %5.4f +/- %5.4f' % (np.mean(q), np.std(q,ddof=1)) pyplot.text(25,(1-0.05*(f+1))*ymax,str,color=fcolor[f],fontsize=10) pyplot.xlabel('Assimilation Cycle',fontweight='bold',fontsize=12) pyplot.ylabel('RMSE',fontweight='bold',fontsize=12) pyplot.title('RMSE - Posterior',fontweight='bold',fontsize=14) pyplot.legend(loc=1) pyplot.hold(False) if save_figures: fig.savefig('%s_ensDA_RMSE_Posterior.eps' % (model.Name),dpi=300,orientation=fOrient,format='eps') #----------------------------------------------------------- #----------------------------------------------------------- fig = pyplot.figure() pyplot.clf() pyplot.hold(True) index = np.arange(nf) + 0.15 width = 0.35 pyplot.bar(index,mean_prior,width,linewidth=0.0,color='0.75',edgecolor='0.75',yerr=std_prior, error_kw=dict(ecolor='black',elinewidth=3,capsize=5)) pyplot.bar(index+width,mean_posterior,width,linewidth=0.0,color='gray',edgecolor='gray',yerr=std_posterior,error_kw=dict(ecolor='black',elinewidth=3,capsize=5)) pyplot.xticks(index+width, blabel) pyplot.xlabel('Ensemble Size', fontweight='bold',fontsize=12) pyplot.ylabel('RMSE', fontweight='bold',fontsize=12) pyplot.title( 'RMSE', fontweight='bold',fontsize=14) pyplot.hold(False) if save_figures: fig.savefig('%s_ensDA_RMSE.eps' % (model.Name),dpi=300,orientation=fOrient,format='eps') #----------------------------------------------------------- #----------------------------------------------------------- fig = pyplot.figure() pyplot.clf() pyplot.hold(True) index = np.arange(nf) + 0.2 width = 0.6 pyplot.bar(index,mean_evratio,width,linewidth=0.0,color='gray',edgecolor='gray',yerr=std_evratio,error_kw=dict(ecolor='black',elinewidth=3,capsize=5)) pyplot.xticks(index+width/2, blabel) pyplot.xlabel('Ensemble Size', fontweight='bold',fontsize=12) pyplot.ylabel('Error - Variance Ratio', fontweight='bold',fontsize=12) pyplot.title( 'Error - Variance Ratio', fontweight='bold',fontsize=14) pyplot.hold(False) if save_figures: fig.savefig('%s_ensDA_evratio.eps' % (model.Name),dpi=300,orientation=fOrient,format='eps') #----------------------------------------------------------- if not save_figures: pyplot.show() print '... all done ...' sys.exit(0)
def main(): ipshell = IPShellEmbed() if len(sys.argv) < 2: logfilename = 'log.csv' # use default filename print 'No input filename specified: using %s' % logfilename else: logfilename = sys.argv[1] if not os.path.exists(logfilename): print '%s does not exist!' % logfilename sys.exit() else: print 'Reading file %s' % logfilename if len(sys.argv) < 3: pngfilename = None print 'No output filename specified: will not write output file for plot' else: pngfilename = sys.argv[2] print 'Plot will be saved as %s' % pngfilename data = np.genfromtxt(logfilename, delimiter=',', skip_header=6, usecols=(0, 1, 3, 4, 5, 6, 7, 8, 9)) t = data[:, 0] stamp = data[:, 1] lm61temp = data[:, 2] #therm1 = data[:,3] therm1 = np.ma.masked_where(np.isnan(data[:, 3]), data[:, 3]) therm2 = data[:, 4] temp0 = data[:, 5] #temp1 = data[:,6] # use masked array rather than nan for bad values data[np.where(data[:, 6] > MAXTEMP), 6] = np.nan data[np.where(data[:, 7] > MAXTEMP), 7] = np.nan data[np.where(data[:, 8] > MAXTEMP), 8] = np.nan temp1 = np.ma.masked_where(np.isnan(data[:, 6]), data[:, 6]) temp2 = np.ma.masked_where(np.isnan(data[:, 7]), data[:, 7]) temp3 = np.ma.masked_where(np.isnan(data[:, 8]), data[:, 8]) offset = stamp[1] - t[1] / 1000 print offset maxstamp = t[len(t) - 1] / 1000 + offset + MAXSEC print maxstamp stamp[stamp < offset] = np.nan stamp[stamp > maxstamp] = np.nan stamp[abs(stamp - t / 1000 - offset) > MAXSEC] = np.nan nancount = np.sum(np.isnan(stamp)) print '%d bad time stamps to interpolate' % nancount # extrapolate - see # http://stackoverflow.com/questions/1599754/is-there-easy-way-in-python-to-extrapolate-data-points-to-the-future extrapolator = UnivariateSpline(t[np.isfinite(stamp)], stamp[np.isfinite(stamp)], k=1) utime = extrapolator(t) # plot 6 columns pyplot.plot(dates.epoch2num(utime), lm61temp, '.', dates.epoch2num(utime), therm1, '.', dates.epoch2num(utime), therm2, '.', dates.epoch2num(utime), temp1, '.', dates.epoch2num(utime), temp2, '.', dates.epoch2num(utime), temp3, '.') ax = pyplot.gca() ax.legend(('LM61', 'Thermistor 1', 'Thermistor 2', 'digital 1', 'digital 2', 'digital 3'), loc=0) ax.set_xlabel('Time') ax.set_ylabel(u'Temp (°C)') ax2 = ax.twinx() clim = pyplot.get(ax, 'ylim') ax2.set_ylim(c2f(clim[0]), c2f(clim[1])) ax2.set_ylabel(u'Temp (°F)') xlocator = dates.AutoDateLocator() xformatter = dates.AutoDateFormatter(xlocator) pyplot.gca().xaxis.set_major_locator(xlocator) pyplot.gca().xaxis.set_major_formatter(dates.DateFormatter('%H:%M')) # generate a PNG file if pngfilename: pyplot.savefig(pngfilename) # show the plot pyplot.show() # open interactive shell ipshell()
def main(): # Import iris data iris = datasets.load_iris() x = iris.data[:, :2] # take the first two features. y = iris.target # label # Splitting data into train, validation and test set # 50% training set, 20% validation set, 30% test set x_train, x_tmp, y_train, y_tmp = train_test_split(x, y, test_size=0.5, random_state=42) x_validate, x_test, y_validate, y_test = train_test_split(x_tmp, y_tmp, test_size=0.4, random_state=42) c = [10**(-3), 10**(-2), 10**(-1), 10**0, 10**1, 10**2, 10**3] g = [10**(-9), 10**(-7), 10**(-5), 10**(-3)] #c = [10**(-2), 10**(-1), 10**0, 10**1, 10**2, 10**3, 10**4, 10**5, 10**6, 10**7, 10**8, 10**9, 10**10] #g = [10**(-9), 10**(-8), 10**(-7), 10**(-6), 10**(-5), 10**(-4), 10**(-3), 10**(-2), 10**(-1), 10**0, 10**1, 10**2, 10**3] best_values = [-1, -1, -1] # respectively best success rate, best C and best gamma a = [ ] # rows are C values and columns are gamma values, each cell is the accuracy for the corresponding C and gamma plt.figure('SVC with rbf-kernel', figsize=(30, 20)) k = 1 for i in c: values = [] for j in g: clf = svm.SVC(kernel='rbf', C=i, gamma=j) clf.fit(x_train, y_train) # create a mesh to plot in x_min, x_max = x_train[:, 0].min() - 1, x_train[:, 0].max() + 1 y_min, y_max = x_train[:, 1].min() - 1, x_train[:, 1].max() + 1 h = (x_max / x_min) / 100 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) z = z.reshape(xx.shape) plt.subplot(len(c), len(g), k) title = 'C=' + str(i) + ' and gamma=' + str(j) plt.title(title, fontsize=30) plt.contourf(xx, yy, z, cmap=plt.get('Paired'), alpha=0.8) plt.scatter(x_train[:, 0], x_train[:, 1], c=y_train, cmap=plt.get('Paired')) plt.xlim(xx.min(), xx.max()) print('With C=' + str(i) + ' and gamma=' + str(j)) full_prediction = clf.predict(x_validate) print( '[-] Number of mislabeled points out of a total %d points: %d' % (len(y_validate), (y_validate != full_prediction).sum())) accuracy = ( 100 * (len(y_validate) - (y_validate != full_prediction).sum())) / len(y_validate) print('[-] With an accuracy of %.3f%s' % (accuracy, '%')) if accuracy > best_values[0]: best_values = accuracy, i, j k += 1 values.append(accuracy) a.append(values) plt.show() plt.close() # 2D heatmap validation accuracy plt.title('Validation Accuracy') plt.xlabel('gamma') plt.ylabel('C') plt.imshow(a, cmap='hot', interpolation='nearest') plt.show() plt.close() print('\nBest C=' + str(best_values[1]) + ' and best gamma=' + str(best_values[2])) # With the best C and gamma evaluating test set print('Evaluating test set') clf = svm.SVC(kernel='rbf', C=best_values[1], gamma=best_values[2]) clf.fit(x_train, y_train) x_min, x_max = x_train[:, 0].min() - 1, x_train[:, 0].max() + 1 y_min, y_max = x_train[:, 1].min() - 1, x_train[:, 1].max() + 1 h = (x_max / x_min) / 100 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) z = z.reshape(xx.shape) title = 'C=' + str(best_values[1]) + ' and gamma=' + str(best_values[2]) plt.title(title, fontsize=20) plt.contourf(xx, yy, z, cmap=plt.get('Paired'), alpha=0.8) plt.scatter(x_train[:, 0], x_train[:, 1], c=y_train, cmap=plt.get('Paired')) plt.xlim(xx.min(), xx.max()) full_prediction = clf.predict(x_test) print('[-] Number of mislabeled points out of a total %d points: %d' % (len(y_test), (y_test != full_prediction).sum())) print('[-] With an accuracy of: %.3f%s' % ((100 * (len(y_test) - (y_test != full_prediction).sum())) / len(y_test), '%')) plt.show() plt.close()
HorizontalSize = 4 VerticalSize = 4 figMSC=plt.figure(num=2,figsize=(HorizontalSize,VerticalSize), edgecolor='k', facecolor = [1,1,0.92]); figMSC.clf() hs = plt.plot(listC0,CI[:,2,:]) plt.grid(True) plt.hold(True) MSC0indselect=90 for im in range(LN): tt = '$N_d$ = %i' %listNd[im] h=plt.plot(listC0[MSC0indselect],CI[MSC0indselect,2,im],'o', label=tt); cc = plt.get(hs[im],'color'); plt.setp(h,color=cc) if im==0: ha=plt.arrow(listC0[MSC0indselect]+0.01,CI[MSC0indselect,2,im]+0.01, -0.005,-0.005, head_width=0.004) plt.hold(False) plt.xlim([0.85, 0.93]) plt.ylim([0.89, 1]) plt.legend(loc='best') dirfigsave = '/Users/maurice/etudes/ctbto/allJOBs2015/reponsesdevelop/rep2' tt='%s/MSCthreshold2.pdf' %dirfigsave figMSC.savefig(tt,format='pdf')
def main(): # name of starting hybrid output diagnostic file, starting index and no. of files [measure, fname, sOI, _] = get_input_arguments() # alpha, beta to compare vary_variable = 'alpha' beta = [0.0, 0.5, 0.75, 1.00] alpha = [0.5, 1.0, 2.0, 2.6] # some more arguments, currently hard-coded save_figures = False # save plots as eps yscale = 'linear' # y-axis of RMSE plots (linear/semilog) yFix = None # fix the y-axis of RMSE plots ( None = automatic ) fOrient = 'portrait' # figure orientation (landscape/portrait) if ( not measure ): measure = 'truth' if ( sOI == -1 ): sOI = 0 fnames = [] if ( vary_variable == 'alpha'): nf = len(alpha) for i in range(0,nf): fnames.append( fname + '_beta=%3.2f' % beta[0] + '_alpha=%2.1f' % alpha[i] + '.nc4' ) elif ( vary_variable == 'beta' ): nf = len(beta) for i in range(0,nf): fnames.append( fname + '_beta=%3.2f' % beta[i] + '_alpha=%2.1f' % alpha[0] + '.nc4' ) if ( len(fnames) <= 15 ): fcolor = ["#000000", "#C0C0C0", "#808080", "#800000", "#FF0000",\ "#800080", "#FF00FF", "#008000", "#00FF00", "#808000",\ "#FFFF00", "#000080", "#0000FF", "#008080", "#00FFFF"] # black, silver, gray, maroon, red # purple, fuchsia, green, lime, olive # yellow, navy, blue, teal, aqua else: fcolor = get_Ndistinct_colors(len(fnames)) # read dimensions and necessary attributes from the diagnostic file [model, DA, ensDA, varDA] = read_diag_info(fnames[0]) if ( ensDA.update == 1 ): estr = 'EnKF' elif ( ensDA.update == 2 ): estr = 'EnSRF' elif ( ensDA.update == 3 ): estr = 'EAKF' if ( varDA.update == 1 ): vstr = '3D' elif ( varDA.update == 2 ): vstr = '4D' # allocate room for variables print 'computing RMSE against %s' % measure xbrmseE = np.zeros((len(fnames),DA.nassim)) xarmseE = np.zeros((len(fnames),DA.nassim)) xbrmseC = np.zeros((len(fnames),DA.nassim)) xarmseC = np.zeros((len(fnames),DA.nassim)) xyrmse = np.zeros((len(fnames),DA.nassim)) flabel = [] blabel = [] mean_prior_C = np.zeros(len(fnames)) mean_prior_E = np.zeros(len(fnames)) mean_posterior_C = np.zeros(len(fnames)) mean_posterior_E = np.zeros(len(fnames)) std_prior_C = np.zeros(len(fnames)) std_prior_E = np.zeros(len(fnames)) std_posterior_C = np.zeros(len(fnames)) std_posterior_E = np.zeros(len(fnames)) for fname in fnames: print 'reading ... %s' % fname f = fnames.index(fname) try: nc = Dataset(fname, mode='r', format='NETCDF4') if ( vary_variable == 'alpha' ): flabel.append(r'$\alpha$ = %2.1f' % alpha[f]) blabel.append('%2.1f' % alpha[f]) elif ( vary_variable == 'beta' ): flabel.append(r'$\beta$ = %3.2f' % nc.hybrid_wght) blabel.append('%3.2f' % nc.hybrid_wght) nc.close() except Exception as Instance: print 'Exception occurred during read of ' + fname print type(Instance) print Instance.args print Instance sys.exit(1) # read the diagnostic file xt, Xb, Xa, y, _, _, xbc, xac, _, _ = read_diag(fname, 0, end_time=DA.nassim) # compute ensemble mean xbm = np.squeeze(np.mean(Xb, axis=1)) xam = np.squeeze(np.mean(Xa, axis=1)) # compute RMSE in prior, posterior and observations if ( measure == 'truth' ): xbrmseE[f,] = np.sqrt( np.sum( (xt - xbm)**2, axis = 1) / model.Ndof ) xarmseE[f,] = np.sqrt( np.sum( (xt - xam)**2, axis = 1) / model.Ndof ) xbrmseC[f,] = np.sqrt( np.sum( (xt - xbc)**2, axis = 1) / model.Ndof ) xarmseC[f,] = np.sqrt( np.sum( (xt - xac)**2, axis = 1) / model.Ndof ) else: xbrmseE[f,] = np.sqrt( np.sum( (y - xbm)**2, axis = 1) / model.Ndof ) xarmseE[f,] = np.sqrt( np.sum( (y - xam)**2, axis = 1) / model.Ndof ) xbrmseC[f,] = np.sqrt( np.sum( (y - xbc)**2, axis = 1) / model.Ndof ) xarmseC[f,] = np.sqrt( np.sum( (y - xac)**2, axis = 1) / model.Ndof ) xyrmse[f,] = np.sqrt( np.sum( (xt - y)**2 ) / model.Ndof ) # start plotting #----------------------------------------------------------- fig = pyplot.figure() pyplot.clf() pyplot.hold(True) for fname in fnames: f = fnames.index(fname) q = np.squeeze(xbrmseE[f,sOI:]) if ( yscale == 'linear' ): pyplot.plot( q,'-',color=fcolor[f],label=flabel[f],linewidth=1) elif ( yscale == 'semilog' ): pyplot.semilogy(q,'-',color=fcolor[f],label=flabel[f],linewidth=1) yl = pyplot.get(pyplot.gca(),'ylim') xl = pyplot.get(pyplot.gca(),'xlim') if ( yFix is None ): ymax = yl[1] else: ymax = yFix pyplot.ylim(0.0, ymax) pyplot.xlim(0.0, len(np.squeeze(xbrmseE[f,sOI:]))) for fname in fnames: f = fnames.index(fname) q = np.squeeze(xbrmseE[f,sOI:]) mean_prior_E[f] = np.mean(q) std_prior_E[f] = np.std(q,ddof=1) str = 'mean rmse : %5.4f +/- %5.4f' % (np.mean(q), np.std(q,ddof=1)) pyplot.text(25,(1-0.05*(f+1))*ymax,str,color=fcolor[f],fontsize=10) pyplot.xlabel('Assimilation Cycle',fontweight='bold',fontsize=12) pyplot.ylabel('RMSE',fontweight='bold',fontsize=12) pyplot.title('RMSE - %s Prior' % estr,fontweight='bold',fontsize=14) pyplot.legend(loc=1) pyplot.hold(False) if save_figures: fig.savefig('%s_%shybDA_RMSE_%s_Prior.eps' % (model.Name, vstr, estr),dpi=300,orientation=fOrient,format='eps') #----------------------------------------------------------- #----------------------------------------------------------- fig = pyplot.figure() pyplot.clf() pyplot.hold(True) for fname in fnames: f = fnames.index(fname) q = np.squeeze(xbrmseC[f,sOI:]) mean_prior_C[f] = np.mean(q) std_prior_C[f] = np.std(q,ddof=1) if ( yscale == 'linear' ): pyplot.plot( q,'-',color=fcolor[f],label=flabel[f],linewidth=1) elif ( yscale == 'semilog' ): pyplot.semilogy(q,'-',color=fcolor[f],label=flabel[f],linewidth=1) yl = pyplot.get(pyplot.gca(),'ylim') xl = pyplot.get(pyplot.gca(),'xlim') if ( yFix is None ): ymax = yl[1] else: ymax = yFix pyplot.ylim(0.0, ymax) pyplot.xlim(0.0, len(np.squeeze(xbrmseC[f,sOI:]))) for fname in fnames: f = fnames.index(fname) q = np.squeeze(xbrmseC[f,sOI:]) str = 'mean rmse : %5.4f +/- %5.4f' % (np.mean(q), np.std(q,ddof=1)) pyplot.text(25,(1-0.05*(f+1))*ymax,str,color=fcolor[f],fontsize=10) pyplot.xlabel('Assimilation Cycle',fontweight='bold',fontsize=12) pyplot.ylabel('RMSE',fontweight='bold',fontsize=12) pyplot.title('RMSE - %sVar Prior' % (vstr), fontweight='bold',fontsize=14) pyplot.legend(loc=1) pyplot.hold(False) if save_figures: fig.savefig('%s_%shybDA_RMSE_%sVar_Prior.eps' % (model.Name, vstr, vstr),dpi=300,orientation=fOrient,format='eps') #----------------------------------------------------------- #----------------------------------------------------------- fig = pyplot.figure() pyplot.clf() pyplot.hold(True) for fname in fnames: f = fnames.index(fname) q = np.squeeze(xarmseE[f,sOI:]) if ( yscale == 'linear' ): pyplot.plot( q,'-',color=fcolor[f],label=flabel[f],linewidth=1) elif ( yscale == 'semilog' ): pyplot.semilogy(q,'-',color=fcolor[f],label=flabel[f],linewidth=1) yl = pyplot.get(pyplot.gca(),'ylim') xl = pyplot.get(pyplot.gca(),'xlim') if ( yFix is None ): ymax = yl[1] else: ymax = yFix pyplot.ylim(0.0, ymax) pyplot.xlim(0.0, len(np.squeeze(xarmseE[f,sOI:]))) for fname in fnames: f = fnames.index(fname) q = np.squeeze(xarmseE[f,sOI:]) mean_posterior_E[f] = np.mean(q) std_posterior_E[f] = np.std(q,ddof=1) str = 'mean rmse : %5.4f +/- %5.4f' % (np.mean(q), np.std(q,ddof=1)) pyplot.text(25,(1-0.05*(f+1))*ymax,str,color=fcolor[f],fontsize=10) pyplot.xlabel('Assimilation Cycle',fontweight='bold',fontsize=12) pyplot.ylabel('RMSE',fontweight='bold',fontsize=12) pyplot.title('RMSE - %s Posterior' % estr,fontweight='bold',fontsize=14) pyplot.legend(loc=1) pyplot.hold(False) if save_figures: fig.savefig('%s_%shybDA_RMSE_%s_Posterior.eps' % (model.Name, vstr, estr),dpi=300,orientation=fOrient,format='eps') #----------------------------------------------------------- #----------------------------------------------------------- fig = pyplot.figure() pyplot.clf() pyplot.hold(True) for fname in fnames: f = fnames.index(fname) q = np.squeeze(xarmseC[f,sOI:]) if ( yscale == 'linear' ): pyplot.plot( q,'-',color=fcolor[f],label=flabel[f],linewidth=1) elif ( yscale == 'semilog' ): pyplot.semilogy(q,'-',color=fcolor[f],label=flabel[f],linewidth=1) yl = pyplot.get(pyplot.gca(),'ylim') xl = pyplot.get(pyplot.gca(),'xlim') if ( yFix is None ): ymax = yl[1] else: ymax = yFix pyplot.ylim(0.0, ymax) pyplot.xlim(0.0, len(np.squeeze(xarmseC[f,sOI:]))) for fname in fnames: f = fnames.index(fname) q = np.squeeze(xarmseC[f,sOI:]) mean_posterior_C[f] = np.mean(q) std_posterior_C[f] = np.std(q,ddof=1) str = 'mean rmse : %5.4f +/- %5.4f' % (np.mean(q), np.std(q,ddof=1)) pyplot.text(25,(1-0.05*(f+1))*ymax,str,color=fcolor[f],fontsize=10) pyplot.xlabel('Assimilation Cycle',fontweight='bold',fontsize=12) pyplot.ylabel('RMSE',fontweight='bold',fontsize=12) pyplot.title('RMSE - %sVar Posterior' % (vstr),fontweight='bold',fontsize=14) pyplot.legend(loc=1) pyplot.hold(False) if save_figures: fig.savefig('%s_%shybDA_RMSE_%sVar_Posterior.eps' % (model.Name, vstr, vstr),dpi=300,orientation=fOrient,format='eps') #----------------------------------------------------------- #----------------------------------------------------------- fig = pyplot.figure() pyplot.clf() pyplot.hold(True) index = np.arange(nf) + 0.15 width = 0.35 pyplot.bar(index,mean_prior_E,width,linewidth=0.0,color='0.75',edgecolor='0.75',yerr=std_prior_E, error_kw=dict(ecolor='black',elinewidth=3,capsize=5)) pyplot.bar(index+width,mean_posterior_E,width,linewidth=0.0,color='gray',edgecolor='gray',yerr=std_posterior_E,error_kw=dict(ecolor='black',elinewidth=3,capsize=5)) pyplot.xticks(index+width, blabel) pyplot.xlabel(r'$\%s$' % vary_variable,fontweight='bold',fontsize=12) pyplot.ylabel('RMSE', fontweight='bold',fontsize=12) pyplot.title('RMSE - %s' % estr, fontweight='bold',fontsize=14) pyplot.hold(False) if save_figures: fig.savefig('%s_%shybDA_RMSE_%s.eps' % (model.Name, vstr, estr),dpi=300,orientation=fOrient,format='eps') #----------------------------------------------------------- #----------------------------------------------------------- fig = pyplot.figure() pyplot.clf() pyplot.hold(True) index = np.arange(nf) + 0.15 width = 0.35 pyplot.bar(index,mean_prior_C,width,linewidth=0.0,color='0.75',edgecolor='0.75',yerr=std_prior_C, error_kw=dict(ecolor='black',elinewidth=3,capsize=5)) pyplot.bar(index+width,mean_posterior_C,width,linewidth=0.0,color='gray',edgecolor='gray',yerr=std_posterior_C,error_kw=dict(ecolor='black',elinewidth=3,capsize=5)) pyplot.xticks(index+width, blabel) pyplot.xlabel(r'$\%s$' % vary_variable ,fontweight='bold',fontsize=12) pyplot.ylabel('RMSE', fontweight='bold',fontsize=12) pyplot.title('RMSE - %sVar' % (vstr), fontweight='bold',fontsize=14) pyplot.hold(False) if save_figures: fig.savefig('%s_%shybDA_RMSE_%sVar.eps' % (model.Name, vstr, vstr),dpi=300,orientation=fOrient,format='eps') #----------------------------------------------------------- if not save_figures: pyplot.show() print '... all done ...' sys.exit(0)
def main(): # Import iris data iris = datasets.load_iris() x = iris.data[:, :2] # take the first two features. y = iris.target # label # Splitting data into train, validation and test set # 50% training set, 20% validation set, 30% test set x_train, x_tmp, y_train, y_tmp = train_test_split(x, y, test_size=0.5, random_state=42) x_validate, x_test, y_validate, y_test = train_test_split(x_tmp, y_tmp, test_size=0.4, random_state=42) c = [10**(-3), 10**(-2), 10**(-1), 10**0, 10**1, 10**2, 10**3] best_values = [-1, -1] # respectively best success rate and best C k = 1 plt.figure('SVC with linear kernel') plt.figure(figsize=(30, 20)) for i in c: clf = svm.SVC(kernel='linear', C=i) clf.fit(x_train, y_train) # create a mesh to plot in x_min, x_max = x_train[:, 0].min() - 1, x_train[:, 0].max() + 1 y_min, y_max = x_train[:, 1].min() - 1, x_train[:, 1].max() + 1 h = (x_max / x_min) / 100 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) z = z.reshape(xx.shape) plt.subplot(3, 3, k) title = 'C=' + str(i) plt.title(title, fontsize=30) plt.contourf(xx, yy, z, cmap=plt.get('Paired'), alpha=0.8) plt.scatter(x_train[:, 0], x_train[:, 1], c=y_train, cmap=plt.get('Paired')) plt.xlim(xx.min(), xx.max()) print('With C=' + str(i)) accuracy = clf.score(x_validate, y_validate) print('[-] Accuracy of ' + str(accuracy * 100) + '%') """ full_prediction = clf.predict(x_validate) print('[-] Number of mislabeled points out of a total %d points: %d' % (len(y_validate), (y_validate != full_prediction).sum())) accuracy = (100 * (len(y_validate) - (y_validate != full_prediction).sum())) / len(y_validate) print('[-] With an accuracy of %.3f%s' % (accuracy, '%')) """ if accuracy > best_values[0]: best_values = accuracy, i k += 1 plt.show() plt.close() print('\nBest values of C=' + str(best_values[1])) # With the best C evaluating test set print('Evaluating test set') clf = svm.SVC(kernel='linear', C=best_values[1]) clf.fit(x_train, y_train) x_min, x_max = x_train[:, 0].min() - 1, x_train[:, 0].max() + 1 y_min, y_max = x_train[:, 1].min() - 1, x_train[:, 1].max() + 1 h = (x_max / x_min) / 100 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) z = z.reshape(xx.shape) title = 'C=' + str(best_values[1]) plt.title(title, fontsize=30) plt.contourf(xx, yy, z, cmap=plt.get('Paired'), alpha=0.8) plt.scatter(x_train[:, 0], x_train[:, 1], c=y_train, cmap=plt.get('Paired')) plt.xlim(xx.min(), xx.max()) accuracy = clf.score(x_test, y_test) print('[-] Accuracy of ' + str(accuracy * 100) + '%') """"" full_prediction = clf.predict(x_test) print('[-] Number of mislabeled points out of a total %d points: %d' % (len(y_test), (y_test != full_prediction).sum())) print('[-] With an accuracy of %.3f%s' % ((100 * (len(y_test) - (y_test != full_prediction).sum())) / len(y_test), '%')) """ plt.show() plt.close()
def main(): ipshell = IPShellEmbed() if len(sys.argv) < 2: logfilename = 'log.csv' # use default filename print 'No input filename specified: using %s' % logfilename else: logfilename = sys.argv[1] if not os.path.exists(logfilename): print '%s does not exist!' % logfilename sys.exit() else: print 'Reading file %s' % logfilename if len(sys.argv) < 3: pngfilename = None print 'No output filename specified: will not write output file for plot' else: pngfilename = sys.argv[2] print 'Plot will be saved as %s' % pngfilename data = np.genfromtxt(logfilename, delimiter=',', skip_header=6, usecols = (0, 1, 3, 4, 5, 6, 7, 8, 9)) t = data[:,0] stamp = data[:,1] lm61temp = data[:,2] #therm1 = data[:,3] therm1 = np.ma.masked_where(np.isnan(data[:,3]), data[:,3]) therm2 = data[:,4] temp0 = data[:,5] #temp1 = data[:,6] # use masked array rather than nan for bad values data[np.where(data[:,6] > MAXTEMP),6] = np.nan data[np.where(data[:,7] > MAXTEMP),7] = np.nan data[np.where(data[:,8] > MAXTEMP),8] = np.nan temp1 = np.ma.masked_where(np.isnan(data[:,6]), data[:,6]) temp2 = np.ma.masked_where(np.isnan(data[:,7]), data[:,7]) temp3 = np.ma.masked_where(np.isnan(data[:,8]), data[:,8]) offset = stamp[1] - t[1] / 1000 print offset maxstamp = t[len(t)-1] / 1000 + offset + MAXSEC print maxstamp stamp[stamp<offset] = np.nan stamp[stamp>maxstamp] = np.nan stamp[abs(stamp-t/1000-offset) > MAXSEC] = np.nan nancount = np.sum(np.isnan(stamp)) print '%d bad time stamps to interpolate' % nancount # extrapolate - see # http://stackoverflow.com/questions/1599754/is-there-easy-way-in-python-to-extrapolate-data-points-to-the-future extrapolator = UnivariateSpline(t[np.isfinite(stamp)],stamp[np.isfinite(stamp)], k=1 ) utime = extrapolator(t) # plot 6 columns pyplot.plot(dates.epoch2num(utime),lm61temp,'.',dates.epoch2num(utime),therm1,'.',dates.epoch2num(utime),therm2,'.',dates.epoch2num(utime),temp1,'.',dates.epoch2num(utime),temp2,'.',dates.epoch2num(utime),temp3,'.') ax = pyplot.gca() ax.legend(('LM61','Thermistor 1','Thermistor 2','digital 1','digital 2','digital 3'),loc=0) ax.set_xlabel('Time') ax.set_ylabel(u'Temp (°C)') ax2 = ax.twinx() clim = pyplot.get(ax,'ylim') ax2.set_ylim(c2f(clim[0]),c2f(clim[1])) ax2.set_ylabel(u'Temp (°F)') xlocator = dates.AutoDateLocator() xformatter = dates.AutoDateFormatter(xlocator) pyplot.gca().xaxis.set_major_locator(xlocator) pyplot.gca().xaxis.set_major_formatter(dates.DateFormatter('%H:%M')) # generate a PNG file if pngfilename: pyplot.savefig(pngfilename) # show the plot pyplot.show() # open interactive shell ipshell()
print 'TLM perturbation solution : %7.4f %7.4f %7.4f' %(perttlm[0],perttlm[1],perttlm[2] ) print 'non-linear difference solution : %7.4f %7.4f %7.4f' %(px[-1,0],px[-1,1],px[-1,2]) # predicted and modeled (actual) change in the forecast metric Jc = xf[0].copy() # single variable metric - Control Jp = pxsave[-1,0].copy() # single variable metric - Perturbation #Jc = sum(xf).copy() # sum metric - Control #Jp = sum(pxsave[-1,:]).copy() # sum metric - Perturbation dJp = np.dot(np.transpose(sxi), xp) # predicted change dJm = Jp - Jc # modeled (actual) change print print 'predicted change in metric : %7.4f' % (dJp) print ' modeled change in metric : %7.4f' % (dJm) xl = pyplot.get(pyplot.gca(),'xlim') yl = pyplot.get(pyplot.gca(),'ylim') pyplot.text(0.9*xl[0],-4,'control trajectory', color='red') pyplot.text(0.9*xl[0],-2,'adjoint sensitivity gradient vector',color='green') pyplot.text(0.9*xl[0],0, 'perturbed state vector', color='blue') pyplot.text(0.9*xl[0],0.9*yl[1], 'predicted change in metric : %7.4f'%(dJp)) pyplot.text(0.9*xl[0],0.9*yl[1]-2,'modeled change in metric : %7.4f'%(dJm)) # now test as a function of perturbation amplitude amp_min = -5.0 amp_max = 5.0 amp_step = 0.1 dJp = np.zeros((len(np.arange(amp_min,amp_max+amp_step,amp_step)),1)) dJm = dJp.copy() k = -1
def main(args): logfilename = os.path.join(args.logdir,'serial.log') oldlogfilename = os.path.join(args.logdir,'serial.log.0') current = Weather() h = 139 # elevation in meters if args.days > 7: print "WARNING: %s days requested; log may contain 7-14 days of data" % args.days # copy DATA lines to temporary file, concatenating current and former logfiles t = tempfile.TemporaryFile() # to have a named file for testing: # t = tempfile.NamedTemporaryFile(delete=False) logfile = open(oldlogfilename,'r') for line in logfile: if re.match("(.*)DATA(.*)", line): t.write(line) logfile.close() logfile = open(logfilename,'r') for line in logfile: if re.match("(.*)DATA(.*)", line): t.write(line) logfile.close() # read from tempfile into numpy array for each parameter t.seek(0) temptemp = np.asarray(re.findall('(\d+) DATA: T= (.+) degC',t.read()), dtype=np.float64) #temptemp[np.where(temptemp<MINTEMP)] = np.nan temp = np.ma.masked_less(temptemp, MINTEMP) current.temp = temp[len(temp)-1,1] # most recent temp now = int(temp[len(temp)-1,0]) # in Unix seconds if args.verbose: print "Timezone offset: %s" % timezone # store as Python datetime, in local time, naive format with no real tzinfo set current.time = dates.num2date(dates.epoch2num(now-timezone)) current.max = np.max(temp[temp[:,0] > (now-86400),1]) current.min = np.min(temp[temp[:,0] > (now-86400),1]) if args.verbose: print "Temperature records: %s" % len(temp) t.seek(0) pressure = np.asarray(re.findall('(\d+) DATA: P= (\d+) Pa',t.read()), dtype=np.float64) current.pressure = sealevel(pressure[len(pressure)-1,1]/100,h) if args.verbose: print "Pressure records: %s" % len(pressure) t.seek(0) humid = np.asarray(re.findall('(\d+) DATA: H= (\d+) %',t.read()), dtype=np.int) t.close() current.humid = humid[len(humid)-1,1] if args.verbose: print "Humidity records: %s" % len(humid) # set start time to midnight local time, # of days ago specified start = (np.floor((now-timezone)/86400.0) - args.days)*86400 + timezone if args.verbose: print "Current timestamp: %s" % now if args.verbose: print "Start timestamp: %s" % start temp=temp[temp[:,0]>start,:] pressure=pressure[pressure[:,0]>start,:] humid=humid[humid[:,0]>start,:] m=temp[0,0] if args.verbose: print "First actual timestamp: %s" % m current.report() save_html(current) fig = Figure(figsize=(8,8)) ax = fig.add_subplot(311) ax.plot(dates.epoch2num(temp[:,0]-timezone),temp[:,1]) ax.set_ylabel(u'Temp (°C)') ax2 = ax.twinx() clim = pyplot.get(ax,'ylim') ax2.set_ylim(c2f(clim[0]),c2f(clim[1])) datelabels(ax) ax2.set_ylabel(u'Temp (°F)') ax = fig.add_subplot(312) ax.plot(dates.epoch2num(humid[:,0]-timezone),humid[:,1],'-') ax.set_ylim(0,100) ax.set_ylabel('Humidity (%)') ax2 = ax.twinx() ax2.set_ylim(0,100) datelabels(ax) ax2.set_ylabel('Humidity (%)') ax = fig.add_subplot(313) ax.plot(dates.epoch2num(pressure[:,0]-timezone),sealevel(pressure[:,1],h)/100,'-') ax.set_ylabel('Pressure (mbar)') ax.set_xlabel('local time (%s)' % TZ) ax2 = ax.twinx() clim = pyplot.get(ax,'ylim') ax2.set_ylim(clim[0]*0.02954,clim[1]*0.02954) datelabels(ax) ax.xaxis.set_major_locator( dates.HourLocator(interval=12) ) ax.xaxis.set_major_formatter( dates.DateFormatter('%H:%M') ) ax2.set_ylabel('P (inches Hg)') canvas = FigureCanvasAgg(fig) canvas.print_figure(os.path.join(args.outdir,'plot.png'), dpi=80) canvas.print_figure(os.path.join(args.outdir,'plot.pdf')) if args.upload: # upload static html file & images os.system('sitecopy -u weather') if args.show: # show the plot # doesn't work with FigureCanvasAgg #pyplot.show() # Linux (or X11 in OS X) os.system("display %s" % os.path.join(args.outdir,'plot.png'))
plt.contour(Z, levels, hold="on", colors="k", origin="upper", extent=extent) plt.axis(v) plt.title("Image, origin 'upper'") plt.subplot(2, 2, 3) plt.imshow(Z, origin="lower", extent=extent, cmap=cmap, norm=norm) v = plt.axis() plt.contour(Z, levels, hold="on", colors="k", origin="lower", extent=extent) plt.axis(v) plt.title("Image, origin 'lower'") plt.subplot(2, 2, 4) # We will use the interpolation "nearest" here to show the actual # image pixels. # Note that the contour lines don't extend to the edge of the box. # This is intentional. The Z values are defined at the center of each # image pixel (each color block on the following subplot), so the # domain that is contoured does not extend beyond these pixel centers. im = plt.imshow(Z, interpolation="nearest", extent=extent, cmap=cmap, norm=norm) v = plt.axis() plt.contour(Z, levels, hold="on", colors="k", origin="image", extent=extent) plt.axis(v) ylim = plt.get(plt.gca(), "ylim") plt.setp(plt.gca(), ylim=ylim[::-1]) plt.title("Image, origin from rc, reversed y-axis") plt.colorbar(im) plt.show()
plt.title("Image, origin 'upper'") plt.subplot(2, 2, 3) plt.imshow(Z, origin='lower', extent=extent, cmap=cmap, norm=norm) v = plt.axis() plt.contour(Z, levels, hold='on', colors='k', origin='lower', extent=extent) plt.axis(v) plt.title("Image, origin 'lower'") plt.subplot(2, 2, 4) # We will use the interpolation "nearest" here to show the actual # image pixels. # Note that the contour lines don't extend to the edge of the box. # This is intentional. The Z values are defined at the center of each # image pixel (each color block on the following subplot), so the # domain that is contoured does not extend beyond these pixel centers. im = plt.imshow(Z, interpolation='nearest', extent=extent, cmap=cmap, norm=norm) v = plt.axis() plt.contour(Z, levels, hold='on', colors='k', origin='image', extent=extent) plt.axis(v) ylim = plt.get(plt.gca(), 'ylim') plt.setp(plt.gca(), ylim=ylim[::-1]) plt.title("Image, origin from rc, reversed y-axis") plt.colorbar(im) plt.show()
params['response_window'][0]) i = lickLat <= ylim[1] ax.plot(changeTimes[resp][i] / 60, lickLat[i], 'o', color=trialColors[lbl], label=lbl) i = (lickLat > ylim[1]) | (np.isnan(lickLat)) ax.plot(changeTimes[resp][i] / 60, np.zeros(i.sum()) + 0.99 * ylim[1], '^', color=trialColors[lbl]) for side in ('right', 'top'): ax.spines[side].set_visible(False) ax.tick_params(direction='out', top=False, right=False) xlim = plt.get(ax, 'xlim') for i in (0, 1): ax.plot(xlim, [params['response_window'][i]] * 2, '--', color='0.5', zorder=0) ax.set_xlim(xlim) ax.set_ylim(ylim) ax.set_xlabel('Time in session (min)') ax.set_ylabel('Reaction time (s)') ax.legend() if params['periodic_flash'] is not None: ax = fig.add_subplot(2, 1, 2) bins = np.arange(0.125, np.nanmax(timeToChange) + 0.125, 0.25) ctBinInd = np.digitize(timeToChange, bins)
def plot_taylor_axes(axes, cax, option): """ Plot axes for Taylor diagram. Plots the x & y axes for a Taylor diagram using the information provided in the AXES dictionary returned by the GET_TAYLOR_DIAGRAM_AXES function. INPUTS: axes : data structure containing axes information for target diagram cax : handle for plot axes option : data structure containing option values. (Refer to GET_TAYLOR_DIAGRAM_OPTIONS function for more information.) option['colcor'] : CORs grid and tick labels color (Default: blue) option['colrms'] : RMS grid and tick labels color (Default: green) option['colstd'] : STD grid and tick labels color (Default: black) option['numberpanels'] : number of panels (quadrants) to use for Taylor diagram option['tickrms'] : RMS values to plot gridding circles from observation point option['titlecor'] : title for CORRELATION axis option['titlerms'] : title for RMS axis option['titlestd'] : title fot STD axis OUTPUTS: ax: returns a list of handles of axis labels Author: Peter A. Rochford Acorn Science & Innovation [email protected] Created on Dec 3, 2016 Author: Peter A. Rochford Symplectic, LLC www.thesymplectic.com [email protected] """ ax = [] axlabweight = 'bold' if option['numberpanels'] == 1: # Single panel if option['titlestd'] == 'on': ttt = plt.ylabel('test', fontsize=14) x = -0.15 * axes['rmax'] y = 0.8 * axes['rmax'] handle = plt.text(x, y, 'Standard Deviation', rotation=90, color=option['colstd'], fontweight=axlabweight, fontsize=plt.get(ttt, 'fontsize'), horizontalalignment='center') ax.append(handle) if option['titlecor'] == 'on': pos1 = 45 DA = 15 lab = 'Correlation Coefficient' c = np.fliplr([np.linspace(pos1 - DA, pos1 + DA, len(lab))])[0] dd = 1.1 * axes['rmax'] for ii, ith in enumerate(c): handle = plt.text(dd * np.cos(ith * np.pi / 180), dd * np.sin(ith * np.pi / 180), lab[ii]) handle.set(rotation=ith - 90, color=option['colcor'], horizontalalignment='center', verticalalignment='bottom', fontsize=plt.get(ax[0], 'fontsize'), fontweight=axlabweight) ax.append(handle) if option['titlerms'] == 'on': pos1 = option['tickrmsangle'] + (180 - option['tickrmsangle']) / 2 DA = 15 pos1 = 160 lab = 'RMSD' c = np.fliplr([np.linspace(pos1 - DA, pos1 + DA, len(lab))])[0] # Find optimal placement of label itick = -1 ratio = 1.0 while (ratio > 0.7): itick += 1 ratio = (option['axismax'] - option['tickrms'] [itick]) / option['axismax'] dd = 0.7 * option['tickrms'][itick] + \ 0.3 * option['tickrms'][itick + 1] # Write label in a circular arc for ii, ith in enumerate(c): xtextpos = axes['dx'] + dd * np.cos(ith * np.pi / 180) ytextpos = dd * np.sin(ith * np.pi / 180) handle = plt.text(xtextpos, ytextpos, lab[ii]) handle.set(rotation=ith - 90, color=option['colrms'], horizontalalignment='center', verticalalignment='top', fontsize=plt.get(ax[0], 'fontsize'), fontweight=axlabweight) ax.append(handle) else: # Double panel if option['titlestd'] == 'on': ttt = plt.ylabel('test', fontsize=14) x = 0 y = -0.15 * axes['rmax'] handle = plt.text(x, y, 'Standard Deviation', rotation=0, color=option['colstd'], fontweight=axlabweight, fontsize=plt.get(ttt, 'fontsize'), horizontalalignment='center') ax.append(handle) if option['titlecor'] == 'on': pos1 = 90 DA = 25 lab = 'Correlation Coefficient' c = np.fliplr([np.linspace(pos1 - DA, pos1 + DA, len(lab))])[0] dd = 1.1 * axes['rmax'] for ii, ith in enumerate(c): handle = plt.text(dd * np.cos(ith * np.pi / 180), dd * np.sin(ith * np.pi / 180), lab[ii]) handle.set(rotation=ith - 90, color=option['colcor'], horizontalalignment='center', verticalalignment='bottom', fontsize=plt.get(ax[0], 'fontsize'), fontweight=axlabweight) ax.append(handle) if option['titlerms'] == 'on': pos1 = 160 DA = 10 lab = 'RMSD' c = np.fliplr([np.linspace(pos1 - DA, pos1 + DA, len(lab))])[0] dd = 1.05 * option['tickrms'][0] for ii, ith in enumerate(c): xtextpos = axes['dx'] + dd * np.cos(ith * np.pi / 180) ytextpos = dd * np.sin(ith * np.pi / 180) handle = plt.text(xtextpos, ytextpos, lab[ii]) handle.set(rotation=ith - 90, color=option['colrms'], horizontalalignment='center', verticalalignment='bottom', fontsize=plt.get(ax[0], 'fontsize'), fontweight=axlabweight) ax.append(handle) # VARIOUS ADJUSTMENTS TO THE PLOT: cax.set_aspect('equal') plt.axis('off') plt.gcf().patch.set_facecolor('w') # set axis limits if option['numberpanels'] == 2: axislim = [axes['rmax'] * x for x in [-1.15, 1.15, 0, 1.15]] plt.axis(axislim) plt.plot([-axes['rmax'], axes['rmax']], [0, 0], color=axes['tc'], linewidth=2) plt.plot([0, 0], [0, axes['rmax']], color=axes['tc']) else: axislim = [axes['rmax'] * x for x in [0, 1.15, 0, 1.15]] plt.axis(axislim) plt.plot([0, axes['rmax']], [0, 0], color=axes['tc'], linewidth=2) plt.plot([0, 0], [0, axes['rmax']], color=axes['tc'], linewidth=2) return ax
print 'non-linear difference solution : %7.4f %7.4f %7.4f' % ( px[-1, 0], px[-1, 1], px[-1, 2]) # predicted and modeled (actual) change in the forecast metric Jc = xf[0].copy() # single variable metric - Control Jp = pxsave[-1, 0].copy() # single variable metric - Perturbation #Jc = sum(xf).copy() # sum metric - Control #Jp = sum(pxsave[-1,:]).copy() # sum metric - Perturbation dJp = np.dot(np.transpose(sxi), xp) # predicted change dJm = Jp - Jc # modeled (actual) change print print 'predicted change in metric : %7.4f' % (dJp) print ' modeled change in metric : %7.4f' % (dJm) xl = pyplot.get(pyplot.gca(), 'xlim') yl = pyplot.get(pyplot.gca(), 'ylim') pyplot.text(0.9 * xl[0], -4, 'control trajectory', color='red') pyplot.text(0.9 * xl[0], -2, 'adjoint sensitivity gradient vector', color='green') pyplot.text(0.9 * xl[0], 0, 'perturbed state vector', color='blue') pyplot.text(0.9 * xl[0], 0.9 * yl[1], 'predicted change in metric : %7.4f' % (dJp)) pyplot.text(0.9 * xl[0], 0.9 * yl[1] - 2, 'modeled change in metric : %7.4f' % (dJm)) # now test as a function of perturbation amplitude amp_min = -5.0
def main(): # name of starting ensDA output diagnostic file, starting index and measure parser = ArgumentParser(description='compare the diag files written by varDA.py',formatter_class=ArgumentDefaultsHelpFormatter) parser.add_argument('-f','--filename',help='name of the diag file to read',required=True) parser.add_argument('-m','--measure',help='measure to evaluate performance',required=False,choices=['obs','truth'],default='truth') parser.add_argument('-b','--begin_index',help='starting index to read',type=int,required=False,default=101) parser.add_argument('-e','--end_index',help='ending index to read',type=int,required=False,default=-1) parser.add_argument('-s','--save_figure',help='save figures',action='store_true',required=False) args = parser.parse_args() fname = args.filename measure = args.measure sOI = args.begin_index eOI = args.end_index save_fig = args.save_figure # Inflation factors to compare #alpha = [1.0, 2.0, 3.0, 3.1, 3.2, 3.4] alpha = [0.25, 0.3, 0.35, 0.4, 0.5, 0.6, 0.7, 1.0] alpha = [1.0, 2.0, 2.5] # some more arguments, currently hard-coded save_figures = False # save plots as eps yscale = 'linear' # y-axis of RMSE plots (linear/semilog) yFix = 0.18 # fix the y-axis of RMSE plots ( None = automatic ) fOrient = 'portrait' # figure orientation (landscape/portrait) if ( not measure ): measure = 'truth' if ( sOI == -1 ): sOI = 0 nf = len(alpha) fnames = [] for i in range(nf): fnames.append( fname + '%3.2f.nc4' % ((alpha[i])) ) if ( len(fnames) <= 15): fcolor = ["#000000", "#C0C0C0", "#808080", "#800000", "#FF0000",\ "#800080", "#FF00FF", "#008000", "#00FF00", "#808000",\ "#FFFF00", "#000080", "#0000FF", "#008080", "#00FFFF"] # black, silver, gray, maroon, red # purple, fuchsia, green, lime, olive # yellow, navy, blue, teal, aqua else: fcolor = get_Ndistinct_colors(len(fnames)) # read general dimensions and necessary attributes from the diagnostic file [model, DA, _, gvarDA] = read_diag_info(fnames[0]) Bc = read_clim_cov(model=model,norm=True) if ( gvarDA.update == 1 ): vstr = '3DVar' elif ( gvarDA.update == 2 ): vstr = '4DVar' # allocate room for variables print 'computing RMSE against %s' % measure xbrmse = np.zeros((len(fnames),DA.nassim)) xarmse = np.zeros((len(fnames),DA.nassim)) xyrmse = np.zeros((len(fnames),DA.nassim)) flabel = [] blabel = [] mean_prior = np.zeros(len(fnames)) mean_posterior = np.zeros(len(fnames)) std_prior = np.zeros(len(fnames)) std_posterior = np.zeros(len(fnames)) mean_niters = np.zeros(len(fnames)) std_niters = np.zeros(len(fnames)) innov = np.zeros(len(fnames)) mean_evratio = np.zeros(len(fnames)) std_evratio = np.zeros(len(fnames)) for fname in fnames: print 'reading ... %s' % fname f = fnames.index(fname) try: nc = Dataset(fname, mode='r', format='NETCDF4') flabel.append(r'$\alpha = %3.2f$' % alpha[f]) blabel.append('%3.2f' % alpha[f]) nc.close() except Exception as Instance: print 'Exception occurred during read of ' + fname print type(Instance) print Instance.args print Instance sys.exit(1) # read the varDA for the specific diagnostic file [_, _, _, varDA] = read_diag_info(fname) # read the diagnostic file xt, xb, xa, y, H, R, niters = read_diag(fname, 0, end_time=DA.nassim) if ( varDA.update == 2 ): y = y[:,:model.Ndof] # compute RMSE in prior, posterior and observations if ( measure == 'truth' ): xbrmse[f,] = np.sqrt( np.sum( (xt - xb)**2, axis = 1) / model.Ndof ) xarmse[f,] = np.sqrt( np.sum( (xt - xa)**2, axis = 1) / model.Ndof ) else: xbrmse[f,] = np.sqrt( np.sum( (y - xb)**2, axis = 1) / model.Ndof ) xarmse[f,] = np.sqrt( np.sum( (y - xa)**2, axis = 1) / model.Ndof ) xyrmse[f,] = np.sqrt( np.sum( (xt - y)**2 ) / model.Ndof ) evratio = niters.copy() evratio = np.zeros(len(niters)) for i in range(DA.nassim): innov = np.sum((y[i,:] - np.dot(np.diag(H[i,:]),xb[ i,:]))**2) totvar = np.sum(varDA.inflation.infl_fac*np.diag(Bc) + R[i,:]) evratio[i] = innov / totvar mean_evratio[f] = np.mean(evratio[sOI:]) std_evratio[f] = np.std( evratio[sOI:],ddof=1) # compute mean and std. dev. in the iteration count mean_niters[f] = np.mean(niters[sOI+1:]) std_niters[f] = np.std( niters[sOI+1:], ddof=1) # start plotting #----------------------------------------------------------- fig = pyplot.figure() pyplot.clf() pyplot.hold(True) for fname in fnames: f = fnames.index(fname) q = np.squeeze(xbrmse[f,sOI:]) if ( yscale == 'linear' ): pyplot.plot( q,'-',color=fcolor[f],label=flabel[f],linewidth=1) elif ( yscale == 'semilog' ): pyplot.semilogy(q,'-',color=fcolor[f],label=flabel[f],linewidth=1) yl = pyplot.get(pyplot.gca(),'ylim') xl = pyplot.get(pyplot.gca(),'xlim') if ( yFix is None ): ymax = yl[1] else: ymax = yFix pyplot.ylim(0.0, ymax) pyplot.xlim(0.0, len(q)) for fname in fnames: f = fnames.index(fname) q = np.squeeze(xbrmse[f,sOI:]) mean_prior[f] = np.mean(q) std_prior[f] = np.std(q,ddof=1) str = 'mean rmse : %5.4f +/- %5.4f' % (np.mean(q), np.std(q,ddof=1)) pyplot.text(25,(1-0.05*(f+1))*ymax,str,color=fcolor[f],fontsize=10) pyplot.xlabel('Assimilation Cycle',fontweight='bold',fontsize=12) pyplot.ylabel('RMSE',fontweight='bold',fontsize=12) pyplot.title('RMSE - Prior',fontweight='bold',fontsize=14) pyplot.legend(loc=1) pyplot.hold(False) if save_figures: fig.savefig('%s_varDA_RMSE_Prior.eps' % (model.Name),dpi=300,orientation=fOrient,format='eps') #----------------------------------------------------------- #----------------------------------------------------------- fig = pyplot.figure() pyplot.clf() pyplot.hold(True) for fname in fnames: f = fnames.index(fname) q = np.squeeze(xarmse[f,sOI:]) if ( yscale == 'linear' ): pyplot.plot( q,'-',color=fcolor[f],label=flabel[f],linewidth=1) elif ( yscale == 'semilog' ): pyplot.semilogy(q,'-',color=fcolor[f],label=flabel[f],linewidth=1) yl = pyplot.get(pyplot.gca(),'ylim') xl = pyplot.get(pyplot.gca(),'xlim') if ( yFix is None ): ymax = yl[1] else: ymax = yFix pyplot.ylim(0.0, ymax) pyplot.xlim(0.0, len(q)) for fname in fnames: f = fnames.index(fname) q = np.squeeze(xarmse[f,sOI:]) mean_posterior[f] = np.mean(q) std_posterior[f] = np.std(q,ddof=1) str = 'mean rmse : %5.4f +/- %5.4f' % (np.mean(q), np.std(q,ddof=1)) pyplot.text(25,(1-0.05*(f+1))*ymax,str,color=fcolor[f],fontsize=10) pyplot.xlabel('Assimilation Cycle',fontweight='bold',fontsize=12) pyplot.ylabel('RMSE',fontweight='bold',fontsize=12) pyplot.title('RMSE - Posterior',fontweight='bold',fontsize=14) pyplot.legend(loc=1) pyplot.hold(False) if save_figures: fig.savefig('%s_varDA_RMSE_Posterior.eps' % (model.Name),dpi=300,orientation=fOrient,format='eps') #----------------------------------------------------------- #----------------------------------------------------------- fig = pyplot.figure() pyplot.clf() pyplot.hold(True) index = np.arange(nf) + 0.15 width = 0.35 bottom = 0.0 pyplot.bar(index,mean_prior-bottom,width,bottom=bottom,linewidth=0.0,color='0.75',edgecolor='0.75',yerr=std_prior, error_kw=dict(ecolor='black',elinewidth=3,capsize=5)) pyplot.bar(index+width,mean_posterior-bottom,width,bottom=bottom,linewidth=0.0,color='gray',edgecolor='gray',yerr=std_posterior,error_kw=dict(ecolor='black',elinewidth=3,capsize=5)) pyplot.xticks(index+width, blabel) pyplot.xlabel('Inflation Factor', fontweight='bold',fontsize=12) pyplot.ylabel('RMSE', fontweight='bold',fontsize=12) pyplot.title( 'RMSE', fontweight='bold',fontsize=14) pyplot.hold(False) if save_figures: fig.savefig('%s_varDA_RMSE.eps' % (model.Name),dpi=300,orientation=fOrient,format='eps') #----------------------------------------------------------- #----------------------------------------------------------- fig = pyplot.figure() pyplot.clf() pyplot.hold(True) index = np.arange(nf) + 0.2 width = 0.6 pyplot.bar(index,mean_niters,width,linewidth=0.0,color='gray',edgecolor='gray',yerr=std_niters,error_kw=dict(ecolor='black',elinewidth=3,capsize=5)) pyplot.xticks(index+width/2, blabel) pyplot.xlabel('Inflation Factor', fontweight='bold',fontsize=12) pyplot.ylabel('No. of Iterations', fontweight='bold',fontsize=12) pyplot.title( 'No. of Iterations', fontweight='bold',fontsize=14) pyplot.hold(False) if save_figures: fig.savefig('%s_varDA_niters.eps' % (model.Name),dpi=300,orientation=fOrient,format='eps') #----------------------------------------------------------- #----------------------------------------------------------- fig = pyplot.figure() pyplot.clf() pyplot.hold(True) index = np.arange(nf) + 0.2 width = 0.6 pyplot.bar(index,mean_evratio,width,linewidth=0.0,color='gray',edgecolor='gray',yerr=std_evratio,error_kw=dict(ecolor='black',elinewidth=3,capsize=5)) pyplot.xticks(index+width/2, blabel) pyplot.xlabel('Inflation Factor', fontweight='bold',fontsize=12) pyplot.ylabel('Error - Variance Ratio', fontweight='bold',fontsize=12) pyplot.title( 'Error - Variance Ratio', fontweight='bold',fontsize=14) pyplot.hold(False) if save_figures: fig.savefig('%s_varDA_evratio.eps' % (model.Name),dpi=300,orientation=fOrient,format='eps') #----------------------------------------------------------- if not save_figures: pyplot.show() print '... all done ...' sys.exit(0)
def plot_simulated_data(ivm, filename=None): import matplotlib import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec from matplotlib.collections import LineCollection from mpl_toolkits.basemap import Basemap if filename is None: out_fname = './summary_orbit_simulated_data.png' else: out_fname = filename # make monotonically increasing longitude signal diff = ivm['glong'].diff() idx, = np.where(diff < 0.) for item in idx: ivm[item:, 'glong'] += 360. f = plt.figure(figsize=(8.5, 7)) time1 = ivm.data.index[0].strftime('%Y-%h-%d %H:%M:%S') if ivm.data.index[0].date() == ivm.data.index[-1].date(): time2 = ivm.data.index[-1].strftime('%H:%M:%S') else: time2 = ivm.data.index[-1].strftime('%Y-%h-%d %H:%M:%S') # Overall Plot Title plt.suptitle(''.join(('SPORT IVM ', time1, ' -- ', time2)), fontsize=18) # create grid for plots gs = gridspec.GridSpec(5, 2, width_ratios=[12, 1]) ax = f.add_subplot(gs[0, 0]) plt.plot(np.log10(ivm['ion_dens']), 'k', label='total') plt.plot(np.log10(ivm['ion_dens'] * ivm['frac_dens_o']), 'r', label='O+') plt.plot(np.log10(ivm['ion_dens'] * ivm['frac_dens_h']), 'b', label='H+') # plt.plot(np.log10(ivm['ion_dens']*ivm['frac_dens_he']), 'g', label='He+') plt.legend(loc=(01.01, 0.15)) ax.set_title('Log Ion Density') ax.set_ylabel('Log Density (N/cc)') ax.set_ylim([1., 6.]) ax.axes.get_xaxis().set_visible(False) ax2 = f.add_subplot(gs[1, 0], sharex=ax) plt.plot(ivm['ion_temp']) plt.legend(loc=(1.01, 0.15)) ax2.set_title('Ion Temperature') ax2.set_ylabel('Temp (K)') ax2.set_ylim([500., 1500.]) ax2.axes.get_xaxis().set_visible(False) # determine altitudes greater than 770 km # idx, = np.where(ivm['alt'] > 770.) ax3 = f.add_subplot(gs[2, 0], sharex=ax) plt.plot(ivm['sim_wind_sc_x'], color='b', linestyle='--') plt.plot(ivm['sim_wind_sc_y'], color='r', linestyle='--') plt.plot(ivm['sim_wind_sc_z'], color='g', linestyle='--') ax3.set_title('Neutral Winds in S/C X, Y, and Z') ax3.set_ylabel('Velocity (m/s)') ax3.set_ylim([-200., 200.]) ax3.axes.get_xaxis().set_visible(False) plt.legend(loc=(1.01, 0.15)) ax3.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%H:%M')) # # xlabels = [label[0:6] for label in xlabels] # plt.setp(ax3.xaxis.get_majorticklabels(), rotation=20, ha='right') ax4 = f.add_subplot(gs[3, 0], sharex=ax) plt.plot(ivm['B_sc_x'] * 1e5, color='b', linestyle='--') plt.plot(ivm['B_sc_y'] * 1e5, color='r', linestyle='--') plt.plot(ivm['B_sc_z'] * 1e5, color='g', linestyle='--') ax4.set_title('Magnetic Field in S/C X, Y, and Z') ax4.set_ylabel('Gauss') ax4.set_ylim([-3.5, 3.5]) # ax3.axes.get_xaxis().set_visible(False) plt.legend(loc=(1.01, 0.15)) ax4.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%H:%M')) # # xlabels = [label[0:6] for label in xlabels] plt.setp(ax4.xaxis.get_majorticklabels(), rotation=20, ha='right') # ivm info ax6 = f.add_subplot(gs[4, 0]) # do world plot if time to be plotted is less than 285 minutes, less than 3 orbits time_diff = ivm.data.index[-1] - ivm.data.index[0] if time_diff > pds.Timedelta(minutes=285): # # do long time plot ivm['glat'].plot(label='glat') #legend=True, label='mlat') ivm['mlt'].plot(label='mlt') #legend=True, label='mlt') plt.title('Satellite Position') plt.legend(['mlat', 'mlt'], loc=(1.01, 0.15)) # ivm['glong'].plot(secondary_y = True, label='glong')#legend=True, secondary_y = True, label='glong') else: # make map the same size as the other plots s1pos = plt.get(ax, 'position').bounds s6pos = plt.get(ax6, 'position').bounds ax6.set_position([s1pos[0], s6pos[1] + .008, s1pos[2], s1pos[3]]) #fix longitude range for plot. Pad longitude so that first sample aligned with #ivm measurement sample lon0 = ivm[0, 'glong'] lon1 = ivm[-1, 'glong'] # print (lon0, lon1) # enforce minimal longitude window, keep graphics from being too disturbed if (lon1 - lon0) < 90: lon0 -= 45. lon1 += 45. if lon1 > 720: lon0 -= 360. lon1 -= 360. ivm[:, 'glong'] -= 360. # print (lon0, lon1) m=Basemap(projection='mill', llcrnrlat=-60, urcrnrlat=60., urcrnrlon=lon1.copy(), \ llcrnrlon=lon0.copy(), resolution='c', ax=ax6, fix_aspect=False) # m is an object which manages drawing to the map # it also acts as a transformation function for geo coords to plotting coords # coastlines m.drawcoastlines(ax=ax6) # get first longitude meridian to plot plon = np.ceil(lon0 / 60.) * 60. m.drawmeridians(np.arange(plon, plon + 360. - 22.5, 60), labels=[0, 0, 0, 1], ax=ax6) m.drawparallels(np.arange(-20, 20, 20)) # time midway through ivm to plot terminator locations midDate = ivm.data.index[len(ivm.data.index) // 2] # plot day/night terminators try: cs = m.nightshade(midDate) except ValueError: pass x, y = m(ivm['glong'].values, ivm['glat'].values) points = np.array([x, y]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) plot_norm = plt.Normalize(300, 500) try: plot_cmap = plt.get_cmap('viridis') except: plot_cmap = plt.get_cmap('jet') lc = LineCollection(segments, cmap=plot_cmap, norm=plot_norm, linewidths=5.0) lc.set_array(ivm['alt'].values) sm = plt.cm.ScalarMappable(cmap=plot_cmap, norm=plot_norm) sm._A = [] ax6.add_collection(lc) ax6_bar = f.add_subplot(gs[4, 1]) #plt.colorbar(sm) cbar = plt.colorbar(cax=ax6_bar, ax=ax6, mappable=sm, orientation='vertical', ticks=[300., 400., 500.]) plt.xlabel('Altitude') plt.ylabel('km') f.tight_layout() # buffer for overall title f.subplots_adjust(bottom=0.06, top=0.91, right=.91) plt.subplots_adjust(hspace=.44) plt.savefig(out_fname) return
def displayGeometResults( inputFilePath, prefix ): I0Filename = inputFilePath + prefix + "I0-orig.nrrd" I1Filename = inputFilePath + prefix + "I1-orig.nrrd" I1EstFilename = inputFilePath + prefix + "orig-EstI1.nrrd" T1EstFilename = inputFilePath + prefix + "orig-EstT1.nrrd" T2EstFilename = inputFilePath + prefix + "orig-EstT2.nrrd" map0OutFilename = inputFilePath + prefix + "map0Out.nrrd" map1OutFilename = inputFilePath + prefix + "map1Out.nrrd" map2OutFilename = inputFilePath + prefix + "map2Out.nrrd" map12OutFilename = inputFilePath + prefix + "map12.nrrd" I0 = nd.Nrrd(I0Filename) I1 = nd.Nrrd(I1Filename) I1Est = nd.Nrrd(I1EstFilename) T1Est = nd.Nrrd(T1EstFilename) T2Est = nd.Nrrd(T2EstFilename) map0Out = nd.Nrrd(map0OutFilename) map1Out = nd.Nrrd(map1OutFilename) map2Out = nd.Nrrd(map2OutFilename) map12Out = nd.Nrrd(map12OutFilename) print "I0 size ", I0.data.shape ysize, xsize = I0.data.shape [gridX,gridY]=np.meshgrid(np.arange(1,xsize+1),np.arange(1,ysize+1)) plt.figure() plt.title(prefix + " Geomet Results") plt.subplot(235) P.imshow(T1Est.data,cmap=cm.gray) v = plt.axis() plt.axis(v) ylim = plt.get(plt.gca(), 'ylim') CS = plt.contour(gridX,gridY,map1Out.data[0,:,:], 20, hold='on', colors='red') CS = plt.contour(gridX,gridY,map1Out.data[1,:,:], 20, hold='on', colors='red') plt.title('Est-T1') plt.subplot(236) P.imshow(T2Est.data,cmap=cm.gray) v = plt.axis() plt.axis(v) ylim = plt.get(plt.gca(), 'ylim') CS = plt.contour(gridX,gridY,map12Out.data[0,:,:], 20, hold='on', colors='red') CS = plt.contour(gridX,gridY,map12Out.data[1,:,:], 20, hold='on', colors='red') plt.title('Est-T2') #plt.figure() plt.subplot(234) P.imshow(I1Est.data,cmap=cm.gray) v = plt.axis() plt.axis(v) ylim = plt.get(plt.gca(), 'ylim') CS = plt.contour(gridX,gridY,map1Out.data[0,:,:], 20, hold='on', colors='red') CS = plt.contour(gridX,gridY,map1Out.data[1,:,:], 20, hold='on', colors='red') plt.title('Est-I1') plt.subplot(231) P.imshow(I0.data,cmap=cm.gray) v = plt.axis() plt.axis(v) ylim = plt.get(plt.gca(), 'ylim') plt.title('Orig-I0') plt.subplot(232) P.imshow(I1.data,cmap=cm.gray) v = plt.axis() plt.axis(v) ylim = plt.get(plt.gca(), 'ylim') plt.title('Orig-I1') outputFileName1 = inputFilePath + prefix + "ALL.png" plt.savefig(outputFileName1)
def plot_taylor_axes(axes, cax, option): ''' Plot axes for Taylor diagram. Plots the x & y axes for a Taylor diagram using the information provided in the AXES dictionary returned by the GET_TAYLOR_DIAGRAM_AXES function. INPUTS: axes : data structure containing axes information for target diagram cax : handle for plot axes option : data structure containing option values. (Refer to GET_TAYLOR_DIAGRAM_OPTIONS function for more information.) option['colcor'] : CORs grid and tick labels color (Default: blue) option['colrms'] : RMS grid and tick labels color (Default: green) option['colstd'] : STD grid and tick labels color (Default: black) option['numberpanels'] : number of panels (quadrants) to use for Taylor diagram option['tickrms'] : RMS values to plot gridding circles from observation point option['titlecor'] : title for CORRELATION axis option['titlerms'] : title for RMS axis option['titlestd'] : title fot STD axis OUTPUTS: ax: returns a list of handles of axis labels Author: Peter A. Rochford Acorn Science & Innovation [email protected] Created on Dec 3, 2016 Author: Peter A. Rochford Symplectic, LLC www.thesymplectic.com [email protected] ''' ax = [] axlabweight = 'bold' if option['numberpanels'] == 1: # Single panel if option['titlestd'] == 'on': ttt = plt.ylabel('test', fontsize=16) x = -0.15 * axes['rmax'] y = 0.7 * axes['rmax'] handle = plt.text(x, y, 'Standard Deviation', rotation=90, color=option['colstd'], fontweight=axlabweight, fontsize=plt.get(ttt, 'fontsize'), horizontalalignment='center') ax.append(handle) if option['titlecor'] == 'on': pos1 = 45 DA = 15 lab = 'Correlation Coefficient' c = np.fliplr([np.linspace(pos1 - DA, pos1 + DA, len(lab))])[0] dd = 1.1 * axes['rmax'] for ii, ith in enumerate(c): handle = plt.text(dd * np.cos(ith * np.pi / 180), dd * np.sin(ith * np.pi / 180), lab[ii]) handle.set(rotation=ith - 90, color=option['colcor'], horizontalalignment='center', verticalalignment='bottom', fontsize=plt.get(ax[0], 'fontsize'), fontweight=axlabweight) ax.append(handle) if option['titlerms'] == 'on': pos1 = option['tickrmsangle'] + (180 - option['tickrmsangle']) / 2 DA = 15 pos1 = 160 lab = 'RMSD' c = np.fliplr([np.linspace(pos1 - DA, pos1 + DA, len(lab))])[0] if option['tickrms'][0] > 0: dd = 0.7 * option['tickrms'][0] + 0.3 * option['tickrms'][1] else: dd = 0.7 * option['tickrms'][1] + 0.3 * option['tickrms'][2] for ii, ith in enumerate(c): xtextpos = axes['dx'] + dd * np.cos(ith * np.pi / 180) ytextpos = dd * np.sin(ith * np.pi / 180) handle = plt.text(xtextpos, ytextpos, lab[ii]) handle.set(rotation=ith - 90, color=option['colrms'], horizontalalignment='center', verticalalignment='top', fontsize=plt.get(ax[0], 'fontsize'), fontweight=axlabweight) ax.append(handle) else: # Double panel if option['titlestd'] == 'on': ttt = plt.ylabel('test', fontsize=14) x = 0 y = -0.15 * axes['rmax'] handle = plt.text(x, y, 'Standard Deviation', rotation=0, color=option['colstd'], fontweight=axlabweight, fontsize=plt.get(ttt, 'fontsize'), horizontalalignment='center') ax.append(handle) if option['titlecor'] == 'on': pos1 = 90 DA = 25 lab = 'Correlation Coefficient' c = np.fliplr([np.linspace(pos1 - DA, pos1 + DA, len(lab))])[0] dd = 1.1 * axes['rmax'] for ii, ith in enumerate(c): handle = plt.text(dd * np.cos(ith * np.pi / 180), dd * np.sin(ith * np.pi / 180), lab[ii]) handle.set(rotation=ith - 90, color=option['colcor'], horizontalalignment='center', verticalalignment='bottom', fontsize=plt.get(ax[0], 'fontsize'), fontweight=axlabweight) ax.append(handle) if option['titlerms'] == 'on': pos1 = 160 DA = 10 lab = 'RMSD' c = np.fliplr([np.linspace(pos1 - DA, pos1 + DA, len(lab))])[0] dd = 1.05 * option['tickrms'][0] for ii, ith in enumerate(c): xtextpos = axes['dx'] + dd * np.cos(ith * np.pi / 180) ytextpos = dd * np.sin(ith * np.pi / 180) handle = plt.text(xtextpos, ytextpos, lab[ii]) handle.set(rotation=ith - 90, color=option['colrms'], horizontalalignment='center', verticalalignment='bottom', fontsize=plt.get(ax[0], 'fontsize'), fontweight=axlabweight) ax.append(handle) # VARIOUS ADJUSTMENTS TO THE PLOT: cax.set_aspect('equal') plt.axis('off') plt.gcf().patch.set_facecolor('w') # set axis limits if option['numberpanels'] == 2: axislim = [axes['rmax'] * x for x in [-1.15, 1.15, 0, 1.15]] plt.axis(axislim) plt.plot([-axes['rmax'], axes['rmax']], [0, 0], color=axes['tc'], linewidth=2) plt.plot([0, 0], [0, axes['rmax']], color=axes['tc']) else: axislim = [axes['rmax'] * x for x in [0, 1.15, 0, 1.15]] plt.axis(axislim) plt.plot([0, axes['rmax']], [0, 0], color=axes['tc'], linewidth=2) plt.plot([0, 0], [0, axes['rmax']], color=axes['tc'], linewidth=2) return ax
def plot_ObImpact(dJa, dJe, sOI=None, eOI=None, title=None, xlabel=None, ylabel=None): color_adj = 'c' color_ens = 'm' width = 0.45 if (title is None): title = '' if (xlabel is None): xlabel = '' if (ylabel is None): ylabel = '' if ((sOI is None)): sOI = 0 if ((eOI is None) or (eOI == -1)): eOI = len(dJa) index = np.arange(eOI - sOI) if (len(index) > 1000): inc = 1000 elif (len(index) > 100): inc = 100 elif (len(index) > 10): inc = 10 else: inc = 1 fig = pyplot.figure() pyplot.hold(True) r0 = pyplot.plot(np.zeros(eOI - sOI + 1), 'k-') r1 = pyplot.bar(index, dJa, width, color=color_adj, edgecolor=color_adj, linewidth=0.0) r2 = pyplot.bar(index + width, dJe, width, color=color_ens, edgecolor=color_ens, linewidth=0.0) stra = r'mean $\delta J_a$ : %5.4f +/- %5.4f' % (np.mean(dJa), np.std(dJa, ddof=1)) stre = r'mean $\delta J_e$ : %5.4f +/- %5.4f' % (np.mean(dJe), np.std(dJe, ddof=1)) locs, labels = pyplot.xticks() newlocs = np.arange(sOI, sOI + len(index) + 1, inc) - sOI newlabels = np.arange(sOI, sOI + len(index) + 1, inc) pyplot.xticks(newlocs, newlabels) yl = pyplot.get(pyplot.gca(), 'ylim') dyl = yl[1] - yl[0] yoff = yl[0] + 0.1 * dyl pyplot.text(5, yoff, stra, fontsize=10, color=color_adj) yoff = yl[0] + 0.2 * dyl pyplot.text(5, yoff, stre, fontsize=10, color=color_ens) pyplot.xlabel(xlabel, fontsize=12) pyplot.ylabel(ylabel, fontsize=12) pyplot.title(title, fontsize=14) fig.canvas.set_window_title(title) pyplot.hold(False) return fig
def plot_taylor_axes(axes, cax, option): """ Plot axes for Taylor diagram. Plots the x & y axes for a Taylor diagram using the information provided in the AXES dictionary returned by the GET_TAYLOR_DIAGRAM_AXES function. INPUTS: axes : data structure containing axes information for target diagram cax : handle for plot axes option : data structure containing option values. (Refer to GET_TAYLOR_DIAGRAM_OPTIONS function for more information.) option['colcor'] : CORs grid and tick labels color (Default: blue) option['colrms'] : RMS grid and tick labels color (Default: green) option['colstd'] : STD grid and tick labels color (Default: black) option['numberpanels'] : number of panels (quadrants) to use for Taylor diagram option['tickrms'] : RMS values to plot gridding circles from observation point option['titlecor'] : title for CORRELATION axis option['titlerms'] : title for RMS axis option['titlestd'] : title fot STD axis OUTPUTS: ax: returns a list of handles of axis labels Author: Peter A. Rochford Acorn Science & Innovation [email protected] Created on Dec 3, 2016 Author: Peter A. Rochford Symplectic, LLC www.thesymplectic.com [email protected] """ ax = [] axlabweight = "bold" if option["numberpanels"] == 1: # Single panel if option["titlestd"] == "on": ttt = plt.ylabel("test", fontsize=14) x = -0.15 * axes["rmax"] y = 0.8 * axes["rmax"] handle = plt.text( x, y, "Standard Deviation", rotation=90, color=option["colstd"], fontweight=axlabweight, fontsize=plt.get(ttt, "fontsize"), horizontalalignment="center", ) ax.append(handle) if option["titlecor"] == "on": pos1 = 45 DA = 15 lab = "Correlation Coefficient" c = np.fliplr([np.linspace(pos1 - DA, pos1 + DA, len(lab))])[0] dd = 1.1 * axes["rmax"] for ii, ith in enumerate(c): handle = plt.text( dd * np.cos(ith * np.pi / 180), dd * np.sin(ith * np.pi / 180), lab[ii], ) handle.set( rotation=ith - 90, color=option["colcor"], horizontalalignment="center", verticalalignment="bottom", fontsize=plt.get(ax[0], "fontsize"), fontweight=axlabweight, ) ax.append(handle) if option["titlerms"] == "on": pos1 = option["tickrmsangle"] + (180 - option["tickrmsangle"]) / 2 DA = 15 pos1 = 160 lab = "RMSD" c = np.fliplr([np.linspace(pos1 - DA, pos1 + DA, len(lab))])[0] # Find optimal placement of label itick = -1 ratio = 1.0 while ratio > 0.7: itick += 1 ratio = (option["axismax"] - option["tickrms"][itick]) / option["axismax"] dd = 0.7 * option["tickrms"][itick] + 0.3 * option["tickrms"][itick + 1] # Write label in a circular arc for ii, ith in enumerate(c): xtextpos = axes["dx"] + dd * np.cos(ith * np.pi / 180) ytextpos = dd * np.sin(ith * np.pi / 180) handle = plt.text(xtextpos, ytextpos, lab[ii]) handle.set( rotation=ith - 90, color=option["colrms"], horizontalalignment="center", verticalalignment="top", fontsize=plt.get(ax[0], "fontsize"), fontweight=axlabweight, ) ax.append(handle) else: # Double panel if option["titlestd"] == "on": ttt = plt.ylabel("test", fontsize=14) x = 0 y = -0.15 * axes["rmax"] handle = plt.text( x, y, "Standard Deviation", rotation=0, color=option["colstd"], fontweight=axlabweight, fontsize=plt.get(ttt, "fontsize"), horizontalalignment="center", ) ax.append(handle) if option["titlecor"] == "on": pos1 = 90 DA = 25 lab = "Correlation Coefficient" c = np.fliplr([np.linspace(pos1 - DA, pos1 + DA, len(lab))])[0] dd = 1.1 * axes["rmax"] for ii, ith in enumerate(c): handle = plt.text( dd * np.cos(ith * np.pi / 180), dd * np.sin(ith * np.pi / 180), lab[ii], ) handle.set( rotation=ith - 90, color=option["colcor"], horizontalalignment="center", verticalalignment="bottom", fontsize=plt.get(ax[0], "fontsize"), fontweight=axlabweight, ) ax.append(handle) if option["titlerms"] == "on": pos1 = 160 DA = 10 lab = "RMSD" c = np.fliplr([np.linspace(pos1 - DA, pos1 + DA, len(lab))])[0] dd = 1.05 * option["tickrms"][0] for ii, ith in enumerate(c): xtextpos = axes["dx"] + dd * np.cos(ith * np.pi / 180) ytextpos = dd * np.sin(ith * np.pi / 180) handle = plt.text(xtextpos, ytextpos, lab[ii]) handle.set( rotation=ith - 90, color=option["colrms"], horizontalalignment="center", verticalalignment="bottom", fontsize=plt.get(ax[0], "fontsize"), fontweight=axlabweight, ) ax.append(handle) # VARIOUS ADJUSTMENTS TO THE PLOT: cax.set_aspect("equal") plt.axis("off") plt.gcf().patch.set_facecolor("w") # set axis limits if option["numberpanels"] == 2: axislim = [axes["rmax"] * x for x in [-1.15, 1.15, 0, 1.15]] plt.axis(axislim) plt.plot([-axes["rmax"], axes["rmax"]], [0, 0], color=axes["tc"], linewidth=2) plt.plot([0, 0], [0, axes["rmax"]], color=axes["tc"]) else: axislim = [axes["rmax"] * x for x in [0, 1.15, 0, 1.15]] plt.axis(axislim) plt.plot([0, axes["rmax"]], [0, 0], color=axes["tc"], linewidth=2) plt.plot([0, 0], [0, axes["rmax"]], color=axes["tc"], linewidth=2) return ax