pint_sympy

pint_sympy

Pint-SymPy integration for unit-aware symbolic calculations.

This module bridges Pint unit registry with SymPy symbolic expressions, providing seamless conversion between physical quantities and symbolic math.

It patches the Pint Quantity and Unit class to add the _sympy_ method, which automatically converts Pint quantities to SymPy expressions with units.

Classes

Name Description
SymPyUnitCache Cache for dynamically created SymPy units to avoid redundant creation.

SymPyUnitCache

SymPyUnitCache()

Cache for dynamically created SymPy units to avoid redundant creation.

Maintains a registry of SymPy unit objects created from Pint definitions, ensuring each unit is only created once and properly configured with scale factors for unit conversion. Used internally by pint_to_sympy() for efficient Pint-to-SymPy conversion.

Methods

Name Description
get_or_create Get cached SymPy unit or create new one with conversion scale factors.
get_or_create
get_or_create(fullname, shortname, is_prefixed)

Get cached SymPy unit or create new one with conversion scale factors.

Retrieves cached SymPy unit object or creates new one from Pint definition, setting up proper scale factors for unit conversion. Handles both prefixed units (kN, cm) using SymPy’s prefix system and non-prefixed compound units (kgf, lbf) by extracting scale factors from Pint base unit conversion.

Parameters
Name Type Description Default
fullname str Full unit name from Pint definition (e.g., ‘kilonewton’, ‘centimeter’, ‘kilogram_force’). Used as SymPy Quantity name. required
shortname str Short unit abbreviation for display (e.g., ‘kN’, ‘cm’, ‘kgf’). Used as SymPy Quantity abbreviation. required
is_prefixed bool Whether the unit uses SI prefixes (True for kN, cm; False for kgf, lbf). Prefixed units handled by SymPy automatically, non-prefixed units require explicit scale factors from Pint. required
Returns
Name Type Description
Any SymPy Quantity object configured for unit conversion. Cached for reuse.
Examples
from keecas.pint_sympy import SymPyUnitCache

# Get or create prefixed unit (kN)
kN = SymPyUnitCache.get_or_create('kilonewton', 'kN', is_prefixed=True)

# Get or create non-prefixed unit (kgf)
kgf = SymPyUnitCache.get_or_create('kilogram_force', 'kgf', is_prefixed=False)

# Subsequent calls return cached objects
kN_cached = SymPyUnitCache.get_or_create('kilonewton', 'kN', is_prefixed=True)
assert kN is kN_cached
Notes
  • Prefixed units (kN, daN, cm) handled automatically by SymPy prefix system
  • Non-prefixed units (kgf, lbf) get scale factors from Pint base unit conversion
  • Scale factors enable full conversion capabilities via pc.convert_to()
  • Created units added to sympy.physics.units module for backward compatibility
  • Cache prevents redundant unit creation and ensures consistency

Functions

Name Description
update_pint_locale Update Pint unit formatter locale for international unit names.
pint_to_sympy Convert Pint quantities to SymPy expressions with units.

update_pint_locale

update_pint_locale(language=None, verbose=False)

Update Pint unit formatter locale for international unit names.

Changes how units are displayed in Pint quantities, switching between compact symbols (kN) and localized full names (kilonewton, chiloNewton, etc.). Useful for engineering documentation in different languages. Automatically called when config.language changes, but can be invoked manually for custom locale control.

NOTE: Respects config.language.disable_pint_locale setting. When True (default), preserves compact unit symbols. When False, enables locale-specific unit names.

Parameters

Name Type Description Default
language str | None Two-letter language code (de, es, fr, it, pt for full support; da, nl, no, sv, en for keecas translations only). If None, uses language from keecas config. Defaults to None. None
verbose bool If True, prints debugging information about locale changes including before/after states and configuration status. Useful for troubleshooting locale behavior. Defaults to False. False

Examples

from keecas import u
from keecas.pint_sympy import update_pint_locale

# Manual locale control with verbose output
update_pint_locale('it', verbose=True)

F = 100*u.kN
print(f"{F}")  # Shows: 100 chiloNewton
Pint locale sync disabled by configuration
100.00 kN
# Manual locale control with verbose output
update_pint_locale('de', verbose=True)

