Constants Example — get_constant and convert_units

This example retrieves eleven mathematical and physical constants via utilities.get_constant(), performs eight representative unit conversions via utilities.convert_units(), and plots 1 atm expressed in five different pressure units on a logarithmic scale.

Example Code

"""IMSL constants and unit conversion example.

Outputs:
- Table of mathematical/physical constants printed to stdout
- Unit conversion demonstrations printed to stdout
- SVG bar chart of pressure unit comparisons saved to test_output/demo_imsl_constants.svg
"""
from __future__ import annotations

from pathlib import Path
from typing import Dict

import matplotlib.pyplot as plt
import numpy as np

from utilities import get_constant, convert_units


def run_demo_imsl_constants() -> Dict[str, object]:
    """Print constants table, demonstrate unit conversion, and save SVG plot.

    Args:
        None

    Returns:
        Dict[str, object]: Dict with ``constants`` (dict), ``conversions``
            (list of tuples), and ``plot_path`` (str).
    """
    constant_names = [
        ("pi", "π"),
        ("e", "e"),
        ("euler_gamma", "Euler-Mascheroni γ"),
        ("golden_ratio", "Golden ratio φ"),
        ("speed_of_light", "Speed of light (m/s)"),
        ("planck", "Planck constant (J·s)"),
        ("boltzmann", "Boltzmann constant (J/K)"),
        ("avogadro", "Avogadro number (mol⁻¹)"),
        ("gas_constant", "Gas constant R (J/mol·K)"),
        ("elementary_charge", "Elementary charge (C)"),
        ("stefan_boltzmann", "Stefan-Boltzmann σ (W/m²·K⁴)"),
    ]

    constants: Dict[str, float] = {}
    print("\nIMSL Constants (IMSL CONST)")
    print("=" * 60)
    print(f"{'Name':<35} {'Value':>22}")
    print("-" * 60)
    for key, label in constant_names:
        val = get_constant(key)
        constants[key] = val
        print(f"{label:<35} {val:>22.6g}")
    print("-" * 60)

    conversions = [
        (1.0, "atm", "Pa"),
        (1.0, "bar", "Pa"),
        (1.0, "psi", "Pa"),
        (100.0, "C", "K"),
        (60.0, "mph", "m/s"),
        (1.0, "kWh", "J"),
        (1.0, "hp", "W"),
        (1.0, "nmi", "m"),
    ]

    print("\nIMSL Unit Conversion (IMSL CUNIT)")
    print("=" * 55)
    print(f"{'Input':<20} {'From':<8} {'To':<8} {'Result':>16}")
    print("-" * 55)
    results = []
    for val, from_u, to_u in conversions:
        result = convert_units(val, from_u, to_u)
        results.append((val, from_u, to_u, result))
        print(f"{val:<20.4g} {from_u:<8} {to_u:<8} {result:>16.6g}")
    print("-" * 55)

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

    pressure_units = ["Pa", "kPa", "bar", "atm", "psi"]
    pressure_values = [convert_units(1.0, "atm", u) for u in pressure_units]

    fig, ax = plt.subplots(figsize=(9, 5))
    bar_colors = ["#b45309", "#d97706", "#f59e0b", "#92400e", "#78350f"]
    bars = ax.bar(pressure_units, pressure_values, color=bar_colors, alpha=0.85,
                  edgecolor="white", linewidth=0.7)
    ax.set_yscale("log")
    ax.set_xlabel("Pressure Unit")
    ax.set_ylabel("Value (equivalent to 1 atm, log scale)")
    ax.set_title("1 atm expressed in different pressure units")
    ax.grid(True, axis="y", alpha=0.4)
    for bar, val in zip(bars, pressure_values):
        ax.text(
            bar.get_x() + bar.get_width() / 2,
            bar.get_height() * 1.3,
            f"{val:.4g}",
            ha="center", va="bottom", fontsize=9,
        )

    fig.tight_layout()
    fig.savefig(plot_path, format="svg")
    plt.close(fig)

    print(f"\nPlot saved to: {plot_path}")
    return {
        "constants": constants,
        "conversions": results,
        "plot_path": str(plot_path),
    }


if __name__ == "__main__":
    run_demo_imsl_constants()

Plot Output

Bar chart of 1 atm expressed in Pa, kPa, bar, atm, psi on a log scale

1 atm expressed in Pa, kPa, bar, atm, and psi. The logarithmic y-axis accommodates the wide numerical range across units.

Console Output

IMSL Constants (IMSL CONST)
============================================================
Name                                                 Value
------------------------------------------------------------
π                                                  3.14159
e                                                  2.71828
Euler-Mascheroni ╬│                                0.577216
Golden ratio φ                                     1.61803
Speed of light (m/s)                           2.99792e+08
Planck constant (J┬╖s)                          6.62607e-34
Boltzmann constant (J/K)                       1.38065e-23
Avogadro number (mol⁻¹)                        6.02214e+23
Gas constant R (J/mol┬╖K)                           8.31446
Elementary charge (C)                          1.60218e-19
Stefan-Boltzmann σ (W/m²·K⁴)                   5.67037e-08
------------------------------------------------------------

IMSL Unit Conversion (IMSL CUNIT)
=======================================================
Input                From     To                 Result
-------------------------------------------------------
1                    atm      Pa                 101325
1                    bar      Pa                 100000
1                    psi      Pa                6894.76
100                  C        K                  373.15
60                   mph      m/s               26.8224
1                    kWh      J                 3.6e+06
1                    hp       W                   745.7
1                    nmi      m                    1852
-------------------------------------------------------

Plot saved to: test_output\demo_imsl_constants.svg