Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Matrix-Free Linear Operator #423

Merged
merged 111 commits into from
Aug 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
111 commits
Select commit Hold shift + click to select a range
d830ae1
add non matching conforming projection operators
FrederikSchnack Jul 14, 2023
a27a062
add some plotting utilities
FrederikSchnack Jul 14, 2023
bbad569
make multipatch examples run
FrederikSchnack Jul 14, 2023
ec10dfd
Use SymPDE development version from GitHub
yguclu Jul 17, 2023
a166d02
allow for non-matching grids in postprocessing
FrederikSchnack Jul 17, 2023
87bbef6
add utils
FrederikSchnack Jul 17, 2023
1a41cd0
adds non-matching domain utilities
FrederikSchnack Jul 18, 2023
e84552a
adds curl-curl test case comparisson
FrederikSchnack Jul 18, 2023
548881a
small changes
FrederikSchnack Jul 24, 2023
b0e64c9
Merge remote-tracking branch 'origin/devel' into non_matching_multipatch
FrederikSchnack Jul 24, 2023
4dbc422
Merge branch 'devel' into non_matching_multipatch
yguclu Jul 25, 2023
b3d1451
add time-domain Maxwell
FrederikSchnack Jul 27, 2023
a806b6d
add time harmonic and time domain maxwell examples
FrederikSchnack Jul 28, 2023
26578f6
add new tests and last example
FrederikSchnack Aug 2, 2023
f68c562
Merge branch 'devel' into non_matching_multipatch
FrederikSchnack Sep 20, 2023
7fbaecf
make Codacy happy
FrederikSchnack Sep 20, 2023
b52041f
add pml example
FrederikSchnack Nov 27, 2023
7f5be32
update non_matching operators and add proposal of tests
FrederikSchnack Nov 27, 2023
1692570
adapt files to new projection
FrederikSchnack Nov 27, 2023
544a237
make codacy happy
FrederikSchnack Nov 28, 2023
7b357bb
add some pml experiments
FrederikSchnack Dec 12, 2023
ebaa9f3
Merge branch 'devel' into non_matching_multipatch
FrederikSchnack Mar 1, 2024
a147990
add docs and readability
FrederikSchnack Mar 5, 2024
c7325da
Merge branch 'devel' into non_matching_multipatch
FrederikSchnack Mar 5, 2024
567ce21
move pml experiments to its own branch
FrederikSchnack Mar 5, 2024
2af29a8
adapt tests
FrederikSchnack Mar 5, 2024
d4fbdbf
change Hodge matrix naming conventions
FrederikSchnack Mar 7, 2024
11a9859
Merge branch 'devel' into non_matching_multipatch
FrederikSchnack Mar 7, 2024
ae90d77
Merge branch 'devel' into non_matching_multipatch
yguclu Mar 19, 2024
05bd083
Merge branch 'devel' into non_matching_multipatch
FrederikSchnack Apr 23, 2024
aa4fd8c
functions stencil index to petsc index and viceversa
e-moral-sanchez May 8, 2024
678de4a
efficient conversion to PETSc of StencilVectors
e-moral-sanchez May 8, 2024
bf176a2
works for 1D stencil matrix with multiple processes
e-moral-sanchez May 13, 2024
c7ac7ce
correct indexing for 2D stencilmatrix
e-moral-sanchez May 15, 2024
6579478
works 1d,2d,3d stencilmatrix without periodic BC
e-moral-sanchez May 15, 2024
a9e0315
efficient conversion of stencilmatrix to PETSc.Mat for 1,2,3D and pe…
e-moral-sanchez May 16, 2024
1579d31
Fixed conversion from 2D BlockStencilVector to Petsc.Vec
e-moral-sanchez May 17, 2024
a78bb93
fix general case also for stencilvector 2D
e-moral-sanchez May 17, 2024
bb05e72
fixed petsc_to_psydac for BlockVectors
e-moral-sanchez May 21, 2024
4174b66
PETSc conversion works for StencilVector and BlockStencilVector of 1 …
e-moral-sanchez May 21, 2024
d019388
conversion works for StencilMatrix
e-moral-sanchez May 21, 2024
4066746
works for BlockLinearOperators, the blocks of which are Stencilmatrices
e-moral-sanchez May 21, 2024
988ba35
Clean up, docstrings
e-moral-sanchez May 21, 2024
6e3a348
fix bugs
e-moral-sanchez May 22, 2024
448670b
sequential case, docstrings
e-moral-sanchez May 22, 2024
22b7646
cleaning
e-moral-sanchez May 22, 2024
32a6a13
erase forgotten comments
e-moral-sanchez May 22, 2024
4a60cd9
Merge branch 'devel' into improve_mat_topetsc
e-moral-sanchez May 22, 2024
ff8c1c0
adds revised Hcurl conforming projections and adapts the tests, prior…
FrederikSchnack May 22, 2024
53c1b3c
adapt conforming examples to new projections
FrederikSchnack May 22, 2024
dcc86b1
update non-matching examples
FrederikSchnack May 23, 2024
df34fe9
fix loop stencil
e-moral-sanchez May 23, 2024
a853a47
work in comments
FrederikSchnack May 23, 2024
5371468
update tests
FrederikSchnack May 23, 2024
9357bdd
Merge branch 'devel' into non_matching_multipatch
FrederikSchnack May 23, 2024
c8b4c07
forgotten prints
e-moral-sanchez May 27, 2024
4de21ca
add pyccel kernel
e-moral-sanchez May 29, 2024
ce1126a
string for type annotations
e-moral-sanchez May 29, 2024
1a45700
clean up plus fix serial case
e-moral-sanchez May 29, 2024
ba230ba
stop using create_domain() -- wip
campospinto May 31, 2024
685f4a5
use Domain.join() to build non-matching domains
campospinto Jun 2, 2024
842f7fc
clean time measurements
e-moral-sanchez Jun 3, 2024
a3a5341
using temp function for sympde Domain.join
campospinto Jun 4, 2024
220f1cf
adding ref
campospinto Jun 4, 2024
73019d1
call exposed domain and codomain in linalg/basic.py
campospinto Jun 7, 2024
52fec60
Merge example scripts and get rid of get_source_and_solution_OBSOLETE
FrederikSchnack Jun 10, 2024
4d5f780
clean up multipatch domain utilities
FrederikSchnack Jun 11, 2024
fffe43f
Coarsen test runs and add timedomain dummy run
FrederikSchnack Jun 11, 2024
d417da4
Make codacy happy
FrederikSchnack Jun 12, 2024
a748a4d
fix typo
FrederikSchnack Jun 12, 2024
25c586b
fix version 12 of macos in tests
e-moral-sanchez Jun 12, 2024
2bceaf6
Expose multipatch modules to docs
FrederikSchnack Jun 17, 2024
383d341
minor documentation related fixes
jowezarek Jun 17, 2024
a9da50e
sphinx fix
campospinto Jun 18, 2024
9995e21
Fixes for CI failures caused by new macOS runner version and numpy 2.0
kvrigor Jun 19, 2024
802ab87
CI: Temporarily disabled docs deployment since base repo is a fork
kvrigor Jun 19, 2024
8a8138f
Merge pull request #3 from campospinto/ci-fixes-jun2024
campospinto Jun 20, 2024
c3f380c
Merge branch 'devel' into improve_mat_topetsc
e-moral-sanchez Jun 21, 2024
cec4c7a
Update macos version
e-moral-sanchez Jun 21, 2024
63f3228
Disable deploy_docs in documentation.yml
FrederikSchnack Jun 21, 2024
ed0427f
Merge branch 'ci-fixes-jun2024' into non_matching_multipatch
FrederikSchnack Jun 21, 2024
d1b9cb0
Merge pull request #4 from campospinto/ci-fixes-jun2024
campospinto Jun 21, 2024
37f2b10
Merge branch 'devel' into improve_mat_topetsc
e-moral-sanchez Jun 21, 2024
4db8dca
simple implementation GeneralLinearOperator
e-moral-sanchez Jun 21, 2024
5d5de58
Merge pull request #1 from campospinto/improve_mat_topetsc
campospinto Jun 21, 2024
6265d1c
Merge branch 'devel' into non_matching_multipatch
FrederikSchnack Jun 21, 2024
bdaa788
Merge pull request #5 from campospinto/non_matching_multipatch
campospinto Jun 21, 2024
618020b
Merge branch 'devel' into minor_bug_fix_linalg_basic
campospinto Jun 21, 2024
a94db57
Merge branch 'devel' into general_linear_operator
e-moral-sanchez Jun 21, 2024
2adf6ad
general linear operator needs toarray, tosparse,transpose method
e-moral-sanchez Jun 23, 2024
6e1bc76
Merge pull request #2 from campospinto/minor_bug_fix_linalg_basic
campospinto Jun 23, 2024
41f3373
improve docstrings
e-moral-sanchez Jul 4, 2024
a567199
Merge branch 'devel' into general_linear_operator
e-moral-sanchez Jul 4, 2024
2067c4c
fixed message notimplementederror
e-moral-sanchez Jul 4, 2024
d32bd98
put import outside class
e-moral-sanchez Jul 4, 2024
b85ec76
set tol to rtol in MINRES
e-moral-sanchez Jul 8, 2024
273ec8f
add features and tests to MatrixFree linear ops
campospinto Jul 12, 2024
9163b3f
tests for matrix free linear ops
campospinto Jul 12, 2024
1e53d49
require scipy >= 1.14 in requirements.txt
campospinto Jul 16, 2024
2e898b8
discard tests with python3.8
campospinto Jul 16, 2024
baf0231
avoid minres iteration if converged
campospinto Jul 16, 2024
2dd2d3b
Style cleanup of stencil2IJV_kernels.py
yguclu Jul 31, 2024
b9a64a0
Apply some PEP8 recommendations to topetsc.py
yguclu Aug 1, 2024
8c45fd4
Merge branch 'devel' into general_linear_operator
yguclu Aug 2, 2024
f193766
Revert "Disable deploy_docs in documentation.yml"
yguclu Jul 31, 2024
f07548f
Revert "CI: Temporarily disabled docs deployment since base repo is a…
yguclu Jul 31, 2024
fcd50ca
Require SciPy >= 1.12, hence Python >= 3.9
yguclu Aug 2, 2024
123aa00
Do not skip tests with Python 3.9
yguclu Aug 2, 2024
e8d53e0
Apply some PEP8 recommendations to linalg/basic.py
yguclu Aug 2, 2024
f3c67b6
Add missing newline at end of file
yguclu Jul 31, 2024
e46742c
Use master branch of Igakit once again
yguclu Jul 31, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions .github/workflows/continuous-integration.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,10 @@ jobs:
fail-fast: false
matrix:
os: [ ubuntu-latest ]
python-version: [ 3.8, 3.9, '3.10', '3.11' ]
python-version: [ 3.9, '3.10', '3.11' ]
isMerge:
- ${{ github.event_name == 'push' && github.ref == 'refs/heads/devel' }}
exclude:
- { isMerge: false, python-version: 3.9 }
- { isMerge: false, python-version: '3.10' }
include:
- os: macos-latest
Expand Down
2 changes: 1 addition & 1 deletion psydac/api/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,4 +67,4 @@
'pyccel-intel' : PSYDAC_BACKEND_IPYCCEL,
'pyccel-pgi' : PSYDAC_BACKEND_PGPYCCEL,
'pyccel-nvidia': PSYDAC_BACKEND_NVPYCCEL,
}
}
8 changes: 4 additions & 4 deletions psydac/api/tests/test_api_2d_compatible_spaces.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ def run_stokes_2d_dir(domain, f, ue, pe, *, homogeneous, ncells, degree, scipy=F
# ... solve linear system using scipy.sparse.linalg or psydac
if scipy:

tol = 1e-11
rtol = 1e-11
equation_h.assemble()
A0 = equation_h.linear_system.lhs.tosparse()
b0 = equation_h.linear_system.rhs.toarray()
Expand All @@ -145,17 +145,17 @@ def run_stokes_2d_dir(domain, f, ue, pe, *, homogeneous, ncells, degree, scipy=F
A1 = a1_h.assemble().tosparse()
b1 = l1_h.assemble().toarray()

x1, info = sp_minres(A1, b1, tol=tol)
x1, info = sp_minres(A1, b1, rtol=rtol)
print('Boundary solution with scipy.sparse: success = {}'.format(info == 0))

x0, info = sp_minres(A0, b0 - A0.dot(x1), tol=tol)
x0, info = sp_minres(A0, b0 - A0.dot(x1), rtol=rtol)
print('Interior solution with scipy.sparse: success = {}'.format(info == 0))

# Solution is sum of boundary and interior contributions
x = x0 + x1

else:
x, info = sp_minres(A0, b0, tol=tol)
x, info = sp_minres(A0, b0, rtol=rtol)
print('Solution with scipy.sparse: success = {}'.format(info == 0))

# Convert to stencil format
Expand Down
110 changes: 109 additions & 1 deletion psydac/linalg/basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
"""

from abc import ABC, abstractmethod
from types import LambdaType
from inspect import signature

import numpy as np
from scipy.sparse import coo_matrix
Expand All @@ -25,7 +27,8 @@
'ComposedLinearOperator',
'PowerLinearOperator',
'InverseLinearOperator',
'LinearSolver'
'LinearSolver',
'MatrixFreeLinearOperator'
)

#===============================================================================
Expand Down Expand Up @@ -1111,3 +1114,108 @@ def solve(self, rhs, out=None):
@property
def T(self):
return self.transpose()

#===============================================================================
class MatrixFreeLinearOperator(LinearOperator):
"""
General linear operator represented by a callable dot method.

Parameters
----------
domain : VectorSpace
The domain of the linear operator.

codomain : VectorSpace
The codomain of the linear operator.

dot : Callable
The method of the linear operator, assumed to map from domain to codomain.
This method can take out as an optional argument but this is not mandatory.

dot_transpose: Callable
The method of the transpose of the linear operator, assumed to map from codomain to domain.
This method can take out as an optional argument but this is not mandatory.

Examples
--------
# example 1: a matrix encapsulated as a (fake) matrix-free linear operator
A_SM = StencilMatrix(V, W)
AT_SM = A_SM.transpose()
A = MatrixFreeLinearOperator(domain=V, codomain=W, dot=lambda v: A_SM @ v, dot_transpose=lambda v: AT_SM @ v)

# example 2: a truly matrix-free linear operator
A = MatrixFreeLinearOperator(domain=V, codomain=V, dot=lambda v: 2*v, dot_transpose=lambda v: 2*v)

"""

def __init__(self, domain, codomain, dot, dot_transpose=None):

assert isinstance(domain, VectorSpace)
assert isinstance(codomain, VectorSpace)
assert isinstance(dot, LambdaType)

self._domain = domain
self._codomain = codomain
self._dot = dot

sig = signature(dot)
self._dot_takes_out_arg = ('out' in [p.name for p in sig.parameters.values() if p.kind == p.KEYWORD_ONLY])

if dot_transpose is not None:
assert isinstance(dot_transpose, LambdaType)
self._dot_transpose = dot_transpose
sig = signature(dot_transpose)
self._dot_transpose_takes_out_arg = ('out' in [p.name for p in sig.parameters.values() if p.kind == p.KEYWORD_ONLY])
else:
self._dot_transpose = None
self._dot_transpose_takes_out_arg = False

@property
def domain(self):
return self._domain

@property
def codomain(self):
return self._codomain

@property
def dtype(self):
return None

def dot(self, v, out=None):
assert isinstance(v, Vector)
assert v.space == self.domain

if out is not None:
assert isinstance(out, Vector)
assert out.space == self.codomain
else:
out = self.codomain.zeros()

if self._dot_takes_out_arg:
self._dot(v, out=out)
else:
# provided dot product does not take an out argument: we simply copy the result into out
self._dot(v).copy(out=out)

return out

def toarray(self):
raise NotImplementedError('toarray() is not defined for MatrixFreeLinearOperator.')

def tosparse(self):
raise NotImplementedError('tosparse() is not defined for MatrixFreeLinearOperator.')

def transpose(self, conjugate=False):
if self._dot_transpose is None:
raise NotImplementedError('no transpose dot method was given -- cannot create the transpose operator')

if conjugate:
if self._dot_transpose_takes_out_arg:
new_dot = lambda v, out=None: self._dot_transpose(v, out=out).conjugate()
else:
new_dot = lambda v: self._dot_transpose(v).conjugate()
else:
new_dot = self._dot_transpose

return MatrixFreeLinearOperator(domain=self.codomain, codomain=self.domain, dot=new_dot, dot_transpose=self._dot)
13 changes: 10 additions & 3 deletions psydac/linalg/solvers.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def inverse(A, solver, **kwargs):
A : psydac.linalg.basic.LinearOperator
Left-hand-side matrix A of linear system; individual entries A[i,j]
can't be accessed, but A has 'shape' attribute and provides 'dot(p)'
function (i.e. matrix-vector product A*p).
function (e.g. a matrix-vector product A*p).

solver : str
Preferred iterative solver. Options are: 'cg', 'pcg', 'bicg',
Expand Down Expand Up @@ -1165,7 +1165,7 @@ def solve(self, b, out=None):
A.dot(x, out=y)
y -= b
y *= -1.0
y.copy(out=res_old)
y.copy(out=res_old) # res = b - A*x

beta = sqrt(res_old.dot(res_old))

Expand Down Expand Up @@ -1193,8 +1193,15 @@ def solve(self, b, out=None):
print( "+---------+---------------------+")
template = "| {:7d} | {:19.2e} |"

# check whether solution is already converged:
if beta < tol:
istop = 1
rnorm = beta
if verbose:
print( template.format(itn, rnorm ))

for itn in range(1, maxiter + 1 ):
while istop == 0 and itn < maxiter:
itn += 1

s = 1.0/beta
y.copy(out=v)
Expand Down
18 changes: 9 additions & 9 deletions psydac/linalg/tests/test_linalg.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ def array_equal(a, b):
def sparse_equal(a, b):
return (a.tosparse() != b.tosparse()).nnz == 0

def is_pos_def(A):
def assert_pos_def(A):
assert isinstance(A, LinearOperator)
A_array = A.toarray()
assert np.all(np.linalg.eigvals(A_array) > 0)
Expand Down Expand Up @@ -50,7 +50,7 @@ def get_StencilVectorSpace(n1, n2, p1, p2, P1, P2):
V = StencilVectorSpace(C)
return V

def get_positive_definite_stencilmatrix(V):
def get_positive_definite_StencilMatrix(V):

np.random.seed(2)
assert isinstance(V, StencilVectorSpace)
Expand Down Expand Up @@ -700,9 +700,9 @@ def test_positive_definite_matrix(n1, n2, p1, p2):
P1 = False
P2 = False
V = get_StencilVectorSpace(n1, n2, p1, p2, P1, P2)
S = get_positive_definite_stencilmatrix(V)
S = get_positive_definite_StencilMatrix(V)

is_pos_def(S)
assert_pos_def(S)

#===============================================================================
@pytest.mark.parametrize('n1', [3, 5])
Expand Down Expand Up @@ -745,7 +745,7 @@ def test_operator_evaluation(n1, n2, p1, p2):
V = get_StencilVectorSpace(n1, n2, p1, p2, P1, P2)

# Initiate positive definite StencilMatrices for which the cg inverse works (necessary for certain tests)
S = get_positive_definite_stencilmatrix(V)
S = get_positive_definite_StencilMatrix(V)

# Initiate StencilVectors
v = StencilVector(V)
Expand All @@ -769,7 +769,7 @@ def test_operator_evaluation(n1, n2, p1, p2):

### 2.1 PowerLO test
Bmat = B.toarray()
is_pos_def(B)
assert_pos_def(B)
uarr = u.toarray()
b0 = ( B**0 @ u ).toarray()
b1 = ( B**1 @ u ).toarray()
Expand Down Expand Up @@ -799,7 +799,7 @@ def test_operator_evaluation(n1, n2, p1, p2):
assert np.array_equal(zeros, z2)

Smat = S.toarray()
is_pos_def(S)
assert_pos_def(S)
varr = v.toarray()
s0 = ( S**0 @ v ).toarray()
s1 = ( S**1 @ v ).toarray()
Expand Down Expand Up @@ -960,8 +960,8 @@ def test_x0update(solver):
P1 = False
P2 = False
V = get_StencilVectorSpace(n1, n2, p1, p2, P1, P2)
A = get_positive_definite_stencilmatrix(V)
is_pos_def(A)
A = get_positive_definite_StencilMatrix(V)
assert_pos_def(A)
b = StencilVector(V)
for n in range(n1):
b[n, :] = 1.
Expand Down
Loading
Loading