Metadata-Version: 2.4
Name: mhd2d
Version: 0.1.0
Summary: A two-dimensional pseudo-spectral magnetohydrodynamics simulation code written in Python.
Author: Xu Chen
License-Expression: GPL-2.0-only
Project-URL: Homepage, https://github.com/cheon888/LAPS2Dpy
Project-URL: Repository, https://github.com/cheon888/LAPS2Dpy
Project-URL: Issues, https://github.com/cheon888/LAPS2Dpy/issues
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE.txt
Requires-Dist: numpy
Requires-Dist: scipy
Requires-Dist: matplotlib
Requires-Dist: pyfftw
Requires-Dist: numba
Provides-Extra: test
Requires-Dist: pytest>=8; extra == "test"
Dynamic: license-file

# LAPS2Dpy

**LAPS2Dpy** is a two–dimensional pseudo-spectral magnetohydrodynamics (MHD) simulation code written in Python.
The code solves the compressible MHD equations using Fourier spectral methods and explicit Runge–Kutta time integration.

This project is a simplified Python implementation inspired by the **UCLA Pseudo-Spectral (LAPS) framework** used in solar wind turbulence studies.

The repository is named **LAPS2Dpy**, while the installed Python package and command-line tool are named **mhd2d**.

The purpose of this code is to provide a lightweight and transparent implementation for:

* Studying fundamental MHD processes such as waves, instabilities, and turbulence 
* Quick tests of numerical setup for plasma simulations
* Educational demonstrations of pseudo-spectral solvers

---

# Numerical Method

The solver uses a **pseudo-spectral method** in a periodic two-dimensional domain.

Main numerical components:

* Fourier spectral derivatives
* fast Fourier transforms (FFT)
* Runge–Kutta time integration
* dealiasing for nonlinear terms
* adaptive timestep based on CFL condition

Spectral transforms are used to compute spatial derivatives efficiently in Fourier space while nonlinear products are evaluated in real space.

---

# Code Structure

The repository is organized into several modules:

```
src/mhd2d/mhd.py
main simulation driver

src/mhd2d/mhdinit.py
initialization of grid, variables, and initial conditions

src/mhd2d/mhdrhs.py
calculation of fluxes and right-hand-side terms

src/mhd2d/mhdrkt.py
Runge–Kutta time integration routines

src/mhd2d/vardt.py
adaptive timestep calculation

src/mhd2d/FFT.py
FFT transforms and dealiasing

src/mhd2d/mhd_param_converse.py
conversion between primitive and conserved variables

src/mhd2d/AEB.py
expanding box model implementation

src/mhd2d/mhdrms.py
diagnostic calculations

src/mhd2d/output.py
simulation output and logging

src/mhd2d/restart.py
restart functionality
```
---

# Installation

The code requires Python ≥ 3.9.

The required Python packages include:

* numpy
* scipy
* matplotlib
* pyfftw
* numba

## Install from PyPI

```bash
conda create -n mhd2d python=3.10
conda activate mhd2d
python3 -m pip install mhd2d
```

This installs the solver and its dependencies into the active Python environment.
Users configure simulations through their own `.input` files; modifying the
installed Python source is not required for the standard workflow.

## Development installation

An editable installation is intended for contributors working on the source code:

```bash
git clone https://github.com/cheon888/LAPS2Dpy.git
cd LAPS2Dpy
python3 -m pip install -e ".[test]"
```

Run the editable-install command from the repository root, where
`pyproject.toml` is located.

---

# Running a Simulation

After installing `mhd2d`, create a new input file from the bundled template:

```bash
mhd2d-init my_case.input
```

Edit `my_case.input`, then run it with the command-line interface:

```bash
mhd2d my_case.input
```

The same simulation can be started through the Python API:

```python
from mhd2d import run

run("my_case.input")
```

`mhd2d-init` will not overwrite an existing file. To replace one intentionally:

```bash
mhd2d-init my_case.input --force
```

The files in `cases_input/` are test and demonstration cases for repository
development. PyPI users do not need to clone the repository. Do not run
`src/mhd2d/mhd.py` directly; use the installed command or Python API.


# Input Configuration

The generated template contains the standard `genr`, `numerical`, `grid`,
`field`, `pert`, `phys`, `AEB`, `Hall`, and `output` groups. Change the values
in the generated copy to define a simulation. In particular, `out_dir` selects
the directory where results are written.

