# Numerical Methods in Physics — Project 03
## Diagonalization of a symmetric tridiagonal matrix (quantum harmonic oscillator)

**Faculty of Physics and Applied Computer Science, AGH University of Krakow**  
**Instructor:** Hamzeh Khanpour  
**Release:** 22 October 2026 | C++17 teaching examples, nine core (E01–E09) and one optional (E10)

### 1. What these materials are, and what they are not

The **official laboratory handout** is the authority for the work that you must complete:
https://galaxy.agh.edu.pl/~chwiej/nmp/labs/nmp_diag_tridiagonal.pdf

Theory reference: https://galaxy.agh.edu.pl/~chwiej/nmp/lectures/nmp_diag_direct.pdf

**The E01–E10 programs are not the complete oscillator project.** E06 diagonalizes a small, unrelated constant tridiagonal matrix; E04 constructs a constant-potential toy; E10 solves a *different* free-particle box with interior nodes. There is no provided script or program that constructs and solves the assigned oscillator, outputs your homework states, or generates your report. That integration is your work.

### 2. A useful order for studying

1. Derive the small symmetric eigenproblem on slides S07–S11, then run E01.
2. Study symmetric tridiagonal storage on S13–S15 and run E02.
3. Derive the finite-difference stencil on S18–S26; run E03 and E04.
4. Practise output-array indexing in S29–S35 and run E05 and E06.
5. Learn weighted physical normalization and Hermite recurrence in S38–S46; run E07 and E08.
6. Use E09 to follow actual C++ samples into a Python plot.
7. Read the *official* task checkpoints on S51–S55, then create your own project in a separate folder.
8. If interested, study E10 as an optional (different-boundary-convention) numerical experiment.

The 135-minute laboratory reserves **50–120 minutes** for your own development. The deck is also a reference you can consult while coding.

### 3. Prerequisites and installation boundaries

Use a Linux terminal and a C++17 compiler (`g++`), `make`, and Python 3. E01–E05 and E07–E09 require **only standard C++17**. E06 and optional E10 require a real compatible LAPACKE installation (`lapacke.h` plus genuine LAPACKE/LAPACK/BLAS libraries). E09 plots require Python 3 and Matplotlib. The AGH computers/Taurus were **not accessed or verified** during this package's preparation.

Typical Debian-based development packages (ask your local lab IT team before installing on managed computers): `g++ make liblapacke-dev liblapack-dev libblas-dev python3-matplotlib`. Actual package/provider names vary. The `lapack_int` type and the linked library must agree about integer width (LP64 or ILP64).

Check:

```bash
pwd
ls examples
mkdir -p bin data plots
g++ --version
make help
make standard
make check-standard
```

**Three different failure classes:** `lapacke.h: No such file` = header search problem (`-I`/`LAPACKE_CPPFLAGS`); `undefined reference to LAPACKE_dstev` = linker library/order problem (`-L`, `LAPACKE_LIBS`); `error while loading shared libraries` = runtime library search problem (`LD_LIBRARY_PATH`, rpath, system configuration). Distinguish them before changing your code.

### 4. Compile each standalone example separately

Every `.cpp` defines its own `main()`: do **not** run `g++ examples/*.cpp` as one program. The Makefile gives reproducible individual targets. The commands below are executed from this package's root.

| ID | Frame(s) | Toy fixture and what it teaches | Analytical/numerical check |
|---|---|---|---|
| E01 | S08–S10 | Symmetric `[[2,1],[1,2]]`; exact eigenpairs | eigenvalues 1,3; residual and norm/orthogonality |
| E02 | S13–S15 | 4×4 tridiagonal `d=2`, `e=-1`, matvec | `[1,2,3,4]` maps to `[0,0,0,5]` |
| E03 | S20–S22 | Central `f''(1)` for `f(x)=x⁴` | `12+2h²`; errors decrease by factor 4 |
| E04 | S24–S27 | Four-node **constant-potential** operator | `d=1.75`, `e=-0.5`, matvec components |
| E05 | S29–S30 | Row-/column-major memory with padding | same logical `(1,2)` at offsets 6 and 9 |
| E06 | S32–S37 | Real `LAPACKE_dstev` on non-QHO 3×3 toy | `2−√2`, `2`, `2+√2`; residual and QᵀQ |
| E07 | S38–S40 | Two-vector discrete norm and global sign | physical norm 1, overlaps 0/−1/+1 |
| E08 | S42–S45 | Hermite recurrence at `x=0.5` | H0=1, H1=1, H2=−1, H3=−5 |
| E09 | S49 | Toy `g(x)=1+x−x²` sampled to CSV | exactly nine independent points and valid plot |
| E10 (optional) | S56 | **Interior-node** free-particle Dirichlet box | known exact discrete formula and O(h²) error |

**One-command builds** (`make standard`, `make lapacke`, `make core`, `make optional`) are conveniences; every program also has a separate target. Here are the individual build and run commands for **all ten**:

```bash
make bin/01_small_symmetric_eigenproblem
./bin/01_small_symmetric_eigenproblem

make bin/02_tridiagonal_storage_matvec
./bin/02_tridiagonal_storage_matvec

make bin/03_central_second_difference
./bin/03_central_second_difference

make bin/04_constant_potential_stencil
./bin/04_constant_potential_stencil

make bin/05_matrix_layout_indices
./bin/05_matrix_layout_indices

make bin/06_lapacke_tridiagonal_eigensolver
./bin/06_lapacke_tridiagonal_eigensolver

make bin/07_grid_norm_overlap_sign
./bin/07_grid_norm_overlap_sign

make bin/08_hermite_gaussian_reference
./bin/08_hermite_gaussian_reference

make bin/09_toy_csv_output
./bin/09_toy_csv_output data/my_toy_samples.csv

# Optional advanced example (requires real LAPACKE):
make bin/10_optional_free_particle_box
./bin/10_optional_free_particle_box
```

If your LAPACKE is in a nonstandard location, override make variables rather than rewriting the sources. For example (substitute **your own** verified paths and compatible libraries):

```bash
make clean
make lapacke LAPACKE_CPPFLAGS='-I/PATH/TO/include' \
  LAPACKE_LIBS='-L/PATH/TO/lib -Wl,-rpath,/PATH/TO/lib -llapacke -llapack -lblas -lm'
```

`make clean` removes **only the named generated example executables**; it protects your `data/`, `plots/`, and your separate project. Do not confuse the presence of a header with a runtime-tested LAPACKE configuration.

### 5. Makefile targets

| Target | Meaning |
|---|---|
| `make help` | Print build and testing routes |
| `make standard` | Build eight dependency-free C++ teaching examples |
| `make lapacke` | Build genuine LAPACKE example E06 |
| `make core` | Build the nine core examples |
| `make optional` | Build E10 |
| `make check-standard` | Run independent arithmetic tests on eight pure C++ examples |
| `make check-lapacke` | Run E06 and check eigenvalues, residual and orthogonality |
| `make check-core` | Run all nine core checks |
| `make check-optional` | Test the optional free-particle convergence case |
| `make check-all` | Test E01–E10 |
| `make check-plot` | Actual E09→CSV→Matplotlib pipeline plus negative tests |
| `make plot` | Create demonstration `data/toy_demo.csv` and `plots/toy_demo.png` **once** |
| `make clean` | Delete named compiled example binaries, not student data |

The `make plot` command deliberately stops rather than overwriting a pre-existing demonstration CSV or PNG. On subsequent attempts choose new filenames or explicitly use the plotter's `--overwrite` option where appropriate. The included files `data/E09_verified_reference.csv` and `plots/E09_verified_reference.png` are genuine sample outputs from E09 and are named so `make plot` remains available on a clean extraction.

### 6. Understand `LAPACKE_dstev`

```cpp
lapack_int LAPACKE_dstev(int matrix_layout, char jobz, lapack_int n,
                         double* d, double* e, double* z, lapack_int ldz);
```

| Argument | Input/output and correct meaning |
|---|---|
| `matrix_layout` | `LAPACK_COL_MAJOR` or `LAPACK_ROW_MAJOR` controls **storage**, not physics |
| `jobz` | `'V'` eigenvalues plus eigenvectors; `'N'` eigenvalues only |
| `n` | Matrix order; LAPACK uses the type `lapack_int` |
| `d` | `n` diagonal coefficients on entry; ascending eigenvalues after success |
| `e` | `n−1` **physical** offdiagonal coefficients; overwritten. E06 allocates `n` elements for safety, not for another physical subdiagonal |
| `z` | Logically an n×n matrix whose columns hold the eigenvectors after `jobz='V'` |
| `ldz` | Stride: `ldz≥n` when storing n×n eigenvectors; here normally n |
| return `info` | 0 = success, negative = bad argument, positive = convergence failure |

For the sampled component at spatial node **i** and state index **k**:

- Column-major: `z[i + k*ldz]`
- Row-major: `z[i*ldz + k]`

Always save an untouched copy of the **original** diagonal and offdiagonal arrays before calling the solver. The routine overwrites `d` and `e`; an eigenpair residual must use the original matrix, not these overwritten values. Compute `T v` directly from the original `d` and `e` using the E02 pattern. Eigenvectors' global signs are arbitrary.

### 7. Why normalization and indexing matter

The solver outputs Euclidean-normalized eigenvectors: `sum_i v_i²=1`. Physical grid normalization is `Delta * sum_i psi_i² = 1`. For an equally spaced grid with `vᵀv=1`, convert to `psi_i = v_i/sqrt(Delta)`. Normalize sampled *analytical* shapes discretely on the same grid before comparing two curves.

The oscillator energies are `E_k=k+1/2`, for zero-based numerical eigenvector/Hermite index `k=0,1,2,...`. The **one-based displayed state** labels in the handout use `s=k+1`, so `E_s=s−1/2` and displayed state `s=30` means `k=29` and polynomial `H_29`, **not** `H_30`.

