Wednesday, May 27, 2020

checking dimensions using Sympy

Suppose we have the expression
F = m a
and we want to validate the consistency of dimensions.

import sympy.physics.units
import sympy.physics.units.systems.si
from sympy.parsing.latex import parse_latex

eq = parse_latex("F = m a")
lhs = eq.lhs
rhs = eq.rhs
set_of_symbols_in_eq = eq.free_symbols

for each recognized symbol, associate that symbol with the ID in the PDG.
for each symbol ID in the PDG, determine the dimensions of that variable.
for each symbol, create a new "_dim" variable for the dimensions based on the lookup table in the PDG

F = sympy.physics.units.mass * sympy.physics.units.length / (sympy.physics.units.time**2)
m = sympy.physics.units.mass
a = sympy.physics.units.length / (sympy.physics.units.time**2)

I wanted to avoid manually entering the AST,
sympy.physics.units.systems.si.dimsys_SI.equivalent_dims(F_dim, m_dim * a_dim)

This conversation 
https://groups.google.com/d/msg/sympy/_RnbbOqhERM/dehog-xpAgAJ
led to

import sympy
from sympy.physics.units import mass, length, time
from sympy.physics.units.systems.si import dimsys_SI
from sympy.parsing.latex import parse_latex
convert the Latex string into SymPy expression
eq = parse_latex("F = m a")
specify the dimension of each symbol 
F = mass * length / time**2
m = mass
a = length / time**2


dimsys_SI.equivalent_dims( eval(str(eq.lhs)), eval(str(eq.rhs)) )

For more on this content, see
https://groups.google.com/d/msg/sympy/_RnbbOqhERM/YAoJAbyPAgAJ

No comments:

Post a Comment