{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Using Sparse Solvers in Python\n", "## ChEN 6355 - Computational Fluid Dynamics\n", "### Tony Saad
Assistant Professor of Chemical Engineering
University of Utah" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We will solve the Poisson equation on the unit square with Dirichlet boundary conditions\n", "\$$\n", "\\nabla^2 u = -S;\\quad u(0) = 0,\\quad u(1) = 0\n", "\$$\n", "We will use a random number generator for the RHS." ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "import scipy.linalg\n", "import scipy.sparse\n", "import scipy.sparse.linalg\n", "import matplotlib.pyplot as plt\n", "%matplotlib inline\n", "%config InlineBackend.figure_format = 'svg'\n", "import pyamg # make sure you install pyamg" ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[-2178. 1089. 0. ... 0. 0. 0.]\n", " [ 1089. -2178. 1089. ... 0. 0. 0.]\n", " [ 0. 1089. -2178. ... 0. 0. 0.]\n", " ...\n", " [ 0. 0. 0. ... -2178. 1089. 0.]\n", " [ 0. 0. 0. ... 1089. -2178. 1089.]\n", " [ 0. 0. 0. ... 0. 1089. -2178.]]\n" ] } ], "source": [ "# 1d example\n", "l = 1.0\n", "ntotal = 34\n", "dx = dy = 1/(ntotal -1)\n", "\n", "n = 32 # interior points excludes BC points where the BC is specified\n", "S = -np.random.rand(n)\n", "\n", "Ae = 1/dx/dx*np.ones(n)\n", "Aw = 1/dx/dx*np.ones(n)\n", "Ap = -(Ae + Aw) # create Ap\n", "\n", "# set BCs on east and west coefs\n", "Ae[-1] = 0.0 # right wall\n", "Aw[0] = 0.0 # left wall\n", "\n", "# create the diagonals\n", "d0 = Ap\n", "de = Ae[:-1]\n", "dw = Aw[1:]\n", "\n", "A = scipy.sparse.diags([d0, de, dw], [0, 1, -1], format='csr')\n", "print(A.toarray())" ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[]" ] }, "execution_count": 38, "metadata": {}, "output_type": "execute_result" }, { "data": { "image/svg+xml": [ "\n", "\n", "\n", "\n" ], "text/plain": [ "