Physicists' Hermite polynomials satisfy `H_{−1}=0`, `H_0=1`, `H_k=2*x*H_{k−1}−2*(k−1)*H_{k−2}`. The exact *shape* is proportional to `H_k(x)*exp(−x²/2)`. A global numerical/analytical sign disagreement is harmless; choose one sign for a whole state using its weighted overlap if needed. Never reverse sign point-by-point.

**Different grids:** The assessed handout defines `Delta = 2*x_max/(n−1)` with n unknowns including both represented endpoints. Some textbooks and E10 use **interior nodes** with zero fixed boundary values and a different `h` formula. Do not silently substitute those grid conventions.

### 8. Actual E09 CSV and plotting example

The E09 program writes `x,y` with nine ordered numerical data rows at `x=0, 0.25, ..., 2`. It refuses to overwrite an existing path. E09's source contains the toy function and can be modified independently of the assessed assignment. The plotting tool reads the actual CSV; it rejects missing or malformed headers, non-finite values, non-increasing x and a pre-existing output unless `--overwrite` is requested.

```bash
mkdir -p data plots
./bin/09_toy_csv_output data/toy_run01.csv
python3 plotting/plot_toy_csv.py data/toy_run01.csv --output plots/toy_run01.png
# Run a second time only with a NEW filename, or explicitly authorize overwrite of a plot:
python3 plotting/plot_toy_csv.py data/toy_run01.csv --output plots/toy_run01.png --overwrite
make check-plot
```

When preparing your official figures, use output from **your own oscillator calculation**, not these toy samples. Always include units/conventions, state identifiers, labels, legend and a description of what is numerical versus exact.

### 9. Official assessed task checklist (not a solution)

**In the laboratory:**

- [ ] Use `n=100`, `x_max=10`, `Delta=20/(n−1)` and grid nodes `x_i=-x_max+i*Delta`.
- [ ] Independently construct the oscillator Hamiltonian diagonal (`1/Delta²+x_i²/2`) and subdiagonal (`−1/(2*Delta²)`) arrays.
- [ ] Use mandatory `LAPACKE_dstev` to diagonalize and save eigenvalues; extract and physically normalize numerical eigenvectors, then save them.
- [ ] Independently compute the analytical Gaussian/Hermite shapes on the same grid, normalize and save them.
- [ ] Produce an energy-spectrum figure comparing exact and numerical values.

**At home, for the report:**

- [ ] Make separate exact-versus-numerical wavefunction plots for displayed states **1, 2, 3, 15, 20, 30** (zero-based indices 0, 1, 2, 14, 19, 29).
- [ ] Repeat calculations with `n=1000` and the unchanged `x_max=10`.
- [ ] Create and discuss new spectra and wavefunction figures. Explain differences caused by central-difference resolution and by restricting the spatial box.

Only the official teacher/handout determines grading, submission details and deadlines. Suggested data-file schemas and additional residual checks here are helpful scientific practices, **not** invented assessed obligations.

### 10. Debugging checklist

| If you see… | First verify… |
|---|---|
| Wrong `d/e` entries | endpoint-inclusive x grid; factor `1/Delta²`; negative `e` sign |
| Crash or scrambled eigenvectors | row/column layout and `ldz`/array allocation; `lapack_int` ABI |
| `info!=0` | invalid argument or solver convergence; stop instead of plotting broken outputs |
| Residual makes no sense | original `d/e` saved before overwrite; correct eigenvector column |
| Wrong ground-state curve | zero-based `k=0` for one-based displayed `s=1` |
| Norm changes with grid | include `Delta` for physical norm and discrete analytical reference |
| Numerical and exact curves oppose | global sign alignment, never per-grid-point sign changes |
| Higher states agree poorly | finite difference / high oscillation / finite box, not only a coding bug |
| CSV missing or parser rejects | actual file path, exact `x,y` columns, finite numbers |
| Plot unexpectedly unchanged | check newest CSV path, output overwrite guard and labels |

### 11. Provenance, sources and verification environment

- **[H] Official assignment:** T. Chwiej, *Project: Diagonalization of symmetric tridiagonal matrix (quantum harmonic oscillator problem)*, PDF title page dated **19 March 2025**, pp. 1–5, URL above. Some machine-readable indexing has a different date; the rendered title page governs this citation.
- **[L] Official theory lecture:** T. Chwiej, *Diagonalization of dense matrices*, 30-page PDF, URL above.
- **[N] Official LAPACK/LAPACKE:** Netlib documentation and your installation's `lapacke.h`/link provider.
- **[T] This package:** E01–E10 fixtures, source code and numerical checks.

All ten examples were built and run during release verification using C++17; eight pure C++ programs needed no numerical libraries. The two LAPACKE programs were actually linked against a compatible third-party OpenBLAS distribution available in the creation environment; that **is not evidence** that the same provider exists on classroom machines. Matplotlib was tested through the actual E09-produced CSV. The final source and result evidence is recorded in the separate production QA report.
