# Numerical Methods in Physics — Sparse systems and SOR

**AGH University of Krakow | Faculty of Physics and Applied Computer Science**  
Instructor: **Hamzeh Khanpour**  
Teaching materials based on Tomasz Chwiej's official Numerical Methods in Physics course.

**Official sources**: [SOR assignment (PDF)](https://galaxy.agh.edu.pl/~chwiej/nmp/labs/nmp_sle_sor.pdf) · [Iterative-methods lecture (PDF)](https://galaxy.agh.edu.pl/~chwiej/nmp/lectures/nmp_sle_iterative.pdf).

## Examples

These are **nine complete SMALL teaching examples**, plus one optional extension, supporting the **56-slide PDF**. The examples are fully independent C++17 programs; each has its own `main()` and self-check. They deliberately **do not** assemble and solve the official `n=500` Poisson/SOR assignment. You must integrate your **own** full CSR storage, SOR outer loop, file output, plots and report for assessment.

The slides are reference material. During the laboratory, the instructor will choose a few derivations and demos; use the rest when implementing your project independently.

## Prerequisites and preflight

* `g++` with C++17 support, `make`, a terminal. The compiled examples require **only standard C++17**, no BLAS/LAPACK/LAPACKE/ROOT/Eigen.
* `python3` for automated tests; Python 3 + Matplotlib for the E09 figure only. Core C++ programs work without Python scientific libraries.
* Check locally: `g++ --version`, `make --version`, `python3 --version`, then `python3 -c 'import matplotlib; print(matplotlib.__version__)'`.
* A check executed in the file author's environment does not guarantee an identical setup on classroom PCs or Taurus; run these commands yourself.

From a **freshly extracted** `student_package/` directory:

```sh
cd student_package
make help
make standard
make check-standard
make optional
make check-optional
```

Each source has exactly one `main()`; do **not** link `examples/*.cpp` together. To compile E01 directly:

```sh
mkdir -p bin
g++ -std=c++17 -Wall -Wextra -Wpedantic -O2 examples/01_second_difference_error.cpp -o bin/01_second_difference_error
./bin/01_second_difference_error
```

The Makefile shortcuts build **each example separately**.

## Examples in study order

| ID | Slides | Self-contained topic | Hand-checkable output |
|---|---|---|---|
| E01 | S09–S10 | `01_second_difference_error.cpp` | centered second difference: 12.5, 12.125, error ratio 4 |
| E02 | S11–S13; S21 | `02_tridiagonal_toy_system.cpp` | A4 q=(0,0,0,-5) |
| E03 | S17–S22 | `03_csr_toy_encoding.cpp` | full CSR arrays row=[0,2,5,8,10] |
| E04 | S23–S25 | `04_csr_toy_matvec.cpp` | A4 q=(0,0,0,-5), dense agreement |
| E05 | S26–S27 | `05_dot_norm_residual.cpp` | dot=40, norm=√14, residual zero |
| E06 | S30–S32 | `06_jacobi_one_sweep.cpp` | Jacobi=(0.5,1,2.5) |
| E07 | S33–S35 | `07_gauss_seidel_one_sweep.cpp` | Gauss–Seidel=(0.5,1.125,2.78125) |
| E08 | S36–S40 | `08_sor_one_sweep.cpp` | SOR ω=1.25: (.625,1.4453125,3.57666015625) |
| E09 | S44–S46 | `09_small_sor_history_csv.cpp` | true dense 3×3 CSV + plotted norm history |
| E10 | S56 | `10_optional_2d_five_point_stencil.cpp` | optional 2D 5-point stencil gives (-1,3,7,11) |

### Exact per-example direct compile and run commands

The following commands assume your working directory is `student_package/` and `bin/` exists:

```sh
mkdir -p bin
g++ -std=c++17 -Wall -Wextra -Wpedantic -O2 examples/01_second_difference_error.cpp -o bin/01_second_difference_error
./bin/01_second_difference_error
g++ -std=c++17 -Wall -Wextra -Wpedantic -O2 examples/02_tridiagonal_toy_system.cpp -o bin/02_tridiagonal_toy_system
./bin/02_tridiagonal_toy_system
g++ -std=c++17 -Wall -Wextra -Wpedantic -O2 examples/03_csr_toy_encoding.cpp -o bin/03_csr_toy_encoding
./bin/03_csr_toy_encoding
g++ -std=c++17 -Wall -Wextra -Wpedantic -O2 examples/04_csr_toy_matvec.cpp -o bin/04_csr_toy_matvec
./bin/04_csr_toy_matvec
g++ -std=c++17 -Wall -Wextra -Wpedantic -O2 examples/05_dot_norm_residual.cpp -o bin/05_dot_norm_residual
./bin/05_dot_norm_residual
g++ -std=c++17 -Wall -Wextra -Wpedantic -O2 examples/06_jacobi_one_sweep.cpp -o bin/06_jacobi_one_sweep
./bin/06_jacobi_one_sweep
g++ -std=c++17 -Wall -Wextra -Wpedantic -O2 examples/07_gauss_seidel_one_sweep.cpp -o bin/07_gauss_seidel_one_sweep
./bin/07_gauss_seidel_one_sweep
g++ -std=c++17 -Wall -Wextra -Wpedantic -O2 examples/08_sor_one_sweep.cpp -o bin/08_sor_one_sweep
./bin/08_sor_one_sweep
g++ -std=c++17 -Wall -Wextra -Wpedantic -O2 examples/09_small_sor_history_csv.cpp -o bin/09_small_sor_history_csv
./bin/09_small_sor_history_csv
g++ -std=c++17 -Wall -Wextra -Wpedantic -O2 examples/10_optional_2d_five_point_stencil.cpp -o bin/10_optional_2d_five_point_stencil
./bin/10_optional_2d_five_point_stencil
```

Or use `make bin/<basename>` and `./bin/<basename>` for any individual file. For example, `make bin/08_sor_one_sweep` and `./bin/08_sor_one_sweep`.

## E09: generate real data and a real convergence graph

The E09 program solves only the separate symmetric positive definite toy

\[
B=egin{pmatrix}4&-1&0\-1&4&-1\0&-1&4\end{pmatrix},\quad
b=(2,4,10)^T,\quad x_\star=(1,2,3)^T.
\]

With `omega=1.1`, initial `x=(0,0,0)`, it writes a CSV containing `iteration,solution_norm,residual_norm`. `iteration=0` is the initial (pre-iteration) vector. Later rows describe completed SOR sweeps. The plot contains solution and absolute-residual norms; zero residuals are not fabricated as positive values for logarithmic plotting.

```sh
make plot
# Output: data/toy_sor_history.csv and plots/toy_sor_history.png
make check-plot
```

**No silent overwrites.** If these files already exist, `make plot` leaves them intact and explains that it is reusing them. For a separate experiment, choose a new output filename:

```sh
./bin/09_small_sor_history_csv --output data/my_toy_history.csv
python3 plotting/plot_toy_sor_history.py --input data/my_toy_history.csv --output plots/my_toy_history.png
```

An explicit `--overwrite` option exists on both commands for replacing a file **you deliberately choose to replace**. If Matplotlib is unavailable, the CSV-writing C++ program is still usable; install the package in an appropriate Python environment rather than changing the C++ task.

## Important physics and algebra convention

The official handout states $V''(x)=-
ho(x)$, yet subsequently prints $A_-v=
ho$ with diagonal $-2/\Delta^2$ and adjacent off-diagonals $+1/\Delta^2$. These are not simultaneously sign-consistent. **The slides explicitly flag the discrepancy and use the algebraic convention printed for the assignment**. The physically consistent form with that matrix would instead be $A_-v=-
ho$. Follow instructor guidance if a correction is announced; **never silently mix conventions**.

The assignment also uses $V_{-1}=V_n=0$ **outside** the $n$ represented unknowns $V_0,\ldots,V_{n-1}$. Imposing zero values at the stored endpoints $V_0,V_{n-1}$ would be a different problem.

### For the official laboratory, you must implement

1. Full CSR arrays for the symmetric tridiagonal matrix (both off-diagonals), the diagonal, dot products and CSR matvec.
2. Your own SOR sweep and outer iteration loop, with absolute residual $\|
ho-A_-v\|_2$.
3. Exactly `n=500`, `Delta=1`, `itmax=10000`, `epsilon=1e-15`, `omega=1`, starting `v_i=1` and $
ho_i=0.1[\sin(2\pi i/(n-1))]^{10}$.
4. Iteration history and four figures: solution norm vs iteration; residual norm vs iteration; source vs position; final potential vs position.
5. At home: compare `omega=1,1.5,1.9,1.99`, then at `omega=1.99`, `epsilon=1e-8` compare zero and random `[0,100]` initial vectors. Report real convergence status and iteration counts.

The tolerance `1e-15` may be lower than the achievable residual floor in ordinary double precision. Hitting `itmax` **is not proof of divergence**. Always distinguish a reached tolerance from the iteration limit. The lecture discusses an optional half-matrix symmetric CSR format; the assignment uses **full CSR**.

## Troubleshooting checklist

* If compilation fails, verify C++17 support and that you compile one `.cpp` per binary.
* If CSR multiplication fails, inspect `row[0]=0`, `row[n]=nnz`, monotone pointers and `0<=col[p]<n`.
* If the sign of your result is surprising, re-check the handout's physical/algebraic convention.
* If Jacobi unexpectedly gives the GS output, you overwrote the `old` vector too early.
* If GS does not agree with SOR at `omega=1`, inspect update order and diagonal division.
* If the residual is not computed as `b-Ax`, a small iterate change cannot replace the missing independent check.
* If a semilog plot disappears, inspect zero or nonfinite residuals; do not replace real zero data with arbitrary numbers.
* The optional E10 has a **different** two-dimensional grid/boundary convention and must not be used as the project's 1D model.

## Reproducibility and responsibilities

The `tests/check_examples.py` script verifies extracted numeric results against separate constants and fixtures; it does not merely search for `PASS`. The plot test also confirms rejection of malformed CSV and unintended overwrites. Outputs may vary at the last floating-point digits between machines but should satisfy the documented tolerances.

**Sources**: Tomasz Chwiej's two official linked PDFs. Student example architecture and AGH teaching style adapted from the instructor-supplied prior laboratory package. The examples remain independent of the assessed project.
