Last active
June 29, 2021 18:09
-
-
Save derb12/3e2670a509e86051ee9dfe5aa76a0a95 to your computer and use it in GitHub Desktop.
A comparison of pentapy's solver when using np.array versus np.asarray
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
""" | |
Modified version of pentapy's 03_perform_simple.py example from | |
https://github.com/GeoStat-Framework/pentapy/blob/develop/examples/03_perform_simple.py | |
The code was modified to include a solve_new function that uses np.asarray rather than | |
np.array whereever the input data is not modified, and to compare the time required to | |
convert the matrix and array using np.array and np.asarray. | |
Modifications of pentapy's code was done in accordance with it's MIT license, which is | |
included below: | |
The MIT License (MIT) | |
Copyright (c) 2021 Sebastian Mueller | |
Permission is hereby granted, free of charge, to any person obtaining a copy | |
of this software and associated documentation files (the "Software"), to deal | |
in the Software without restriction, including without limitation the rights | |
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
copies of the Software, and to permit persons to whom the Software is | |
furnished to do so, subject to the following conditions: | |
The above copyright notice and this permission notice shall be included in all | |
copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
SOFTWARE. | |
""" | |
from __future__ import division, absolute_import, print_function | |
import warnings | |
import numpy as np | |
from pentapy import solve | |
from pentapy import tools | |
import perfplot | |
# imports to simulate being in pentapy.core.py | |
from pentapy.tools import shift_banded, create_banded, _check_penta | |
from pentapy.solver import penta_solver1, penta_solver2 | |
# solve_new uses np.asarray instead of np.array wherever the input would not be | |
# modified; otherwise, it is a direct copy of pentapy's solve function | |
def solve_new(mat, rhs, is_flat=False, index_row_wise=True, solver=1): | |
""" | |
Solver for a pentadiagonal system. | |
The matrix can be given as a full n x n matrix or as a flattend one. | |
The flattend matrix can be given in a row-wise flattend form:: | |
[[Dup2[0] Dup2[1] Dup2[2] ... Dup2[N-2] 0 0 ] | |
[Dup1[0] Dup1[1] Dup1[2] ... Dup1[N-2] Dup1[N-1] 0 ] | |
[Diag[0] Diag[1] Diag[2] ... Diag[N-2] Diag[N-1] Diag[N] ] | |
[0 Dlow1[1] Dlow1[2] ... Dlow1[N-2] Dlow1[N-1] Dlow1[N]] | |
[0 0 Dlow2[2] ... Dlow2[N-2] Dlow2[N-2] Dlow2[N]]] | |
Or a column-wise flattend form:: | |
[[0 0 Dup2[2] ... Dup2[N-2] Dup2[N-1] Dup2[N] ] | |
[0 Dup1[1] Dup1[2] ... Dup1[N-2] Dup1[N-1] Dup1[N] ] | |
[Diag[0] Diag[1] Diag[2] ... Diag[N-2] Diag[N-1] Diag[N] ] | |
[Dlow1[0] Dlow1[1] Dlow1[2] ... Dlow1[N-2] Dlow1[N-1] 0 ] | |
[Dlow2[0] Dlow2[1] Dlow2[2] ... Dlow2[N-2] 0 0 ]] | |
Dup1 and Dup2 are the first and second upper minor-diagonals | |
and Dlow1 resp. Dlow2 are the lower ones. | |
If you provide a column-wise flattend matrix, you have to set:: | |
index_row_wise=False | |
Parameters | |
---------- | |
mat : :class:`numpy.ndarray` | |
The Matrix or the flattened Version of the pentadiagonal matrix. | |
rhs : :class:`numpy.ndarray` | |
The right hand side of the equation system. | |
is_flat : :class:`bool`, optional | |
State if the matrix is already flattend. Default: ``False`` | |
index_row_wise : :class:`bool`, optional | |
State if the flattend matrix is row-wise flattend. Default: ``True`` | |
solver : :class:`int` or :class:`str`, optional | |
Which solver should be used. The following are provided: | |
* ``[1, "1", "PTRANS-I"]`` : The PTRANS-I algorithm | |
* ``[2, "2", "PTRANS-II"]`` : The PTRANS-II algorithm | |
* ``[3, "3", "lapack", "solve_banded"]`` : | |
scipy.linalg.solve_banded | |
* ``[4, "4", "spsolve"]`` : | |
The scipy sparse solver without umf_pack | |
* ``[5, "5", "spsolve_umf", "umf", "umf_pack"]`` : | |
The scipy sparse solver with umf_pack | |
Default: ``1`` | |
Returns | |
------- | |
result : :class:`numpy.ndarray` | |
Solution of the equation system | |
""" | |
if solver in [1, "1", "PTRANS-I"]: | |
if is_flat and index_row_wise: | |
mat_flat = np.asarray(mat, dtype=np.double) | |
_check_penta(mat_flat) | |
elif is_flat: | |
mat_flat = np.array(mat, dtype=np.double) | |
_check_penta(mat_flat) | |
shift_banded(mat_flat, copy=False) | |
else: | |
mat_flat = create_banded(mat, col_wise=False, dtype=np.double) | |
rhs = np.asarray(rhs, dtype=np.double) | |
try: | |
return penta_solver1(mat_flat, rhs) | |
except ZeroDivisionError: | |
warnings.warn("pentapy: PTRANS-I not suitable for input-matrix.") | |
return np.full_like(rhs, np.nan) | |
elif solver in [2, "2", "PTRANS-II"]: | |
if is_flat and index_row_wise: | |
mat_flat = np.asarray(mat, dtype=np.double) | |
_check_penta(mat_flat) | |
elif is_flat: | |
mat_flat = np.array(mat, dtype=np.double) | |
_check_penta(mat_flat) | |
shift_banded(mat_flat, copy=False) | |
else: | |
mat_flat = create_banded(mat, col_wise=False, dtype=np.double) | |
rhs = np.asarray(rhs, dtype=np.double) | |
try: | |
return penta_solver2(mat_flat, rhs) | |
except ZeroDivisionError: | |
warnings.warn("pentapy: PTRANS-II not suitable for input-matrix.") | |
return np.full_like(rhs, np.nan) | |
elif solver in [3, "3", "lapack", "solve_banded"]: # pragma: no cover | |
try: | |
from scipy.linalg import solve_banded | |
except ImportError: # pragma: no cover | |
raise ValueError( | |
"pentapy.solve: " | |
+ "scipy.linalg.solve_banded could not be imported" | |
) | |
if is_flat and index_row_wise: | |
mat_flat = np.array(mat) | |
_check_penta(mat_flat) | |
shift_banded(mat_flat, col_to_row=False, copy=False) | |
elif is_flat: | |
mat_flat = np.asarray(mat) | |
else: | |
mat_flat = create_banded(mat) | |
return solve_banded((2, 2), mat_flat, rhs) | |
elif solver in [4, "4", "spsolve"]: # pragma: no cover | |
try: | |
from scipy import sparse as sps | |
from scipy.sparse.linalg import spsolve | |
except ImportError: | |
raise ValueError( | |
"pentapy.solve: scipy.sparse could not be imported" | |
) | |
if is_flat and index_row_wise: | |
mat_flat = np.array(mat) | |
_check_penta(mat_flat) | |
shift_banded(mat_flat, col_to_row=False, copy=False) | |
elif is_flat: | |
mat_flat = np.asarray(mat) | |
else: | |
mat_flat = create_banded(mat) | |
size = mat_flat.shape[1] | |
M = sps.spdiags(mat_flat, [2, 1, 0, -1, -2], size, size, format="csc") | |
return spsolve(M, rhs, use_umfpack=False) | |
elif solver in [ | |
5, | |
"5", | |
"spsolve_umf", | |
"umf", | |
"umf_pack", | |
]: # pragma: no cover | |
try: | |
from scipy import sparse as sps | |
from scipy.sparse.linalg import spsolve | |
except ImportError: | |
raise ValueError( | |
"pentapy.solve: scipy.sparse could not be imported" | |
) | |
if is_flat and index_row_wise: | |
mat_flat = np.array(mat) | |
_check_penta(mat_flat) | |
shift_banded(mat_flat, col_to_row=False, copy=False) | |
elif is_flat: | |
mat_flat = np.asarray(mat) | |
else: | |
mat_flat = create_banded(mat) | |
size = mat_flat.shape[1] | |
M = sps.spdiags(mat_flat, [2, 1, 0, -1, -2], size, size, format="csc") | |
return spsolve(M, rhs, use_umfpack=True) | |
else: # pragma: no cover | |
raise ValueError("pentapy.solve: unknown solver (" + str(solver) + ")") | |
def get_les(size): | |
"""Create the matrix and array for fitting.""" | |
mat = (np.random.random((5, size)) - 0.5) * 1e-5 | |
# create index-row-wise matrix so that solver can be called with index_row_wise=True | |
tools.shift_banded(mat, copy=False) | |
V = np.array(np.random.random(size) * 1e5) | |
return mat, V | |
def solve_1(in_val): | |
"""PTRANS-I""" | |
mat, V = in_val | |
return solve(mat, V, is_flat=True, solver=1) | |
def solve_2(in_val): | |
"""PTRANS-II""" | |
mat, V = in_val | |
return solve(mat, V, is_flat=True, solver=2) | |
def solve_1_new(in_val): | |
"""PTRANS-I with new solver.""" | |
mat, V = in_val | |
return solve_new(mat, V, is_flat=True, solver=1) | |
def solve_2_new(in_val): | |
"""PTRANS-II with new solver.""" | |
mat, V = in_val | |
return solve_new(mat, V, is_flat=True, solver=2) | |
def use_np_array(in_val): | |
"""Used to see the time required just calling np.array on the matrix and rhs.""" | |
mat, V = in_val | |
new_mat = np.array(mat, dtype=np.double) | |
new_V = np.array(V, dtype=np.double) | |
def use_np_asarray(in_val): | |
"""Used to see the time required just calling np.asarray on the matrix and rhs.""" | |
mat, V = in_val | |
new_mat = np.asarray(mat, dtype=np.double) | |
new_V = np.asarray(V, dtype=np.double) | |
perfplot.show( | |
setup=get_les, | |
kernels=[ | |
solve_1, | |
solve_2, | |
solve_1_new, | |
solve_2_new, | |
use_np_array, | |
use_np_asarray | |
], | |
labels=[ | |
"PTRANS-I", | |
"PTRANS-II", | |
"new-I", | |
"new-II", | |
"np.array", | |
"np.asarray" | |
], | |
n_range=[int(2 ** k) for k in np.arange(6, 18.5, 0.5)], | |
xlabel="Size [n]", | |
logy=True, | |
logx=True, | |
equality_check=None # don't check output since use_np_(as)array output is different than solvers | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment