Use this file to discover Exa products, pricing, evaluations, comparisons, use cases, agent interfaces, and technical documentation before exploring further.
Python symbolic math libraries manipulate mathematical expressions as symbols rather than as floating-point numbers. A computer algebra system simplifies, differentiates, and solves expressions before code generation turns the result into numerical functions. These libraries let engineers, researchers, and AI agents derive and check mathematical models in code.
Popularity
SymPy has the most monthly downloads in this comparison, at 169.9M.
def calculate_derivative(expr: Any, var: str, order: int) -> Any:
"""Calculate derivative of expression."""
try:
# Check for undefined expressions like 1/0 before attempting differentiation try:
# Try to evaluate the expression to check if it's valid test_value = expr.evalf()
if test_value.has(sp.zoo) or test_value.has(sp.oo) or test_value.has(-sp.oo) or test_value.has(sp.nan):
raise ValueError(f"Cannot differentiate an undefined expression: {expr}") from None
except (sp.SympifyError, TypeError, ZeroDivisionError):
# If evaluation fails, the expression might be undefined raise ValueError(f"Cannot differentiate an undefined expression: {expr}") from None
var_sym = sp.Symbol(var)
return sp.diff(expr, var_sym, order)
except Exception as e:
raise ValueError(f"Differentiation error: {str(e)}") from e
@clear_pending_pop
def _solve(self, assumptions: Optional[List[FNode]]=None) -> bool:
if assumptions is not None:
bool_ass = []
other_ass = []
for x in assumptions:
if x.is_literal():
bool_ass.append(self.converter.convert(x))
else:
other_ass.append(x)
# maps the fresh literal standing for each non-literal assumption to it self._assumption_keys = {}
if len(other_ass) > 0:
self.push()
for x in other_ass:
key = self.mgr.FreshSymbol(template="_assumption_%d")
self._assumption_keys[key] = x
self.z3.add(self.converter.convert(self.mgr.Implies(key, x)))
bool_ass.append(self.converter.convert(key))
self.pending_pop = True
res = self.z3.check(*bool_ass)
else:
res = self.z3.check()
sres = str(res)
assert sres in ['unknown', 'sat', 'unsat']
if sres == 'unknown':
raise SolverReturnedUnknownResultError
return (sres == 'sat')
def convexify_obj(
obj: cp.Minimize | cp.Maximize,
linearization_map: dict[int, LinearizationData] | None = None,
) -> cp.Minimize | None:
"""Convexify an objective function for DCCP problems.
Linearize non-DCP objectives. If the objective is already DCP, returns it unchanged.
If the objective is a maximization problem, it is negated to convert it into a
minimization problem.
Parameters
---------- obj : cp.Minimize | cp.Maximize
Objective of a problem to be convexified.
linearization_map : dict, optional
Map for caching linearization parameters.
Returns
------- cp.Minimize or None
Convexified objective if linearization is possible, None otherwise.
"""
# negate the objective if it is a maximization problem expr = obj.expr
if isinstance(obj, cp.Maximize):
expr = -expr
if obj.is_dcp():
logger.debug("Objective is already DCP.")
return cp.Minimize(expr)
# linearize the objective expression. If it fails, the gradient is not defined lin = linearize(expr, linearization_map)
if lin is not None:
return cp.Minimize(lin)
return None
CasADi
Builds symbolic models with automatic differentiation for numerical optimization.
Downloads / mo
4.1M
Stars
2.3K
Last release
3.8.2
License
LGPL-3.0-or-later
Strengths
Computes model derivatives.Build Jacobians and gradients from symbolic model expressions.
Generates self-contained C code.Export supported function objects as C code.
Limitations
Existing models need CasADi syntax.Reimplement existing models with CasADi expressions before using its differentiation tools.
Algebraic manipulation is limited.Choose a computer algebra system for broader symbolic expression manipulation.
def overlaps(i,j):
"""
Returns True if two instructions i,j overlap in their encoding.
TODO: Add operand constraints into the solver formula.
"""
if(i.pseudo or j.pseudo):
return False
ILEN=32
instr = Symbol("instr" , BVType(width=ILEN))
imask = Symbol("imask" , BVType(width=ILEN))
imatch = Symbol("imatch" , BVType(width=ILEN))
jmask = Symbol("jmask" , BVType(width=ILEN))
jmatch = Symbol("jmatch" , BVType(width=ILEN))
domains = And([
EQ(imask , BV(i.mask() ,width=ILEN)),
EQ(imatch, BV(i.match(),width=ILEN)),
EQ(jmask , BV(j.mask() ,width=ILEN)),
EQ(jmatch, BV(j.match(),width=ILEN))
])
problem = And([
EQ(instr & imask, imatch),
EQ(instr & jmask, jmatch)
])
formula = And(domains, problem)
return is_sat(formula)
FAQ
SymPy suits general computer algebra, symbolic calculus, and equation solving. CVXPY and Pyomo suit optimization models. Z3 suits satisfiability problems over arithmetic, Boolean, and bit-vector expressions. CasADi suits numerical optimization that needs automatic derivatives.
SymPy is a computer algebra system in Python for symbolic calculus, equation solving, and expression manipulation. It also generates code for numerical use.
CVXPY is a domain-specific language for modeling convex optimization problems in Python.
Pyomo is an optimization modeling framework with algebraic modeling expressions and interfaces to solvers.
CasADi builds symbolic models with automatic differentiation for numerical optimization and generates self-contained C code. Existing models must be rewritten in CasADi syntax.
For coding agents
Found your symbolic math library? Help your agent use it.
Connect Exa so your coding agent can find the library’s documentation, check its API, and look up implementations while you build.