pythonsageipycanvas

Type is not JSON serializable error in ipycanvas


I am trying to use ipycanvas in Jupyter notebook with SageMath 9.3 (I also tried 9.3.rc2) for macOS 11.4, and Python 3. When I was using SageMath 9.2 and Python 3 ipycanvas was working fine, but when I updated sage to SageMath 9.3 I started having problems.

The first thing I did was installing again ipycanvas on my mac terminal

$ sage —pip install ipycanvas

And the installation was apparently successful.

However, even running a minimal instance of ipycanvas produces type JSON serializable errors, e.g.,

canvas = Canvas(width=200, height=200)
canvas.stroke_style = 'blue'
canvas.stroke_line(0, 0, 150, 150)
canvas

enter image description here

I cannot figure out why I am getting an error this time. How do I serialize sage rationals?

The solution I found is just converting every sage number to a float. However this is a little bit annoying while typing. Am I missing something?


Solution

  • TL; DR Unfortunately you will need to convert the numbers that you need to pass to ipycanvas

    I think you have figured out the answer in your own question. It turns out that numbers in Sage notebooks are by default interpreted as Sage types (check out https://doc.sagemath.org/html/en/tutorial/tour_coercion.html#types-versus-parents for more info on types coercion). So when you type, say 7 it casts as Integer(7) as in the element 7 in the ring of integers Z.

    The class Integer is highly optimised for algebraic computations, however it contains some methods/attributes that cannot be JSON- serialised*, which is what ipycanvas need to render javascript.