A = 50*u.cm**2
print(f"{A}")  # Shows: 50 Zentimeter ** 2
Pint locale sync disabled by configuration
50.00 cm²
from keecas import config, u

# Keep compact symbols (default behavior)
config.language.disable_pint_locale = True  # Default

F = 100*u.kN
print(f"{F}")  # Shows: 100 kN (compact symbol preserved)
100.00 kN
# Fallback language behavior
update_pint_locale('sv')  # Swedish - no Pint locale available

# Unit names stay in English, but keecas terms (VERIFIED, etc.) are Swedish
F = 100*u.kN
print(f"{F}")  # Shows: 100 kilonewton (English fallback)
100.00 kN

Notes

  • Automatically called when config.language changes
  • Respects config.language.disable_pint_locale (default: True)
  • Full Pint locale support: de, es, fr, it, pt (5 languages)
  • Fallback to English units: da, nl, no, sv, en (5 languages)
  • Conservative behavior: doesn’t change locale unnecessarily
  • Manual mode activated if user directly modifies unitregistry.formatter

pint_to_sympy

pint_to_sympy(quantity)

Convert Pint quantities to SymPy expressions with units.

Bridges Pint’s physical quantities with SymPy’s symbolic math, enabling symbolic calculations with units. Called automatically via SymPy’s sympy protocol when using sympify() or SymPy operations on Pint quantities. Creates SymPy units dynamically as needed and configures them for full conversion support.

NOTE: This function is called automatically by SymPy. Users typically don’t invoke it directly - just use Pint quantities in SymPy expressions.

Parameters

Name Type Description Default
quantity pint.Quantity Pint Quantity object with magnitude and units (e.g., 100u.kN, 50u.cm**2). Can also be pint.Unit object (treated as 1*unit). required

Returns

Name Type Description
Any SymPy expression combining magnitude and units as symbolic quantities,
Any ready for symbolic manipulation and unit conversion.

Examples

from keecas import symbols, u, pc, show_eqn
from sympy import sympify

# Automatic conversion via sympify
F_pint = 100*u.kN
F_sympy = sympify(F_pint)  # Calls pint_to_sympy automatically

print(type(F_pint))   # <class 'pint.Quantity'>
print(type(F_sympy))  # <class 'sympy.Mul'>
<class 'pint.Quantity'>
<class 'sympy.core.mul.Mul'>
# Use in symbolic expressions
F, A_load = symbols(r"F, A_{load}")

_p = {
    F: 100*u.kN,      # Pint quantity
    A_load: 50*u.cm**2
}

# Pint quantities automatically converted in SymPy operations
sigma = symbols(r"\sigma")
_e = {
    sigma: "F / A_load" | pc.parse_expr
}

_v = {
    k: v | pc.subs(_p | _e) | pc.convert_to([u.MPa]) | pc.N
    for k, v in _e.items()
}

show_eqn([_p | _e, _v])

\[\begin{align} F & = 100{\,}\text{kN} & \\[8pt] A_{load} & = 50{\,}\text{cm}^{2} & \\[8pt] \sigma & = \dfrac{F}{A_{load}} & = 20.0{\,}\text{MPa} \end{align}\]

# Compound units with exponents
A = 50*u.cm**2  # Area

# Automatically handles exponents
A_sympy = sympify(A)
print(A_sympy)  # 50*centimeter**2
50*centimeter**2
# Custom Pint units work seamlessly
pressure = 10*u.MPa
force = 100*u.kgf  # Non-SI unit

# Both convert correctly in SymPy
p_sympy = sympify(pressure)
f_sympy = sympify(force) | pc.convert_to(u.N)

Notes

  • Automatically creates new SymPy units if they don’t exist in sympy.physics.units
  • Uses SymPyUnitCache to avoid redundant unit creation
  • Maintains unit relationships and dimensional analysis capabilities
  • Handles both prefixed units (kN, cm) and non-prefixed units (kgf, lbf)
  • Configured via sympy protocol: Pint objects work directly in SymPy expressions
  • All Pint units convert correctly via pc.convert_to() after conversion