operator_tests.py 1.12 KB
Newer Older
Philipp Arras's avatar
Move it  
Philipp Arras committed
1
2
3
4
import numpy as np

from ..field import Field

Philipp Arras's avatar
Philipp Arras committed
5
__all__ = ['adjoint_implementation', 'inverse_implemenation']
Philipp Arras's avatar
Move it  
Philipp Arras committed
6
7


Philipp Arras's avatar
Philipp Arras committed
8
def adjoint_implementation(op, domain_dtype=np.float64, target_dtype=np.float64, atol=0, rtol=1e-7):
Philipp Arras's avatar
Fixups    
Philipp Arras committed
9
10
11
12
    f1 = Field.from_random("normal", domain=op.domain, dtype=domain_dtype)
    f2 = Field.from_random("normal", domain=op.target, dtype=target_dtype)
    res1 = f1.vdot(op.adjoint_times(f2))
    res2 = op.times(f1).vdot(f2)
Philipp Arras's avatar
Move it  
Philipp Arras committed
13
14
15
16
17
18
    np.testing.assert_allclose(res1, res2, atol=atol, rtol=rtol)

    # Return relative error
    return (res1 - res2) / (res1 + res2) * 2


Philipp Arras's avatar
Philipp Arras committed
19
20
def inverse_implementation(op, domain_dtype=np.float64, target_dtype=np.float64, atol=0, rtol=1e-7):
    foo = Field.from_random(domain=op.target, random_type='normal', dtype=target_dtype)
Philipp Arras's avatar
Fixups    
Philipp Arras committed
21
    res = op(op.inverse_times(foo)).val
Philipp Arras's avatar
Philipp Arras committed
22
    np.testing.assert_allclose(res, foo.val, atol=atol, rtol=rtol)
Philipp Arras's avatar
Move it  
Philipp Arras committed
23

Philipp Arras's avatar
Philipp Arras committed
24
    foo = Field.from_random(domain=op.domain, random_type='normal', dtype=domain_dtype)
Philipp Arras's avatar
Fixups    
Philipp Arras committed
25
    res = op.inverse_times(op(foo)).val
Philipp Arras's avatar
Philipp Arras committed
26
    np.testing.assert_allclose(res, foo.val, atol=atol, rtol=rtol)
Philipp Arras's avatar
Move it  
Philipp Arras committed
27
28

    # Return relative error
Philipp Arras's avatar
Philipp Arras committed
29
    return (res - foo.val) / (res + foo.val) * 2