EVLSF Example — Toeplitz Matrix Eigenvalues

This example creates a 4x4 symmetric Toeplitz matrix and computes its eigenvalues using eigensystems.evlsf() along with the spectral condition number via eigensystems.condition_number().

Example Code

"""IMSL EVLSF example: eigenvalues of a symmetric Toeplitz matrix.

Reproduces the IMSL EVLSF style example:
- Create a 4x4 symmetric Toeplitz matrix.
- Compute eigenvalues with evlsf().
- Compute condition number with condition_number().
- Line plot of sorted eigenvalues.
- Save to test_output/example_imsl_evlsf.svg

Outputs:
- Printed table of eigenvalues and condition number
- SVG line plot saved to test_output/
"""
from __future__ import annotations

from pathlib import Path

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np

from eigensystems import condition_number, evlsf


def run_demo_evlsf() -> dict:
    """Run IMSL EVLSF example: symmetric Toeplitz matrix eigenvalues.

    Creates a 4x4 symmetric Toeplitz matrix, computes its eigenvalues
    (which are real and ascending by definition of evlsf), computes the
    spectral condition number, and produces a line plot.

    Args:
        None

    Returns:
        dict: Result dictionary with keys ``eigenvalues`` (np.ndarray),
            ``condition`` (float), and ``plot_path`` (str).
    """
    # 4x4 symmetric Toeplitz: T[i,j] = 4 - |i-j|
    n = 4
    a = np.array([[4.0 - abs(i - j) for j in range(n)] for i in range(n)])

    result = evlsf(a)
    cond = condition_number(a)

    print("\nIMSL EVLSF Example: Symmetric Toeplitz Matrix Eigenvalues")
    print("Matrix T[i,j] = 4 - |i-j|:")
    for row in a:
        print("  " + "  ".join(f"{v:6.2f}" for v in row))
    print("-" * 50)
    print(f"{'Index':<8} {'Eigenvalue':>16}")
    print("-" * 50)
    for i, ev in enumerate(result.eigenvalues):
        print(f"  {i+1:<6} {ev:>16.8f}")
    print("-" * 50)
    print(f"  Condition number (2-norm): {cond:.6f}")
    print(f"  Sum of eigenvalues:        {np.sum(result.eigenvalues):.6f}")
    print(f"  Trace of A:                {np.trace(a):.6f}")

    output_dir = Path("test_output")
    output_dir.mkdir(parents=True, exist_ok=True)
    plot_path = output_dir / "example_imsl_evlsf.svg"

    fig, ax = plt.subplots(figsize=(7, 5))
    idx = np.arange(1, n + 1)
    ax.plot(idx, result.eigenvalues, "o-", color="#be123c", linewidth=2,
            markersize=9, markerfacecolor="#e11d48", markeredgecolor="#7f1d1d",
            label="Eigenvalues (evlsf)")
    ax.fill_between(idx, result.eigenvalues, alpha=0.15, color="#be123c")
    ax.set_xticks(idx)
    ax.set_xticklabels([f{i}" for i in idx])
    ax.set_xlabel("Eigenvalue index (ascending)")
    ax.set_ylabel("Eigenvalue")
    ax.set_title(
        "IMSL EVLSF: Symmetric Toeplitz Matrix Eigenvalues\n"
        f"(condition number = {cond:.3f})"
    )
    ax.legend()
    ax.axhline(0, color="gray", linewidth=0.8, linestyle="--")
    fig.tight_layout()
    fig.savefig(plot_path, format="svg")
    plt.close(fig)
    print(f"\nPlot saved: {plot_path}")

    return {
        "eigenvalues": result.eigenvalues,
        "condition": cond,
        "plot_path": str(plot_path),
    }


if __name__ == "__main__":
    run_demo_evlsf()

Plot Output

Line plot of sorted Toeplitz eigenvalues

Eigenvalues of the 4x4 symmetric Toeplitz matrix, sorted in ascending order. The shaded region highlights the spectral range.

Console Output

IMSL EVLSF Example: Symmetric Toeplitz Matrix Eigenvalues
Matrix T[i,j] = 4 - |i-j|:
    4.00    3.00    2.00    1.00
    3.00    4.00    3.00    2.00
    2.00    3.00    4.00    3.00
    1.00    2.00    3.00    4.00
--------------------------------------------------
Index          Eigenvalue
--------------------------------------------------
  1            0.58578644
  2            0.90098049
  3            3.41421356
  4           11.09901951
--------------------------------------------------
  Condition number (2-norm): 18.947211
  Sum of eigenvalues:        16.000000
  Trace of A:                16.000000

Plot saved: test_output\example_imsl_evlsf.svg