For a custom background or perturbation implemented outside the installed
package, pass user functions through the Python API:

```python
from pathlib import Path

from mhd2d import run


def my_background(uu, params, grid):
    # Fill the primitive-variable array here.
    return uu


def my_perturbation(uu, params, grid):
    # Apply the user-defined perturbation here.
    return uu


run(
    Path("my_case.input"),
    background_initializer=my_background,
    perturbation_initializer=my_perturbation,
)
```

The primitive-variable order is `rho`, `ux`, `uy`, `uz`, `Bx`, `By`, `Bz`,
and pressure. User-defined functions let users add cases without modifying the
installed `mhd2d` source.

<img width="562" height="610" alt="Screenshot 2026-03-31 at 10 18 40 PM" src="https://github.com/user-attachments/assets/96c0a882-9337-432e-89ea-638ffc1804f6" />




Simulation output will be written to the directory specified in the input parameters.

# Output
* Field snapshots
During the simulation, the code will create a series of `outXXX.dat` files.
Each file stores a snapshot of the simulation, including the simulation time and the physical variables.

- Simulation time: `t`
- Physical variables:
  - Data shape: `(nvar, nx, ny)`
  - Dimension 1: `nvar = 8`
    - `uu[0,:,:]`: density, `rho`
    - `uu[1,:,:]`: x velocity, `ux`
    - `uu[2,:,:]`: y velocity, `uy`
    - `uu[3,:,:]`: z velocity, `uz`
    - `uu[4,:,:]`: x magnetic field, `bx`
    - `uu[5,:,:]`: y magnetic field, `by`
    - `uu[6,:,:]`: z magnetic field, `bz`
    - `uu[7,:,:]`: total energy, `E`
  - Dimension 2: `nx`, the number of grid points in the x direction
  - Dimension 3: `ny`, the number of grid points in the y direction

* Grid information: `nx`, `ny`
---

# Examples 
## Case：Rotating Magnetic Field Perturbation (Circularly Polarized) (mhd12.input) 
- **Description**: This case initializes a rotating magnetic field perturbation along the $x$-direction. The perturbation satisfies the condition $B_y^2 + B_z^2 = dB^2$, representing a circularly polarized wave structure.
- **Figures**:
  
![bz_map](https://github.com/user-attachments/assets/6c6f5404-650f-446f-b457-98bed894e1de)





## Case：Current sheet (mhd7.input) 
- **Description**: This case initializes a classic 2D current sheet configuration (e.g., a Harris-type sheet) where the primary magnetic field undergoes a sharp reversal across a narrow region. This setup is widely used to study magnetic reconnection and tearing mode instabilities in plasma.
- **Figures**:
  
![Bx_map](https://github.com/user-attachments/assets/c4674323-4170-4473-812b-f47207229154)
![By_map](https://github.com/user-attachments/assets/2935042b-b54a-4e5e-81d9-37818e495695)

## Case: 2D Gaussian perturbation in Pressure (mhd51.input) 
- **Description**: This case introduces a localized 2D Gaussian perturbation in the thermal pressure field against a uniform background. The initial localized high-pressure region acts as a driver, generating outward-propagating magneto-acoustic (fast and slow) waves. It is an excellent test for observing the coupling between fluid dynamics and magnetic fields.
- **Figures**:
  
![bx_map](https://github.com/user-attachments/assets/ff68f12d-e171-479d-8c33-cbc3325f71b3)
![p_map](https://github.com/user-attachments/assets/37bab451-2bf3-4ab1-a4cd-23e298a2abe4)
<img width="800" height="700" alt="Figure_1" src="https://github.com/user-attachments/assets/6cac6ff4-8ce1-412b-8bfa-66a177ce045c" />


---

# References

If you use this code or its methodology, please cite the following work related to the UCLA pseudo-spectral framework:

Shi, C., et al. (2024).
*LAPS: An MPI-parallelized 3D pseudo-spectral Hall-MHD simulation code incorporating the expanding box model.*
Frontiers in Astronomy and Space Sciences.

Shi, C., et al. (2020).
*Propagation of Alfvén waves in the expanding solar wind with the fast–slow stream interaction.*
The Astrophysical Journal.

---

# License

This project is distributed under the **GNU General Public License v2.0**.

---

# Author

Xu Chen 
Shi Chen
