-
Notifications
You must be signed in to change notification settings - Fork 34
[SPH][NIMHD] Add Non-Ideal MHD terms #1765
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
y-lapeyre
wants to merge
39
commits into
Shamrock-code:main
Choose a base branch
from
y-lapeyre:MHD/nonideal
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
39 commits
Select commit
Hold shift + click to select a range
5b5fc0a
add NIMHD terms
y-lapeyre 5f4c2ea
enable NIMHD
y-lapeyre a7ede8d
typos + correct dimentionality
y-lapeyre 547a81d
B -> Bhat
y-lapeyre 015819b
Merge branch 'main' into MHD/nonideal
y-lapeyre 32aec9b
correct summation for J
y-lapeyre 54d00cf
Merge branch 'MHD/nonideal' of github.com:y-lapeyre/Shamrock into MHD…
y-lapeyre 42428b4
Merge branch 'main' into MHD/nonideal
y-lapeyre 70586aa
fix potential division by 0
y-lapeyre 23b20f0
fix pre-commit
y-lapeyre 6636ce8
correctly communicate J in ghosts
y-lapeyre 071924a
fix ghost com fields
y-lapeyre 8b64f74
clean up rogue J's
y-lapeyre 06c57c9
remove logs
y-lapeyre 347fa18
test1
y-lapeyre 36ae82e
move computeJ to solvergraph
y-lapeyre 452bbcf
correct ghost communication
y-lapeyre b231638
why is everything a nan
y-lapeyre 2aec96b
mismatch in obj_cnt in communicate_merge_ghost_fields
y-lapeyre 30f5b05
fixed communication, now empty (?) field problem
y-lapeyre a9bd332
remove logs
y-lapeyre 140d56f
fix J handling (independant com)
y-lapeyre 4ef2daf
fix subfact
y-lapeyre b01a705
fix dt_AD and J comm
y-lapeyre bf3c101
fixed memory issue
y-lapeyre 09caf22
Merge branch 'main' into MHD/nonideal
y-lapeyre 1d693f6
[autofix.ci] automatic fix: pre-commit hooks
autofix-ci[bot] 8ff7743
Merge branch 'MHD/nonideal' of github.com:y-lapeyre/Shamrock into MHD…
y-lapeyre 2f1bb96
Merge branch 'MHD/nonideal' of github.com:y-lapeyre/Shamrock into MHD…
y-lapeyre 02c1b44
clean up
y-lapeyre ffa662f
clean up + add warning
y-lapeyre c956764
edit out typo
y-lapeyre 4fa54e6
remove log
y-lapeyre db3c168
Merge branch 'main' into MHD/nonideal
y-lapeyre b2456f5
correct wrongful merge deletion
y-lapeyre 3dbec73
remove prints
y-lapeyre 60e828a
add wave damping test runscript
y-lapeyre 34f60c1
Put NIMHD in experimental mode
y-lapeyre d12fbe0
Merge branch 'main' into MHD/nonideal
y-lapeyre File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,259 @@ | ||
| """ | ||
| Wave damping test in SPH with non-ideal MHD | ||
| =========================================== | ||
|
|
||
| This example runs the wave damping test, aimed at evaluating the behaviour of the ambipolar diffusion term. | ||
| The RMS of the magnetic field components is | ||
| monitored and compared to the analytical dispersion relation. | ||
| """ | ||
|
|
||
| # sphinx_gallery_multi_image = "single" | ||
|
|
||
| import os | ||
|
|
||
| import matplotlib.pyplot as plt | ||
| import numpy as np | ||
|
|
||
| import shamrock | ||
|
|
||
| shamrock.enable_experimental_features() | ||
|
|
||
| # Initialize shamrock (if not already done by the executable) | ||
| if not shamrock.sys.is_initialized(): | ||
| shamrock.change_loglevel(1) | ||
| shamrock.sys.init("0:0") | ||
|
|
||
| # Use shamrock plotting style | ||
| shamrock.matplotlib.set_shamrock_mpl_style() | ||
|
|
||
| # %% | ||
| # Define physical parameters and unit system | ||
| # ------------------------------------------ | ||
| # We use a unit system where mu_0 = 1 in code units (defined via UnitSystem). | ||
| # The code unit system is set to have unit_length = 1, unit_mass = 1.2566370621219e-06 | ||
| # so that mu_0 = 1 exactly. | ||
|
|
||
| Lx = 1.0 # box length | ||
| dr = 0.09 # particle spacing | ||
| rho0 = 1.0 # initial density | ||
| Bx0 = 1.0 # background field in x | ||
| C_ADc = 0.01 # ambipolar diffusion coefficient (Phantom convention) | ||
| cs = 1.0 # isothermal sound speed | ||
| t_target = 5.0 # total simulation time | ||
| dt_dump = 0.01 * t_target # dump interval | ||
|
|
||
| # Unit system and constants | ||
| codeu = shamrock.UnitSystem( | ||
| unit_time=1.0, | ||
| unit_length=1.0, | ||
| unit_mass=1.2566370621219e-06, | ||
| ) | ||
| ucte = shamrock.Constants(codeu) | ||
| mu_0 = ucte.mu_0() # = 1 in these units | ||
| c = ucte.c() # speed of light (used only for unit conversion) | ||
|
|
||
| # Derived quantities | ||
| vA = Bx0 / np.sqrt(rho0) # Alfven speed | ||
| etaAD_cgs = C_ADc * vA * vA # ambipolar diffusivity (cgs-like) | ||
| etaAD_si = etaAD_cgs * (4 * np.pi / c) # SI conversion (not used in code) | ||
|
|
||
| print(f"mu_0 = {mu_0}, vA = {vA:.3f}, etaAD = {etaAD_cgs:.3e}") | ||
|
|
||
| # %% | ||
| # Create context and SPH model | ||
| # ---------------------------- | ||
| ctx = shamrock.Context() | ||
| ctx.pdata_layout_new() | ||
| model = shamrock.get_Model_SPH(context=ctx, vector_type="f64_3", sph_kernel="C4") | ||
|
|
||
| # %% | ||
| # Set up simulation configuration | ||
| # ------------------------------- | ||
| cfg = model.gen_default_config() | ||
| cfg.set_units(codeu) | ||
| cfg.set_artif_viscosity_None() # no artificial viscosity | ||
| cfg.set_NonIdealMHD(sigma_mhd=1, sigma_u=0, etaO=0, etaH=0, etaAD=etaAD_cgs) | ||
| cfg.set_boundary_periodic() # periodic boundaries in all directions | ||
| cfg.set_eos_isothermal(cs) # isothermal equation of state | ||
| cfg.print_status() | ||
| model.set_solver_config(cfg) | ||
|
|
||
| # Initialize scheduler and particle container | ||
| model.init_scheduler(int(1e6), 1) | ||
|
|
||
| # %% | ||
| # Generate particle distribution in an FCC lattice | ||
| # ------------------------------------------------ | ||
| bmin = (-Lx / 2.0, -np.sqrt(3) / 4.0 * Lx, -np.sqrt(6) / 4.0 * Lx) | ||
| bmax = (Lx / 2.0, np.sqrt(3) / 4.0 * Lx, np.sqrt(6) / 4.0 * Lx) | ||
|
|
||
| # Adjust box to exactly fit the lattice | ||
| bmin, bmax = model.get_ideal_fcc_box(dr, bmin, bmax) | ||
| xm, ym, zm = bmin | ||
| xM, yM, zM = bmax | ||
| Lx_actual = xM - xm | ||
|
|
||
| model.resize_simulation_box(bmin, bmax) | ||
| model.add_cube_fcc_3d(dr, bmin, bmax) | ||
|
|
||
| vol_b = (xM - xm) * (yM - ym) * (zM - zm) | ||
| totmass = rho0 * vol_b | ||
| pmass = model.total_mass_to_part_mass(totmass) | ||
| model.set_particle_mass(pmass) | ||
|
|
||
| # %% | ||
| # Set initial conditions | ||
| # ---------------------- | ||
| # Background magnetic field in x, and a sinusoidal velocity perturbation in z. | ||
| k = 2 * np.pi / Lx_actual | ||
| v0 = 0.01 * vA | ||
|
|
||
|
|
||
| def B_func(r): | ||
| return (Bx0, 0.0, 0.0) | ||
|
|
||
|
|
||
| def vel_func(r): | ||
| x, y, z = r | ||
| vz = v0 * np.sin(k * (x - xm)) | ||
| return (0.0, 0.0, vz) | ||
|
|
||
|
|
||
| def u_func(r): | ||
| return 0.0 | ||
|
|
||
|
|
||
| model.set_field_value_lambda_f64_3("B/rho", B_func) | ||
| model.set_field_value_lambda_f64_3("vxyz", vel_func) | ||
| model.set_field_value_lambda_f64("uint", u_func) | ||
|
|
||
| # %% | ||
| # Set CFL parameters | ||
| # ------------------ | ||
| model.set_cfl_cour(0.3) | ||
| model.set_cfl_force(0.25) | ||
|
|
||
| # %% | ||
| # Prepare storage for time series and output directory | ||
| # ---------------------------------------------------- | ||
| times = [] | ||
| Brmsx = [] | ||
| Brmsy = [] | ||
| Brmsz = [] | ||
|
|
||
| dump_folder = "_wave_dump" | ||
| if shamrock.sys.world_rank() == 0: | ||
| os.makedirs(dump_folder, exist_ok=True) | ||
|
|
||
| # %% | ||
| # Time loop with data collection | ||
| # ------------------------------ | ||
| t_sum = 0.0 | ||
| i_dump = 0 | ||
| next_dt_target = t_sum + dt_dump | ||
|
|
||
| while next_dt_target <= t_target + 1e-12: | ||
| # Evolve until next dump time | ||
| model.evolve_until(next_dt_target) | ||
| t_now = model.get_time() | ||
|
|
||
| # Collect particle data from the context | ||
| data = ctx.collect_data() | ||
| h_arr = data["hpart"] | ||
| hfac = 1.0 | ||
| rho = pmass * (hfac / h_arr) * (hfac / h_arr) * (hfac / h_arr) | ||
| Bx = data["B/rho"][:, 0] * rho | ||
| By = data["B/rho"][:, 1] * rho | ||
| Bz = data["B/rho"][:, 2] * rho | ||
|
|
||
| # Compute RMS values | ||
| rms_x = np.sqrt(np.mean(Bx**2)) | ||
| rms_y = np.sqrt(np.mean(By**2)) | ||
| rms_z = np.sqrt(np.mean(Bz**2)) | ||
|
|
||
| times.append(t_now) | ||
| Brmsx.append(rms_x) | ||
| Brmsy.append(rms_y) | ||
| Brmsz.append(rms_z) | ||
|
|
||
| # (Optional) write VTK for visualisation | ||
| model.do_vtk_dump(os.path.join(dump_folder, f"wave_{i_dump:04d}.vtk"), True) | ||
|
|
||
| print(f"t = {t_now:.3f}, rms Bz = {rms_z:.5f}") | ||
|
|
||
| i_dump += 1 | ||
| next_dt_target += dt_dump | ||
|
|
||
| # Convert to numpy arrays | ||
| times = np.array(times) | ||
| Brmsx = np.array(Brmsx) | ||
| Brmsy = np.array(Brmsy) | ||
| Brmsz = np.array(Brmsz) | ||
|
|
||
| # %% | ||
| # Analytical solution | ||
| # ------------------- | ||
| # For the damping of a sinusoidal Alfven wave with ambipolar diffusion, | ||
| # the dispersion relation gives: | ||
| # omega = omega_R + i omega_I | ||
| # with omega_I = - (k^2 etaAD)/2 (damping rate) | ||
| # and omega_R = 0.5 * sqrt( - (k^2 etaAD)^2 - 4 (k vA)^2 ) | ||
| # The z-component of B (the perturbed component) evolves as: | ||
| # Bz(t) = Bz(0) * |sin(omega_R t)| * exp(omega_I t) | ||
| # where Bz(0) = (rho0 * v0 * Bx0) / (vA * sqrt(2)) | ||
|
|
||
| Lx = 1.0 | ||
| # Phantom's exact dispersion relation | ||
| Bx0 = 1.0 | ||
| rho0 = 1.0 | ||
| C_ADc = 0.01 # ion-neutral coupling, same as Phantom | ||
| vA = Bx0 / np.sqrt(rho0) # no mu_0 since mu_0=1 in your code units | ||
| v0 = 0.01 * vA | ||
| k = 2 * np.pi / Lx # = 2*pi since Lx=1 | ||
|
|
||
| etaAD_cgs = C_ADc * vA * vA | ||
| etaAD_si = etaAD_cgs * 4 * np.pi / c | ||
| etaAD = etaAD_cgs | ||
|
|
||
| quadb = (k) ** 2 * etaAD | ||
| quadc = -((k * vA) ** 2) | ||
| omegaI = -0.5 * quadb # negative = damping | ||
| omegaR = 0.5 * np.sqrt(-(quadb**2) - 4 * quadc) | ||
|
|
||
| h0 = (4 * np.pi) * v0 * Bx0 / (vA * np.sqrt(2.0)) | ||
|
|
||
| print(f"omegaR = {omegaR:.4f}, omegaI = {omegaI:.4f}, h0 = {h0:.4f}") | ||
|
|
||
| time_th = np.linspace(0, t_target, 1000) | ||
| theory = h0 * np.abs(np.sin(omegaR * time_th)) * np.exp(omegaI * time_th) | ||
|
|
||
| # %% | ||
| # Plot results | ||
| # ------------ | ||
| fig, axs = plt.subplots(1, 4, figsize=(12, 8)) | ||
|
|
||
| axs[0].plot(times, Brmsz, "b-", linewidth=2) | ||
| axs[0].set_xlabel("Time (s)") | ||
| axs[0].set_ylabel("rms Bz") | ||
| axs[0].grid(alpha=0.3) | ||
|
|
||
| axs[1].plot(times, Brmsy, "g-", linewidth=2) | ||
| axs[1].set_xlabel("Time (s)") | ||
| axs[1].set_ylabel("rms By") | ||
| axs[1].grid(alpha=0.3) | ||
|
|
||
| axs[2].plot(times, Brmsx, "m-", linewidth=2) | ||
| axs[2].set_xlabel("Time (s)") | ||
| axs[2].set_ylabel("rms Bx") | ||
| axs[2].grid(alpha=0.3) | ||
|
|
||
| axs[3].plot(time_th, theory, "r--", linewidth=2) | ||
| axs[3].set_xlabel("Time (s)") | ||
| axs[3].set_ylabel("rms Bz theory") | ||
| axs[3].grid(alpha=0.3) | ||
|
|
||
| plt.tight_layout() | ||
| plt.savefig(os.path.join(dump_folder, "wave_damping_analysis.png"), dpi=150) | ||
| plt.show() | ||
|
|
||
| print("Analysis completed. Results saved in", dump_folder) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I low key want to change the expermental prompt with one similar to this though