def DGSA_plot(SA_dataframe, num_plot, title=None): ''' Distance based Generalized Sensitivity Analysis method Args: SA_dataframe: (pd.DataFrame) StandardizedSensitivity data frame from DGSA num_plot: (int) Numbers of bar plot, from the most sensitivity parameter Output: Pareto Plot for SA ''' SA_stats = SA_dataframe.values max_SA_stats = np.max(SA_stats) min_SA_stats = np.min(SA_stats) SA_color = np.zeros(SA_stats.shape) if max_SA_stats == 1: SA_color[SA_stats >= 1] = (SA_stats[SA_stats >= 1] - 0.999) / (1.01 - 1) else: SA_color[SA_stats >= 1] = (SA_stats[SA_stats >= 1] - 1) / (max_SA_stats - 1) SA_color[SA_stats < 1] = (SA_stats[SA_stats < 1] - 1) / (1 - min_SA_stats) names = SA_dataframe.index fig, ax = plt.subplots(figsize=(6, 9)) order = np.argsort(-SA_stats[:, 0])[:num_plot] ax.barh(np.arange(num_plot), SA_stats[order, 0], edgecolor='k', color=cm.RdBu_r(SA_color[order, 0] * 0.5 + 0.5), linewidth=0.5) ax.invert_yaxis() plt.yticks(np.arange(num_plot), names[order], fontsize=12) plt.xticks(fontsize=12) plt.axvline(x=1, linestyle='--', c='k') if title: plt.title(title, fontsize=18) plt.show()
allru = ['pi', 'b025', 'b050', 'b100'] allnams = [ 'piControl', 'stabilization-ssp585-2025', 'stabilization-ssp585-2050', 'stabilization-ssp585-2100' ] colors = ['black', 'forestgreen', 'orange', 'violet'] allnams2 = allnams + ['ssp585', 'historical'] allru2 = allru + ['ssp585', 'hist'] colors2 = colors + ['indianred', 'steelblue'] #################################################################################################### ### New colormap for temperature col = cm.RdBu_r(np.linspace(0., 1, 256)) col2 = cm.PuRd_r(np.linspace(0.35, 0.75, 80)) col3 = cm.bone_r(np.linspace(0.35, 0.75, 80)) colors = np.concatenate([col3, col, col2]) from matplotlib import colors as mcolors heatmap = mcolors.LinearSegmentedColormap.from_list('heat_strong', colors) ### dpi = 150 save = False fps = 7 ######################## LEGGO 245 filna = '/nas/archive_CMIP6/CMIP6/model-output/EC-Earth-Consortium/EC-Earth3/{}/atmos/Amon/r4i1p1f1/{}/{}*nc' # yeamean_245 = dict()
def main(): # read in table with pre-computed metrics over each season and state table = pd.read_csv(config.STATES_DIR + '/_overview/final_table_merged.csv') table2 = pd.read_csv(config.STATES_DIR + '/_overview/final_table_ens.csv') states = list(set(table.State.values)) # limit to specific metrics table_rmse = table[table.Metric == 'RMSE'] table_corr = table[table.Metric == 'PEARSON'] table_mape = table[table.Metric == 'MAPE'] table2_rmse = table2[table2.Metric == 'RMSE'] table2_corr = table2[table2.Metric == 'PEARSON'] table2_mape = table2[table2.Metric == 'MAPE'] #################################################### ############ Figure 3 ############ #################################################### # get list of differences between RMSEs rmse_diffs = [float(table_rmse[(table_rmse.Model == 'ARGO') & (table_rmse.State == st)]['ARGONet Period'].values[0]) \ / float(table_rmse[(table_rmse.Model == 'Net') & (table_rmse.State == st)]['ARGONet Period'].values[0]) for st in states] # reorder states with respect to the ordered diffs states_rmse_order = [states[i] for i in argsort(rmse_diffs)[::-1]] # states_corr_order = [states[i] for i in argsort(corr_diffs)] # states_mape_order = [states[i] for i in argsort(mape_diffs)[::-1]] ### GENERATE ARRAYS FOR BAR PLOTS ### # ARRAYS FOR RMSE (PANEL 1) argo_rmse = [] for st in states_rmse_order: tmp = table[(table.Metric == 'RMSE') & (table.Model == 'ARGO') & (table.State == st)]['ARGONet Period'].values[0] argo_rmse.append(tmp) net_rmse = [] for st in states_rmse_order: tmp = table[(table.Metric == 'RMSE') & (table.Model == 'Net') & (table.State == st)]['ARGONet Period'].values[0] net_rmse.append(tmp) ar_rmse = [] for st in states_rmse_order: tmp = table[(table.Metric == 'RMSE') & (table.Model == 'AR52') & (table.State == st)]['ARGONet Period'].values[0] ar_rmse.append(tmp) # END BLOCK # get list of differences between RMSEs rmse_diffs2 = [table2_rmse[(table2_rmse.Model == 'ARGO') & (table2_rmse.State == st)]['ARGONet Period'].values[0] \ / table2_rmse[(table2_rmse.Model == 'ARGONet') & (table2_rmse.State == st)]['ARGONet Period'].values[0] for st in states] # reorder states with respect to the ordered diffs states_rmse_order2 = [states[i] for i in argsort(rmse_diffs2)[::-1]] ### GENERATE ARRAYS FOR BAR PLOTS ### # ARRAYS FOR RMSE (PANEL 1) argo_rmse2 = [] for st in states_rmse_order2: tmp = table2[(table2.Metric == 'RMSE') & (table2.Model == 'ARGO') & (table2.State == st)]['ARGONet Period'].values[0] argo_rmse2.append(tmp) argonet_rmse2 = [] for st in states_rmse_order2: tmp = table2[(table2.Metric == 'RMSE') & (table2.Model == 'ARGONet') & (table2.State == st)]['ARGONet Period'].values[0] argonet_rmse2.append(tmp) ar_rmse2 = [] for st in states_rmse_order2: tmp = table2[(table2.Metric == 'RMSE') & (table2.Model == 'AR52') & (table2.State == st)]['ARGONet Period'].values[0] ar_rmse2.append(tmp) # END BLOCK from math import sqrt def filt(x, y): mat = np.array(zip(x, y)) mat = mat[~np.any(mat == 0, axis=1) & ~np.any(mat == -.001, axis=1)] return mat[:, 0], mat[:, 1] # scoring metric functions def RMSE(predictions, targets): predictions, targets = filt(predictions, targets) return sqrt(((predictions - targets)**2).mean()) # error_bars = np.zeros((2, len(states_rmse_order))) # for state_num, state in enumerate(states_rmse_order): # preds = pd.read_csv(config.STATES_DIR + '/{0}/top_ens_preds.csv'.format(state)) # # target = preds['ILI'].values # argo = preds['ARGO(gt,ath)'].values # argonet = preds['ARGONet'].values # # # methods = np.column_stack((target, argo, argonet)) # # # # geometric probability = 1 / mean length # p = 1./52 # # samples = 1000 # n_models = methods.shape[1] - 1 # # # calculate observed relative efficiency # eff_obs = np.zeros(n_models) # for i in range(n_models): # eff_obs[i] = RMSE(methods[:, 0], methods[:, i + 1]) # eff_obs = eff_obs / eff_obs[-1] # # # perform bootstrap # scores = np.zeros((samples, n_models)) # for iteration in range(samples): # # construct bootstrap resample # new, n1, n2 = sbb.resample(methods, p) # # # calculate sample relative efficiencies # for model in range(n_models): # scores[iteration, model] = RMSE(new[:, 0], new[:, model + 1]) # scores[iteration] = scores[iteration] / scores[iteration, -1] # # # define the variable containing the deviations from the observed rel eff # scores_residual = scores - eff_obs # # # construct output array # report_array = np.zeros((3,n_models)) # for comp in range(n_models): # tmp = scores_residual[:, comp] # # # 90% confidence interval by sorting the deviations and choosing the endpoints of the 95% region # tmp = np.sort(tmp) # report_array[0, comp] = eff_obs[comp] # report_array[1, comp] = eff_obs[comp] + tmp[int(round(samples * 0.05))] # report_array[2, comp] = eff_obs[comp] + tmp[int(round(samples * 0.95))] # # print report_array.T # # error_bars[0, state_num] = report_array[0, 0] - report_array[1, 0] # error_bars[1, state_num] = report_array[2, 0] - report_array[0, 0] ind = np.arange(len(states)) from matplotlib import cm c_range = np.linspace(.2, .8, len(ind)) # c_range[np.abs(c_range - 0.5) < 0.05] -= 0.05 * np.sign(c_range[np.abs(c_range - 0.5) < 0.05]) cmap = cm.RdBu_r(c_range) improvement = np.array( [float(argo_rmse[i]) / float(net_rmse[i]) for i in ind]) improvement2 = np.array([argo_rmse2[i] / argonet_rmse2[i] for i in ind]) colors = cm.RdBu(4 * (improvement - 1) / max(improvement) + 0.5) colors2 = cm.RdBu(4 * (improvement2 - 1) / max(improvement2) + 0.5) # print colors f, (ax1, ax2) = plt.subplots(2, 1) p = ax1.scatter(ind, improvement - 1, s=50, color=colors, edgecolor='k', linewidth=0.5) ax1.set_ylabel('Improvement of Net', labelpad=14, fontsize=12) ax1.set_ylim([-0.38, 0.38]) ax1.set_xlim([-1.5, 37]) ax1.set_xticks(ind) ax1.set_xticklabels(states_rmse_order) p = ax2.scatter(ind, improvement2 - 1, s=50, color=colors2, edgecolor='k', linewidth=0.5, alpha=1) ax2.set_ylabel('Improvement of ARGONet', labelpad=14, fontsize=12) ax2.set_ylim([-0.38, 0.38]) ax2.set_xlim([-1.5, 37]) ax2.set_xticks(ind) ax2.set_xticklabels(states_rmse_order2) ax1.spines['top'].set_visible(False) ax1.spines['right'].set_visible(False) ax1.spines['left'].set_bounds(-.3, .3) ax1.spines['bottom'].set_bounds(-.5, 36.5) ax1.spines['bottom'].set_linewidth(1) ax1.spines['left'].set_linewidth(1.5) ax1.tick_params(axis='y', length=4, width=1, rotation=0, labelsize=12) ax1.tick_params(axis='x', length=0, width=1, rotation=90, labelsize=9) ax1.set_yticks([-.3, 0, .3]) ax1.set_yticklabels(['0.7', '1', '1.3']) # ax1.locator_params(axis='y', tight=True, nbins=4) ax1.axhline(y=0, color='k', linestyle='--', alpha=0.25) ax2.spines['top'].set_visible(False) ax2.spines['right'].set_visible(False) ax2.spines['left'].set_bounds(-.3, .3) ax2.spines['bottom'].set_bounds(-.5, 36.5) ax2.tick_params(axis='y', length=4, width=1, rotation=0, labelsize=12) ax2.tick_params(axis='x', length=0, width=1, rotation=90, labelsize=9) ax2.set_yticks([-.3, 0, .3]) ax2.set_yticklabels(['0.7', '1', '1.3']) # ax2.locator_params(axis='y', tight=True, nbins=4) ax2.spines['bottom'].set_linewidth(1) ax2.spines['left'].set_linewidth(1.5) ax2.axhline(y=0, color='k', linestyle='--', alpha=0.25) # ax1.set_title("Net") # ax2.set_title("ARGONet") fig = plt.gcf() fig.set_size_inches(8, 6) fig.savefig(config.STATES_DIR + '/_overview/improvements.png', format='png', dpi=300) plt.show()
def plotLOSQuantiles(n_rel, figureName): # load each cleaned AMPL outfile and store in a list all_ampl = list() for rel in range(1, n_rel): if rel < 10: num_str = '000' + str(rel) elif rel < 100: num_str = '00' + str(rel) else: num_str = '0' + str(rel) realization_data = pd.read_csv('Cleaned_zip/cleaned/ampl_' + num_str + '.csv') #, usecols=AMPL_cols) realization_data.fillna(0, inplace=True) all_ampl.append(realization_data) # Calculate LOS metrics for each year (missing leap years, fix later?) annual_LOS_rel = np.zeros([n_rel, 20]) annual_LOS_vul = np.zeros([n_rel, 20]) # loop through each realization for rel in range(0, n_rel - 1): current_rel = all_ampl[rel] for day in np.linspace(0, 6935, 20): day = int(day) year = int(day / 365) current_year = current_rel.iloc[day:day + 365] annual_LOS_rel[rel, year], annual_LOS_vul[ rel, year] = calculateLevelOfService(current_year) # Calculate percentiles across realizations LOS_rel = np.zeros([20, 100]) LOS_vul = np.zeros([20, 100]) # Extract 90th percentile from each LOS for year in range(0, 20): for p in range(0, 100): LOS_rel[year, p] = np.percentile(annual_LOS_rel[:, year], (p + 1)) LOS_vul[year, p] = np.percentile(annual_LOS_vul[:, year], (p + 1)) # plot time varying distribution cmap = matplotlib.cm.get_cmap("RdBu_r") fig = plt.figure(figsize=(8, 6)) ax = fig.add_subplot(1, 1, 1) for i in np.linspace(5, 95, 19): i = int(i) ax.fill_between(range(2020, 2040), LOS_rel[:, i - 5], LOS_rel[:, i], color=cm.RdBu_r((i - 1) / 100.0), alpha=0.75, edgecolor='none') ax.set_xticks(range(2020, 2040)) ax.set_xticklabels(range(2020, 2040), rotation='vertical') ax.set_xlim([2020, 2039]) plt.xlabel('years') plt.ylabel('Annual failure rate') plt.savefig(figureName, bbox_inches='tight') return
def get_color(value): return cm.RdBu_r(float((value - central) / range))
# Initiate value of y_input y_input = 0 # Create statistics df['mean'] = df.mean(axis=1) df['std'] = df.std(axis=1, ddof=1) #standard deviation for sample df['sem'] = (df['std'] * 1.96) / np.sqrt(3650) #std error mean sample times constant 1.96 for normal distribution and 95% CI. df['prob'] = st.norm.cdf((y_input - df['mean'])/(df['sem'])) # Plot figure plt.close() plt.figure(dpi=150) plt.axes(frameon=False) bplot = plt.bar(df.index, df['mean'], yerr=df['sem'], color=cm.RdBu_r(df['prob']), capsize=5, edgecolor='black') # Plot cleaning plt.xticks(df.index, df.index.values.astype(str)) plt.xlabel('Year', fontsize=12) plt.ylabel('Sample Mean', fontsize=12) plt.title('Normal distributions with 95% confidence intervals on mean.\n') # Define function to run when event is triggered def onclick(event): y_input = event.ydata.astype(np.int64) df['prob'] = st.norm.cdf((y_input - df['mean'])/(df['sem'])) bplot = plt.bar(df.index, df['mean'], yerr=df['sem'], color=cm.RdBu_r(df['prob']), capsize=5, edgecolor='black') plt.gca().set_title('Normal distributions with 95% confidence intervals on mean.\nSelected y-value: {}'.format(y_input)) plt.savefig('Week3.png')
def onclick(event): y_input = event.ydata.astype(np.int64) df['prob'] = st.norm.cdf((y_input - df['mean'])/(df['sem'])) bplot = plt.bar(df.index, df['mean'], yerr=df['sem'], color=cm.RdBu_r(df['prob']), capsize=5, edgecolor='black') plt.gca().set_title('Normal distributions with 95% confidence intervals on mean.\nSelected y-value: {}'.format(y_input)) plt.savefig('Week3.png')
def blot(gdata, args=(), figure=None, squeeze=False, streamline=False, quiver=False, contour=False, diverging=False, group=None, xscale=1.0, yscale=1.0, style=None, legend=True, labelPrefix='', xlabel=None, ylabel=None, title=None, logx=False, logy=False, logz=False, color=None, fixaspect=False, vmin=None, vmax=None, edgecolors=None, **kwargs): """Plots Gkeyll data Unifies the plotting across a wide range of Gkyl applications. Can be used for both 1D an 2D data. Uses a proper colormap by default. Args: """ #----------------------------------------------------------------- #-- Data Loading ------------------------------------------------- numDims = gdata.getNumDims(squeeze=True) if numDims > 2: raise Exception('Only 1D and 2D plots are currently supported') #end # Get the handles on the grid and values grid = gdata.getGrid() values = gdata.getValues() lower, upper = gdata.getBounds() cells = gdata.getNumCells() # Squeeze the data (get rid of "collapsed" dimensions) axLabel = ['z_0', 'z_1', 'z_2', 'z_3', 'z_4', 'z_5'] if len(grid) > numDims: idx = [] for d in range(len(grid)): if cells[d] <= 1: idx.append(d) #end #end if idx: grid = np.delete(grid, idx) lower = np.delete(lower, idx) upper = np.delete(upper, idx) cells = np.delete(cells, idx) axLabel = np.delete(axLabel, idx) values = np.squeeze(values, tuple(idx)) #end numComps = values.shape[-1] if streamline or quiver: step = 2 else: step = 1 #end idxComps = range(int(np.floor(numComps / step))) numComps = len(idxComps) if xscale != 1.0: axLabel[0] = axLabel[0] + r' $\times$ {:.3e}'.format(xscale) #end if numDims == 2 and yscale != 1.0: axLabel[1] = axLabel[1] + r' $\times$ {:.3e}'.format(yscale) #end sr = np.sqrt(numComps) #determine the number of rows and columns if sr == np.ceil(sr): numRows = int(sr) numCols = int(sr) elif np.ceil(sr) * np.floor(sr) >= numComps: numRows = int(np.floor(sr)) numCols = int(np.ceil(sr)) else: numRows = int(np.ceil(sr)) numCols = int(np.ceil(sr)) # Prepare the figure if figure is None: fig = [] if numDims == 1: tooltips = [(axLabel[0], "$x"), ("value", "$y") ] #getting tooltips ready for different dimensions else: if streamline or quiver: tooltips = None else: tooltips = [(axLabel[0], "$x"), (axLabel[1], "$y"), ("value", "@image")] #end #end for comp in idxComps: if logx and logy: fig.append( blt.figure(tooltips=tooltips, x_axis_type="log", y_axis_type="log", frame_height=int(600.0 / numRows), frame_width=int(600.0 / numRows), outline_line_color='black', min_border_left=70, min_border_right=50, min_border_bottom=10)) elif logx: fig.append( blt.figure( tooltips=tooltips, x_axis_type="log", frame_height=int( 600.0 / numRows ), #adjust figures with the size based on the screen size frame_width=int(600.0 / numRows), outline_line_color='black', min_border_left=70, min_border_right=50, min_border_bottom=10) ) #adjust spacings betweewn subplots to be aligned elif logy: fig.append( blt.figure(tooltips=tooltips, y_axis_type="log", frame_height=int(600.0 / numRows), frame_width=int(600.0 / numRows), outline_line_color='black', min_border_left=70, min_border_right=50, min_border_bottom=10)) else: fig.append( blt.figure(tooltips=tooltips, frame_height=int(600.0 / numRows), frame_width=int(600.0 / numRows), outline_line_color='black', min_border_left=70, min_border_right=60, min_border_bottom=10)) #-- Preparing the Axes ------------------------------------------- for comp in idxComps: fig[comp].xaxis.minor_tick_line_color = None #deleting minor ticks fig[comp].yaxis.minor_tick_line_color = None fig[comp].xaxis.major_label_text_font_size = '12pt' #tick font size adjustment fig[comp].yaxis.major_label_text_font_size = '12pt' fig[comp].xaxis.axis_label_text_font_size = '12pt' #label font size adjustment fig[comp].yaxis.axis_label_text_font_size = '12pt' fig[comp].xaxis.formatter = bm.BasicTickFormatter( precision=1) #adjust floating numbers of ticks fig[comp].yaxis.formatter = bm.BasicTickFormatter(precision=1) if numDims != 1: if comp % numCols != 0: #hiding labels for unnecessary locations fig[comp].yaxis.major_label_text_font_size = '0pt' #end if comp < (numRows - 1) * numCols: fig[comp].xaxis.major_label_text_font_size = '0pt' #end #end if comp >= (numRows - 1) * numCols: if xlabel is None: fig[comp].xaxis.axis_label = axLabel[0] else: #if there is xlabel to be specified fig[comp].xaxis.axis_label = xlabel #end #end #end if comp % numCols == 0: if ylabel is None: if numDims == 2: fig[comp].yaxis.axis_label = axLabel[1] #end else: fig[comp].yaxis.axis_label = ylabel #end #end #end #-- Main Plotting Loop ------------------------------------------- for comp in idxComps: if len(idxComps) > 1: if labelPrefix == "": label = str(comp) else: label = '{:s}_c{:d}'.format(labelPrefix, comp) #end else: label = labelPrefix #end #end # Special plots if numDims == 1: x = 0.5 * (grid[0][1:] + grid[0][:-1]) fig[comp].line(x, values[..., comp], line_width=2, legend=label) elif numDims == 2: if contour: pass elif streamline: magnitude = np.sqrt(values[..., 2 * comp]**2 + values[..., 2 * comp + 1]**2) gridCC = _gridNodalToCellCentered(grid, cells) plt.subplots(numRows, numCols, sharex=True, sharey=True) strm = plt.streamplot( gridCC[0] * xscale, gridCC[1] * yscale, # make streamline plot by matplotlib first values[..., 2 * comp].transpose(), values[..., 2 * comp + 1].transpose(), color=magnitude.transpose(), linewidth=2) lines = strm.lines # get the line and color data of matplotlib streamline pathes = lines.get_paths() arr = lines.get_array().data points = np.stack([p.vertices.T for p in pathes], axis=0) X = points[:, 0, :].tolist() Y = points[:, 1, :].tolist() mapper = bt.linear_cmap(field_name="color", palette=bp.Inferno256, low=arr.min(), high=arr.max()) # use the data to create a multiline, use linear_map and palette to set the color of the lines: source = bm.ColumnDataSource(dict(x=X, y=Y, color=arr)) fig[comp].multi_line("x", "y", line_color=mapper, source=source, line_width=3) colormapper = bm.LinearColorMapper( palette='Inferno256', low=np.amin(magnitude.transpose()), high=np.amax(magnitude.transpose())) #adding a color bar color_bar = bm.ColorBar( color_mapper=colormapper, width=7, location=(0, 0), formatter=bm.BasicTickFormatter( precision=1), #deleting unnecessary floating numbers ticker=bm.BasicTicker(desired_num_ticks=4), label_standoff=13, major_label_text_font_size='12pt', border_line_color=None, padding=2, bar_line_color='black') fig[comp].add_layout(color_bar, 'right') elif quiver: gridCC = _gridNodalToCellCentered(grid, cells) x_range = gridCC[0] * xscale #setting x coordinates y_range = gridCC[1] * yscale #setting y coordinates dx = grid[0][1] - grid[0][0] dy = grid[1][1] - grid[1][0] freq = 7 v_x = values[..., 2 * comp].transpose() v_y = values[..., 2 * comp + 1].transpose() X, Y = np.meshgrid(x_range, y_range) speed = np.sqrt(v_x**2 + v_y**2) theta = np.arctan2(v_y * dy, v_x * dx) #arctan(y/x) maxSpeed = speed.max() x0 = X[::freq, ::freq].flatten() y0 = Y[::freq, ::freq].flatten() length = speed[::freq, ::freq].flatten() / maxSpeed angle = theta[::freq, ::freq].flatten() x1 = x0 + 0.9 * freq * dx * v_x[::freq, ::freq].flatten( ) / speed[::freq, ::freq].max() y1 = y0 + 0.9 * freq * dy * v_y[::freq, ::freq].flatten( ) / speed[::freq, ::freq].max() fig[comp].segment(x0, y0, x1, y1, color='black') #vector line fig[comp].triangle(x1, y1, size=4.0, angle=angle - np.pi / 2, color='black') #vector arrow elif diverging: gridCC = _gridNodalToCellCentered(grid, cells) vmax = np.abs(values[..., comp]).max() x_range = grid[0] * xscale #setting x coordinates y_range = grid[1] * yscale #setting y coordinates CmToRgb = (255 * cm.RdBu_r(range(256))).astype( 'int') #extract colors from maplotlib colormap RgbToHexa = [ bc.RGB(*tuple(rgb)).to_hex() for rgb in CmToRgb ] # convert RGB numbers into colormap hexacode string mapper = bm.LinearColorMapper(palette=RgbToHexa, low=-vmax, high=vmax) #adding a color bar fig[comp].image(image=[values[..., comp].transpose()], x=x_range[0], y=y_range[0], dw=(x_range[-1] - x_range[0]), dh=(y_range[-1] - y_range[0]), color_mapper=mapper) color_bar = bm.ColorBar( color_mapper=mapper, width=7, location=(0, 0), formatter=bm.BasicTickFormatter( precision=1), #deleting unnecessary floating numbers ticker=bm.BasicTicker(desired_num_ticks=4), label_standoff=14, major_label_text_font_size='12pt', border_line_color=None, padding=2, bar_line_color='black') fig[comp].add_layout(color_bar, 'right') # Basic plots else: gridCC = _gridNodalToCellCentered(grid, cells) x_range = grid[0] * xscale #setting x coordinates y_range = grid[1] * yscale #setting y coordinates if logz: tmp = np.array(values[..., comp]) if vmin is not None or vmax is not None: for i in range(tmp.shape[0]): for j in range(tmp.shape[1]): if vmin and tmp[i, j] < vmin: tmp[i, j] = vmin #end if vmax and tmp[i, j] > vmax: tmp[i, j] = vmax #end #end if vmin is not None: vminTemp = vmin else: vminTemp = np.amin(values[..., comp]) #end if vmax is not None: vmaxTemp = vmax else: vmaxTemp = np.amax(values[..., comp]) #end mapper = bm.LogColorMapper(palette='Inferno256', low=vminTemp, high=vmaxTemp) fig[comp].image(image=[tmp.transpose()], x=x_range[0], y=y_range[0], dw=(x_range[-1] - x_range[0]), dh=(y_range[-1] - y_range[0]), color_mapper=mapper) color_bar = bm.ColorBar( color_mapper=mapper, #adding a colorbar width=7, location=(0, 0), formatter=bm.BasicTickFormatter( precision=1 ), #deleting unnecessary floating numbers ticker=bm.BasicTicker(), label_standoff=13, major_label_text_font_size='12pt', border_line_color=None, padding=2, bar_line_color='black') fig[comp].add_layout(color_bar, 'right') else: mapper = bm.LinearColorMapper(palette='Inferno256', low=np.amin(values[..., comp]), high=np.amax(values[..., comp])) fig[comp].image(image=[values[..., comp].transpose()], x=x_range[0], y=y_range[0], dw=(x_range[-1] - x_range[0]), dh=(y_range[-1] - y_range[0]), color_mapper=mapper) color_bar = bm.ColorBar( color_mapper=mapper, #adding a colorbar width=7, location=(0, 0), formatter=bm.BasicTickFormatter( precision=1 ), #deleting unnecessary floating numbers ticker=bm.BasicTicker(desired_num_ticks=4), label_standoff=13, major_label_text_font_size='12pt', border_line_color=None, padding=2, bar_line_color='black') fig[comp].add_layout(color_bar, 'right') #end #end else: raise ValueError("{:d}D data not yet supported".format(numDims)) #end #-- Additional Formatting ------------------------------------ if not quiver: fig[comp].x_range.range_padding = 0 if numDims == 2: fig[comp].y_range.range_padding = 0 #end #end if legend: if numDims == 2: x_range = grid[0] * xscale y_range = grid[1] * yscale #The legends are not embedded into the plot but the text numbers on the top of plots. Refer to 1D line plot. legend_number = bm.Label( x=x_range[0] + (x_range[-1] - x_range[0]) * 0.005, y=y_range[-1] - (y_range[-1] - y_range[0]) * 0.115, text=label, render_mode='css', background_fill_color='white', background_fill_alpha=0.9, border_line_cap='round') fig[comp].add_layout(legend_number) #end #end if title: if comp < numCols: fig[comp].title.text = title #end #end if not legend: if numDims == 1: fig[comp].legend.visible = False #end #end gp = bl.gridplot(children=fig, toolbar_location='right', ncols=numCols, merge_tools=True) return gp
object.data.materials.append(new_mat) scene.collection.objects.link(object) n_cones += 1 # Remove the original "master" cone which has been copied to each cell location from the simulation data bpy.data.objects.remove(master_cone) # For each data file generated by mumax, keyframe the orientation and material color of each cone. for i in tqdm.tqdm(range(data.shape[0]), desc='Animating frame'): n_cones = 0 for iz in range(nz): for iy in range(ny): for ix in range(nx): if n_cones % step == 0: color = cm.RdBu_r(data[i, iz, iy, ix, 2]) name = f'Cone({ix},{iy},{iz})' object = bpy.data.objects[name] material = bpy.data.materials[name] m = mathutils.Vector(data[i, iz, iy, ix]) object.rotation_quaternion = m.to_track_quat('Z', 'Y') material.node_tree.nodes[1].inputs[0].default_value = [ color[0], color[1], color[2], 1 ] material.node_tree.nodes[1].inputs[0].keyframe_insert( data_path='default_value', frame=i * time_dilation_factor) object.keyframe_insert(data_path='rotation_quaternion', frame=i * time_dilation_factor)
"""For the initial explanation at the beginning of the animation, use the RdBu_r matplotlib colormap to set the color of the cone at (0, 0) from the z-component of the cone orientation. """ import bpy import numpy as np import matplotlib.cm as cm import matplotlib.colors as colors # Get the first cone and its corresponding material. This cone is manipulated # as part of the explanation at the beginning of the animation. obj = bpy.data.objects['Cone(0,0,0)'] mat = bpy.data.materials['Cone(0,0,0)'] for frame in range(150): # This is the 'rotation_euler' fcurve associated with the y-coordinate fc = obj.animation_data.action.fcurves[2] mz = np.cos(fc.evaluate(frame)) normalizer = colors.Normalize(vmin=-1, vmax=1) # mat.node_tree.nodes[1] is the Principled BSDF shader which sets # the color of the cone. mat.node_tree.nodes[1].inputs[0].default_value = cm.RdBu_r(normalizer(mz)) mat.node_tree.nodes[1].inputs[0].keyframe_insert(data_path='default_value', frame=frame)
def generatePlotsAndHistogramFromHRITScene(scene, time_slot, outputFolder): scene.image.night_overview().save(outputFolder + time_slot.strftime("%Y-%m-%d_%H%M") + "___night_overview" + ".png") scene.image.natural().save(outputFolder + time_slot.strftime("%Y-%m-%d_%H%M") + "___natural" + ".png") fig = plt.figure(figsize=(12, 8), dpi=80, facecolor='w', edgecolor='w', frameon=True) plt.imshow(scene["IR_108"].data - scene["IR_039"].data, cmap="RdBu_r", vmin=-20, vmax=20) title = time_slot.strftime("%Y-%m-%d_%H%M") + "___IR_108-IR_039" plt.title(title) plt.colorbar() plt.xticks([]) plt.yticks([]) plt.savefig(outputFolder + title + ".png", bbox_inches='tight') plt.close() fig = plt.figure(figsize=(12, 8), dpi=80, facecolor='w', edgecolor='w', frameon=True) plt.imshow(scene["IR_108"].data, cmap="jet", vmin=210, vmax=300) title = time_slot.strftime("%Y-%m-%d_%H%M") + "___IR_108" plt.title(title) plt.colorbar() plt.xticks([]) plt.yticks([]) plt.savefig(outputFolder + title + ".png", bbox_inches='tight') plt.close() fig = plt.figure(figsize=(12, 8), dpi=80, facecolor='w', edgecolor='w', frameon=True) plt.imshow(scene["IR_039"].data, cmap="jet", vmin=210, vmax=300) title = time_slot.strftime("%Y-%m-%d_%H%M") + "___IR_039" plt.title(title) plt.colorbar() plt.xticks([]) plt.yticks([]) plt.savefig(outputFolder + title + ".png", bbox_inches='tight') plt.close() fig = plt.figure(figsize=(16, 8), dpi=80, facecolor='w', edgecolor='w', frameon=True) N, bins, patches = plt.hist( (scene["IR_108"].data - scene["IR_039"].data).flatten(), arange(-50, 15, 0.3), edgecolor="none") title = time_slot.strftime("%Y-%m-%d_%H%M") + "___IR_108-IR_039" plt.ylim((0, 20000)) ax = plt.gca() ax.set_axis_bgcolor('#CECECE') fracs = bins.astype(float) / bins.max() norm = colors.Normalize(-1, 1) for thisfrac, thispatch in zip(fracs, patches): color = cm.RdBu_r(norm(thisfrac)) thispatch.set_facecolor(color) plt.savefig(outputFolder + title + "_histogram.png", bbox_inches='tight') driver = gdal.GetDriverByName('GTiff') dsO = driver.Create(outputFolder + title + "_IR_108-IR_039.tif", len(scene["IR_108"].data[0]), len(scene["IR_108"].data), 1, gdal.GDT_Float32) dsO.GetRasterBand(1).WriteArray(scene["IR_108"].data - scene["IR_039"].data) dsO.FlushCache() # Write to disk. return
def plot_qubits_dynamic (T, n, dm = None, interaction = False): #start only after run function Ts = T._Ts if dm is not None: density_matrix = dm else: density_matrix = T._results[n].states if (interaction): dm_interaction = density_matrix else: H0 = T._H0[0][0]*T._H0[0][1][0] +T._H0[1][0]*T._H0[1][1][0] + T._H0[2][0]*T._H0[2][1][0] # constant part of Hamiltonian # H0 = T._H0[0][0]*T._H0[0][1][0]+T._H0[1][0]*T._H0[1][1][0] H0_list_expm = empty_like(Ts,dtype = Qobj) H0_list_expm_conj = empty_like(Ts, dtype = Qobj) dm_interaction = empty_like(Ts, dtype = Qobj) for ind, t in enumerate (Ts): H_current = H0*t*1j matrix_exp = H_current.expm() H0_list_expm [ind] = matrix_exp H0_list_expm_conj[ind] = matrix_exp.dag() dm_interaction[ind] = matrix_exp*density_matrix[ind]*matrix_exp.dag() qubit1_z_interaction = expect(T.build_2qubit_operator('Z','id'), dm_interaction) qubit1_y_interaction = expect(T.build_2qubit_operator('Y','id'), dm_interaction) qubit1_x_interaction = expect(T.build_2qubit_operator('X','id'), dm_interaction) qubit2_z_interaction = expect(T.build_2qubit_operator('id','Z'), dm_interaction) qubit2_y_interaction = expect(T.build_2qubit_operator('id','Y'), dm_interaction) qubit2_x_interaction = expect(T.build_2qubit_operator('id','X'), dm_interaction) fig = figure(figsize=(14,7)) axes = fig.add_axes([0.05, 0.2, 0.4, 0.8], projection="3d") axes1 = fig.add_axes([0.55, 0.2, 0.4, 0.8], projection="3d") sph = Bloch(fig=fig, axes=axes) sph.clear() sph.sphere_alpha = 0 sph.zlabel = [r'$\left|e\rightangle\right.$', r"$\left|g\rightangle\right.$"] sph.xlpos = [1.3, -1.3] sph.xlabel = [r'$\left.|+\right\rangle$', r"$\left.|-\right\rangle$"] sph.ylpos = [1.2, -1.3] sph.ylabel = [r'$\left.|-_i\right\rangle$', r"$\left.|+_i\right\rangle$"] sph.xlpos = [1.3, -1.3] nrm=matplotlib.colors.Normalize(0,Ts[-1]) colors=cm.RdBu_r(nrm(Ts)) sph.point_size=[40] sph.point_color = list(colors) sph.point_marker=['.'] sph.add_points([qubit1_x_interaction, qubit1_y_interaction, qubit1_z_interaction], meth='m') #sph.add_points ([[1/sqrt(2),1,0],[1/sqrt(2),0,0],[0,0,1]]) sph.render(fig,axes) sph1 = Bloch(fig=fig, axes=axes1) sph1.clear() sph1.sphere_alpha = 0 sph1.zlabel = [r'$\left|e\rightangle\right.$', r"$\left|g\rightangle\right.$"] sph1.xlpos = [1.3, -1.3] sph1.xlabel = [r'$\left.|+\right\rangle$', r"$\left.|-\right\rangle$"] sph1.ylpos = [1.2, -1.3] sph1.ylabel = [r'$\left.|-_i\right\rangle$', r"$\left.|+_i\right\rangle$"] sph1.xlpos = [1.3, -1.3] sph1.point_size=[40] sph1.point_color = list(colors) sph1.point_marker=['.'] sph1.add_points([qubit2_x_interaction, qubit2_y_interaction, qubit2_z_interaction], meth='m') #sph.add_points ([[1/sqrt(2),1,0],[1/sqrt(2),0,0],[0,0,1]]) sph1.render(fig,axes) m = cm.ScalarMappable(cmap=cm.RdBu_r, norm=nrm) m.set_array(Ts) m.set_clim(0, Ts[-1]) position=fig.add_axes([0.05,0.15,0.4,0.03]) cb = fig.colorbar(m, orientation='horizontal', cax=position) cb.set_label("Time, ns") cb.set_ticks(np.linspace(0,round(Ts[-1]),6)) sph.make_sphere() m1 = cm.ScalarMappable(cmap=cm.RdBu_r, norm=nrm) m1.set_array(Ts) m1.set_clim(0, Ts[-1]) position1=fig.add_axes([0.55,0.15,0.4,0.03]) cb1 = fig.colorbar(m1, orientation='horizontal', cax=position1) cb1.set_label("Time, ns") cb1.set_ticks(np.linspace(0,round(Ts[-1]),6)) sph1.make_sphere() axes.text2D(0.3,1, "Qubit 1 state evolution",transform=axes.transAxes, fontsize = 20) axes1.text2D(1,1, "Qubit 2 state evolution",transform=axes.transAxes, fontsize = 20) return fig