<jupyter_start><jupyter_text>Tutorial - SymPy in 10 minutes          IntroductionIn this tutorial we will learn the basics of [Jupyter](http://jupyter.org/) and [SymPy](https://es.wikipedia.org/wiki/SymPy). SymPy is a Python library for symbolic computation. It provides computer algebra capabilities either as a standalone application, as a library to other applications, or live on the web as [SymPy Live](http://live.sympy.org/) or [SymPy Gamma](http://www.sympygamma.com/). Sympy is similar to other CAS (Computer Algebra Software) like Mathematica, Maple or Maxima.A more complete tutorial can be found at [http://docs.sympy.org/latest/tutorial/index.html](http://docs.sympy.org/latest/tutorial/index.html).Before using SymPy we should load it, like any other Python libary. We will use```pythoninit_session()```to make some imports, this will help us in its interactive use. For scripting it would be better to do the imports diffferently, for example```pythonimport sympy as sym```and then call the functions from SymPy in the following manner```pythonx = sym.Symbols("x")expr = sym.cos(x)**2 + 3*xderiv = expr.diff(x)```where we computed the derivative of $cos^2(x) + 3x$, that should be $-2\sin(x)\cos(x) + 3$.For further information on the Jupyter Notebook you can refer to the [User Manual](https://athena.brynmawr.edu/jupyter/hub/dblank/public/Jupyter%20Notebook%20Users%20Manual.ipynb).<jupyter_code>%matplotlib notebook
import numpy as np
import matplotlib.pyplot as plt
from sympy import *
init_session()
plt.style.use("seaborn-notebook")<jupyter_output>IPython console for SymPy 1.2 (Python 3.6.5-64-bit) (ground types: gmpy)

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.2/<jupyter_text>Let us start with some simple calculations. Belowe we have a _code cell_ with an addition. Place the cursor on it and press SHIFT + ENTER to evaluate it.<jupyter_code>1 + 3<jupyter_output><empty_output><jupyter_text>Let us make some calculations<jupyter_code>factorial(5)
Out[4]* 10
1 // 3
1 / 3
S(1) / 3<jupyter_output><empty_output><jupyter_text>We can evaluate an expression to its floating point version<jupyter_code>sqrt(2*pi)
float(Out[9])<jupyter_output><empty_output><jupyter_text>In the previous line we used the expression **Out[8]** that stores the output from the evaluation in cell 8 (In[8]). We can also store expressions as variables, just as any Python variable.<jupyter_code>radius = 10
height = 100
area = pi * radius**2
volume = area * height
volume
float(volume)<jupyter_output><empty_output><jupyter_text>So far, we have just used SymPy as a calculator. Let us try more advanced calculations Definite and indefinite integrals<jupyter_code>integrate(sin(x), x)
integrate(sin(x), (x, 0, pi))<jupyter_output><empty_output><jupyter_text>We can define a function and integrate it<jupyter_code>f = lambda x: x**2 + 5
f(5)
integrate(f(z), z)
integrate(1/(x**2 + y), x)<jupyter_output><empty_output><jupyter_text>If we assume that the denominator is positive, the expression can be factorized further<jupyter_code>a = symbols("a", positive=True)
integrate(1/(x**2 + a), x)<jupyter_output><empty_output><jupyter_text>We just learnt the basics, we can try some examples now.**Note:** If you want to know more about a specific function you can use ``help()`` or the IPython magic command ``??``<jupyter_code>help(integrate)
integrate??<jupyter_output><empty_output><jupyter_text>Examples  Solving algebraic equationsRight now, there are two main options for solution of algebraic systems, namely: [``solveset`` and ``solve``](http://docs.sympy.org/latest/tutorial/solvers.html).The preferred method is ``solveset`` (see this[explanation](http://docs.sympy.org/latest/modules/solvers/solveset.html), althoughthere are systems that can be solved using ``solve`` and not ``solveset``.To solve equations using ``solveset``:<jupyter_code>a, b, c = symbols("a b c")
solveset(a*x**2 + b*x + c, x)<jupyter_output><empty_output><jupyter_text>We should enter the equations as equated to 0, or as an equation<jupyter_code>solveset(Eq(a*x**2 + b*x, -c), x)<jupyter_output><empty_output><jupyter_text>Currently solveset is not capable of solving the following types of equations:- Non-linear multivariate system- Equations solvable by LambertW (Transcendental equation solver).solve can be used for such cases:<jupyter_code>solve([x*y - 1, x - 2], x, y)
solve(x*exp(x) - 1, x )<jupyter_output><empty_output><jupyter_text>Linear AlgebraWe use ``Matrix`` to create matrices. Matrices can contain expressions. And we use the method ``.inv()`` to compute the inverse and ``*`` to multiply matrices.<jupyter_code>A = Matrix([
        [1, -1],
        [1, sin(c)]
    ])
display(A)
B = A.inv()
display(B)
A * B<jupyter_output><empty_output><jupyter_text>This should be the identity matrix, let us simplify the expression. There are several simplification functions, and ``simplify`` is the most general one. Simplifying is a complicated matter... if you are uncertain; use ``simplify``.<jupyter_code>simplify(A * B)<jupyter_output><empty_output><jupyter_text>PlottingWe can make 2D and 3D plots<jupyter_code>%matplotlib inline
from sympy.plotting import plot3d
plot(sin(x), (x, -pi, pi));
monkey_saddle = x**3 - 3*x*y**2
p = plot3d(monkey_saddle, (x, -2, 2), (y, -2, 2))<jupyter_output><empty_output><jupyter_text>Derivatives and differential equationsWe can use the function ``diff`` or the method ``.diff()`` to compute derivatives.<jupyter_code>f = lambda x: x**2
diff(f(x), x)
f(x).diff(x)
g = lambda x: sin(x)
diff(g(f(x)), x)<jupyter_output><empty_output><jupyter_text>Yes, SymPy knows about the chain rule.To finish, let us solve a second order ODE$$ u''(t) + \omega^2 u(t) = 0$$<jupyter_code>u = symbols("u", cls=Function)
omega = symbols("omega", positive=True)
ode = u(t).diff(t, 2) + omega**2 * u(t)
dsolve(ode, u(t))<jupyter_output><empty_output><jupyter_text>Turning Sympy expression into evaluable functions``lambdify`` provides convenient functions to transform sympy expressions to lambda functions which can be used to calculate numerical values very fast.Let's try a first example<jupyter_code>f = lambdify(x, x**2, "numpy")
f(3)
f(np.array([1, 2, 3]))<jupyter_output><empty_output><jupyter_text>We can try a more difficult one<jupyter_code>fun = diff(sin(x)*cos(x**3) - sin(x)/x, x)
fun
fun_numpy = lambdify(x, fun, "numpy")<jupyter_output><empty_output><jupyter_text>and then evaluate it for some points in, let's say, $[0, 5]$<jupyter_code>pts = np.linspace(0, 5, 1000)
fun_pts = fun_numpy(pts + 1e-6) # To avoid division by 0
plt.plot(pts, fun_pts);<jupyter_output><empty_output><jupyter_text>References- <NAME>. ["10 minute (wx)Maxima tutorial:"](https://andrejv.github.io/wxmaxima/tutorials/10minute.zip), (2008). Accessed on: July 25, 2017.- <NAME>, and <NAME>. ["Rainbow color map (still) considered harmful."](https://data3.mprog.nl/course/15%20Readings/40%20Reading%204/Borland_Rainbow_Color_Map.pdf) IEEE computer graphics and applications 27.2 (2007): 14-17. The following cell change the style of the notebook.<jupyter_code>from IPython.core.display import HTML
def css_styling():
    styles = open('../styles/custom_barba.css', 'r').read()
    return HTML(styles)
css_styling()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.13141711229946523, 'fraction_numerical': 0.017780748663101604, 'mean_word_length': 6.024413145539906, 'pattern_counts': {'":': 0, '<': 87, '<?xml version=': 0, '>': 105, 'https://': 4, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '21', 'dir': 'jupyter-structured-clean-dedup', 'id': '235172', 'license': 'MIT', 'n_tokens_mistral': 2664, 'n_tokens_neox': 2523, 'n_words': 773, 'path': 'notebooks/sympy/sympy_in_10_minutes.ipynb', 'repo_name': 'nicoguaro/AdvancedMath', 'size': '7509'}