SymPy: Symbolic Mathematics in Python
sympy.org
sympy.org
To illustrate what I mean by "expressing systems of equations in a declarative way", here is a toy-example of how to estimate the position of the a sensor with respect to a robot's center if you have access to a dataset containing robot positions and the sensor positions. The 'naive' approach (it very often works) is to solve an over-constrained system with a gradient-descent. To perform a gradient descent, you need a residual function and its jacobian. Here's how you would do to compute it with Sympy. (Note: you'd just have to define the `transform` and `invert` functions...)
# Pose of a sensor in robot frame (to be estimated)
xa, ya = symbols("xa, ya")
a = Matrix([xa, ya, ta])
# Position of the robot at time t
rx, ry, rt = symbols("rx, ry, rt")
rk = Matrix([rx, ry, rt])
# Measure of the sensor at time t
gx, gy = symbols("gx, gy")
gk = Matrix([gx, gy, 0])
# Estimated x (from the measures)
estimated_a = transform(invert(rk), gk)
# compute the norm of the gk, squared
n2_mat = norm2(estimated_a - a)
n2 = sympy.collect(sympy.expand(n2_mat[0, 0]), a).simplify()
# Compute the jacobian
J = n2_mat.jacobian([xa, ya, ta])
# Print what is necessary for Guass-Markov regression
print("\n\nres =", n2)
print("\nJacobian = ", J)Finite differences does indeed have stability issues, and even if you apply some tricks will only give you about half float precision
Anyway,if your day job needs something like this you're better off using a lisp than python.
First write down the equations, then let SymPy do the laborious math part and turn the output into C code.
I'm guessing this is why you don't see a lot of SymPy projects in the wild. It was used for some intermediate calculations, and the results were turned into the product's code and the symbolic code is thrown away.
You could maybe calculate the Jacobian in C code using automatic differentiation. Might be less C-code, might be less elementary operations done in the C code, and you would not need to be copy-pasting complex symbolically derived formulas from Python to C.
Problem was that the symbolic results were way too complicated and the simplify function didn't help much. So, I got back to manual differentiation.
Here is a little tutorial for anyone looking to get started: https://minireference.com/static/tutorials/sympy_tutorial.pd...
Also available in runnable notebook format: https://colab.research.google.com/github/minireference/sympy... (read only = http://nbviewer.ipython.org/github/minireference/sympytut_no... )
Last but not least, for anyone interested in trying SymPy without installing anything, there is always the SymPy live shell: https://live.sympy.org/ (runs Python + SymPy in the browser thanks to WebAssembly)
Obviously you could find a list of every ticker symbol and create a few thousand symbols before parsing, but you don't always have the luxury of a complete/up-to-date list, or doing so might create too many symbol objects and cause performance problems.
As far as I know, Wolfram/Mathematica, LaTex, SymPy, Jupyter, Sage etc all rely on typewriter text for composing and inputting math. For this (and only this) reason, Maple is the only application that ever resonated with me, because input may be written in the same form it's written by hand, and it's baffling this capability isn't more commonplace. Is this a barrier to anyone else?
A very long time ago I used to play around with Derive5 in my youth. It was the most affordable Computer Algebra System (CAS) of the time and I learned to program in that funky one liner programming language where I had to strip all the white space from my editor and always be careful to balance parenthesis. I should dig up those old files and upload them to my github. I've been actually meaning to reimplement those operations in a more modern CAS system and see if I can more densely plot these curves I was studying with some iso-arc-length families of exponentials about the point (0,1).
The results were Mathematica failed to solve 1,523 problems, Sympy failed to solve 48,529.
So it has some catching up to do.
As an open source project depending on volunteers (or is it just the one major author?) I am impressed that sympy does as much as it does.
Not that I want to dispute this, but depending on what you meant, there is in fact such an algorithm: https://en.wikipedia.org/wiki/Risch_algorithm
Though often it is not implemented because it is quite complex (its details covering two thick books) and many of the special cases it covers rarely crop up in the real world, so the effort isn't worth it.
The caveat of Risch's algorithm is that it only "works" if the function you are trying to integrate has an elementary antiderivative. Many of the problems that Mathematica can solve (but SymPy fails at) involved special (i.e. non-elementary) functions.
I imagine the difference is even bigger in things like solving ODE's/PDE's.
Nice. The PhDs just need take care their contributions aren't misappropriated. See https://en.m.wikipedia.org/wiki/Rule_110
By comparison, open source projects are developed by people with a wide range of knowledge level and commitment, and you simply can't expect the quality to be the same.
I find that discussions on HN often fail to acknowledge that proprietary software is usually extremely good at their domain, and what companies put into UX, support and the development/feedback loop are actually very valuable.
Thank you for allowing me to disambiguate.
I have not met any developers for either of these products but I know that SymPy has a huge list of contributors for a project of its size. See: https://github.com/sympy/sympy/blob/master/AUTHORS
You may not be hearing about SymPy users because SymPy is not a monolithic product. It is a library. If you know mathematicians big into using Python, they are probably aware of SymPy as it is the main attraction when it comes to symbolic computation in Python. They wouldn't necessarily spit out a bunch of libraries in the same breath as "I use Python."
1261 is an impressive number of contributors. I am interested to see if I could round up some people to hack up some of these test failures.
In the same vein, I was expecting SymPy to be like 80% of Mathematica but the given benchmark says it's about 25%. So I was suprised.
And I'm not thinking about UX, support, etc. which are indeed not often very good because, I guess, people prefer to put their energy in things that have the bigger leverage.
Additionally, SageMath (which depends on SymPy) is the more comparable product (and is open source).
Why does that matter?
2) able to be around if a single CEO isn't around (Wolfram)
3) able to continue if the supporting company is not profitable anymore
4) possibility of greater oversight if popularity rises
5) extensible if one puts the effort into it
This is like opining that the best "car" out there is a gokart you can get complete schematics on, for all of these reasons. I think most of us would accept the argument that the better cars are the ones that pass metrics aimed at cars. In this analogy, the better algebra system is the one that does the most algebra.
Additionally, Mathematica is not really that expensive.
You can try to broaden it to saying it is a better vehicle for you. And, sure, for a lot of folks the cost will be important there. As a CAS, though, Mathematica is tough to beat.
I'm not arguing that SymPy is going to beat Mathematica on benchmarks. But if both of them meet your needs, and you like having money and/or control of the code, SymPy wins.
Similarly, a lamborghini is almost certainly an objectively faster car. Such that if you were discussing fast vehicles and someone pointed out that their ebike was good enough for them, it would be a statement out of nowhere that is not using the rubric for ordering that was being discussed. Are they wrong that the ebike is a better choice for them? Almost certainly not. Would it be valid to say that it is the best fast vehicle because of that? (I say this as someone that loves bikes and is fairly anti car...)
And there would be other rubrics that would shine light in either direction regarding python. Arguably, the stewardship of the language lost a lot of trust with people in the hilariously bad 2->3 migration. More so in how bad dependency management has become. Yes, you can roll your own, but people with large support contracts can almost certainly offload a lot of that to the team on Mathematica, if that is truly a concern.
(I could similarly cast shade on Mathematica, but I think my point is made. Yes, you can have a rubric that changes which is the better choice for a situation. No, there is no total ordering of correct choices.)
I also think the math systems will lag for more than just donations. The work to make a good CAS is pretty intense. A lot like a good SAT system. Or really anything that is deep in the weeds of computer science. A lot of us are so far removed from the math that they focus on, that it can be mind bending to try and get back into it. (Indeed, for a lot like me, we were probably never really great at it, in the first place.)
Mathematica and Matlab are interesting to consider, as they are likely very well integrated into older workflow systems from the mainframe era. In particular, I'd expect the high end simulations for car and vehicle designs are much more integrated with those than anything open source. And a lot of that is largely availability of what they are integrating with. Most of us do not have the science labs and all of the equipment that goes with it.
Which, I think, is a bad feedback loop on this. For folks without those labs, Mathematica/Matlab are prohibitively expensive. For those with the labs, they are probably a rounding error. And there is no real path from the current equilibrium to one that can get it to more people. (The old path was free access in college. But that is becoming less of a thing in modern programming jobs.)
I ask because I always see open source thrown around as if it's some paragon of quality and productiveness. In reality, the actual usefulness of a product is fairly independent of its open source status. And rarely does it matter all that much to a project that a software component is open source or not.
I have also modified and extended open source implementations in sage to work with cases I needed. And I've added some of this back to sage.
It is undeniable that Mathematica evaluates crazy integrals better than most other tools. But it will happily output complete nonsense. And you can't check!
Do you actually do this verification? How do you accomplish this? The software stacks are huge. Why do you trust other people over the people who develop Mathematica, who just happened to be paid?
It is also true that, just like with a generic math research paper, that I don't check every claim of every step of every implementation of every algorithm in the process. But checking is possible, and when we find errors (which we do frequently) we can look and try to explain what it happening.
But when we find errors in tools such as Mathematica, we cannot. We report the errors and then know nothing more. (And sometimes the errors are never fixed).
- "How should logarithms be taught?" [with python and SymPy] https://news.ycombinator.com/item?id=28518565#28519356
From "SymPy - a Python library for symbolic mathematics" (2020) https://news.ycombinator.com/item?id=23767513 :
> NumPy for Matlab users: https://numpy.org/doc/stable/user/numpy-for-matlab-users.htm...
> SymPy vs Matlab: https://github.com/sympy/sympy/wiki/SymPy-vs.-Matlab
How do I speed up the start time for it - any ideas? Recompile it with PyPy or similar?
https://nbviewer.org/url/canonical.org/~kragen/sw/dev3/sympy... (solving a multivariate quadratic with math pretty-printing)
https://nbviewer.org/url/canonical.org/~kragen/sw/dev3/tiny-... (my cheatsheet of quick-and-dirty numpy/pylab plots, including some sympy examples)
https://nbviewer.org/url/canonical.org/~kragen/sw/dev3/secan... (using sympy to symbolically differentiate an existing python function, which is something you can't usually do, in order to find its minimum in closed form)
https://nbviewer.org/url/canonical.org/~kragen/sw/dev3/max-p... (some basic circuit analysis with basic calculus with sympy)
https://nbviewer.org/url/canonical.org/~kragen/sw/dev3/latex... (various fiddling around with mathjax formatting and sympy, including some analysis of minsky's circle algorithm from hakmem)
I checked now, and it seems that on this front a lot of development in sympy made it possible that we know how very good libraries built on top of it [1] [2]. There is even now a Jupyter notebook example on schwarzschild metric [3].
[1] https://docs.einsteinpy.org
[2]https://github.com/spacetimeengineer/spacetimeengine
[3] https://github.com/sympy/sympy/blob/master/examples/intermed...
I haven't used Mathematica much, but I have a feeling that it's still more symbolically powerful (or requires less wrangling) than SymPy? I'd appreciate if somebody with more experience in Mathematica could lay it out flat for me if that's the case.
Their downsides are that their languages are not very well suited as general purpose languages, many times the algebraic manipulations you have to perform aren't that complicated and you'd rather work in a "real" language.
Yet another case where python isn't the best in class but still workable and able to benefit from its vast general-purpose ecosystem.
That said sympy is quite a cool little library for learning.
Look, we all love open source, but we aren't doing anybody any favors by pretending the open source alternative is better when it isn't. I would encourage anyone whose needs are satisfied by sympy/sagemath to opt for the open alternative, but the question was whether or not Mathematica as of now, early 2024, is better. The unfortunate reality is that it is.
I can do an import sage as the top of any python script.
It's a library.
And since I get all of python for free it's better than Mathematica.
Your windows/Linux analogy is also not very relevant here. Both are popular in different areas.
Getting some random laptop and figuring out what kernel mods to enable and hope that the specific chipset revision was supported, or maybe a patch available that might work was, in fact, a lot of bullshit to put up with to get, say, sound.
sympy will do a lot. but you're probably going to have to reach for a big book of integrals, or find a friendly mathematician to identify the equation and possible approaches. Mathematica as a paid product has a lot of time and effort spent avoiding resorting to asking for help. Much much more built in.
As an undergrad or a hobbyist you probably want to stay "lower" and slog through the calculations when you're stuck. This is part of the process of understanding. But as a professional, or a more advanced user, screwing around for a week looking for a solution is a waste of time and expertise. Spring the cash, and move forward immediately.
I'm not trying to put words in your mouth, but I think there is some nuance that this maybe helps people understand your point.
"Better" really really depends on where you are and what you're trying to do.
I will say a really nice thing about Mathematica is consistency.
How does this aspect work out in practice?
https://github.com/daniel-molina/visualequation
https://pypi.org/project/latex2sympy2/
https://ipython.org/ipython-doc/2/interactive/qtconsole.html
Edit: That might be overcomplicating things, there are already better alternatives: https://tex.stackexchange.com/questions/57068/wysiwyg-latex-...
https://github.com/jupyterlite/jupyterlite/tree/main/py/jupy... :
> Initial support for interactive visualization libraries such as: altair, bqplot, ipywidgets, matplotlib, and plotly
Especially the print(latex(...)) command has helped a ton to write large matrices in notes for courses.
For example Country="US" and Type="Sales" is not exclusive with Type in ("Sales", "Purchase")
What would be an approach to solving this?
You might, for example, create a new logical expression for each pair of your original expressions, joining each pair with AND, and then join those AND pairs with OR. Then ask the SMT solver to generate an unsatisfiability proof.
I have in the past used Mathematica, which I did think was more powerful for symbolic math to be honest, but it had the downside of not being free...!
For many operations it is orders of magnitude faster than sympy.
oh, i see you said 'oldest commit'. well, what's news about sympy is the 14 years of commits since then
https://news.ycombinator.com/newsguidelines.html says
> On-Topic: Anything that good hackers would find interesting. That includes more than hacking and startups. If you had to reduce it to a sentence, the answer might be: anything that gratifies one's intellectual curiosity.
and, though it's not even stated, it includes more than news
Where are you getting 14 years from?