Create the strongest calculator environment with Sympy + Jupyter

Let's create the strongest calculator environment with Sympy + Jupyter.

What is Sympy?

Sympy is an algebraic math library written in Python, think of it like Mathematica or Maxima. It's easier for programmers to write formulas in Python, the page below is a great introduction to Sympy, and if you don't know Sympy, read on.

3.2. Sympy: Algebraic Calculations in Python

Use Sympy from Jupyter

You don't have to do anything special, but type'magic' to display the formulas and graphs in the first cell of Jupyter.

from sympy import *
init_printing()

Next, let's type a formula.

x = Symbol('x')
y = Symbol('y')
Rational(3 ,2)*pi + exp(I*x) / (x**2 + y)
\frac{3 \pi}{2} + \frac{e{i x}}{x{2} + y}

If the formula comes out, it is successful.

Untitled - Google Chrome_021.png

About init_session ()

According to the information from @ void99_, there is something called ʻinit_session that is more sophisticated than ʻinit_printing.

from sympy import *
init_session()

Frequently used variables and functions are predefined, which is convenient.

IPython console for SymPy 1.0 (Python 3.5.2-64-bit) (ground types: python)

These commands were executed:
>>> from __future__ import division
>>> from sympy import *
>>> x, y, z, t = symbols('x y z t')
>>> k, m, n = symbols('k m n', integer=True)
>>> f, g, h = symbols('f g h', cls=Function)
>>> init_printing()

Documentation can be found at http://docs.sympy.org/1.0/

Symbol settings

Formula symbols can be set with `Symbol'.

x = Symbol('x')
y = Symbol('y')

Multiple symbols can be set at once by using symbols.

x, y = symbols("x y")

It can also be set using the sympy.abc module.

from sympy.abc import x, y

Formula simplification

The most convenient function when treating it as a calculator is to simplify the formula. If you knead the formula, you can make a very long formula, but if you use Sympy, it is one shot.

For example, suppose you have the following formula: This formula is probably a Bezier curve formula or something that I knead.

(A-B)*C + B**2 + (-B-A)*C + B**2

Written in Sympy, it looks like this:

from sympy.abc import A, B, C
f = (A-B)*C + B**2 + (-B-A)*C + B**2
2 B^{2} + C \left(- A - B\right) + C \left(A - B\right)

Substituting an expression into Sympy will sort the terms for clarity. If you want to further simplify the formula, use simpfly.

simplify(f)
2 B \left(B - C\right)

ʻAhas disappeared and it has become extremely simple. You can also useratsimp`, which is often used in Maxima.

ratsimp(f)
2 B^{2} - 2 B C

There are many types of formula simplifications, see below for details.

http://docs.sympy.org/dev/modules/simplify/simplify.html

Solve the equation

from sympy.abc import A, B, C, D

(A-B)*D + C**2 + (-B-A)*C+B**2
B^{2} + C^{2} + C \left(- A - B\right) + D \left(A - B\right)

