def test_forcing_output(self): sim = self.sim sim.time_stepping.start() sim.state.compute("rot_fft") sim.state.compute("rot_fft") with self.assertRaises(ValueError): sim.state.compute("abc") sim.state.compute("abc", RAISE_ERROR=False) ux_fft = sim.state.compute("ux_fft") uy_fft = sim.state.compute("uy_fft") sim.state.init_statespect_from(ux_fft=ux_fft) sim.state.init_statespect_from(uy_fft=uy_fft) sim.output.compute_enstrophy() if mpi.nb_proc == 1: plt.close("all") sim.output.frequency_spectra.compute_frequency_spectra() sim.output.plot_summary() sim.output.spectra.plot2d() sim.output.spatial_means.plot_energy() sim.output.spatial_means.plot_dt_energy() sim.output.spatial_means.plot_energy_shear_modes() plt.close("all") sim.output.spatial_means.compute_time_means() sim.output.spatial_means.load_dataset() sim.output.spatial_means.time_first_saved() sim.output.spatial_means.time_last_saved() sim.output.spectra_multidim.plot() with self.assertRaises(ValueError): sim.state.get_var("test") sim2 = fls.load_sim_for_plot(sim.output.path_run) sim2.output spatio_temporal_spectra = sim2.output.spatio_temporal_spectra spatio_temporal_spectra.compute_frequency_spectra() spatio_temporal_spectra.print_info_frequency_spectra() spatio_temporal_spectra.plot_frequency_spectra_individual_mode( mode=(1, 1)) spatio_temporal_spectra.plot_kx_omega_cross_section() spatio_temporal_spectra.plot_kz_omega_cross_section() sim2.output.increments.load() sim2.output.increments.plot() sim2.output.increments.load_pdf_from_file() sim2.output.phys_fields.animate( "ux", dt_frame_in_sec=1e-6, dt_equations=0.3, repeat=False, clim=(-1, 1), save_file=False, numfig=1, ) sim2.output.phys_fields.plot() # `compute('q')` two times for better coverage... sim.state.get_var("q") sim.state.get_var("q") sim.state.get_var("div") path_run = sim.output.path_run if mpi.nb_proc > 1: path_run = mpi.comm.bcast(path_run) sim3 = fls.load_state_phys_file(path_run, modif_save_params=False) sim3.params.time_stepping.t_end += 0.2 sim3.time_stepping.start() if mpi.nb_proc == 1: sim3.output.phys_fields.animate( "ux", dt_frame_in_sec=1e-6, dt_equations=0.3, repeat=False, clim=(-1, 1), save_file=False, numfig=1, ) plt.close("all")
def plot_kz_omega_cross_section( self, path_file=None, field="ap_fft", ikx_plot=None, func_plot="pcolormesh", INSET_PLOT=True, ): # if ax_inset is not None: # D efine path dir as po six path path_dir = self.path_dir # If path_file does not exist. if not path_file: path_file = sorted((path_dir / "Spectrum").glob("spectrum*"))[-1] # Print path_file print(f"Path = {path_file}") # Load data with h5py.File(path_file, "r") as file: temp_spectrum_mean = file["spectrum"][...] omegas = file["omegas"][...] # Load simulation object sim = load_state_phys_file(path_dir.parent, merge_missing_params=True) # Compute kx_decimate and ky_decimate kx_decimate = sim.oper.kx[::sim.params.output.spatio_temporal_spectra. spatial_decimate] kz_decimate = sim.oper.ky[::sim.params.output.spatio_temporal_spectra. spatial_decimate] # Omegas omegas *= 2 * np.pi omegas *= 1 / (sim.params.N) #### PLOT OMEGA - KZ kzmin_plot = 0 kzmax_plot = 80 if kzmax_plot > sim.oper.kymax_dealiasing: kzmax_plot = sim.oper.kymax_dealiasing ikzmin_plot = np.argmin(abs(kz_decimate - kzmin_plot)) ikzmax_plot = np.argmin(abs(kz_decimate - kzmax_plot)) omega_max_plot = 0 omega_min_plot = -3 omegas = np.append(omegas, 0) imin_omegas_plot = np.argmin(abs(omegas - omega_min_plot)) - 1 kzs_grid, omegas_grid = np.meshgrid( kz_decimate[ikzmin_plot:ikzmax_plot], omegas[imin_omegas_plot:]) if not ikx_plot: ikx_plot = 1 # Parameters figure fig, ax = plt.subplots() ax.set_xlim(left=kzmin_plot, right=kzmax_plot - sim.oper.deltaky / 2) ax.set_ylim(top=omega_max_plot, bottom=omega_min_plot) ax.set_xlabel(r"$k_z$", fontsize=16) ax.set_ylabel(r"$\omega / N$", fontsize=16) ax.tick_params(axis="x", labelsize=16) ax.tick_params(axis="y", labelsize=16) ax.set_title(fr"$log_{{10}} E({kx_decimate[ikx_plot]}, k_z, \omega)$") # Compute index array corresponding to field. if field == "ap_fft": i_field = 0 elif field == "am_fft": i_field = 1 else: raise ValueError(f"field = {field} not known.") # Compute data temp_spectrum_mean = temp_spectrum_mean[i_field] # todo: fix the warnings that we get while testing data = np.log10(temp_spectrum_mean[imin_omegas_plot:, ikx_plot, ikzmin_plot:ikzmax_plot]) new = np.empty([ temp_spectrum_mean.shape[0] + 1, temp_spectrum_mean.shape[1], temp_spectrum_mean.shape[2], ]) new[:-1] = temp_spectrum_mean new[-1] = temp_spectrum_mean[-1] data = np.log10(new[imin_omegas_plot:, ikx_plot, ikzmin_plot:ikzmax_plot]) # Maximum and minimum values vmin = np.min(data[abs(data) != np.inf]) vmin = -3 vmax = np.max(data) vmax = 0 # Plot with contourf import matplotlib.cm as cm if func_plot == "contourf": cf = ax.contourf(kzs_grid, omegas_grid, data, cmap=cm.viridis, vmin=vmin, vmax=vmax) elif func_plot == "pcolormesh": kzs_grid = kzs_grid - (sim.oper.deltaky / 2) omegas_grid = omegas_grid - (omegas[1] / 2) cf = ax.pcolormesh(kzs_grid, omegas_grid, data, cmap=cm.viridis, vmin=vmin, vmax=vmax) else: print(f"Function plot not known.") # Plot colorbar m = plt.cm.ScalarMappable(cmap=cm.viridis) m.set_array(data) m.set_clim(vmin, vmax) plt.colorbar(m) # Plot dispersion relation ax.plot( kzs_grid[0][ikzmin_plot:ikzmax_plot], -(kx_decimate[ikx_plot] / np.sqrt(kx_decimate[ikx_plot]**2 + kzs_grid[0][ikzmin_plot:ikzmax_plot]**2)), color="k", ) # Check if angle string or float instance. if (isinstance(sim.params.forcing.tcrandom_anisotropic.angle, str) and "°" in sim.params.forcing.tcrandom_anisotropic.angle): angle = math.radians( float( sim.params.forcing.tcrandom_anisotropic.angle.split("°") [0])) else: angle = sim.params.forcing.tcrandom_anisotropic.angle # Plot forcing region ax.axvline( sim.oper.deltaky * sim.params.forcing.nkmin_forcing * np.sin(angle), color="red", ) ax.axvline( sim.oper.deltaky * sim.params.forcing.nkmax_forcing * np.sin(angle), color="red", ) # Inset plot if INSET_PLOT: ax_inset = self._add_inset_plot(fig) if ax_inset is not None: ax_inset.axvline(x=self.sim.oper.kx[ikx_plot], color="k") # Tight layout of the figure fig.tight_layout()
elif not kz_negative_enable: index = 2 if not index in np.arange(len(list_simulations)): raise ValueError("index should be defined.") path = list_simulations[index] ### Parameters skip = 2 tmin = 4 tmax = 400 scale = "log" # can be "linear" # Load object simulation sim = load_state_phys_file(path.as_posix(), merge_missing_params=True) poper = sim.params.oper pforcing = sim.params.forcing # Load data with h5py.File((path / "spectra_multidim.h5").as_posix(), "r") as f: times = f["times"][...] itmin = np.argmin(abs(times - tmin)) itmax = np.argmin(abs(times - tmax)) times = times[itmin:itmax:skip] kx = f["kxE"][...] ap_fft_spectrum = f["spectrumkykx_ap_fft"] data_ap = ap_fft_spectrum[itmin:itmax:skip, :, :]
def test_forcing_output(self): sim = self.sim sim.time_stepping.start() sim.state.compute("rot_fft") sim.state.compute("rot_fft") sim.state.compute("ux_fft") sim.state.compute("uy_fft") if mpi.nb_proc == 1: sim.output.spectra.plot1d() sim.output.spectra.plot2d() sim.output.spectra.load2d_mean() sim.output.spectra.load1d_mean() sim.output.spatial_means.plot() sim.output.spatial_means.plot_dt_energy() sim.output.spatial_means.plot_dt_enstrophy() sim.output.spatial_means.compute_time_means() sim.output.spatial_means.load_dataset() sim.output.spatial_means.time_first_saved() sim.output.spatial_means.time_last_saved() sim.output.print_stdout.plot_energy() sim.output.print_stdout.plot_deltat() sim.output.spectra_multidim.plot() sim.output.spect_energy_budg.plot() with self.assertRaises(ValueError): sim.state.get_var("test") sim2 = fls.load_sim_for_plot(sim.output.path_run) sim2.output sim2.output.increments.load() sim2.output.increments.plot() sim2.output.increments.load_pdf_from_file() sim2.output.increments.plot_pdf() sim2.output.phys_fields.animate( "ux", dt_frame_in_sec=1e-6, dt_equations=0.3, repeat=False, clim=(-1, 1), save_file=False, numfig=1, ) sim2.output.phys_fields.plot() # `compute('q')` two times for better coverage... sim.state.get_var("q") sim.state.get_var("q") sim.state.get_var("div") path_run = sim.output.path_run if mpi.nb_proc > 1: path_run = mpi.comm.bcast(path_run) sim3 = fls.load_state_phys_file(path_run, modif_save_params=False) sim3.params.time_stepping.t_end += 0.2 sim3.time_stepping.start() plt.close("all")
times = np.asarray(times) tmin = 2450 tmax = 2452 key = "ap" SAVE = True itmin = np.argmin(abs(times - tmin)) itmax = np.argmin(abs(times - tmax)) if not itmax: itmax = times.shape[0] if itmax < itmin: raise ValueError("itmax should be larger than itmin") # Load simulation sim = load_state_phys_file(os.path.dirname(paths_files[-1])) Lx = sim.params.oper.Lx Lz = sim.params.oper.Ly nx = sim.params.oper.nx nz = sim.params.oper.ny N = sim.params.N # Array of wave-numbers in m^-1 kx = 2 * pi * np.fft.fftfreq(nx, Lx / nx) kz = 2 * pi * np.fft.fftfreq(nz, Lz / nz) KX, KZ = np.meshgrid(kx, kz) omega_k = sim.params.N * (KX / np.sqrt(KX**2 + KZ**2)) # Create 3D_arrays
def test_output(self): sim = self.sim sim.time_stepping.start() if mpi.nb_proc == 1: phys_fields = sim.output.phys_fields phys_fields.plot(equation=f"iz=0", numfig=1000) phys_fields.get_field_to_plot_from_state() phys_fields.get_field_to_plot_from_state(sim.state.get_var("vx")) phys_fields.get_field_to_plot_from_state("vx", "x=0") phys_fields.get_field_to_plot_from_state("vx", "ix=0") phys_fields.get_field_to_plot_from_state("vx", "y=0") phys_fields.get_field_to_plot_from_state("vx", "iy=0") phys_fields.get_field_to_plot_from_state("vx", "z=0") # compute twice for better coverage sim.state.compute("rotz") sim.state.compute("rotz") sim.state.compute("divh") sim.output.phys_fields._get_grid1d("iz=0") sim.output.phys_fields._get_grid1d("iy=0") path_run = sim.output.path_run if mpi.nb_proc > 1: path_run = mpi.comm.bcast(path_run) if mpi.nb_proc == 1: sim2 = fls.load_sim_for_plot(path_run) sim2.output.print_stdout.load() sim2.output.print_stdout.plot() sim2.output.spatial_means.load() sim2.output.spatial_means.load_dataset() sim2.output.spatial_means.plot() sim2.output.spectra.load1d_mean() sim2.output.spectra.load3d_mean() sim2.output.spectra.plot1d( tmin=0.1, tmax=10, delta_t=0.01, coef_compensate=5 / 3, coef_plot_k3=1.0, coef_plot_k53=1.0, ) sim2.output.spectra.plot3d( tmin=0.1, tmax=10, delta_t=0.01, coef_compensate=5 / 3, coef_plot_k3=1.0, coef_plot_k53=1.0, ) sim2.output.phys_fields.set_equation_crosssection( f"x={sim.oper.Lx/4}" ) sim2.output.phys_fields.animate("vx") sim2.output.phys_fields.plot( field="vx", time=10, equation=f"z={sim.oper.Lz/4}" ) sim3 = fls.load_state_phys_file(path_run, modif_save_params=False) sim3.params.time_stepping.t_end += 0.2 sim3.time_stepping.start() if mpi.nb_proc == 1: sim3.output.phys_fields.animate( "vx", dt_frame_in_sec=1e-6, dt_equations=0.3, repeat=False, clim=(-1, 1), save_file=False, numfig=1, ) sys.argv = ["fluidsim-create-xml-description", path_run] run() plt.close("all")
vmin=vmin, vmax=vmax, cmap=cmap, zorder=0) cbar = fig.colorbar(contours, ax=ax) cbar.solids.set_rasterized(True) if __name__ == "__main__": matplotlib_rc(fontsize=10) path_fig = exit_if_figure_exists(__file__) set_figsize(6.65, 5.8) fig, axes = plt.subplots(2, 2) short_names = ["noise_c20nh1920Buinf", "noise_c400nh1920Buinf"] sim0 = fls.load_state_phys_file(paths_sim[short_names[0]], merge_missing_params=True) sim1 = sim0 sim1 = fls.load_state_phys_file(paths_sim[short_names[1]], merge_missing_params=True) keys = ["div", "uy", "div", "uy"] for ax, sim, key_field in zip(axes.ravel(), [sim0, sim0, sim1, sim1], keys): fig_phys_subplot(sim, fig, ax, key_field, x_slice=[0, 3], y_slice=[0, 3]) label = {"h": "h", "uy": "u_y", "div": r"\nabla.\mathbf{u}"} fig.text(0.46, 0.05, r"${}$".format(label[keys[0]]))
if len(paths_sim) == 0: # Make FIRST SIMULATION params = make_parameters_simulation(gamma, key_viscosity) sim = Simul(params) sim = normalization_initialized_field(sim) sim.time_stepping.start() else: # Look for path largest resolution new_file = sorted(paths_sim[-1].glob("State_phys*"))[-1] path_file = sorted(new_file.glob("state_phys*"))[0].as_posix() # Compute resolution from path res_str = new_file.name.split("_")[-1] # sim = load_state_phys_file(paths_sim[-1]) sim = load_state_phys_file(paths_sim[-1]) params = _deepcopy(sim.params) params.oper.nx = int(res_str.split("x")[0]) params.oper.ny = int(res_str.split("x")[1]) params.init_fields.type = "from_file" params.init_fields.from_file.path = path_file params.time_stepping.t_end += t_end params.NEW_DIR_RESULTS = True modify_parameters(params) sim = Simul(params)
import argparse import fluidsim as fls parser = argparse.ArgumentParser( description='Resume a Fluidsim simulation from a path') parser.add_argument('path', help='path to an incomplete simulation directory') args = parser.parse_args() sim = fls.load_state_phys_file(args.path, modif_save_params=False) sim.time_stepping.start()
from pathlib import Path import matplotlib.pyplot as plt import fluidsim as fls paths = sorted((Path(fls.FLUIDSIM_PATH) / "examples").glob("dedalus_*")) path = paths[-1] sim = fls.load_state_phys_file(path) sim.output.phys_fields.plot("dz_b") plt.show()
def test_forcing_output(self): sim = self.sim sim.time_stepping.start() sim.state.compute("rot_fft") sim.state.compute("rot_fft") with self.assertRaises(ValueError): sim.state.compute("abc") sim.state.compute("abc", RAISE_ERROR=False) ux_fft = sim.state.compute("ux_fft") uy_fft = sim.state.compute("uy_fft") sim.state.init_statespect_from(ux_fft=ux_fft) sim.state.init_statespect_from(uy_fft=uy_fft) if mpi.nb_proc == 1: sim.output.spectra.plot1d() sim.output.spectra.plot2d() sim.output.spectra.load2d_mean() sim.output.spectra.load1d_mean() sim.output.spatial_means.plot() sim.output.spatial_means.plot_dt_energy() sim.output.spatial_means.plot_dt_enstrophy() sim.output.spatial_means.compute_time_means() sim.output.spatial_means.load_dataset() sim.output.spatial_means.time_first_saved() sim.output.spatial_means.time_last_saved() sim.output.print_stdout.plot_energy() sim.output.print_stdout.plot_deltat() sim.output.spectra_multidim.plot() sim.output.spect_energy_budg.plot() with self.assertRaises(ValueError): sim.state.get_var("test") sim2 = fls.load_sim_for_plot(sim.output.path_run) sim2.output sim2.output.increments.load() sim2.output.increments.plot() sim2.output.increments.load_pdf_from_file() sim2.output.increments.plot_pdf() sim2.output.phys_fields.animate( "ux", dt_frame_in_sec=1e-6, dt_equations=0.3, repeat=False, clim=(-1, 1), save_file=False, numfig=1, ) sim2.output.phys_fields.plot() # `compute('q')` two times for better coverage... sim.state.get_var("q") sim.state.get_var("q") sim.state.get_var("div") path_run = sim.output.path_run if mpi.nb_proc > 1: path_run = mpi.comm.bcast(path_run) sim3 = fls.load_state_phys_file(path_run, modif_save_params=False) sim3.params.time_stepping.t_end += 0.2 sim3.time_stepping.start() if mpi.nb_proc == 1: sim3.output.phys_fields.animate( "ux", dt_frame_in_sec=1e-6, dt_equations=0.3, repeat=False, clim=(-1, 1), save_file=False, numfig=1, ) plt.close("all") # test_enstrophy_conservation # Verify that the enstrophy growth rate due to nonlinear tendencies # (advection term) must be zero. self.sim.params.forcing.enable = False tendencies_fft = self.sim.tendencies_nonlin() state_spect = self.sim.state.state_spect oper = self.sim.oper Frot_fft = tendencies_fft.get_var("rot_fft") rot_fft = state_spect.get_var("rot_fft") T_rot = (Frot_fft.conj() * rot_fft + Frot_fft * rot_fft.conj()).real / 2.0 sum_T = oper.sum_wavenumbers(T_rot) self.assertAlmostEqual(sum_T, 0, places=14)