test_losses[i].append(test_loss[i] / len(test_dataloader)) test_accuracies[i].append(accuracy[i] / len(test_dataloader)) train_losses_averaged = [[] for net in nets] interval = 250 for n in range(len(train_losses)): for i in range(0, len(train_losses[n]), interval): try: train_losses_averaged[n].append( np.mean(train_losses[n][i:i + interval])) except IndexError: train_losses_averaged[n].append(np.mean(train_losses[n][i:])) fig = plt.figure(figsize=(20, 12)) gs = GridSpec(2, 2, figure=fig) ax1 = plt.subplot(gs[0, :]) ax2 = plt.subplot(gs[1, 0]) ax3 = plt.subplot(gs[1, 1]) for i in range(n_nets): ax1.plot(train_losses_averaged[i], label="Net {}: {} layers".format(i + 1, nets_details[i][0])) ax2.plot(test_losses[i], alpha=0.6) ax3.plot(test_accuracies[i], alpha=0.6) ax1.set_title('Training loss (mean per 250 batches)') ax1.set_xlabel('Batch') ax1.set_ylabel('Loss') ax1.legend(loc='upper right')
lambda date: dt.strptime(date[:19],'%Y-%m-%d %H:%M:%S')) #Convert dates in to weekday, night, day, default (calcualted from other 3 to avoid dummy variable trap) dataset['pickup_datetime'] = dataset['pickup_datetime'].apply( lambda date: get_time_interval(date)) #Split weekday, night and day in to columns dataset['work_hour'] = dataset['pickup_datetime'].apply( lambda date: date[0]) dataset['night'] = dataset['pickup_datetime'].apply( lambda date: date[1]) #Remove date dataset = dataset.drop(['pickup_datetime'], axis=1) #Checking for outliers in the data fare_amount = dataset.fare_amount passenger_count = dataset.passenger_count linear_distance = dataset.linear_distance plt.subplot(GridSpec(1, 3)[0, 0]) plt.boxplot(fare_amount) plt.title('fare_amount') plt.subplot(GridSpec(1, 3)[0, 1]) plt.boxplot(passenger_count) plt.title('passenger_count') plt.subplot(GridSpec(1, 3)[0, 2]) plt.boxplot(linear_distance) plt.title('linear_distance') plt.show() #Getting fare_amount outliner values fare_amount = fare_amount[fare_amount < 22.25] fare_amount = fare_amount[fare_amount > 0] #Getting passenger_count outliner values passenger_count = passenger_count[passenger_count < 4] passenger_count = passenger_count[passenger_count > 0]
def change_geometry(self, numrows, numcols, num): """change subplot geometry, e.g., from 1,1,1 to 2,2,3""" self._subplotspec = GridSpec(numrows, numcols, figure=self.figure)[num - 1] self.update_params() self.set_position(self.figbox)
def raters_variability_plot( mdata, figsize=(22, 22), width=101, out_file=None, raters=("rater_1", "rater_2", "rater_3"), only_overlap=True, rater_names=("Rater 1", "Rater 2a", "Rater 2b"), ): if only_overlap: mdata = mdata[np.all(~np.isnan(mdata[raters]), axis=1)] # Swap raters 2 and 3 # i, j = cols.index('rater_2'), cols.index('rater_3') # cols[j], cols[i] = cols[i], cols[j] # mdata.columns = cols sites_list = sorted(set(mdata.site.values.ravel().tolist())) sites_len = [] for site in sites_list: sites_len.append(len(mdata.loc[mdata.site == site])) sites_len, sites_list = zip(*sorted(zip(sites_len, sites_list))) blocks = [(slen - 1) // width + 1 for slen in sites_len] fig = plt.figure(figsize=figsize) gs = GridSpec( len(sites_list), 1, width_ratios=[1], height_ratios=blocks, hspace=0.05 ) for s, gsel in zip(sites_list, gs): ax = plt.subplot(gsel) plot_raters( mdata.loc[mdata.site == s, raters], ax=ax, width=width, size=0.40 if len(raters) == 3 else 0.80, ) ax.set_yticklabels([s]) # ax.add_line(Line2D([0.0, width], [8.0, 8.0], color='k')) # ax.annotate( # '%d images' % width, xy=(0.5 * width, 8), xycoords='data', # xytext=(0.5 * width, 9), fontsize=20, ha='center', va='top', # arrowprops=dict(arrowstyle='-[,widthB=1.0,lengthB=0.2', lw=1.0) # ) # ax.annotate('QC Prevalences', xy=(0.1, -0.15), xytext=(0.5, -0.1), xycoords='axes fraction', # fontsize=20, ha='center', va='top', # arrowprops=dict(arrowstyle='-[, widthB=3.0, lengthB=0.2', lw=1.0)) newax = plt.axes([0.6, 0.65, 0.25, 0.16]) newax.grid(False) newax.set_xticklabels([]) newax.set_xticks([]) newax.set_yticklabels([]) newax.set_yticks([]) nsamples = len(mdata) for i, rater in enumerate(raters): nsamples = len(mdata) - sum(np.isnan(mdata[rater].values)) good = 100 * sum(mdata[rater] == 1.0) / nsamples bad = 100 * sum(mdata[rater] == -1.0) / nsamples text_x = 0.92 text_y = 0.5 - 0.17 * i newax.text( text_x - 0.36, text_y, "%2.1f%%" % good, color="limegreen", weight=1000, size=25, horizontalalignment="right", verticalalignment="center", transform=newax.transAxes, ) newax.text( text_x - 0.18, text_y, "%2.1f%%" % max((0.0, 100 - good - bad)), color="dimgray", weight=1000, size=25, horizontalalignment="right", verticalalignment="center", transform=newax.transAxes, ) newax.text( text_x, text_y, "%2.1f%%" % bad, color="tomato", weight=1000, size=25, horizontalalignment="right", verticalalignment="center", transform=newax.transAxes, ) newax.text( 1 - text_x, text_y, rater_names[i], color="k", size=25, horizontalalignment="left", verticalalignment="center", transform=newax.transAxes, ) newax.text( 0.5, 0.95, "Imbalance of ratings", color="k", size=25, horizontalalignment="center", verticalalignment="top", transform=newax.transAxes, ) newax.text( 0.5, 0.85, "(ABIDE, aggregated)", color="k", size=25, horizontalalignment="center", verticalalignment="top", transform=newax.transAxes, ) if out_file is None: out_file = "raters.svg" fname, ext = op.splitext(out_file) if ext[1:] not in ["pdf", "svg", "png"]: ext = ".svg" out_file = fname + ".svg" fig.savefig( op.abspath(out_file), format=ext[1:], bbox_inches="tight", pad_inches=0, dpi=300 ) return fig
def plot_histograms(X, Y, rating_label="rater_1", out_file=None): import re import seaborn as sn from ..classifier.data import read_dataset sn.set(style="whitegrid") mdata, pp_cols = read_dataset(X, Y, rate_label=rating_label) mdata["rater"] = mdata[[rating_label]].values.ravel() for col in mdata.columns.ravel().tolist(): if col.startswith("rater_"): del mdata[col] mdata = mdata.loc[mdata.rater.notnull()] zscored = mdata.copy() # TODO: zscore_dataset was removed # zscored = zscore_dataset( # mdata, excl_columns=['rater', 'size_x', 'size_y', 'size_z', # 'spacing_x', 'spacing_y', 'spacing_z']) pat = re.compile(r"^(spacing|summary|size)") colnames = [col for col in sorted(pp_cols) if pat.match(col)] nrows = len(colnames) # palette = ['dodgerblue', 'darkorange'] fig = plt.figure(figsize=(18, 2 * nrows)) gs = GridSpec(nrows, 2, hspace=0.2) for i, col in enumerate(sorted(colnames)): ax_nzs = plt.subplot(gs[i, 0]) ax_zsd = plt.subplot(gs[i, 1]) sn.distplot( mdata.loc[(mdata.rater == 0), col], norm_hist=False, label="Accept", ax=ax_nzs, color="dodgerblue", ) sn.distplot( mdata.loc[(mdata.rater == 1), col], norm_hist=False, label="Reject", ax=ax_nzs, color="darkorange", ) ax_nzs.legend() sn.distplot( zscored.loc[(zscored.rater == 0), col], norm_hist=False, label="Accept", ax=ax_zsd, color="dodgerblue", ) sn.distplot( zscored.loc[(zscored.rater == 1), col], norm_hist=False, label="Reject", ax=ax_zsd, color="darkorange", ) alldata = mdata[[col]].values.ravel().tolist() minv = np.percentile(alldata, 0.2) maxv = np.percentile(alldata, 99.8) ax_nzs.set_xlim([minv, maxv]) alldata = zscored[[col]].values.ravel().tolist() minv = np.percentile(alldata, 0.2) maxv = np.percentile(alldata, 99.8) ax_zsd.set_xlim([minv, maxv]) if out_file is None: out_file = "histograms.svg" fname, ext = op.splitext(out_file) if ext[1:] not in ["pdf", "svg", "png"]: ext = ".svg" out_file = fname + ".svg" fig.savefig(out_file, format=ext[1:], bbox_inches="tight", pad_inches=0, dpi=100) return fig
def plot_granule(self, granule, mark_fns=False): import matplotlib.pyplot as plt import cartopy.crs as ccrs from matplotlib.colors import LogNorm, Normalize from matplotlib.gridspec import GridSpec try: fs = self.validation_files[granule] except KeyError: raise Exception( f"No validation data available for granule {granule}.") match_up_file = fs["match_up_file"] gprof_file = fs["gprof_file"] qprof_file = fs["qprof_file"] mrms_data = xr.load_dataset(match_up_file) gprof_data = RetrievalFile(gprof_file, has_sensitivity=True).to_xarray_dataset() qprof_data = RetrievalFile(qprof_file).to_xarray_dataset() gs = GridSpec(2, 2) f = plt.figure(figsize=(15, 15)) rain_norm = LogNorm(1e-2, 1e2) lats = mrms_data["latitude"] lons = mrms_data["longitude"] valid = gprof_data["surface_precip"] >= 0.0 rqi = mrms_data["radar_quality_index"] ax = plt.subplot(gs[0, 0], projection=ccrs.PlateCarree()) ax.plot(lons[:, 0], lats[:, 0], ls="--", c="grey") ax.plot(lons[:, -1], lats[:, -1], ls="--", c="grey") ax.pcolormesh(lons, lats, rqi, norm=Normalize(0, 1)) ax.coastlines() p_mrms = mrms_data["surface_precipitation"] p = mrms_data["surface_precipitation"] p = np.maximum(p, 1e-3) ax = plt.subplot(gs[0, 1], projection=ccrs.PlateCarree()) ax.plot(lons[:, 0], lats[:, 0], ls="--", c="grey") ax.plot(lons[:, -1], lats[:, -1], ls="--", c="grey") ax.pcolormesh(lons, lats, p, norm=rain_norm) ax.coastlines() p_qprof = qprof_data["surface_precip"] p = qprof_data["surface_precip"].data p[~valid] = np.nan ax = plt.subplot(gs[1, 0], projection=ccrs.PlateCarree()) ax.pcolormesh(lons, lats, p, norm=rain_norm) ax.plot(lons[:, 0], lats[:, 0], ls="--", c="grey") ax.plot(lons[:, -1], lats[:, -1], ls="--", c="grey") fns = (p_qprof <= 1e-2) * (p_mrms > 1e-2) ax.scatter(lons.data[fns], lats.data[fns], c="white", marker=".", alpha=1.0) ax.coastlines() p_gprof = gprof_data["surface_precip"] p = gprof_data["surface_precip"] ax = plt.subplot(gs[1, 1], projection=ccrs.PlateCarree()) ax.pcolormesh(lons, lats, p, norm=rain_norm) ax.plot(lons[:, 0], lats[:, 0], ls="--", c="grey") ax.plot(lons[:, -1], lats[:, -1], ls="--", c="grey") fns = (p_gprof <= 1e-2) * (p_mrms > 1e-2) ax.scatter(lons.data[fns], lats.data[fns], c="white", marker=".", alpha=0.2) ax.coastlines() plt.show() return f
def __init__(self, fig, *args, horizontal=None, vertical=None, aspect=None, anchor='C'): """ Parameters ---------- fig : :class:`matplotlib.figure.Figure` args : tuple (*numRows*, *numCols*, *plotNum*) The array of subplots in the figure has dimensions *numRows*, *numCols*, and *plotNum* is the number of the subplot being created. *plotNum* starts at 1 in the upper left corner and increases to the right. If *numRows* <= *numCols* <= *plotNum* < 10, *args* can be the decimal integer *numRows* * 100 + *numCols* * 10 + *plotNum*. """ self.figure = fig if len(args) == 1: if isinstance(args[0], SubplotSpec): self._subplotspec = args[0] else: try: s = str(int(args[0])) rows, cols, num = map(int, s) except ValueError: raise ValueError( 'Single argument to subplot must be a 3-digit integer') self._subplotspec = GridSpec(rows, cols)[num - 1] # num - 1 for converting from MATLAB to python indexing elif len(args) == 3: rows, cols, num = args rows = int(rows) cols = int(cols) if isinstance(num, tuple) and len(num) == 2: num = [int(n) for n in num] self._subplotspec = GridSpec(rows, cols)[num[0] - 1:num[1]] else: self._subplotspec = GridSpec(rows, cols)[int(num) - 1] # num - 1 for converting from MATLAB to python indexing else: raise ValueError('Illegal argument(s) to subplot: %s' % (args, )) # total = rows*cols # num -= 1 # convert from matlab to python indexing # # i.e., num in range(0,total) # if num >= total: # raise ValueError( 'Subplot number exceeds total subplots') # self._rows = rows # self._cols = cols # self._num = num # self.update_params() # sets self.fixbox self.update_params() pos = self.figbox.bounds Divider.__init__(self, fig, pos, horizontal or [], vertical or [], aspect=aspect, anchor=anchor)
def rfi_catalog(self, outpath, band={}, write={}, writepath='', fit={}, fit_window=[0, 10**12], bins='auto', flag_slices=['Unflagged', 'All'], bin_window=np.array([]), plot_type='freq-time', fraction=True): if plot_type == 'freq-time': Amp = {} for flag_slice in flag_slices: Amp.update( self.one_d_hist_prepare(flag_slice=flag_slice, fit=fit[flag_slice], write=write[flag_slice], bins=bins, writepath=writepath, fit_window=fit_window, bin_window=bin_window)) plot_type_keys = ['freq-time', 'ant-freq', 'ant-time'] aspect_values = [3, 1, 0.2] x_type_values = ['freq', 'freq', 'time'] y_type_values = ['time', 'ant', 'ant'] plot_type_title_values = ['', ' t = ', ' f = '] x_label_values = ['Frequency (Mhz)', 'Frequency (Mhz)', 'Time-Pair'] y_label_values = ['Time Pair', 'Antenna #', 'Antenna #'] path_label_values = ['', 't', 'f'] aspect = dict(zip(plot_type_keys, aspect_values)) x_type = dict(zip(plot_type_keys, x_type_values)) y_type = dict(zip(plot_type_keys, y_type_values)) plot_type_titles = dict(zip(plot_type_keys, plot_type_title_values)) x_labels = dict(zip(plot_type_keys, x_label_values)) y_labels = dict(zip(plot_type_keys, y_label_values)) path_labels = dict(zip(plot_type_keys, path_label_values)) if self.UV.Npols > 1: gs = GridSpec(3, 2) gs_loc = [[1, 0], [1, 1], [2, 0], [2, 1]] else: gs = GridSpec(2, 1) gs_loc = [ [1, 0], ] for flag_slice in flag_slices: if band[flag_slice] is 'fit': max_loc = min(Amp[flag_slice][1][np.where( Amp[flag_slice][0] == np.amax(Amp[flag_slice][0]))]) band[flag_slice] = [ np.amin(Amp[flag_slice][1][:-1][np.logical_and( Amp[flag_slice][2] < 1, Amp[flag_slice][1][:-1] > max_loc)]), 10 * np.amax(Amp[flag_slice][1]) ] W, uniques = self.waterfall_hist_prepare(band[flag_slice], plot_type=plot_type, fraction=fraction, flag_slice=flag_slice) N_events = W.shape[3] for k in range(N_events): fig = plt.figure(figsize=(14, 8)) ax = fig.add_subplot(gs[0, :]) if plot_type == 'freq-time': self.one_d_hist_plot(fig, ax, Amp, ' RFI Catalog ' + self.obs) if plot_type == 'ant-freq': Amp = {} for flag in flag_slices: Amp.update( self.one_d_hist_prepare(flag_slice=flag, time_drill=uniques[k], fit=fit[flag_slice], bins=bins, fit_window=fit_window, bin_window=bin_window)) Amp.update( self.one_d_hist_prepare(flag_slice=flag, time_exc=uniques[k], fit=fit[flag_slice], bins=bins, fit_window=fit_window, bin_window=bin_window)) self.one_d_hist_plot( fig, ax, Amp, '%s Drill %s %i' % (self.obs, plot_type_titles[plot_type], uniques[k])) elif plot_type == 'ant-time': unique_freqs = [ '%.1f' % (self.UV.freq_array[0, m] * 10**(-6)) for m in uniques ] Amp = {} for flag in flag_slices: Amp.update( self.one_d_hist_prepare(flag_slice=flag, freq_drill=uniques[k], fit=fit[flag_slice], bins=bins, fit_window=fit_window, bin_window=bin_window)) Amp.update( self.one_d_hist_prepare(flag_slice=flag, freq_exc=uniques[k], fit=fit[flag_slice], bins=bins, fit_window=fit_window, bin_window=bin_window)) self.one_d_hist_plot( fig, ax, Amp, '%s Drill %s %s Mhz' % (self.obs, plot_type_titles[plot_type], unique_freqs[k])) ax.axvline(x=min(band[flag_slice]), color='black') ax.axvline(x=max(band[flag_slice]), color='black') if self.UV.Npols > 1: MAXW_list = range(4) MAXW_list[:2] = [ max([np.amax(W[:, :, l, k]) for l in [0, 1]]) for m in [0, 1] ] MAXW_list[2:4] = [ max([np.amax(W[:, :, l, k]) for l in [2, 3]]) for m in [0, 1] ] MINW_list = range(4) MINW_list[:2] = [ min([np.amin(W[:, :, l, k]) for l in [0, 1]]) for m in [0, 1] ] MINW_list[2:4] = [ min([np.amin(W[:, :, l, k]) for l in [2, 3]]) for m in [0, 1] ] else: MAXW_list = [ np.amax(W[:, :, 0, k]), ] MINW_list = [ np.amin(W[:, :, 0, k]), ] for n in range(self.UV.Npols): ax = fig.add_subplot(gs[gs_loc[n][0], gs_loc[n][1]]) self.image_plot( fig, ax, W[:, :, n, k], '%s %s' % (self.pol_titles[self.UV.polarization_array[n]], flag_slice), MINW_list[n], MAXW_list[n], aspect_ratio=aspect[plot_type], fraction=fraction, y_type=y_type[plot_type], x_type=x_type[plot_type]) plt.tight_layout() if plot_type == 'freq-time': fig.savefig('%s%s_%s_%s.png' % (outpath, self.obs, plot_type, flag_slice)) else: fig.savefig('%s%s%s%s_%s%i.png' % (outpath, self.obs, plot_type, flag_slice, path_labels[plot_type], uniques[k])) plt.close(fig)
def main(): try: os.mkdir(args.output_directory) except: pass xp = np using_gpu = args.gpu_device >= 0 if using_gpu: cuda.get_device(args.gpu_device).use() xp = cupy if not args.dataset_path == None: assert args.dataset_path_1 == None, 'dataset_path already specified' assert args.dataset_path_2 == None, 'dataset_path already specified' dataset_1 = gqn.data.Dataset(args.dataset_path) dataset_2 = gqn.data.Dataset(args.dataset_path) elif not (args.dataset_path_1 == None or args.dataset_path_2 == None): dataset_1 = gqn.data.Dataset(args.dataset_path_1) dataset_2 = gqn.data.Dataset(args.dataset_path_2) else: raise TypeError('dataset path incorrectly specified') if not args.snapshot_path == None: assert args.snapshot_path_1 == None, 'snapshot_path already specified' assert args.snapshot_path_2 == None, 'snapshot_path already specified' hyperparams_1 = HyperParameters(snapshot_directory=args.snapshot_path) model_1 = Model(hyperparams_1, snapshot_directory=args.snapshot_path) hyperparams_2 = HyperParameters(snapshot_directory=args.snapshot_path) model_2 = Model(hyperparams_2, snapshot_directory=args.snapshot_path) elif not (args.snapshot_path_1 == None or args.snapshot_path_2 == None): hyperparams_1 = HyperParameters( snapshot_directory=args.snapshot_path_1) model_1 = Model(hyperparams_1, snapshot_directory=args.snapshot_path_1) hyperparams_2 = HyperParameters( snapshot_directory=args.snapshot_path_2) model_2 = Model(hyperparams_2, snapshot_directory=args.snapshot_path_2) else: raise TypeError('snapshot path incorrectly specified') if using_gpu: model_1.to_gpu() model_2.to_gpu() plt.style.use("dark_background") fig = plt.figure(figsize=(13, 8)) num_views_per_scene = 6 num_generation = 2 total_frames_per_rotation = 24 image_shape = (3, ) + hyperparams_1.image_size blank_image = make_uint8(np.full(image_shape, 0)) file_number = 1 with chainer.no_backprop_mode(): for subset_1, subset_2 in zip(dataset_1, dataset_2): iterator_1 = gqn.data.Iterator(subset_1, batch_size=1) iterator_2 = gqn.data.Iterator(subset_2, batch_size=1) count = 0 for data_indices_1, data_indices_2 in zip(iterator_1, iterator_2): if count < 2: count += 1 continue snapshot_array = [] observed_image_array_1 = xp.zeros( (num_views_per_scene, ) + image_shape, dtype=np.float32) observed_viewpoint_array_1 = xp.zeros((num_views_per_scene, 7), dtype=np.float32) observed_image_array_2 = xp.zeros( (num_views_per_scene, ) + image_shape, dtype=np.float32) observed_viewpoint_array_2 = xp.zeros((num_views_per_scene, 7), dtype=np.float32) # shape: (batch, views, height, width, channels) # range: [-1, 1] images_1, viewpoints_1, original_images_1 = subset_1[ data_indices_1] images_2, viewpoints_2, original_images_2 = subset_2[ data_indices_2] # (batch, views, height, width, channels) -> (batch, views, channels, height, width) images_1 = images_1.transpose( (0, 1, 4, 2, 3)).astype(np.float32) images_1 = images_1 / 255.0 images_1 += np.random.uniform(0, 1.0 / 256.0, size=images_1.shape).astype( np.float32) images_2 = images_2.transpose( (0, 1, 4, 2, 3)).astype(np.float32) images_2 = images_2 / 255.0 images_2 += np.random.uniform(0, 1.0 / 256.0, size=images_2.shape).astype( np.float32) # (batch, views, height, width, channels) -> (batch, views, channels, height, width) original_images_1 = original_images_1.transpose( (0, 1, 4, 2, 3)).astype(np.float32) original_images_1 = original_images_1 / 255.0 original_images_1 += np.random.uniform( 0, 1.0 / 256.0, size=original_images_1.shape).astype(np.float32) original_images_2 = original_images_2.transpose( (0, 1, 4, 2, 3)).astype(np.float32) original_images_2 = original_images_2 / 255.0 original_images_2 += np.random.uniform( 0, 1.0 / 256.0, size=original_images_2.shape).astype(np.float32) batch_index = 0 # Generate images without observations r_1 = xp.zeros(( num_generation, hyperparams_1.representation_channels, ) + hyperparams_1.chrz_size, dtype=np.float32) r_2 = xp.zeros(( num_generation, hyperparams_2.representation_channels, ) + hyperparams_2.chrz_size, dtype=np.float32) angle_rad = 0 current_scene_original_images_cpu_1 = original_images_1[ batch_index] current_scene_original_images_1 = to_gpu( current_scene_original_images_cpu_1) current_scene_original_images_cpu_2 = original_images_2[ batch_index] current_scene_original_images_2 = to_gpu( current_scene_original_images_cpu_2) gqn.animator.Snapshot.make_graph( id='sq_d_graph_1', pos=8, graph_type='plot', mode='sequential', frame_in_rotation=total_frames_per_rotation, num_of_data_per_graph=num_views_per_scene + 1, trivial_settings={ 'colors': [ 'red', 'blue', 'green', 'orange', 'white', 'cyan', 'magenta' ], 'markers': ['', '', '', '', '', '', ''] }) gqn.animator.Snapshot.make_graph( id='sq_d_graph_2', pos=16, graph_type='plot', mode='sequential', frame_in_rotation=total_frames_per_rotation, num_of_data_per_graph=num_views_per_scene + 1, trivial_settings={ 'colors': [ 'red', 'blue', 'green', 'orange', 'white', 'cyan', 'magenta' ], 'markers': ['', '', '', '', '', '', ''] }) gqn.animator.Snapshot.make_graph( id='sq_d_avg_graph', pos=17, graph_type='bar', mode='simultaneous', frame_in_rotation=9, frame_per_cycle=total_frames_per_rotation, num_of_data_per_graph=2, trivial_settings={ 'colors': ['red', 'blue'], 'markers': ['', ''], 'legends': ['Test', 'Train'] }) sq_d_sums_1 = [0 for i in range(num_views_per_scene + 1)] sq_d_sums_2 = [0 for i in range(num_views_per_scene + 1)] for t in range(total_frames_per_rotation): grid_master = GridSpec(nrows=4, ncols=9, height_ratios=[1, 1, 1, 1]) grid_master.update(wspace=0.5, hspace=0.8) snapshot = gqn.animator.Snapshot( unify_ylim=True, layout_settings={ 'subplot_count': 17, 'grid_master': grid_master, 'subplots': [{ 'subplot_id': 1, 'subplot': GridSpecFromSubplotSpec( nrows=1, ncols=1, subplot_spec=grid_master[0, 0]) }, { 'subplot_id': 2, 'subplot': GridSpecFromSubplotSpec( nrows=1, ncols=1, subplot_spec=grid_master[0, 1]) }, { 'subplot_id': 3, 'subplot': GridSpecFromSubplotSpec( nrows=1, ncols=1, subplot_spec=grid_master[0, 2]) }, { 'subplot_id': 4, 'subplot': GridSpecFromSubplotSpec( nrows=1, ncols=1, subplot_spec=grid_master[1, 0]) }, { 'subplot_id': 5, 'subplot': GridSpecFromSubplotSpec( nrows=1, ncols=1, subplot_spec=grid_master[1, 1]) }, { 'subplot_id': 6, 'subplot': GridSpecFromSubplotSpec( nrows=1, ncols=1, subplot_spec=grid_master[1, 2]) }, { 'subplot_id': 7, 'subplot': GridSpecFromSubplotSpec( nrows=2, ncols=2, subplot_spec=grid_master[0:2, 3:5]) }, { 'subplot_id': 8, 'subplot': GridSpecFromSubplotSpec( nrows=2, ncols=2, subplot_spec=grid_master[0:2, 5:7]) }, { 'subplot_id': 9, 'subplot': GridSpecFromSubplotSpec( nrows=1, ncols=1, subplot_spec=grid_master[2, 0]) }, { 'subplot_id': 10, 'subplot': GridSpecFromSubplotSpec( nrows=1, ncols=1, subplot_spec=grid_master[2, 1]) }, { 'subplot_id': 11, 'subplot': GridSpecFromSubplotSpec( nrows=1, ncols=1, subplot_spec=grid_master[2, 2]) }, { 'subplot_id': 12, 'subplot': GridSpecFromSubplotSpec( nrows=1, ncols=1, subplot_spec=grid_master[3, 0]) }, { 'subplot_id': 13, 'subplot': GridSpecFromSubplotSpec( nrows=1, ncols=1, subplot_spec=grid_master[3, 1]) }, { 'subplot_id': 14, 'subplot': GridSpecFromSubplotSpec( nrows=1, ncols=1, subplot_spec=grid_master[3, 2]) }, { 'subplot_id': 15, 'subplot': GridSpecFromSubplotSpec( nrows=2, ncols=2, subplot_spec=grid_master[2:4, 3:5]) }, { 'subplot_id': 16, 'subplot': GridSpecFromSubplotSpec( nrows=2, ncols=2, subplot_spec=grid_master[2:4, 5:7]) }, { 'subplot_id': 17, 'subplot': GridSpecFromSubplotSpec( nrows=4, ncols=2, subplot_spec=grid_master[0:4, 7:9]) }] }) for i in [1, 2, 3, 4, 5, 6, 9, 10, 11, 12, 13, 14]: snapshot.add_media(media_type='image', media_data=make_uint8(blank_image), media_position=i) if i == 1: snapshot.add_title(text='Test', target_media_pos=i) if i == 9: snapshot.add_title(text='Train', target_media_pos=i) query_viewpoints = rotate_query_viewpoint( angle_rad, num_generation, xp) generated_images_1 = model_1.generate_image( query_viewpoints, r_1, xp) generated_images_2 = model_2.generate_image( query_viewpoints, r_2, xp) total_sq_d_1, _ = gqn.math.get_squared_distance( to_cpu(current_scene_original_images_1[t]), to_cpu(generated_images_1[0])) sq_d_sums_1[0] += total_sq_d_1 total_sq_d_2, _ = gqn.math.get_squared_distance( to_cpu(current_scene_original_images_2[t]), to_cpu(generated_images_2[0])) sq_d_sums_2[0] += total_sq_d_2 for i in [7]: snapshot.add_media(media_type='image', media_data=make_uint8( generated_images_1[0]), media_position=i) snapshot.add_title(text='GQN Output', target_media_pos=i) for i in [15]: snapshot.add_media(media_type='image', media_data=make_uint8( generated_images_2[0]), media_position=i) snapshot.add_title(text='GQN Output', target_media_pos=i) for i in [8, 16]: snapshot.add_title(text='Squared Distance', target_media_pos=i) gqn.animator.Snapshot.add_graph_data( graph_id='sq_d_graph_1', data_id='sq_d_data_0', new_data=total_sq_d_1, frame_num=t, ) gqn.animator.Snapshot.add_graph_data( graph_id='sq_d_graph_2', data_id='sq_d_data_0', new_data=total_sq_d_2, frame_num=t, ) if t == total_frames_per_rotation - 1: sq_d_sums_1[0] /= total_frames_per_rotation sq_d_sums_2[0] /= total_frames_per_rotation gqn.animator.Snapshot.add_graph_data( graph_id='sq_d_avg_graph', data_id='sq_d_data_0', new_data=sq_d_sums_1[0], frame_num=0) gqn.animator.Snapshot.add_graph_data( graph_id='sq_d_avg_graph', data_id='sq_d_data_1', new_data=sq_d_sums_2[0], frame_num=0) snapshot_array.append(snapshot) angle_rad += 2 * math.pi / total_frames_per_rotation # Generate images with observations for m in range(num_views_per_scene): kl_div_sum = 0 observed_image_1 = images_1[batch_index, m] observed_viewpoint_1 = viewpoints_1[batch_index, m] observed_image_2 = images_2[batch_index, m] observed_viewpoint_2 = viewpoints_2[batch_index, m] observed_image_array_1[m] = to_gpu(observed_image_1) observed_viewpoint_array_1[m] = to_gpu( observed_viewpoint_1) observed_image_array_2[m] = to_gpu(observed_image_2) observed_viewpoint_array_2[m] = to_gpu( observed_viewpoint_2) r_1 = model_1.compute_observation_representation( observed_image_array_1[None, :m + 1], observed_viewpoint_array_1[None, :m + 1]) r_2 = model_2.compute_observation_representation( observed_image_array_2[None, :m + 1], observed_viewpoint_array_2[None, :m + 1]) r_1 = cf.broadcast_to(r_1, (num_generation, ) + r_1.shape[1:]) r_2 = cf.broadcast_to(r_2, (num_generation, ) + r_2.shape[1:]) angle_rad = 0 for t in range(total_frames_per_rotation): grid_master = GridSpec(nrows=4, ncols=9, height_ratios=[1, 1, 1, 1]) grid_master.update(wspace=0.5, hspace=0.8) snapshot = gqn.animator.Snapshot( unify_ylim=True, layout_settings={ 'subplot_count': 17, 'grid_master': grid_master, 'subplots': [{ 'subplot_id': 1, 'subplot': GridSpecFromSubplotSpec( nrows=1, ncols=1, subplot_spec=grid_master[0, 0]) }, { 'subplot_id': 2, 'subplot': GridSpecFromSubplotSpec( nrows=1, ncols=1, subplot_spec=grid_master[0, 1]) }, { 'subplot_id': 3, 'subplot': GridSpecFromSubplotSpec( nrows=1, ncols=1, subplot_spec=grid_master[0, 2]) }, { 'subplot_id': 4, 'subplot': GridSpecFromSubplotSpec( nrows=1, ncols=1, subplot_spec=grid_master[1, 0]) }, { 'subplot_id': 5, 'subplot': GridSpecFromSubplotSpec( nrows=1, ncols=1, subplot_spec=grid_master[1, 1]) }, { 'subplot_id': 6, 'subplot': GridSpecFromSubplotSpec( nrows=1, ncols=1, subplot_spec=grid_master[1, 2]) }, { 'subplot_id': 7, 'subplot': GridSpecFromSubplotSpec( nrows=2, ncols=2, subplot_spec=grid_master[0:2, 3:5]) }, { 'subplot_id': 8, 'subplot': GridSpecFromSubplotSpec( nrows=2, ncols=2, subplot_spec=grid_master[0:2, 5:7]) }, { 'subplot_id': 9, 'subplot': GridSpecFromSubplotSpec( nrows=1, ncols=1, subplot_spec=grid_master[2, 0]) }, { 'subplot_id': 10, 'subplot': GridSpecFromSubplotSpec( nrows=1, ncols=1, subplot_spec=grid_master[2, 1]) }, { 'subplot_id': 11, 'subplot': GridSpecFromSubplotSpec( nrows=1, ncols=1, subplot_spec=grid_master[2, 2]) }, { 'subplot_id': 12, 'subplot': GridSpecFromSubplotSpec( nrows=1, ncols=1, subplot_spec=grid_master[3, 0]) }, { 'subplot_id': 13, 'subplot': GridSpecFromSubplotSpec( nrows=1, ncols=1, subplot_spec=grid_master[3, 1]) }, { 'subplot_id': 14, 'subplot': GridSpecFromSubplotSpec( nrows=1, ncols=1, subplot_spec=grid_master[3, 2]) }, { 'subplot_id': 15, 'subplot': GridSpecFromSubplotSpec( nrows=2, ncols=2, subplot_spec=grid_master[2:4, 3:5]) }, { 'subplot_id': 16, 'subplot': GridSpecFromSubplotSpec( nrows=2, ncols=2, subplot_spec=grid_master[2:4, 5:7]) }, { 'subplot_id': 17, 'subplot': GridSpecFromSubplotSpec( nrows=4, ncols=2, subplot_spec=grid_master[0:4, 7:9]) }] }) for i, observed_image in zip([1, 2, 3, 4, 5, 6], observed_image_array_1): snapshot.add_media( media_type='image', media_data=make_uint8(observed_image), media_position=i) if i == 1: snapshot.add_title(text='Test', target_media_pos=i) for i, observed_image in zip([9, 10, 11, 12, 13, 14], observed_image_array_2): snapshot.add_media( media_type='image', media_data=make_uint8(observed_image), media_position=i) if i == 9: snapshot.add_title(text='Train', target_media_pos=i) query_viewpoints = rotate_query_viewpoint( angle_rad, num_generation, xp) generated_images_1 = model_1.generate_image( query_viewpoints, r_1, xp) generated_images_2 = model_2.generate_image( query_viewpoints, r_2, xp) total_sq_d_1, _ = gqn.math.get_squared_distance( to_cpu(current_scene_original_images_1[t]), to_cpu(generated_images_1[0])) sq_d_sums_1[m + 1] += total_sq_d_1 total_sq_d_2, _ = gqn.math.get_squared_distance( to_cpu(current_scene_original_images_2[t]), to_cpu(generated_images_2[0])) sq_d_sums_2[m + 1] += total_sq_d_2 for i in [7]: snapshot.add_media(media_type='image', media_data=make_uint8( generated_images_1[0]), media_position=i) snapshot.add_title(text='GQN Output', target_media_pos=i) for i in [15]: snapshot.add_media(media_type='image', media_data=make_uint8( generated_images_2[0]), media_position=i) snapshot.add_title(text='GQN Output', target_media_pos=i) for i in [8, 16]: snapshot.add_title(text='Squared Distance', target_media_pos=i) gqn.animator.Snapshot.add_graph_data( graph_id='sq_d_graph_1', data_id='sq_d_data_' + str(m + 1), new_data=total_sq_d_1, frame_num=t, ) gqn.animator.Snapshot.add_graph_data( graph_id='sq_d_graph_2', data_id='sq_d_data_' + str(m + 1), new_data=total_sq_d_2, frame_num=t, ) if t == total_frames_per_rotation - 1: sq_d_sums_1[m + 1] /= total_frames_per_rotation sq_d_sums_2[m + 1] /= total_frames_per_rotation gqn.animator.Snapshot.add_graph_data( graph_id='sq_d_avg_graph', data_id='sq_d_data_0', new_data=sq_d_sums_1[m + 1], frame_num=m + 1) gqn.animator.Snapshot.add_graph_data( graph_id='sq_d_avg_graph', data_id='sq_d_data_1', new_data=sq_d_sums_2[m + 1], frame_num=m + 1) angle_rad += 2 * math.pi / total_frames_per_rotation # plt.pause(1e-8) snapshot_array.append(snapshot) plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=0, hspace=0) anim = animation.FuncAnimation( fig, func_anim_upate, fargs=(fig, [snapshot_array]), interval=1 / 24, frames=(num_views_per_scene + 1) * total_frames_per_rotation) anim.save("{}/shepard_matzler_{}.mp4".format( args.output_directory, file_number), writer="ffmpeg", fps=12) file_number += 1
feh.append('-'+d['mod_name'][i].split('/')[-1].split('fehm')[1].split('.fits')[0]) age = np.array(age).astype('float') feh = np.array(feh).astype('float') # ----- Trace plot ----- # ndiscard0 = 1000 with PdfPages('trace1.pdf') as pdf: n_fig, n_row = 1, 10 plot_scale = 100 for k in np.arange(len(d['mod_name'])): if (k % n_row == 0): fig = plt.figure(n_fig, figsize=(10,10)) gs = GridSpec(n_row, 1, left=0.10, bottom=0.10, right=0.85, top=0.975, height_ratios=[1]*n_row, hspace=0.05) n_fig += 1 ax = fig.add_subplot(gs[k % n_row, 0]) Y = d['samp'][ndiscard0:, :, k][::plot_scale, :] X = np.linspace(ndiscard0, len(d['samp']), Y.shape[0]+1).astype('int')[1:] yl, yh = np.percentile(Y, [0.27, 99.73]) ax.set_ylim(yl-np.std(Y), yh+np.std(Y)) ax.tick_params(axis='both', labelsize=12.0) ax.plot(X, Y, '-', color='k', alpha=0.3) ax.text(1.01, 0.95, f"Age = {age[k]:.1f} Gyr", fontsize=12.0, ha='left', va='top', transform=ax.transAxes) ax.text(1.01, 0.70, f"[Fe/H] = {feh[k]:.2f}", fontsize=12.0, ha='left', va='top', transform=ax.transAxes) if ((k % n_row == n_row-1) | (k == np.arange(len(d['mod_name']))[-1])):
from matplotlib.gridspec import GridSpec l = 1.0 n = 11 gs = (n, n, n) signal = np.fromfile("signal.bin").reshape(gs) m = np.fromfile("map.bin").reshape(gs) s_min = signal.min() s_max = signal.max() for ix in xrange(0, n): print "plotting slice ix = %i" % ix fig = plt.figure(figsize=(8, 5)) gs = GridSpec(2, 2, height_ratios=(1, 30)) ax1 = fig.add_subplot(gs[1, 0]) ax2 = fig.add_subplot(gs[1, 1]) cax1 = fig.add_subplot(gs[0, 0]) cax2 = fig.add_subplot(gs[0, 1]) # signal im1 = ax1.imshow(signal[ix], vmin=s_min, vmax=s_max, extent=(0, l, 0, l)) ax1.set_xlabel(r"$z$") cb1 = plt.colorbar(im1, cax=cax1, orientation="horizontal") cb1.solids.set_rasterized(True) cax1.tick_params(bottom=False, labelbottom=False, top=True, labeltop=True) cb1.set_label(r"$s$", labelpad=-40)
def fit_para(L, d, eps_2D): return (eps_2D - 1) * d / L + 1 def fit_vert(L, d, eps_2D): return 1 / (d / L * (1 / eps_2D - 1) + 1) root = "../../data/distance/" g = os.walk(root) # print(g) names = next(g)[1] # print(names) # names = sorted(names) gs = GridSpec(7, 1, hspace=0.3) fig1 = plt.figure(figsize=(3, 3.2)) fig2 = plt.figure(figsize=(3, 3.2)) ax1_r = fig1.add_subplot(gs[5:]) ax1 = fig1.add_subplot(gs[:5]) ax2_r = fig2.add_subplot(gs[5:]) ax2 = fig2.add_subplot(gs[:5]) colors = { "mos2": "#1f77b4", "mose2": "#ff7f0e", "mote2": "#2ca02c", "ws2": "#d62728", "wse2": "#9467bd", "wte2": "#8c564b", }
import numpy as np from matplotlib.gridspec import GridSpec from matplotlib.patches import Circle from scc.turn import Turn from scc.turnparams import TurnParams KAPPA_MAX = random.uniform(0.1, 5) SIGMA_MAX = random.uniform(0.1, 5) DELTA = random.uniform(-2 * math.pi, 2 * math.pi) print(" DELTA is " + str(DELTA)) print(" KAPPA_MAX is " + str(KAPPA_MAX)) print(" SIGMA_MAX is " + str(SIGMA_MAX)) # Create a new subplot from a grid of 3x3 gs = GridSpec(3, 3) fig = plt.figure(figsize=(8, 14)) ax0 = fig.add_subplot(gs[:-1, :]) ax0.set_label("x-y") ax1 = fig.add_subplot(gs[-1, :]) ax1.set_label("s-theta") tparam = TurnParams(KAPPA_MAX, SIGMA_MAX) turn = Turn(tparam, DELTA) # plot outer circle: omega = tparam.omega ax0.add_patch( Circle(omega, tparam.outer_rad, facecolor='none', edgecolor='black'))
rcParams['xtick.major.size'] = 3 # major tick size in points rcParams['xtick.minor.size'] = 2 # minor tick size in points rcParams['xtick.major.width'] = 0.75 # major tick width in points rcParams['xtick.minor.width'] = 0.75 # minor tick width in points rcParams['ytick.major.size'] = 3 # major tick size in points rcParams['ytick.minor.size'] = 2 # minor tick size in points rcParams['ytick.major.width'] = 0.75 # major tick width in points rcParams['ytick.minor.width'] = 0.75 # minor tick width in points #%% fig = plt.figure(figsize=(5.9 / 1.5, 2.2 * 2)) # gs = GridSpec(2, 1) ax = plt.subplot(gs[0, 0]) # uwavelock date = 20180315 sequence = 87 scanned_parameter = 'ARP_FineBias' df1 = utils.simple_data_processing(date, sequence, scanned_parameter) sequence = 88 scanned_parameter = 'ARP_FineBias' df2 = utils.simple_data_processing(date, sequence, scanned_parameter) df = pd.concat([df1, df2], axis=0) #df = df[1::] p1 = df['od1']
def create(path: str, name: str, header: dict, traces: List[Trace], old_style: bool = False) -> Figure: rcParams.update({'font.size': 9}) log.info('Making PID plot...') fig = plt.figure('Response plot: Log number: ' + header['logNum'] + ' ' + path, figsize=(16, 8)) # gridspec devides window into 24 horizontal, 3*10 vertical fields gs1 = GridSpec(24, 3 * 10, wspace=0.6, hspace=0.7, left=0.04, right=1., bottom=0.05, top=0.97) for i, trace in enumerate(traces): ax0 = plt.subplot(gs1[0:6, i * 10:i * 10 + 9]) plt.title(trace.name) plt.plot(trace.time, trace.gyro, label=trace.name + ' gyro') plt.plot(trace.time, trace.input, label=trace.name + ' loop input') plt.ylabel('degrees/second') ax0.get_yaxis().set_label_coords(-0.1, 0.5) plt.grid() tracelim = np.max([np.abs(trace.gyro), np.abs(trace.input)]) plt.ylim([-tracelim * 1.1, tracelim * 1.1]) plt.legend(loc=1) plt.setp(ax0.get_xticklabels(), visible=False) ax1 = plt.subplot(gs1[6:8, i * 10:i * 10 + 9], sharex=ax0) plt.hlines(header['tpa_percent'], trace.time[0], trace.time[-1], label='tpa', colors='red', alpha=0.5) plt.fill_between(trace.time, 0., trace.throttle, label='throttle', color='grey', alpha=0.2) plt.ylabel('throttle %') ax1.get_yaxis().set_label_coords(-0.1, 0.5) plt.grid() plt.xlim([trace.time[0], trace.time[-1]]) plt.ylim([0, 100]) plt.legend(loc=1) plt.xlabel('log time in s') if old_style: # response vs. time in color plot plt.setp(ax1.get_xticklabels(), visible=False) ax2 = plt.subplot(gs1[9:16, i * 10:i * 10 + 9], sharex=ax0) plt.pcolormesh(trace.avr_t, trace.time_resp, np.transpose(trace.spec_sm), vmin=0, vmax=2.) plt.ylabel('response time in s') ax2.get_yaxis().set_label_coords(-0.1, 0.5) plt.xlabel('log time in s') plt.xlim([trace.avr_t[0], trace.avr_t[-1]]) else: # response vs throttle plot. more useful. ax2 = plt.subplot(gs1[9:16, i * 10:i * 10 + 9]) plt.title(trace.name + ' response', y=0.88, color='w') plt.pcolormesh(trace.thr_response['throt_scale'], trace.time_resp, trace.thr_response['hist2d_norm'], vmin=0., vmax=2.) plt.ylabel('response time in s') ax2.get_yaxis().set_label_coords(-0.1, 0.5) plt.xlabel('throttle in %') plt.xlim([0., 100.]) cmap = plt.cm.get_cmap('Blues') cmap._init() alphas = np.abs(np.linspace(0., 0.5, cmap.N, dtype=np.float64)) cmap._lut[:-3, -1] = alphas ax3 = plt.subplot(gs1[17:, i * 10:i * 10 + 9]) plt.contourf(*trace.resp_low[2], cmap=cmap, linestyles=None, antialiased=True, levels=np.linspace(0, 1, 20, dtype=np.float64)) plt.plot(trace.time_resp, trace.resp_low[0], label=trace.name + ' step response ' + '(<' + str(int(Trace.threshold)) + ') ' + ' PID ' + header[trace.name + 'PID']) if trace.high_mask.sum() > 0: cmap = plt.cm.get_cmap('Oranges') cmap._init() alphas = np.abs(np.linspace(0., 0.5, cmap.N, dtype=np.float64)) cmap._lut[:-3, -1] = alphas plt.contourf(*trace.resp_high[2], cmap=cmap, linestyles=None, antialiased=True, levels=np.linspace(0, 1, 20, dtype=np.float64)) plt.plot(trace.time_resp, trace.resp_high[0], label=trace.name + ' step response ' + '(>' + str(int(Trace.threshold)) + ') ' + ' PID ' + header[trace.name + 'PID']) plt.xlim([-0.001, 0.501]) plt.legend(loc=1) plt.ylim([0., 2]) plt.ylabel('strength') ax3.get_yaxis().set_label_coords(-0.1, 0.5) plt.xlabel('response time in s') plt.grid() meanfreq = 1. / (traces[0].time[1] - traces[0].time[0]) ax4 = plt.subplot(gs1[12, -1]) t = BANNER + " | Betaflight: Version " + header['version'] + ' | Craftname: ' + header[ 'craftName'] + \ ' | meanFreq: ' + str(int(meanfreq)) + ' | rcRate/Expo: ' + header['rcRate'] + '/' + header[ 'rcExpo'] + '\nrcYawRate/Expo: ' + header['rcYawRate'] + '/' \ + header['rcYawExpo'] + ' | deadBand: ' + header['deadBand'] + ' | yawDeadBand: ' + \ header['yawDeadBand'] \ + ' | Throttle min/tpa/max: ' + header['minThrottle'] + '/' + header['tpa_breakpoint'] + '/' + \ header['maxThrottle'] \ + ' | dynThrPID: ' + header['dynThrottle'] + '| D-TermSP: ' + header[ 'dTermSetPoint'] + '| vbatComp: ' + header['vbatComp'] plt.text(0, 0, t, ha='left', va='center', rotation=90, color='grey', alpha=0.5, fontsize=TEXTSIZE) ax4.axis('off') log.info('Saving as image...') plt.savefig(path[:-13] + name + '_' + str(header['logNum']) + '_response.png') return fig
def map_disp(pipeline_data, xis, plot='show', num_steps=(20, 20), fov=((-500, 500), (-500, 500))): x_fov_start = fov[0][0] # limits of the FoV in mm y_fov_start = fov[1][0] # limits of the FoV in mm x_fov_end = fov[0][1] # limits of the FoV in mm y_fov_end = fov[1][1] # limits of the FoV in mm num_steps = np.atleast_1d(num_steps) xis = np.unique(np.abs(np.array(xis))) if len(num_steps) == 1: num_steps = [num_steps[0], num_steps[0]] x_bin = np.linspace(x_fov_start, x_fov_end, num_steps[0] + 1) y_bin = np.linspace(y_fov_start, y_fov_end, num_steps[1] + 1) x_fov = 0.5 * (x_bin[1:] + x_bin[:-1]) y_fov = 0.5 * (y_bin[1:] + y_bin[:-1]) x_cen = 0.5 * (x_fov_start + x_fov_end) y_cen = 0.5 * (y_fov_start + y_fov_end) bkg_mask = pipeline_data['skewness'] < 0 data_mask = pipeline_data['skewness'] > 0 x, y = arrival_lessard(pipeline_data[data_mask], xis) x_bkb, y_bkb = arrival_lessard(pipeline_data[bkg_mask], -xis) for i, xi in enumerate(np.unique(xis)): fig = plt.figure(figsize=(15, 12)) gs = GridSpec(4, 5) ax1 = plt.subplot(gs[:3, :3]) h_bkg, _, _ = np.histogram2d(x_bkb[:, i], y_bkb[:, i], bins=(x_bin, y_bin)) h, _, _ = np.histogram2d(x[:, i], y[:, i], bins=(x_bin, y_bin)) img = ax1.pcolormesh(x_bin, y_bin, (h - h_bkg).T) data_center = np.logical_and(np.abs(x[:, i] - x_cen) < 10, np.abs(y[:, i] - y_cen) < 10) # plt.plot(pipeline_data['x'][data_mask][data_center], # pipeline_data['y'][data_mask][data_center], 'r+', ms=10) plt.grid() ax5 = plt.subplot(gs[3, 3:]) plotted = pipeline_data['width'] # pipeline_data['length']/pipeline_data['width'] ax5.hist(plotted[data_mask][data_center][pipeline_data['skewness'] > 0], facecolor='b') ax5.hist(plotted[data_mask][data_center][pipeline_data['skewness'] < 0], facecolor='r') # colorbar ax4 = plt.subplot(gs[:3, 4]) plt.colorbar(img, cax=ax4) # projection on Y axis ax2 = plt.subplot(gs[:3, 3], sharey=ax1) ax2.plot(np.sum(h, axis=0), y_fov, label='data') ax2.plot(np.sum(h_bkg, axis=0), y_fov, label='bkg') ax2.plot(np.sum(h-h_bkg, axis=0), y_fov, label='excess') plt.setp(ax2.get_yticklabels(), visible=False) # projection on X axis ax3 = plt.subplot(gs[3, :3], sharex=ax1) ax3.plot(x_fov, np.sum(h, axis=1), label='data') ax3.plot(x_fov, np.sum(h_bkg, axis=1), label='bkg') ax3.plot(x_fov, np.sum(h-h_bkg, axis=1), label='excess') ax3.legend() plt.setp(ax3.get_xticklabels(), visible=False) plt.tight_layout() if len(xis)> 1: plot_name = plot.replace('.png', '_xi{:.2f}.png'.format(xi)) else: plot_name = plot if plot == "show": plt.show() else: plt.savefig(plot_name) print(plot_name, 'created') plt.close(fig)
def test_skewt_gridspec(): """Test using SkewT on a GridSpec sub-plot.""" fig = plt.figure(figsize=(9, 9)) gs = GridSpec(1, 2) SkewT(fig, subplot=gs[0, 1], aspect='auto') return fig
print('impact = ', impact) print('DATA SAVED TO ', targetdir) print('---------------------------') # ----------------------------------------------- # # from grid_lightcurve_plots.py days_side = 100 # how many days left and right from eclipse midpoint I want to go; # 100 for b=17%; 30 for scaled, 50 for M_Earth, 100 for b=30% y_range = 42 # half of height of ring system plots; # 42 for b=17%; 20 for scaled, 35 for M_Earth at 20% R_Hill, 60 for b=30% fig_title = "both m and a from 3 *inner* moons / b = 17.2% Hill sphere radius, m = galilean *5, a = supergalilean *40, v = 13.3 km/s, Hill sphere half filled" fig_grid = plt.figure() # create the figure # fig_grid.tight_layout() # plt.suptitle(fig_title) # include title of the whole thing gs1 = GridSpec(3, 1) # first row of grids (i = 60) ax_rings_1 = plt.subplot(gs1[0:2, 0]) ax_light_1 = plt.subplot(gs1[2, 0]) ##################### ### Make light curve axis = ax_light_1 # Importing the light curve data time, flux, flux_errxx = bring.lightcurve_import( data + "/model_i" + str(n) + "_phi" + str(m) + '.dat', 'time', 'flux', 'flux_rms') # interpolation for 5min-sampling new_time, new_flux = bring.interpol_5min(time, flux)
def plot_contours(self, granule, mrms_input_data=None): import matplotlib.pyplot as plt import cartopy.crs as ccrs from matplotlib.colors import LogNorm, Normalize from matplotlib.gridspec import GridSpec try: fs = self.validation_files[granule] except KeyError: raise Exception( f"No validation data available for granule {granule}.") match_up_file = fs["match_up_file"] gprof_file = fs["gprof_file"] qprof_file = fs["qprof_file"] mrms_data = xr.load_dataset(match_up_file) gprof_data = RetrievalFile(gprof_file, has_sensitivity=True).to_xarray_dataset() qprof_data = RetrievalFile(qprof_file).to_xarray_dataset() gs = GridSpec(1, 1) f = plt.figure(figsize=(15, 15)) levels = [1e0] #np.logspace(0, 2, 5) lats = mrms_data["latitude"] lons = mrms_data["longitude"] valid = gprof_data["surface_precip"] >= 0.0 rain_norm = LogNorm(1e-2, 1e2) p_mrms = mrms_data["surface_precipitation"].data p_qprof = qprof_data["surface_precip"].data p_gprof = gprof_data["surface_precip"].data ax = plt.subplot(gs[0, 0], projection=ccrs.PlateCarree()) ax.contourf(lons, lats, np.maximum(p_mrms, 1e-2), cmap="plasma", norm=rain_norm) ax.contour(lons, lats, p_gprof, levels=levels, cmap="Blues", norm=rain_norm) ax.contour(lons, lats, p_qprof, levels=levels, cmap="Greens", norm=rain_norm) #ax.scatter(lons, lats, marker=".", s=2, cmap="Greys", c="grey") if mrms_input_data is not None: lats = mrms_input_data["latitude"] lons = mrms_input_data["longitude"] p = mrms_input_data["precip_rate"] for i in range(len(mrms_input_data.time)): ax.contour(lons, lats, p.data[i, :, :], levels=levels, colors=f"C{i}", alpha=1.0, linewidths=1) ax.coastlines() return f
decompose_loss = criterion(decompose_output, x_) optimizer_decompose.zero_grad() decompose_loss.backward() optimizer_decompose.step() decompose_model.eval() # output1 = torch.FloatTensor(decompose_output.cpu()) # compose_output = compose_model(output1.cuda()) # compose_loss = criterion(compose_output, batch_x) # optimizer_compose.zero_grad() # compose_loss.backward() # optimizer_compose.step() # compose_model.eval() fig = plt.figure() gs = GridSpec(nrows=2, ncols=4) highfreq1 = fig.add_subplot(gs[0, 0]) highfreq2 = fig.add_subplot(gs[0, 1]) highfreq3 = fig.add_subplot(gs[0, 2]) output1 = fig.add_subplot(gs[0, 3]) lowfreq1 = fig.add_subplot(gs[1, 0]) lowfreq2 = fig.add_subplot(gs[1, 1]) lowfreq3 = fig.add_subplot(gs[1, 2]) output2 = fig.add_subplot(gs[1, 3]) highfreq1.axis('off') highfreq2.axis('off') highfreq3.axis('off') output1.axis('off') lowfreq1.axis('off')
def spectrogramFigure(sigDat, specDat, oName=None): r"""Generate spectrogram figure. Generate figure showing the intensity normalized spectrogram accompanied by subplots that compare the intensities per unit time and frequency, obtained for the initial analytic signal, to the normalized marginals, computed for the spectrogram. Notes ----- Requires the functionality of pythons matplotlib. Scales the spectrogram data so that maximum intensity per time and frequency is unity. In the processing of the input data only the real part of the time domain signal Et on input is considered. Paramters --------- sigDat : tuple(array_like, array_like) The tuple consists of two arrays in the form (t,Et), where t contains the time samples and Et the corrsponding time domain signal. res : Results The spectrogram ``Results'' data structure with attributes ``tau'' the delay time samples for the spectrogram, ``w'' the angular frequency samples for the spectrogram, ``P'' the analytic signal spectrogram, ``IAE1'' the integrated absolute error of the estimated time marginal, and, ``IAE2'' the integrated absolute error of the estimated frequency marginal. oName : str Filename for output figure (default: 'figure0.eps'). """ t, Et = sigDat tDelay, wOpt, Ptw = specDat.tau, specDat.w, specDat.P tMin, tMax = tDelay[0], tDelay[-1] wMin, wMax = wOpt[0], wOpt[-1] if not oName: oName = 'figure0.png' import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.colors as col from matplotlib.gridspec import GridSpec, GridSpecFromSubplotSpec mm2inch = lambda x: x / 10. / 2.54 mpl.rcParams['xtick.direction'] = 'out' mpl.rcParams['ytick.direction'] = 'out' mpl.rcParams['xtick.labelsize'] = 6 mpl.rcParams['ytick.labelsize'] = 6 mpl.rcParams['axes.labelsize'] = 6 mpl.rcParams['font.family'] = 'sans-serif' mpl.rcParams['font.size'] = 6 mpl.rcParams['lines.linewidth'] = 1.0 mpl.rcParams['axes.linewidth'] = 0.5 mpl.rcParams['figure.figsize'] = mm2inch(90), mm2inch(2. / 3 * 90) mpl.rcParams["legend.handlelength"] = 1. mpl.rcParams["legend.handletextpad"] = 0.15 mpl.rcParams["legend.borderpad"] = 0.15 mpl.rcParams["legend.labelspacing"] = 0.15 cmap = mpl.cm.get_cmap('jet') fig = plt.figure() plt.subplots_adjust(left=0.12, bottom=0.17, right=0.98, top=0.96, wspace=0.08, hspace=0.06) gs = GridSpec(1, 1) gsSub = GridSpecFromSubplotSpec(4, 6, subplot_spec=gs[0, 0]) ax2 = plt.subplot(gsSub[1:, 0:5]) ax1 = plt.subplot(gsSub[0, 0:5], sharex=ax2) ax3 = plt.subplot(gsSub[1:, 5], sharey=ax2) def _setColorbar(im, refPos): """colorbar helper""" x0, y0, w, h = refPos.x0, refPos.y0, refPos.width, refPos.height cax = fig.add_axes([x0 + 0.02 * w, y0 + 0.64 * h, 0.02 * w, 0.25 * h]) cbar = fig.colorbar( im, cax=cax, ticks=[1e-8, 1e-7, 1e-6, 1e-5, 1e-4, 1e-3, 1e-2, 1e-1], orientation='vertical') cbar.outline.set_color('white') cbar.ax.tick_params(color='white', labelcolor='white', right=True, direction='in', labelright=True, labelleft=False, left=False, length=2.) cbar.set_ticks((1e-7, 1e-5, 1e-3, 1e-1)) def _setKey(ax, lns): """key helper""" labs = [l.get_label() for l in lns] lg = ax.legend(lns, labs, title=r"", loc=2, fontsize=6) lg = ax.legend_ lg.get_frame().set_linewidth(0.5) def _fft(t, Xt): r"""Scaled Fourier transform.""" return (t[1] - t[0]) * nfft.fft(Xt) / np.sqrt(2. * np.pi) def _ifft(w, Xw): r"""Scaled inverse Fourier transform.""" return (w[1] - w[0]) * nfft.ifft(Xw) / np.sqrt(2. * np.pi) * w.size # TOP SUBFIGURE: ########################################################################## # COMPARISON OF INTENSITY PER UNIT TIME (ORIGINAL DATA) AND TIME MARGINAL (SPECTROGRAM) ### normEt2 = 1. / np.trapz(np.abs(Et)**2, x=t) l1 = ax1.semilogy(t, np.abs(Et)**2 * normEt2, color='gray', label=r"$|\mathcal{E}(\tau)|^2$") P1 = np.trapz(Ptw, x=wOpt, axis=0) normP1 = 1. / np.trapz(P1, x=tDelay) l2 = ax1.semilogy(tDelay, P1 * normP1, color='black', label=r"$\mathsf{P}_1(\tau)$") _setKey(ax1, l1 + l2) ax1.set_ylim(1e-7, 2e-2) ax1.set_xlim(tMin, tMax) ax1.set_yticks((1e-6, 1e-4, 1e-2)) ax1.xaxis.set_ticks_position('bottom') ax1.yaxis.set_ticks_position('left') ax1.tick_params(axis='y', length=2., direction='in') ax1.tick_params(axis='x', length=2., direction='in', labelbottom='off') # RIGHT SUBFIGURE: ######################################################################## # COMPARISON OF INTENSITY PER UNIT FREQUENCY (ORIGINAL DATA) AND FREQUENCY MARGINAL ####### w = nfft.fftfreq(Et.size, d=t[1] - t[0]) * 2 * np.pi Ew = _fft(t, np.real(Et)) Ew[1:Ew.size / 2] *= 2 Ew[Ew.size / 2 + 1:] = 0 normEw = 1. / np.trapz(np.abs(Ew)**2, x=w) l1 = ax3.semilogx(np.abs(Ew)**2 * normEw, w, color='gray', label=r"$|\hat{\mathcal{E}}(\omega)|^2$") P2 = np.trapz(Ptw, x=tDelay, axis=-1) normP2 = 1. / np.trapz(P2, x=wOpt) l2 = ax3.semilogx(P2 * normP2, wOpt, color='black', label=r"$\mathsf{P}_2(\omega)$") _setKey(ax3, l1 + l2) ax3.set_ylim(wMin, wMax) ax3.set_xlim(5e-5, 20) ax3.set_xticks((1e-4, 1e-2, 1e0)) ax3.xaxis.set_ticks_position('bottom') ax3.yaxis.set_ticks_position('left') ax3.tick_params(axis='y', length=2., direction='in', labelleft='off') ax3.tick_params(axis='x', length=2., direction='in') # CENTER FIGURE: SPECTROGRAM DATA ########################################################## I = Ptw[:-1, :-1] / Ptw.max() imA = ax2.pcolorfast(tDelay, wOpt, I, norm=col.LogNorm(vmin=1e-5 * I.max(), vmax=I.max()), cmap=cmap) _setColorbar(imA, ax2.get_position()) ax2.set_xlim(tMin, tMax) ax2.set_ylim(wMin, wMax) ax2.xaxis.set_ticks_position('bottom') ax2.yaxis.set_ticks_position('left') ax2.tick_params(axis='y', length=2., direction='in', color='white') ax2.tick_params(axis='x', length=2., direction='in', color='white') ax2.set_xlabel(r"Delay $\tau\,\mathrm{(fs)}$") ax2.set_ylabel(r"Angular frequency $\omega\,\mathrm{(rad/fs)}$") ax2.text(0.02, 0.975, r"$P_S(\tau,\omega)$", color='white', horizontalalignment='left', verticalalignment='top', transform=ax2.transAxes, fontweight='heavy') plt.savefig(oName, dpi=800) plt.close()
def __init__(self, fig, *args, **kwargs): """ Parameters ---------- fig : `matplotlib.figure.Figure` *args : tuple (*nrows*, *ncols*, *index*) or int The array of subplots in the figure has dimensions ``(nrows, ncols)``, and *index* is the index of the subplot being created. *index* starts at 1 in the upper left corner and increases to the right. If *nrows*, *ncols*, and *index* are all single digit numbers, then *args* can be passed as a single 3-digit number (e.g. 234 for (2, 3, 4)). """ self.figure = fig if len(args) == 1: if isinstance(args[0], SubplotSpec): self._subplotspec = args[0] else: try: s = str(int(args[0])) rows, cols, num = map(int, s) except ValueError: raise ValueError('Single argument to subplot must be ' 'a 3-digit integer') self._subplotspec = GridSpec(rows, cols, figure=self.figure)[num - 1] # num - 1 for converting from MATLAB to python indexing elif len(args) == 3: rows, cols, num = args rows = int(rows) cols = int(cols) if rows <= 0: raise ValueError(f'Number of rows must be > 0, not {rows}') if cols <= 0: raise ValueError(f'Number of columns must be > 0, not {cols}') if isinstance(num, tuple) and len(num) == 2: num = [int(n) for n in num] self._subplotspec = GridSpec( rows, cols, figure=self.figure)[(num[0] - 1):num[1]] else: if num < 1 or num > rows * cols: raise ValueError( f"num must be 1 <= num <= {rows*cols}, not {num}") self._subplotspec = GridSpec(rows, cols, figure=self.figure)[int(num) - 1] # num - 1 for converting from MATLAB to python indexing else: raise ValueError(f'Illegal argument(s) to subplot: {args}') self.update_params() # _axes_class is set in the subplot_class_factory self._axes_class.__init__(self, fig, self.figbox, **kwargs) # add a layout box to this, for both the full axis, and the poss # of the axis. We need both because the axes may become smaller # due to parasitic axes and hence no longer fill the subplotspec. if self._subplotspec._layoutbox is None: self._layoutbox = None self._poslayoutbox = None else: name = self._subplotspec._layoutbox.name + '.ax' name = name + layoutbox.seq_id() self._layoutbox = layoutbox.LayoutBox( parent=self._subplotspec._layoutbox, name=name, artist=self) self._poslayoutbox = layoutbox.LayoutBox( parent=self._layoutbox, name=self._layoutbox.name + '.pos', pos=True, subplot=True, artist=self)
def plot_abide_stripplots( inputs, figsize=(15, 2), out_file=None, rating_label="rater_1", dpi=100 ): import seaborn as sn from ..classifier.helper import FEATURE_NORM from ..classifier.data import read_dataset from ..classifier.sklearn.preprocessing import BatchRobustScaler sn.set(style="whitegrid") mdata = [] pp_cols = [] for X, Y, sitename in inputs: sitedata, cols = read_dataset( X, Y, rate_label=rating_label, binarize=False, site_name=sitename ) sitedata["database"] = [sitename] * len(sitedata) if sitename == "DS030": sitedata["site"] = [sitename] * len(sitedata) mdata.append(sitedata) pp_cols.append(cols) mdata = pd.concat(mdata) pp_cols = pp_cols[0] for col in mdata.columns.ravel().tolist(): if col.startswith("rater_") and col != rating_label: del mdata[col] mdata = mdata.loc[mdata[rating_label].notnull()] for col in ["size_x", "size_y", "size_z", "spacing_x", "spacing_y", "spacing_z"]: del mdata[col] try: pp_cols.remove(col) except ValueError: pass zscored = BatchRobustScaler(by="site", columns=FEATURE_NORM).fit_transform(mdata) sites = list(set(mdata.site.values.ravel())) nsites = len(sites) # palette = ['dodgerblue', 'darkorange'] palette = ["limegreen", "tomato"] if len(set(mdata[[rating_label]].values.ravel().tolist())) == 3: palette = ["tomato", "gold", "limegreen"] # pp_cols = pp_cols[:5] nrows = len(pp_cols) fig = plt.figure(figsize=(figsize[0], figsize[1] * nrows)) # ncols = 2 * (nsites - 1) + 2 gs = GridSpec(nrows, 4, wspace=0.02) gs.set_width_ratios([nsites, len(inputs), len(inputs), nsites]) for i, colname in enumerate(pp_cols): ax_nzs = plt.subplot(gs[i, 0]) axg_nzs = plt.subplot(gs[i, 1]) axg_zsc = plt.subplot(gs[i, 2]) ax_zsc = plt.subplot(gs[i, 3]) # plots sn.stripplot( x="site", y=colname, data=mdata, hue=rating_label, jitter=0.18, alpha=0.6, split=True, palette=palette, ax=ax_nzs, ) sn.stripplot( x="site", y=colname, data=zscored, hue=rating_label, jitter=0.18, alpha=0.6, split=True, palette=palette, ax=ax_zsc, ) sn.stripplot( x="database", y=colname, data=mdata, hue=rating_label, jitter=0.18, alpha=0.6, split=True, palette=palette, ax=axg_nzs, ) sn.stripplot( x="database", y=colname, data=zscored, hue=rating_label, jitter=0.18, alpha=0.6, split=True, palette=palette, ax=axg_zsc, ) ax_nzs.legend_.remove() ax_zsc.legend_.remove() axg_nzs.legend_.remove() axg_zsc.legend_.remove() if i == nrows - 1: ax_nzs.set_xticklabels(ax_nzs.xaxis.get_majorticklabels(), rotation=80) ax_zsc.set_xticklabels(ax_zsc.xaxis.get_majorticklabels(), rotation=80) axg_nzs.set_xticklabels(axg_nzs.xaxis.get_majorticklabels(), rotation=80) axg_zsc.set_xticklabels(axg_zsc.xaxis.get_majorticklabels(), rotation=80) else: ax_nzs.set_xticklabels([]) ax_zsc.set_xticklabels([]) axg_nzs.set_xticklabels([]) axg_zsc.set_xticklabels([]) ax_nzs.set_xlabel("", visible=False) ax_zsc.set_xlabel("", visible=False) ax_zsc.set_ylabel("", visible=False) ax_zsc.yaxis.tick_right() axg_nzs.set_yticklabels([]) axg_nzs.set_xlabel("", visible=False) axg_nzs.set_ylabel("", visible=False) axg_zsc.set_yticklabels([]) axg_zsc.set_xlabel("", visible=False) axg_zsc.set_ylabel("", visible=False) for yt in ax_nzs.yaxis.get_major_ticks()[1:-1]: yt.label1.set_visible(False) for yt in axg_nzs.yaxis.get_major_ticks()[1:-1]: yt.label1.set_visible(False) for yt in zip( ax_zsc.yaxis.get_majorticklabels(), axg_zsc.yaxis.get_majorticklabels() ): yt[0].set_visible(False) yt[1].set_visible(False) if out_file is None: out_file = "stripplot.svg" fname, ext = op.splitext(out_file) if ext[1:] not in ["pdf", "svg", "png"]: ext = ".svg" out_file = fname + ".svg" fig.savefig( op.abspath(out_file), format=ext[1:], bbox_inches="tight", pad_inches=0, dpi=dpi ) return fig
inputT = [T0, 1.0, 1.001, 3.0, 3.001, 4.0, 4.001, 6.0, 6.001, TN] inputF = [0.0, 0.0, 1.0, 1.0, 0.0, 0.0, -2.0, -2.0, 0.0, 0.0] x = cart.simulate(x_init, t, inputT, inputF) with plt.style.context("dark_background"): color1 = plt.rcParams['axes.prop_cycle'].by_key()['color'][0] color2 = plt.rcParams['axes.prop_cycle'].by_key()['color'][1] color3 = plt.rcParams['axes.prop_cycle'].by_key()['color'][2] color4 = plt.rcParams['axes.prop_cycle'].by_key()['color'][3] color5 = plt.rcParams['axes.prop_cycle'].by_key()['color'][4] color6 = plt.rcParams['axes.prop_cycle'].by_key()['color'][5] fig = plt.figure(figsize=(10, 5)) gs = GridSpec(3, 2, figure=fig) ax0 = fig.add_subplot(gs[:, 0]) ax1 = fig.add_subplot(gs[0, 1]) ax11 = ax1.twinx() ax2 = fig.add_subplot(gs[1, 1]) ax21 = ax2.twinx() ax3 = fig.add_subplot(gs[2, 1]) points = np.full(5, None) ax1.plot(t, x[:, 0], color=color1) ax1.set_ylabel(r'x (m)', color=color1) ax11.plot(t, x[:, 1], color=color2) ax11.set_ylabel(r'$\dot{x}$ ($\frac{m}{s}$)', color=color2)
num_inputs, shuffle=shuffle): return ret x_batch, y_batch = get_mini_batch(x_test, y_test) output, other_recordings = run_snn(x_batch.to_dense()) mem_rec, spk_rec = other_recordings fig = plt.figure(dpi=100) plot_voltage_traces(mem_rec, spk_rec) plt.show() plot_voltage_traces(output) plt.show() num_plt = 4 gs = GridSpec(1, num_plt) fig = plt.figure(figsize=(7, 3), dpi=150) for i in range(num_plt): plt.subplot(gs[i]) plt.imshow(spk_rec[i].detach().cpu().numpy().T, cmap=plt.cm.gray_r, origin="lower") if i == 0: plt.xlabel("Time") plt.ylabel("Units") sns.despine() plt.show()
def render(car=None, ped=None, noise=None, ped_obs=None, gif=False): if gif: return else: fig = plt.figure(constrained_layout=True) if noise is not None and (car is not None or ped is not None or ped_obs is not None): # Plotting Noise and trajectories gs = GridSpec(4, 2, figure=fig) ax1 = fig.add_subplot(gs[:, 0]) ax2 = fig.add_subplot(gs[0, 1]) ax3 = fig.add_subplot(gs[1, 1]) ax4 = fig.add_subplot(gs[2, 1]) ax5 = fig.add_subplot(gs[3, 1]) ax1.set_title( 'Car, Actual Pedestrian, and Observed Pedestrian Trajectories') elif noise is not None: # Only plotting noise gs = GridSpec(4, 1, figure=fig) ax2 = fig.add_subplot(gs[0, 0]) ax3 = fig.add_subplot(gs[1, 0]) ax4 = fig.add_subplot(gs[2, 0]) ax5 = fig.add_subplot(gs[3, 0]) else: # Only plotting trajectories gs = GridSpec(1, 1, figure=fig) ax1 = fig.add_subplot(gs[0, 0]) ax1.set_title( 'Car, Actual Pedestrian, and Observed Pedestrian Trajectories') if noise is not None: axs = [ax2, ax3, ax4, ax5] ax_titles = [ 'Noise: Pedestrian X Velocity', 'Noise: Pedestrian Y Velocity', 'Noise: Pedestrian X Position', 'Noise: Pedestrian Y Position' ] x = np.arange(noise.shape[0] + 2) for idx, ax in enumerate(axs): y = np.concatenate(([0], noise[:, idx], [0])) ax.step(x, y, color='black', where='pre') ax.axhline(0, color='black', lw=2) ycopy = y.copy() ycopy[y < 0] = 0 ax.fill_between(x, ycopy, facecolor='green', step='pre') ycopy = y.copy() ycopy[y >= 0] = 0 ax.fill_between(x, ycopy, facecolor='red', step='pre') ax.set_title(ax_titles[idx]) if ped is not None: ax1.quiver(ped[:, 2], ped[:, 3], ped[:, 0], ped[:, 1], scale=50) ped_final_pos = ped[-1, 2:] rad = 0.125 circle = Circle((ped_final_pos[0], ped_final_pos[1]), radius=rad) pc = PatchCollection([circle], facecolor='blue', alpha=0.2, edgecolor='blue') ax1.add_collection(pc) if ped_obs is not None: ax1.quiver(ped_obs[:, 2], ped_obs[:, 3], ped_obs[:, 0], ped_obs[:, 1], scale=50, color='gray') if car is not None: ax1.quiver(car[:, 2], car[:, 3], car[:, 0], car[:, 1], scale=500) car_final_pos = car[-1, 2:] x_dist = 2.5 y_dist = 1.4 rect = Rectangle( (car_final_pos[0] - x_dist / 2, car_final_pos[1] - y_dist / 2), x_dist, y_dist) pc = PatchCollection([rect], facecolor='red', alpha=0.2, edgecolor='red') ax1.add_collection(pc) plt.show() return
def plot_figure5(): fig = plt.figure(figsize=(8, 9)) gs = GridSpec(nrows=3, ncols=1) gs.update(wspace=0.3) data_name_1_a = './Br3Ca1Cs1/scfph/kapa_300/kappa_spec_culm.dat' data_name_2_a = './Br3Ca1Cs1/scfph/kapa_100/kappa_spec_culm.dat' ax1 = plt.subplot(gs[0]) frequency1_a, kl1_a, kl_cumulative1_a = read_cumulative_kappa( data_name_1_a) frequency2_a, kl2_a, kl_cumulative2_a = read_cumulative_kappa( data_name_2_a) data_name_1_b = './BrCsSn/scfph/kapa_300/kappa_spec_culm.dat' data_name_2_b = './BrCsSn/phonons/kappa_spec_culm.dat' ax2 = plt.subplot(gs[1]) frequency1_b, kl1_b, kl_cumulative1_b = read_cumulative_kappa( data_name_1_b) frequency2_b, kl2_b, kl_cumulative2_b = read_cumulative_kappa( data_name_2_b) data_name_1_c = './Br3Cd1Cs1/scfph2/kapa_300/kappa_spec_culm.dat' data_name_2_c = './Br3Cd1Cs1/phonons/kappa_spec_culm.dat' ax3 = plt.subplot(gs[2]) frequency1_c, kl1_c, kl_cumulative1_c = read_cumulative_kappa( data_name_1_c) frequency2_c, kl2_c, kl_cumulative2_c = read_cumulative_kappa( data_name_2_c) plot_single_figure(ax1, frequency1=frequency1_a, kl=kl1_a, frequency2=frequency2_a, kl2=kl2_a, xmax=32, ymax1=5, ymax2=2.5, kl_cumulative1=kl_cumulative1_a, kl_cumulative2=kl_cumulative2_a, x1_text=0.7, y1_text=0.4, x2_text=0.74, y2_text=0.8, s1='300 K', s2='100 K', text_name='CsCaBr3 (SCP+BTE)') plot_single_figure(ax2, frequency1=frequency1_b, kl=kl1_b, frequency2=frequency2_b, kl2=kl2_b, xmax=23, ymax1=3, ymax2=1.2, kl_cumulative1=kl_cumulative1_b, kl_cumulative2=kl_cumulative2_b, x1_text=0.6, y1_text=0.78, x2_text=0.6, y2_text=0.5, s1='SCP + BTE', s2='HP + BTE', text_name='CsSnBr3 (300 K)') plot_single_figure(ax3, frequency1=frequency1_c, kl=kl1_c, frequency2=frequency2_c, kl2=kl2_c, xmax=23, ymax1=3, ymax2=0.8, kl_cumulative1=kl_cumulative1_c, kl_cumulative2=kl_cumulative2_c, x1_text=0.7, y1_text=0.78, x2_text=0.6, y2_text=0.2, s1='SCP + BTE', s2='HP + BTE', text_name='CsCdBr3 (300 K)', xlabel='Frequency (meV)') plt.tight_layout() fig_name = './figure5.eps' if fig_name: plt.savefig(fig_name, dpi=500) plt.show()
def change_geometry(self, numrows, numcols, num): """Change subplot geometry, e.g., from (1, 1, 1) to (2, 2, 3).""" self._subplotspec = GridSpec(numrows, numcols)[num-1] self.update_params() self.set_position(self.figbox)
def __init__(self, fig, *args, **kwargs): """ *fig* is a :class:`matplotlib.figure.Figure` instance. *args* is the tuple (*numRows*, *numCols*, *plotNum*), where the array of subplots in the figure has dimensions *numRows*, *numCols*, and where *plotNum* is the number of the subplot being created. *plotNum* starts at 1 in the upper left corner and increases to the right. If *numRows* <= *numCols* <= *plotNum* < 10, *args* can be the decimal integer *numRows* * 100 + *numCols* * 10 + *plotNum*. """ self.figure = fig if len(args) == 1: if isinstance(args[0], SubplotSpec): self._subplotspec = args[0] else: try: s = str(int(args[0])) rows, cols, num = map(int, s) except ValueError: raise ValueError('Single argument to subplot must be ' 'a 3-digit integer') self._subplotspec = GridSpec(rows, cols, figure=self.figure)[num - 1] # num - 1 for converting from MATLAB to python indexing elif len(args) == 3: rows, cols, num = args rows = int(rows) cols = int(cols) if isinstance(num, tuple) and len(num) == 2: num = [int(n) for n in num] self._subplotspec = GridSpec( rows, cols, figure=self.figure)[(num[0] - 1):num[1]] else: if num < 1 or num > rows * cols: raise ValueError( ("num must be 1 <= num <= {maxn}, not {num}").format( maxn=rows * cols, num=num)) self._subplotspec = GridSpec(rows, cols, figure=self.figure)[int(num) - 1] # num - 1 for converting from MATLAB to python indexing else: raise ValueError('Illegal argument(s) to subplot: %s' % (args, )) self.update_params() # _axes_class is set in the subplot_class_factory self._axes_class.__init__(self, fig, self.figbox, **kwargs) # add a layout box to this, for both the full axis, and the poss # of the axis. We need both because the axes may become smaller # due to parasitic axes and hence no longer fill the subplotspec. if self._subplotspec._layoutbox is None: self._layoutbox = None self._poslayoutbox = None else: name = self._subplotspec._layoutbox.name + '.ax' name = name + layoutbox.seq_id() self._layoutbox = layoutbox.LayoutBox( parent=self._subplotspec._layoutbox, name=name, artist=self) self._poslayoutbox = layoutbox.LayoutBox( parent=self._layoutbox, name=self._layoutbox.name + '.pos', pos=True, subplot=True, artist=self)
def h_top_legend(style=[]): """A figure with three sets of axes horizontally and a legend. Arguments --------- style : str or array, optional style sheet(s). Default: tp. Returns ------- figure figure. axes axes. function function to add a pre-posistioned legend. """ if isinstance(style, str): style = [style] default_style.extend(style) plt.style.use(default_style) fig = plt.figure(figsize=(27 / 2.54, 9.1 / 2.54)) grid = GridSpec(1, 3) ax = [ fig.add_subplot(grid[0, 0]), fig.add_subplot(grid[0, 1]), fig.add_subplot(grid[0, 2]) ] plt.subplots_adjust(left=0.06, right=0.98, bottom=0.11, top=0.87, wspace=0.3) def add_legend(custom=False, *args, **kwargs): """Adds a pre-positioned legend. Accepts all normal plt.legend inputs (title etc.). Arguments --------- custom : bool, optional enable manual editing of handles and labels arguments. Default: False. *args, **kwargs passed to ax.legend. Returns ------- legend legend. """ if 'ncol' not in kwargs: if 'handles' in kwargs: kwargs['ncol'] = len(kwargs['handles']) elif 'labels' in kwargs: kwargs['ncol'] = len(kwargs['labels']) else: kwargs['ncol'] = len(ax[1].get_legend_handles_labels()[0]) if custom: legend = ax[1].legend(loc="lower center", bbox_to_anchor=(0.5, 1), *args, **kwargs) else: handles, labels = tp.axes.legend.consolidate(ax) legend = ax[1].legend(loc="lower center", bbox_to_anchor=(0.5, 1), handles=handles, labels=labels, *args, **kwargs) return legend return fig, ax, add_legend