<s> """<STR_LIT>""" <EOL> from __future__ import division <EOL> from sympy import Add , Mul , Pow <EOL> from sympy . core . compatibility import reduce <EOL> from sympy . physics . unitsystems import Dimension , Unit , Quantity <EOL> def dim_simplify ( expr ) : <EOL> """<STR_LIT>""" <EOL> if isinstance ( expr , Dimension ) : <EOL> return expr <EOL> args = [ ] <EOL> for arg in expr . args : <EOL> if isinstance ( arg , ( Mul , Pow , Add ) ) : <EOL> arg = dim_simplify ( arg ) <EOL> args . append ( arg ) <EOL> if all ( [ arg . is_number or ( isinstance ( arg , Dimension ) and arg . is_dimensionless ) for arg in args ] ) : <EOL> return Dimension ( { } ) <EOL> if isinstance ( expr , Pow ) : <EOL> if isinstance ( args [ <NUM_LIT:0> ] , Dimension ) : <EOL> return args [ <NUM_LIT:0> ] . pow ( args [ <NUM_LIT:1> ] ) <EOL> else : <EOL> raise ValueError ( "<STR_LIT>" % args [ <NUM_LIT:0> ] ) <EOL> elif isinstance ( expr , Add ) : <EOL> if ( all ( isinstance ( arg , Dimension ) for arg in args ) or <EOL> all ( arg . is_dimensionless for arg in args if isinstance ( arg , Dimension ) ) ) : <EOL> return reduce ( lambda x , y : x . add ( y ) , args ) <EOL> else : <EOL> raise ValueError ( "<STR_LIT>" % expr ) <EOL> elif isinstance ( expr , Mul ) : <EOL> args = [ arg for arg in args if isinstance ( arg , Dimension ) ] <EOL> return reduce ( lambda x , y : x . mul ( y ) , args ) <EOL> raise ValueError ( "<STR_LIT>" , expr ) <EOL> def qsimplify ( expr ) : <EOL> """<STR_LIT>""" <EOL> def redmul ( x , y ) : <EOL> """<STR_LIT>""" <EOL> if isinstance ( x , Quantity ) : <EOL> return x . mul ( y ) <EOL> elif isinstance ( y , Quantity ) : <EOL> return y . mul ( x ) <EOL> else : <EOL> return x * y <EOL> args = [ ] <EOL> for arg in expr . args : <EOL> arg = arg . evalf ( ) <EOL> if isinstance ( arg , ( Mul , Pow , Add ) ) : <EOL> arg = qsimplify ( arg ) <EOL> args . append ( arg ) <EOL> q_args , o_args = [ ] , [ ] <EOL> for arg in args : <EOL> if isinstance ( arg , Quantity ) : <EOL> q_args . append ( arg ) <EOL> elif isinstance ( arg , Unit ) : <EOL> q_args . append ( arg . as_quantity ) <EOL> else : <EOL> o_args . append ( arg ) <EOL> if isinstance ( expr , Pow ) : <EOL> return args [ <NUM_LIT:0> ] . pow ( args [ <NUM_LIT:1> ] ) <EOL> elif isinstance ( expr , Add ) : <EOL> if q_args != [ ] : <EOL> quantities = reduce ( lambda x , y : x . add ( y ) , q_args ) <EOL> else : <EOL> quantities = [ ] <EOL> return reduce ( lambda x , y : x + y , o_args , quantities ) <EOL> elif isinstance ( expr , Mul ) : <EOL> if q_args != [ ] : <EOL> quantities = reduce ( lambda x , y : x . mul ( y ) , q_args ) <EOL> else : <EOL> quantities = [ ] <EOL> return reduce ( redmul , o_args , quantities ) <EOL> else : <EOL> return expr </s>
