def comp_crossshore_diff(data_list, title, cases, savename): ## Settings sns.set_palette(sns.color_palette("muted")) ## Parameters savename = savename.replace(".jpg", "") + "/cross_diff" _yslices = np.array([7.56]) * 1e6 _tslice = 1.6e5 ## Figure fig, ax = plt.subplots(_yslices.size, 1) fig.set_size_inches(FIGSIZE_NORMAL) fig.set_dpi(FIG_DPI) fig.set_tight_layout(True) fig.suptitle(f"{title}\nChange in Cross-shore Profile") if not isinstance(ax, np.ndarray): ax = np.array([ax]) ## Subplots for i in range(ax.size): _ax = ax[i] _ax.axhline(color="black", linewidth=1) _ax.axvline(color="black", linewidth=1) _ax.grid() _ax.set_xlim([0, 600]) _ax.set_ylim([-0.2, 0.2]) _ax.set_title(f"$y = {_yslices[i]/1000.}$km") _ax.set_ylabel("$\\Delta SSE$ [m]") if i == ax.size: _ax.set_xlabel("x [km]") reference = data_list[0]["wl"].interp(t=fu.to_timestr(_tslice), y=_yslices[i]) for _j in range(len(data_list) - 1): j = _j + 1 data = data_list[j] # Plot data plt.plot( data["x"] / 1000., data["wl"].interp(t=fu.to_timestr(_tslice), y=_yslices[i]) - reference, color=f"C{j}", label=f"Case {cases[j]:02.0f}") _ax.legend() fig.savefig(savename, bbox_inches="tight", dpi=FIG_DPI) print(f"Saved figure as '{savename}'") return
def comp_alongshore_diff(data_list, title, cases, savename): ## Settings sns.set_palette(sns.color_palette("muted")) ## Parameters savename = savename.replace(".jpg", "") + "/along_diff" _ylims = np.array([[0, 4], [1, 6], [2, 8], [3, 10]]) * 1e3 _times = [4e4, 8e4, 12e4, 16e4] ## Figure fig, ax = plt.subplots(2, 2, sharex=False, sharey=True) fig.set_size_inches(FIGSIZE_NORMAL) fig.set_dpi(FIG_DPI) fig.set_tight_layout(True) fig.suptitle(f"{title}\nChange in Along-shore Profile") # Subplots for i in range(ax.size): _ax = ax[i // 2, i % 2] # select subplot _ax.grid() _ax.set_xlim(_ylims[i]) _ax.set_ylim([-0.2, 0.2]) _ax.set_title(f"$t = {_times[i]:0.0f}$s") _ax.axhline(color="black", linewidth=1) _ax.axvline(color="black", linewidth=1) if i // 2: _ax.set_xlabel("$y$ [km]") if not i % 2: _ax.set_ylabel("$\\Delta SSE$ [m]") reference = data_list[0]["wl"].interp(t=fu.to_timestr(_times[i]), x=10e3) for _j in range(len(data_list) - 1): j = _j + 1 data = data_list[j] _ax.plot(data["y"] / 1000., data["wl"].interp(t=fu.to_timestr(_times[i]), x=10e3) - reference, color=f"C{j}", label=f"Case {cases[j]:02.0f}") if i == 0: _ax.legend() fig.savefig(savename, bbox_inches="tight", dpi=FIG_DPI) print(f"Saved figure as '{savename}'") return
def comp_crossshore(data_list, title, cases, savename): ## Settings sns.set_palette(sns.color_palette("muted")) ## Parameters savename = savename.replace(".jpg", "") + "/cross" _yslices = np.array([7.56]) * 1e6 _tslice = 1.6e5 ## Figure fig, ax = plt.subplots(_yslices.size, 1) fig.set_size_inches(FIGSIZE_NORMAL) fig.set_dpi(FIG_DPI) fig.set_tight_layout(True) fig.suptitle(f"{title}\nCross-shore Profile of Sea Surface Elevation") if not isinstance(ax, np.ndarray): ax = np.array([ax]) ## Subplots for i in range(ax.size): _ax = ax[i] _ax.axhline(color="black", linewidth=1) _ax.axvline(color="black", linewidth=1) _ax.grid() _ax.set_xlim([0, 600]) _ax.set_ylim([0, 0.9]) _ax.set_title(f"$y = {_yslices[i]/1000.}$km") _ax.set_ylabel("$SSE$ [m]") if i == ax.size: _ax.set_xlabel("x [km]") for j in range(len(data_list)): data = data_list[j] # Compute best fit parameters k0, y0 = fa.compute_decay_parameter(data, _yslices[i], _tslice) # Plot data plt.plot(data["x"] / 1000., data["wl"].interp(t=fu.to_timestr(_tslice), y=_yslices[i]), color=f"C{j}", label=f"Case {cases[j]:02.0f}") # Plot best fit plt.plot(data["x"] / 1000., fa.exp_decay(data["x"], k0, y0), color=f"C{j}", linestyle="--", label=f"Best fit: $1/k_0 = {1./k0/1000.:0.1f}$km") _ax.legend() fig.savefig(savename, bbox_inches="tight", dpi=FIG_DPI) print(f"Saved figure as '{savename}'") return
def compute_decay_parameter(data, y, t): """"Computes the decay parameter and scaling parameter for data at given y and t """ wl = data["wl"].interp(t=fu.to_timestr(t), y=y) if np.all(np.isnan(wl)): return np.nan, 0 popt, _ = curve_fit( exp_decay, # f data["x"], # xdata wl, # ydata p0=[1. / 100000., 1.], # p0 ) k0, y0 = popt return k0, y0
def vis_contour(data, t, saveloc=None, keep_open=False, variable="wl", xlims=None, ylims=None): ## Check input if variable in ["wl"]: cmap = cmo.cm.balance elif variable in ["u", "v"]: cmap = cmo.cm.delta else: raise ValueError(f"Excpected {variable=} to be 'wl', 'u' or 'v'") if np.isscalar(t): t_arr = np.array([t]) elif isinstance(t, list): t_arr = np.array(t) elif isinstance(t, (list, np.ndarray)): t_arr = t else: raise ValueError(f"{t=} is not an array, but {type(t)}") t_num = t_arr.size del t ## Paths if saveloc is None: saveloc = os.path.dirname(os.path.realpath(__file__)) + "/tests" if saveloc.endswith(".jpg"): saveloc.replace(".jpg", "") os.makedirs(saveloc, exist_ok=True) savename = saveloc + f"/contour_{variable}_n{t_num}_{np.mean(t_arr)/3600:0.0f}" ## Get parameters x = data["x"] y = data["y"] var = data[variable] x = x - x.min() var_max = float(np.nanmax([np.abs([var.max(), var.min()])])) var_min = -1. * var_max if xlims is None: xlims = [y.min() / 1000. / 10., y.max() / 1000.] if ylims is None: ylims = [0, 200] ## Figure fig, ax = plt.subplots(t_num, 1, squeeze=False, sharex=True) fig.set_size_inches(FIGSIZE_LONG) fig.set_dpi(FIG_DPI) # fig.set_tight_layout(True) ax = np.ravel(ax) norm = Normalize(var_min, var_max) im = cm.ScalarMappable(norm=norm, cmap=cmap) ## Subplots for i in range(t_num): ax[i].contourf(y / 1000, x / 1000, var.interp(t=fu.to_timestr(t_arr[i])).T, 100, cmap=cmap, norm=norm, vmin=var_min, vmax=var_max) ax[i].set_ylabel("$x$ [km]") # ax[i].set_title(f"$t = {t_arr[i] / 3600:0.1f}$h") ax[i].annotate(f"$t = {t_arr[i] / 3600:0.1f}$h", xy=(0.99, 0.98), xycoords="axes fraction", ha="right", va="top") ax[i].set_xlim(xlims) ax[i].set_ylim(ylims) ax[-1].set_xlabel("$y$ [km]") fig.colorbar(im, ax=ax.ravel().tolist(), label="Sea Surface Elevation [m]", aspect=50) ## Save figure fig.savefig(savename, bbox_inches="tight", dpi=FIG_DPI, pil_kwargs={ "optimize": True, "compress_level": 9 }) print(f"Saved figure {savename}") ## End if not keep_open: plt.close("all")
def vis_crossshore(data, y=1e5, t=3600, saveloc=None, keep_open=False): ## Check input if np.isscalar(y): y_list = np.array([y]) elif isinstance(y, (list, np.ndarray)): y_list = np.array(y) else: raise ValueError(f"{y=} is not a number or array_like") if np.isscalar(t): t_list = np.array([t]) elif isinstance(t, (list, np.ndarray)): t_list = np.array(t) else: raise ValueError(f"{t=} is not a number or array_like") del t, y y_num = y_list.size t_num = t_list.size if (t_num == 1) and (y_num == 1): figsize = FIGSIZE_NORMAL elif (t_num == 1) and (y_num > 1): figsize = FIGSIZE_WIDE elif (t_num > 1) and (y_num == 1): figsize = FIGSIZE_HIGH elif (t_num > 1) and (y_num > 1): figsize = FIGSIZE_SQUARE else: raise ValueError( f"Error in determining figsize for {y_num=} and {t_num=}") ## Paths if saveloc is None: saveloc = os.path.dirname(os.path.realpath(__file__)) + "/tests" if saveloc.endswith(".jpg"): saveloc.replace(".jpg", "") os.makedirs(saveloc, exist_ok=True) savename = saveloc + "/cross_shore_" if y_num == 1: savename += f"y{y_list[0]/1000:0.0f}_" else: savename += f"yn{y_num}_" if t_num == 1: savename += f"t{t_list[0]/3600:0.0f}" else: savename += f"tn{t_num}" ## Figure fig, ax = plt.subplots(t_num, y_num, squeeze=False, sharex=True, sharey=True) fig.set_size_inches(figsize) fig.set_dpi(FIG_DPI) fig.set_tight_layout(True) for i in range(t_num): for j in range(y_num): # Make best fit k0, y0 = fa.compute_decay_parameter(data, y_list[j], t_list[i]) wl_model = fa.exp_decay(data["x"], k0, y0) # Plot data ax[i, j].plot(data["x"] / 1000., data["wl"].interp(y=y_list[j], t=fu.to_timestr(t_list[i])), color="C0", label="Waterlevel") # Plot best fit ax[i, j].plot(data["x"] / 1000., wl_model, color="C0", linestyle="--", label=f"Best fit with $1/k0={1./k0/1000.:0.1f}$ km") # ax[i, j].axhline(color="black", linewidth=1) ax[i, j].legend() ax[i, j].set_xlim(0, data["x"].max() / 1000.) ax[i, j].set_title( f"$y={y_list[j]/1000:0.0f}$ km; $t={t_list[i]/3600:0.1f}$ hours" ) ax[i, j].grid() for i in range(t_num): ax[i, 0].set_ylabel("$SSE$ [m]") for j in range(y_num): ax[-1, j].set_xlabel("$x$ [km]") fig.savefig(savename, bbox_inches="tight", dpi=FIG_DPI, pil_kwargs={ "optimize": True, "compress_level": 9 }) print(f"Saved figure {savename}") ## End if not keep_open: plt.close("all")
def vis_alongshore(data, t=3600, x=1e4, saveloc=None, keep_open=False): ## Check input if not np.isscalar(x): raise ValueError(f"{x=} is not a number") if np.isscalar(t): t_list = np.array([t]) elif isinstance(t, (list, np.array)): t_list = np.array(t) else: raise ValueError(f"{t=} is not a number or array_like") t_num = t_list.size del t if t_num < 3: figsize = FIGSIZE_NORMAL else: figsize = FIGSIZE_HIGH ## Paths if saveloc is None: saveloc = os.path.dirname(os.path.realpath(__file__)) + "/tests" if saveloc.endswith(".jpg"): saveloc.replace(".jpg", "") os.makedirs(saveloc, exist_ok=True) savename = saveloc + f"/along_shore_x{x/1000:0.0f}_tn{t_num}" ## Extract data y = data["y"] wl = data["wl"].interp(t=fu.to_timestr(t_list), x=x) ## Figure fig, ax = plt.subplots(t_num, 1, squeeze=False, sharex=True) fig.set_size_inches(figsize) fig.set_dpi(FIG_DPI) fig.set_tight_layout(True) ax = np.ravel(ax) for i in range(t_num): ax[i].plot(y / 1000., wl[i]) ax[i].axhline(color="black", linewidth=1) ax[i].set_xlim(0, y.max() / 1000.) ax[i].set_ylabel("$SSE$ [m]") ax[i].set_title( f"$x={x/1000:0.0f}$ km and $t={t_list[i]/3600:0.1f}$ hours") ax[i].grid() ax[-1].set_xlabel("$y$ [km]") fig.savefig(savename, bbox_inches="tight", dpi=FIG_DPI, pil_kwargs={ "optimize": True, "compress_level": 9 }) print(f"Saved figure {savename}") ## End if not keep_open: plt.close("all")
### Figure pressure print("Figure: pressure") plot_times = [4e4, 8e4, 12e4, 16e4] try: fig, ax = plt.subplots(2, 2, sharex=True, sharey=True) fig.set_size_inches(FIGSIZE_SQUARE) fig.set_dpi(FIG_DPI) fig.suptitle("Pressure distribution [Pa]") fig.set_tight_layout(True) for i in range(4): _ax = ax[i // 2, i % 2] im = _ax.contourf(x / 1000, y / 1000, p.interp(t=fu.to_timestr(plot_times[i])), vmin=0, vmax=2000) _ax.set_xlim([0, 300]) _ax.set_ylim([0, y.max() / 1000]) _ax.set_title(f"$t = {plot_times[i] : 0.0f}$s") if i // 2: _ax.set_xlabel("$x$ [km]") if not i % 2: _ax.set_ylabel("$y$ [km]") fig.colorbar(im, ax=_ax) # _ax.axhline(7.56e3, linestyle="--", color="gray", linewidth=1) # _ax.axvline(10, linestyle="--", color="gray", linewidth=1) # _ax.axvline(100, linestyle="--", color="gray", linewidth=1) # _ax.axvline(200, linestyle="--", color="gray", linewidth=1)