# Using Sparse Solvers in Python
## ChEN 6355 - Computational Fluid Dynamics
### Tony Saad <br/> Assistant Professor of Chemical Engineering <br/> University of Utah

We will solve the Poisson equation on the unit square with Dirichlet boundary conditions
\begin{equation}
\nabla^2 u = -S;\quad u(0) = 0,\quad u(1) = 0
\end{equation}
We will use a random number generator for the RHS.


```python
import numpy as np
import scipy.linalg
import scipy.sparse
import scipy.sparse.linalg
import matplotlib.pyplot as plt
%matplotlib inline
%config InlineBackend.figure_format = 'svg'
import pyamg # make sure you install pyamg
```


```python
# 1d example
l = 1.0
ntotal = 34
dx = dy = 1/(ntotal -1)

n = 32 # interior points excludes BC points where the BC is specified
S = -np.random.rand(n)

Ae = 1/dx/dx*np.ones(n)
Aw = 1/dx/dx*np.ones(n)
Ap = -(Ae + Aw) # create Ap

# set BCs on east and west coefs
Ae[-1] = 0.0 # right wall
Aw[0] = 0.0 # left wall

# create the diagonals
d0 = Ap
de = Ae[:-1]
dw = Aw[1:]

A = scipy.sparse.diags([d0, de, dw], [0, 1, -1], format='csr')
print(A.toarray())
```

    [[-2178.  1089.     0. ...     0.     0.     0.]
     [ 1089. -2178.  1089. ...     0.     0.     0.]
     [    0.  1089. -2178. ...     0.     0.     0.]
     ...
     [    0.     0.     0. ... -2178.  1089.     0.]
     [    0.     0.     0. ...  1089. -2178.  1089.]
     [    0.     0.     0. ...     0.  1089. -2178.]]



```python
# direct solver
Ainv = scipy.sparse.linalg.inv(A.tocsc())
u = Ainv@S
plt.plot(u)
# to add the values at the boundary points you can augment u with two extra values
```




    [<matplotlib.lines.Line2D at 0xd1f80b588>]




    

    



```python
# scipy sparse solver
u = scipy.sparse.linalg.spsolve(A,S)
plt.plot(u)
```




    [<matplotlib.lines.Line2D at 0xd1f8e29e8>]




    

    



```python
# cg solver
u,err = scipy.sparse.linalg.cg(A,S)
plt.plot(u)
```




    [<matplotlib.lines.Line2D at 0xd1f9c7128>]




    

    



```python
# amg solver
ml = pyamg.ruge_stuben_solver(A)                   
u = ml.solve(S, tol=1e-9,cycle='V')
plt.plot(u)
```




    [<matplotlib.lines.Line2D at 0xd1fa9e860>]




    

    



```python
import urllib
import requests
from IPython.core.display import HTML
def css_styling():
    styles = requests.get("https://raw.githubusercontent.com/saadtony/NumericalMethods/master/styles/custom.css")
    return HTML(styles.text)
css_styling()



```




CSS style adapted from https://github.com/barbagroup/CFDPython. Copyright (c) Barba group
<link href='http://fonts.googleapis.com/css?family=Merriweather' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Bitter' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Oxygen' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Lora' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Fenix' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Alegreya+Sans:100,300,400,500,700,800,900,100italic,300italic,400italic,500italic,700italic,800italic,900italic' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Source+Code+Pro:300,400' rel='stylesheet' type='text/css'>

<style>
    @font-face {
        font-family: "Computer Modern";
        src: url('http://mirrors.ctan.org/fonts/cm-unicode/fonts/otf/cmunss.otf');
    }

    /*div.cell{
        width:800px;
        margin-left:16% !important;
        margin-right:auto;
    } */

    /* set the font size in tables */
    tr, td, th{
        font-size:110%;
    }

    /* spec for headers */
    h1 {
        font-family: 'Bitter', serif;
    }

    h2 {
        font-family: 'Fenix', serif;
    }

    h3{
        font-family: 'Fenix', serif;
        margin-top:12px;
        margin-bottom: 3px;
    }

    h4{
        font-family: 'Fenix', serif;
    }

    h5 {
        font-family: 'Alegreya Sans', sans-serif;
    }

    div.text_cell_render{
        font-family: 'Merriweather','Alegreya Sans','Lora', 'Oxygen', "Helvetica Neue", Arial, Helvetica, Geneva, sans-serif;
        line-height: 160%;
        font-size: 130%;
    }

    .CodeMirror{
        font-family: "Source Code Pro";
        font-size: 100%;
    }

    .text_cell_render h1 {
        font-weight: 200;
        font-size: 32pt;
        line-height: 120%;
        color:#CD2305;
        margin-bottom: 0.5em;
        margin-top: 0.5em;
        display: block;
    }

    .text_cell_render h2 {
        font-size: 26pt;
        text-align: center;
    }

    .text_cell_render h3 {
        font-size: 20pt;
    }

    .text_cell_render h4 {
        font-size: 18pt;
    }

    .text_cell_render h5 {
        font-weight: 300;
        font-size: 16pt;
        color: #CD2305;
        font-style: italic;
        margin-bottom: .5em;
        margin-top: 0.5em;
        display: block;
    }

    .warning{
        color: rgb( 240, 20, 20 )
    }  

/*  div#notebook {background-color: #1e1e1e; border-top: none;}
    div#notebook-container {background-color: rgb(180, 180, 180);}
 */

</style>







```python

```

0b4ef3c5af16b05aad4c44f10a80cd2f1eef29e6
ipynb
Jupyter Notebook
Using Sparse Solvers in Python.ipynb
himelbarua/uCFD
0e76fc85e01484e2d7827b58ca711f418d290211
MIT
2019-03-27T05:23:00.000Z
2022-03-13T10:38:53.000Z
Using Sparse Solvers in Python.ipynb
himelbarua/uCFD
0e76fc85e01484e2d7827b58ca711f418d290211
MIT
2021-04-26T17:42:13.000Z
2021-04-26T17:42:13.000Z
Using Sparse Solvers in Python.ipynb
saadtony/uCFD
0e76fc85e01484e2d7827b58ca711f418d290211
MIT
2019-07-31T16:01:21.000Z
2022-01-26T05:01:29.000Z
Qwen/Qwen-72B
1. YES
2. YES