If you want to solve ʻA in the above formula, use solve`.

solve((A-B)*D + C**2 + (-B-A)*C+B**2, A)
\left [ \frac{1}{C - D} \left(B^{2} - B C - B D + C^{2}\right)\right ]

Assign a value to a variable in an expression

You can assign a value to a variable in an expression with subs.

f = (A-B)*D + C**2 + (-B-A)*C+B**2

# A,B,Assign a value to C
f.subs([(A, 10), (B, 20), (C, 30)])
- 10 D + 400

The argument of subs can also be passed a dictionary.

f.subs({A: 10, B: 20, C: 30})
- 10 D + 400

If there is only one variable you want to assign, you can specify a variable in the first argument and a value in the second argument.

f.subs(A, 10)
B^{2} + C^{2} + C \left(- B - 10\right) + D \left(- B + 10\right)

Derivative / partial differential

Use diff for differentiation / partial differentiation.

diff(x**2 + 3*x + 100)
2 x + 3

For partial differential, specify the second argument.

diff(3*x**2 + 3*x*y + y**2, x)
6 x + 3 y

Factorization / prime factorization

Factorize uses factor.

factor(x**2-x-6)
\left(x - 3\right) \left(x + 2\right)

Use factor int for prime factorization.

factorint(3417)
>>> {3:1,17:1,67:1}

The dictionary is returned, which means 3 ^ 1 * 17 ^ 1 * 67 ^ 1 = 3417.

Matrix / vector

Use the Matrix class.

Matrix([[1, 0], [0, 1]])
\left[\begin{matrix}1 & 0\\0 & 1\end{matrix}\right]

There is a vector, but it is difficult to use, so treat it as a one-column matrix.

θ = Symbol("θ")

P = Matrix([2*cos(θ), 2*sin(θ)])
\left[\begin{matrix}2 \cos{\left (θ \right )}\\2 \sin{\left (θ \right )}\end{matrix}\right]

To perform vector operations, use the transpose function to transpose.

transpose(P) * P
\left[\begin{matrix}4 \sin^{2}{\left (θ \right )} + 4 \cos^{2}{\left (θ \right )}\end{matrix}\right]

Copy and paste formulas in Latex

With Jupyter and Sympy, you can easily copy the output formulas to Qiita. Right-click on the formula and select Show Math As → Tex Commands.

メニュー_013.png

A pop-up like this will appear, so copy and paste the formula.

MathJax Equation Source - Google Chrome_015.png

This Latex is convenient because it can be pasted directly on Qiita.

Output formula with AA

ASCII art with pprint? You can also output formulas with.

pprint(Integral(sqrt(1/x), x), use_unicode=True)
"""
⌠           
⎮     ___   
⎮    ╱ 1    
⎮   ╱  ─  dx
⎮ ╲╱   x    
⌡  
"""

It's convenient when pasting formulas into source code.

Draw a graph

You can draw a graph with sympy.plotting.plot. It is convenient because you can pass the formula of Sympy as an argument as it is.

from sympy.plotting import plot

y = -(x+2)*(x+1)*(x-1)

#x is-Draw a graph from 4 to 4
plot(y, (x, -4, 4))

ダウンロード (9).png

Get started quickly with .ipynb templates

Jupyter + Sympy is very convenient, but you have to type magic in the first cell every time. This is surprisingly troublesome, isn't it?

In my article, there is Generate Jupyter notebook ".ipynb" in Python. Using this, let's write a script that will generate ipynb with various inputs from the beginning.

Cooperation between Jupyter and PyCharm

PyCharm is a Python integrated development environment (IDE), which has very powerful complementary features and is the strongest Python development environment. Actually, PyCharm can be linked with Jupyter, and Jupyter's expressive power + PyCharm's powerful complementary function is quite comfortable.

メニュー_011.png

However, when dealing with mathematical formulas, PyCharm's Jupyter output is poor, so it is better to use the browser version of Jupyter. So I don't use PyCharm's Jupyter, instead I use ʻExtranal Tools`.

Create an .ipynb generation script

Create the following script somewhere that is easy to refer to.

#!/usr/bin/env python3
# coding:utf-8
import sys
import os
import nbformat

output_dir = sys.argv[1]
output_file = input("input ipynb name:")

nb = nbformat.v4.new_notebook()

title = "#title"

code = """
%matplotlib inline
from sympy import *
init_session()
"""

nb["cells"] = [
    nbformat.v4.new_markdown_cell(title),
    nbformat.v4.new_code_cell(code)
]

if not output_file.endswith(".ipynb"):
    output_file += ".ipynb"

with open(os.path.join(output_dir, output_file), "w") as f:
    nbformat.write(nb, f)

print("ok.")

Register as PyCharm's External Tool

Open PyCharm's File (F) menu and select Settings ...

メニュー_016.png

Select "Tools"-> "External Tools" in the settings dialog and press the "+" button.

Settings_017.png

The setting dialog will appear, so add the following items.

item input
Name Please enter a suitable name
Description Please enter an appropriate explanation
Program Python path where Jupyter is installed
Parameters The script path from earlier$FileDir$

Edit Tool_018.png

You can now generate .ipynb from PyCharm's right-click menu!

Select "External Toos"-> "Registered Tool Name" from the right-click menu of PyCharm.

メニュー_019.png

When you enter the file name in the console, various pre-filled .ipynb files will be generated from the beginning.

python35 - [~-PycharmProjects-python35] - ...-document-document.ipynb - PyCharm Community Edition 2016.3.2_020.png

If you have a more convenient way to use it, please post it.

Afterword

The output of .ipynb was longer than Sympy, but Sympy is very useful.

It is very useful for game programmers and those who use mathematical formulas. This library is for those who are not good at math.

Recommended Posts

Create the strongest calculator environment with Sympy + Jupyter
Create an environment with virtualenv
Switch virtual environment with jupyter
Reflect the virtual environment created with Miniconda in Jupyter notebook
Easy Jupyter environment construction with Cloud9
Create a virtual environment with Python!
Prepare the development environment with anyenv
Get the strongest environment with VS Code, Remote-Containers and remote docker-daemon
Create an arbitrary machine learning environment with GCP + Docker + Jupyter Lab
Build Jupyter Lab (Python) environment with Docker
[Python] Create a virtual environment with Anaconda
Create a graph using the Sympy module
Build the execution environment of Jupyter Lab
Create Python + uWSGI + Nginx environment with Docker
Create a virtual environment with Python_Mac version
The strongest Python development environment PyCharm's recommendation
The strongest Python integrated development environment PyCharm
If you want to enter the virtual environment with jupyter, nb_conda_kernels is recommended
Note: Prepare the environment of CmdStanPy with docker
Prepare the execution environment of Python3 with Docker
Analytical environment construction with Docker (jupyter notebook + PostgreSQL)
Build the fastest Django development environment with docker-compose
Execution environment on the Web by "Project Jupyter"
Create execution environment for each language with boot2docker
Create a virtual environment with conda in Python
Create a python3 build environment with Sublime Text3
Try using conda virtual environment with Jupyter Notebook
Create Nginx + uWSGI + Python (Django) environment with docker
Fill the browser with the width of Jupyter Notebook
I tried playing with the calculator on tkinter
Create a translation tool with the Translate Toolkit
How to quickly create a machine learning environment using Jupyter Notebook with UbuntuServer 16.04 LTS
Virtual environment construction with Docker + Flask (Python) + Jupyter notebook
How to create a submenu with the [Blender] plugin
The story of sharing the pyenv environment with multiple users
Create a virtual environment with Anaconda installed via Pyenv
Monitor the training model with TensorBord on Jupyter Notebook
Create a Todo app with the Django REST framework
The strongest PySide / PyQt development environment is also PyCharm
Create a python development environment with vagrant + ansible + fabric
code-server Online environment (2) Create a virtual network with Boto3
An easy way to create an import module with jupyter
Create a tweet heatmap with the Google Maps API
Preparing the execution environment of PyTorch with Docker November 2019
Create an OpenAI Gym environment with bash on Windows 10
Install Ubuntu 20.04 with GUI and prepare the development environment
Create a Japanese OCR environment with Anaconda (tesseract + pyocr)
Create a django environment with docker-compose (MariaDB + Nginx + uWSGI)
Create an environment for test automation with AirtestIDE (Tips)
Create a machine learning environment from scratch with Winsows 10
[No venv required] The strongest Python development environment created with Remote Containers [VS Code / Docker]
How to quickly create a machine learning environment using Jupyter Notebook with UbuntuServer 16.04 LTS with anaconda