Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • jcarpent/eigenpy
  • gsaurel/eigenpy
  • stack-of-tasks/eigenpy
3 results
Show changes
Showing
with 1113 additions and 121 deletions
import numpy as np
import eigenpy
dim = 100
rng = np.random.default_rng()
A = rng.random((dim, dim))
A = (A + A.T) * 0.5 + np.diag(10.0 + rng.random(dim))
llt = eigenpy.LLT(A)
L = llt.matrixL()
assert eigenpy.is_approx(L.dot(np.transpose(L)), A)
X = rng.random((dim, 20))
B = A.dot(X)
X_est = llt.solve(B)
assert eigenpy.is_approx(X, X_est)
assert eigenpy.is_approx(A.dot(X_est), B)
import numpy as np
import eigenpy
dim = 100
rng = np.random.default_rng()
A = np.eye(dim)
minres = eigenpy.MINRES(A)
X = rng.random((dim, 20))
B = A.dot(X)
X_est = minres.solve(B)
print("A.dot(X_est):", A.dot(X_est))
print("B:", B)
assert eigenpy.is_approx(A.dot(X_est), B, 1e-6)
import numpy as np
import eigenpy
rows = 20
cols = 100
rng = np.random.default_rng()
A = rng.random((rows, cols))
# Test HouseholderQR decomposition
householder_qr = eigenpy.HouseholderQR()
householder_qr = eigenpy.HouseholderQR(rows, cols)
householder_qr = eigenpy.HouseholderQR(A)
householder_qr_eye = eigenpy.HouseholderQR(np.eye(rows, rows))
X = rng.random((rows, 20))
assert householder_qr_eye.absDeterminant() == 1.0
assert householder_qr_eye.logAbsDeterminant() == 0.0
Y = householder_qr_eye.solve(X)
assert (X == Y).all()
# Test FullPivHouseholderQR decomposition
fullpiv_householder_qr = eigenpy.FullPivHouseholderQR()
fullpiv_householder_qr = eigenpy.FullPivHouseholderQR(rows, cols)
fullpiv_householder_qr = eigenpy.FullPivHouseholderQR(A)
fullpiv_householder_qr = eigenpy.FullPivHouseholderQR(np.eye(rows, rows))
X = rng.random((rows, 20))
assert fullpiv_householder_qr.absDeterminant() == 1.0
assert fullpiv_householder_qr.logAbsDeterminant() == 0.0
Y = fullpiv_householder_qr.solve(X)
assert (X == Y).all()
assert fullpiv_householder_qr.rank() == rows
fullpiv_householder_qr.setThreshold(1e-8)
assert fullpiv_householder_qr.threshold() == 1e-8
assert eigenpy.is_approx(np.eye(rows, rows), fullpiv_householder_qr.inverse())
# Test ColPivHouseholderQR decomposition
colpiv_householder_qr = eigenpy.ColPivHouseholderQR()
colpiv_householder_qr = eigenpy.ColPivHouseholderQR(rows, cols)
colpiv_householder_qr = eigenpy.ColPivHouseholderQR(A)
colpiv_householder_qr = eigenpy.ColPivHouseholderQR(np.eye(rows, rows))
X = rng.random((rows, 20))
assert colpiv_householder_qr.absDeterminant() == 1.0
assert colpiv_householder_qr.logAbsDeterminant() == 0.0
Y = colpiv_householder_qr.solve(X)
assert (X == Y).all()
assert colpiv_householder_qr.rank() == rows
colpiv_householder_qr.setThreshold(1e-8)
assert colpiv_householder_qr.threshold() == 1e-8
assert eigenpy.is_approx(np.eye(rows, rows), colpiv_householder_qr.inverse())
# Test CompleteOrthogonalDecomposition
cod = eigenpy.CompleteOrthogonalDecomposition()
cod = eigenpy.CompleteOrthogonalDecomposition(rows, cols)
cod = eigenpy.CompleteOrthogonalDecomposition(A)
cod = eigenpy.CompleteOrthogonalDecomposition(np.eye(rows, rows))
X = rng.random((rows, 20))
assert cod.absDeterminant() == 1.0
assert cod.logAbsDeterminant() == 0.0
Y = cod.solve(X)
assert (X == Y).all()
assert cod.rank() == rows
cod.setThreshold(1e-8)
assert cod.threshold() == 1e-8
assert eigenpy.is_approx(np.eye(rows, rows), cod.pseudoInverse())
import importlib
bind_optional = importlib.import_module("@MODNAME@")
def test_none_if_zero():
x = bind_optional.none_if_zero(0)
y = bind_optional.none_if_zero(-1)
assert x is None
assert y == -1
def test_struct_ctors():
# test struct ctors
struct = bind_optional.mystruct()
assert struct.a is None
assert struct.b is None
assert struct.msg == "i am struct"
## no 2nd arg automatic overload using bp::optional
struct = bind_optional.mystruct(2)
assert struct.a == 2
assert struct.b is None
struct = bind_optional.mystruct(13, -1.0)
assert struct.a == 13
assert struct.b == -1.0
def test_struct_setters():
struct = bind_optional.mystruct()
struct.a = 1
assert struct.a == 1
struct.b = -3.14
assert struct.b == -3.14
# set to None
struct.a = None
struct.b = None
struct.msg = None
assert struct.a is None
assert struct.b is None
assert struct.msg is None
def test_factory():
struct = bind_optional.create_if_true(False, None)
assert struct is None
struct = bind_optional.create_if_true(True, None)
assert struct.a == 0
assert struct.b is None
def test_random_mat():
M = bind_optional.random_mat_if_true(False)
assert M is None
M = bind_optional.random_mat_if_true(True)
assert M.shape == (4, 4)
test_none_if_zero()
test_struct_ctors()
test_struct_setters()
test_factory()
test_random_mat()
import bind_virtual_factory as bvf
class ImplClass(bvf.MyVirtualClass):
def __init__(self):
self.val = 42
bvf.MyVirtualClass.__init__(self)
def createData(self):
return ImplData(self)
# override MyVirtualClass::doSomethingPtr(shared_ptr data)
def doSomethingPtr(self, data):
print("Hello from doSomething!")
assert isinstance(data, ImplData)
print("Data value:", data.value)
data.value += 1
# override MyVirtualClass::doSomethingPtr(data&)
def doSomethingRef(self, data):
print("Hello from doSomethingRef!")
print(type(data))
assert isinstance(data, ImplData)
print("Data value:", data.value)
data.value += 1
class ImplData(bvf.MyVirtualData):
def __init__(self, c):
# parent virtual class requires arg
bvf.MyVirtualData.__init__(self, c)
self.value = c.val
def test_instantiate_child():
obj = ImplClass()
data = obj.createData()
print(data)
def test_call_do_something_ptr():
obj = ImplClass()
print("Calling doSomething (by ptr)")
d1 = bvf.callDoSomethingPtr(obj)
print("Output data.value:", d1.value)
def test_call_do_something_ref():
obj = ImplClass()
print("Ref variant:")
d2 = bvf.callDoSomethingRef(obj)
print(d2.value)
print("-----")
def test_iden_fns():
obj = ImplClass()
d = obj.createData()
print(d, type(d))
# take and return const T&
d1 = bvf.iden_ref(d)
print(d1, type(d1))
assert isinstance(d1, ImplData)
# take a shared_ptr, return const T&
d2 = bvf.iden_shared(d)
assert isinstance(d2, ImplData)
print(d2, type(d2))
print("copy shared ptr -> py -> cpp")
d3 = bvf.copy_shared(d)
assert isinstance(d3, ImplData)
print(d3, type(d3))
test_instantiate_child()
test_call_do_something_ptr()
test_call_do_something_ref()
test_iden_fns()
import numpy as np
from complex import ascomplex, imag, real
rows = 10
cols = 20
rng = np.random.default_rng()
def test(dtype):
Z = np.zeros((rows, cols), dtype=dtype)
Z.real = rng.random((rows, cols))
Z.imag = rng.random((rows, cols))
Z_real = real(Z)
assert (Z_real == Z.real).all()
Z_imag = imag(Z)
assert (Z_imag == Z.imag).all()
Y = np.ones((rows, cols))
Y_complex = ascomplex(Y)
assert (Y_complex.real == Y).all()
assert (Y_complex.imag == np.zeros((rows, cols))).all()
# Float
test(np.csingle)
# Double
test(np.cdouble)
# Long Double
test(np.clongdouble)
from deprecation_policy import (
X,
some_deprecated_function,
some_future_deprecated_function,
)
some_deprecated_function()
some_future_deprecated_function()
X().deprecated_member_function()
from __future__ import print_function
import eigenpy
import numpy as np
quat = eigenpy.Quaternion()
# By default, we convert as numpy.matrix
coeffs_vector = quat.coeffs()
assert len(coeffs_vector.shape) == 2
# Switch to numpy.array
eigenpy.switchToNumpyArray()
coeffs_vector = quat.coeffs()
coeffs_vector = quat.coeffs()
assert len(coeffs_vector.shape) == 1
import numpy as np
from eigen_ref import (
asConstRef,
asRef,
copyRowVectorFromConstRef,
copyVectorFromConstRef,
editBlock,
fill,
getBlock,
getRefToStatic,
has_ref_member,
modify_block,
printMatrix,
)
def test_fill_print(mat):
print("print matrix:")
printMatrix(mat)
print("calling fill():")
fill(mat, 1.0)
assert np.array_equal(mat, np.full(mat.shape, 1.0))
print("fill a slice")
mat[:, :] = 0.0
fill(mat[:3, :2], 1.0)
printMatrix(mat[:3, :2])
assert np.array_equal(mat[:3, :2], np.ones((3, 2)))
def test_create_ref_to_static(mat):
# create ref to static:
print()
print("[asRef(int, int)]")
A_ref = getRefToStatic(mat.shape[0], mat.shape[1])
A_ref.fill(1.0)
A_ref[0, 1] = -1.0
print("make second reference:")
A_ref2 = getRefToStatic(mat.shape[0], mat.shape[1])
print(A_ref2)
assert np.array_equal(A_ref, A_ref2)
A_ref2.fill(0)
assert np.array_equal(A_ref, A_ref2)
def test_read_block():
data = np.array([[0, 0.2, 0.3, 0.4], [0, 1, 0, 0], [0, 0, 0, 0], [1, 0, 0, 0]])
data_strided = data[:, 0]
data_strided_copy = copyVectorFromConstRef(data_strided)
assert np.all(data_strided == data_strided_copy)
data_strided_copy = copyRowVectorFromConstRef(data_strided)
assert np.all(data_strided == data_strided_copy)
def test_create_ref(mat):
print("[asRef(mat)]")
ref = asRef(mat)
assert np.array_equal(ref, mat), f"ref=\n{ref}\nmat=\n{mat}"
assert not (ref.flags.owndata)
assert ref.flags.writeable
def test_create_const_ref(mat):
print("[asConstRef]")
const_ref = asConstRef(mat)
assert np.array_equal(const_ref, mat), f"ref=\n{const_ref}\nmat=\n{mat}"
assert not (const_ref.flags.writeable)
assert not (const_ref.flags.owndata)
def test_edit_block(rows, cols):
print("set mat data to arange()")
mat.fill(0.0)
mat[:, :] = np.arange(rows * cols).reshape(rows, cols)
mat0 = mat.copy()
for i, rowsize, colsize in ([0, 3, 2], [1, 1, 2], [0, 3, 1]):
print(f"taking block [{i}:{rowsize + i}, {0}:{colsize}]")
B = getBlock(mat, i, 0, rowsize, colsize)
B = B.reshape(rowsize, colsize)
lhs = mat[i : rowsize + i, :colsize]
assert np.array_equal(lhs, B), f"got lhs\n{lhs}\nrhs B=\n{B}"
B[:] = 1.0
rhs = np.ones((rowsize, colsize))
assert np.array_equal(mat[i : rowsize + i, :colsize], rhs)
mat[:, :] = mat0
mat.fill(0.0)
mat_copy = mat.copy()
print("[editBlock]")
editBlock(mat, 0, 0, 3, 2)
mat_copy[:3, :2] = np.arange(6).reshape(3, 2)
assert np.array_equal(mat, mat_copy)
class ModifyBlockImpl(modify_block):
def call(self, mat):
n, m = mat.shape
mat[:, :] = np.arange(n * m).reshape(n, m)
modify = ModifyBlockImpl()
modify.modify(2, 3)
Jref = np.zeros((10, 10))
Jref[:2, :3] = np.arange(6).reshape(2, 3)
assert np.array_equal(Jref, modify.J)
hasref = has_ref_member()
A = np.ones((3, 3)) / 2
hasref.Jref[:, :] = A
J_true = np.zeros((4, 4))
J_true[:3, 1:] = A
assert np.array_equal(hasref.J, J_true)
def do_test(mat):
test_fill_print(mat)
test_create_ref_to_static(mat)
test_create_const_ref(mat)
test_create_ref(mat)
test_edit_block(rows, cols)
test_read_block()
print("=" * 10)
if __name__ == "__main__":
rows = 8
cols = 10
mat = np.ones((rows, cols), order="F")
mat[0, 0] = 0
mat[1:5, 1:5] = 6
do_test(mat)
# mat2 = np.ones((rows, cols))
# mat2[:2, :5] = 0.
# mat2[2:4, 1:4] = 2
# mat2[:, -1] = 3
# do_test(mat2)
import numpy as np
import eigenpy
dim = 100
rng = np.random.default_rng()
A = rng.random((dim, dim))
es = eigenpy.EigenSolver(A)
V = es.eigenvectors()
D = es.eigenvalues()
assert eigenpy.is_approx(A.dot(V).real, V.dot(np.diag(D)).real)
assert eigenpy.is_approx(A.dot(V).imag, V.dot(np.diag(D)).imag)
from __future__ import print_function
from eigenpy import *
from geometry import *
import numpy as np
from numpy import cos,sin
from geometry import (
AngleAxis,
Quaternion,
testInAngleAxis,
testInQuaternion,
testOutAngleAxis,
testOutQuaternion,
)
from numpy import cos
verbose = True
def isapprox(a,b,epsilon=1e-6):
if issubclass(a.__class__,np.ndarray) and issubclass(b.__class__,np.ndarray):
return np.allclose(a,b,epsilon)
def isapprox(a, b, epsilon=1e-6):
if issubclass(a.__class__, np.ndarray) and issubclass(b.__class__, np.ndarray):
return np.allclose(a, b, epsilon)
else:
return abs(a-b)<epsilon
return abs(a - b) < epsilon
# --- Quaternion ---------------------------------------------------------------
q = Quaternion(1,2,3,4)
# Coefficient initialisation
verbose and print("[Quaternion] Coefficient initialisation")
q = Quaternion(1, 2, 3, 4)
q.normalize()
assert(isapprox(np.linalg.norm(q.coeffs()),q.norm()))
assert(isapprox(np.linalg.norm(q.coeffs()),1))
assert isapprox(np.linalg.norm(q.coeffs()), q.norm())
assert isapprox(np.linalg.norm(q.coeffs()), 1)
# Coefficient-vector initialisation
verbose and print("[Quaternion] Coefficient-vector initialisation")
v = np.array([0.5, -0.5, 0.5, 0.5])
for k in range(10000):
qv = Quaternion(v)
assert isapprox(qv.coeffs(), v)
# Angle axis initialisation
verbose and print("[Quaternion] AngleAxis initialisation")
r = AngleAxis(q)
q2 = Quaternion(r)
assert(q==q)
assert(isapprox(q.coeffs(),q2.coeffs()))
assert(q2.isApprox(q2))
assert(q2.isApprox(q2,1e-2))
assert q == q
assert isapprox(q.coeffs(), q2.coeffs())
assert q2.isApprox(q2)
assert q2.isApprox(q2, 1e-2)
Rq = q.matrix()
Rr = r.matrix()
assert(isapprox(Rq*Rq.T,np.eye(3)))
assert(isapprox(Rr,Rq))
assert isapprox(Rq.dot(Rq.T), np.eye(3))
assert isapprox(Rr, Rq)
# Rotation matrix initialisation
verbose and print("[Quaternion] Rotation Matrix initialisation")
qR = Quaternion(Rr)
assert(q.isApprox(qR))
assert(isapprox(q.coeffs(),qR.coeffs()))
assert q.isApprox(qR)
assert isapprox(q.coeffs(), qR.coeffs())
assert(isapprox(qR[3],1./np.sqrt(30)))
assert isapprox(qR[3], 1.0 / np.sqrt(30))
try:
qR[5]
print("Error, this message should not appear.")
qR[5]
print("Error, this message should not appear.")
except RuntimeError as e:
if verbose: print("As expected, catched exception: ",e)
if verbose:
print("As expected, caught exception: ", e)
# --- Angle Vector ------------------------------------------------
r = AngleAxis(.1,np.matrix([1,0,0],np.double).T)
if verbose: print("Rx(.1) = \n\n",r.matrix(),"\n")
assert( isapprox(r.matrix()[2,2],cos(r.angle)))
assert( isapprox(r.axis,np.matrix("1;0;0")) )
assert( isapprox(r.angle,0.1) )
assert(r.isApprox(r))
assert(r.isApprox(r,1e-2))
r = AngleAxis(0.1, np.array([1, 0, 0], np.double))
if verbose:
print("Rx(.1) = \n\n", r.matrix(), "\n")
assert isapprox(r.matrix()[2, 2], cos(r.angle))
assert isapprox(r.axis, np.array([1.0, 0, 0]))
assert isapprox(r.angle, 0.1)
assert r.isApprox(r)
assert r.isApprox(r, 1e-2)
r.axis = np.matrix([0,1,0],np.double).T
assert( isapprox(r.matrix()[0,0],cos(r.angle)))
r.axis = np.array([0, 1, 0], np.double).T
assert isapprox(r.matrix()[0, 0], cos(r.angle))
ri = r.inverse()
assert( isapprox(ri.angle,-.1) )
assert isapprox(ri.angle, -0.1)
R = r.matrix()
r2 = AngleAxis(np.dot(R,R))
assert( isapprox(r2.angle,r.angle*2) )
r2 = AngleAxis(np.dot(R, R))
assert isapprox(r2.angle, r.angle * 2)
# --- USER FUNCTIONS -----------------------------------------------------------
ro = testOutAngleAxis()
assert(ro.__class__ == AngleAxis)
assert ro.__class__ == AngleAxis
res = testInAngleAxis(r)
assert( res==r.angle )
assert res == r.angle
qo = testOutQuaternion()
assert(qo.__class__ == Quaternion)
assert qo.__class__ == Quaternion
res = testInQuaternion(q)
assert(q.norm() == res)
assert q.norm() == res
import eigenpy
ldlt1 = eigenpy.LDLT()
ldlt2 = eigenpy.LDLT()
id1 = ldlt1.id()
id2 = ldlt2.id()
assert id1 != id2
assert id1 == ldlt1.id()
assert id2 == ldlt2.id()
from __future__ import print_function
import platform
import numpy as np
import matrix as eigenpy
import numpy as np
verbose = True
if verbose: print("===> From empty MatrixXd to Py")
if verbose:
print("===> From empty MatrixXd to Py")
M = eigenpy.emptyMatrix()
assert M.shape == (0,0)
assert M.shape == (0, 0)
if verbose: print("===> From empty VectorXd to Py")
if verbose:
print("===> From empty VectorXd to Py")
v = eigenpy.emptyVector()
assert v.shape == (0,1)
assert v.shape == (0,)
if verbose:
print("===> From Py to Matrix1")
eigenpy.matrix1x1(np.array([1]))
if verbose: print("===> From MatrixXd to Py")
M = eigenpy.naturals(3,3,verbose)
Mcheck = np.reshape(np.matrix(range(9),np.double),[3,3])
assert np.array_equal(Mcheck,M)
if verbose:
print("===> From MatrixXd to Py")
M = eigenpy.naturals(3, 3, verbose)
Mcheck = np.reshape(np.array(range(9), np.double), [3, 3])
assert np.array_equal(Mcheck, M)
if verbose: print("===> From Matrix3d to Py")
M33= eigenpy.naturals33(verbose)
assert np.array_equal(Mcheck,M33)
if verbose:
print("===> From Matrix3d to Py")
M33 = eigenpy.naturals33(verbose)
assert np.array_equal(Mcheck, M33)
if verbose: print("===> From VectorXd to Py")
v = eigenpy.naturalsX(3,verbose)
vcheck = np.matrix([range(3),],np.double).T
assert np.array_equal(vcheck ,v)
if verbose:
print("===> From VectorXd to Py")
v = eigenpy.naturalsX(3, verbose)
vcheck = np.array(range(3), np.double).T
assert np.array_equal(vcheck, v)
if verbose: print("===> From Py to Eigen::MatrixXd")
if verbose: print("===> From Py to Eigen::MatrixXd")
if verbose: print("===> From Py to Eigen::MatrixXd")
Mref = np.reshape(np.matrix(range(64),np.double),[8,8])
if verbose:
print("===> From Py to Eigen::MatrixXd")
if verbose:
print("===> From Py to Eigen::MatrixXd")
if verbose:
print("===> From Py to Eigen::MatrixXd")
Mref = np.reshape(np.array(range(64), np.double), [8, 8])
if verbose: print("===> Matrix 8x8")
# Test base function
Mref_from_base = eigenpy.base(Mref)
assert np.array_equal(Mref, Mref_from_base)
# Test plain function
Mref_from_plain = eigenpy.plain(Mref)
assert np.array_equal(Mref, Mref_from_plain)
if verbose:
print("===> Matrix 8x8")
M = Mref
assert( np.array_equal(M,eigenpy.reflex(M,verbose)) );
assert np.array_equal(M, eigenpy.reflex(M, verbose))
if verbose: print("===> Block 0:3x0:3")
M = Mref[0:3,0:3]
assert( np.array_equal(M,eigenpy.reflex(M,verbose)) );
if verbose:
print("===> Block 0:3x0:3")
M = Mref[0:3, 0:3]
assert np.array_equal(M, eigenpy.reflex(M, verbose))
if verbose: print("===> Block 1:3x1:3")
M = Mref[1:3,1:3]
assert( np.array_equal(M,eigenpy.reflex(M,verbose)) );
if verbose:
print("===> Block 1:3x1:3")
M = Mref[1:3, 1:3]
assert np.array_equal(M, eigenpy.reflex(M, verbose))
if verbose: print("===> Block 1:5:2x1:5:2")
M = Mref[1:5:2,1:5:2]
assert( np.array_equal(M,eigenpy.reflex(M,verbose)) );
if verbose:
print("===> Block 1:5:2x1:5:2")
M = Mref[1:5:2, 1:5:2]
assert np.array_equal(M, eigenpy.reflex(M, verbose))
if verbose: print("===> Block 1:8:3x1:5")
M = Mref[1:8:3,1:5]
assert( np.array_equal(M,eigenpy.reflex(M,verbose)) );
if verbose:
print("===> Block 1:8:3x1:5")
M = Mref[1:8:3, 1:5]
assert np.array_equal(M, eigenpy.reflex(M, verbose))
if verbose: print("===> Block transpose 1:8:3x1:6:2")
M = Mref[1:8:3,0:6:2].T
assert( np.array_equal(M,eigenpy.reflex(M,verbose)) );
if verbose:
print("===> Block transpose 1:8:3x1:6:2")
M = Mref[1:8:3, 0:6:2].T
assert np.array_equal(M, eigenpy.reflex(M, verbose))
if verbose: print("===> Block Vector 1x0:6:2")
M = Mref[1:2,0:6:2]
assert( np.array_equal(M,eigenpy.reflex(M,verbose)) );
if verbose:
print("===> Block Vector 1x0:6:2")
M = Mref[1:2, 0:6:2]
assert np.array_equal(M.squeeze(), eigenpy.reflex(M, verbose))
if verbose: print("===> Block Vector 1x0:6:2 tanspose")
M = Mref[1:2,0:6:2].T
assert( np.array_equal(M,eigenpy.reflex(M,verbose)) );
if verbose:
print("===> Block Vector 1x0:6:2 tanspose")
M = Mref[1:2, 0:6:2].T
assert np.array_equal(M.squeeze(), eigenpy.reflex(M, verbose))
if verbose: print("===> Block Vector 0:6:2x1")
M = Mref[0:6:2,1:2]
assert( np.array_equal(M,eigenpy.reflex(M,verbose)) );
if verbose:
print("===> Block Vector 0:6:2x1")
M = Mref[0:6:2, 1:2]
assert np.array_equal(M.squeeze(), eigenpy.reflex(M, verbose))
if verbose: print("===> Block Vector 0:6:2x1 tanspose")
M = Mref[0:6:2,1:2].T
assert( np.array_equal(M,eigenpy.reflex(M,verbose)) );
if verbose:
print("===> Block Vector 0:6:2x1 tanspose")
M = Mref[0:6:2, 1:2].T
assert np.array_equal(M.squeeze(), eigenpy.reflex(M, verbose))
if verbose: print("===> From Py to Eigen::VectorXd")
if verbose: print("===> From Py to Eigen::VectorXd")
if verbose: print("===> From Py to Eigen::VectorXd")
if verbose:
print("===> From Py to Eigen::VectorXd")
if verbose:
print("===> From Py to Eigen::VectorXd")
if verbose:
print("===> From Py to Eigen::VectorXd")
if verbose: print("===> Block Vector 0:6:2x1 1 dim")
M = Mref[0:6:2,1].T
if verbose:
print("===> Block Vector 0:6:2x1 1 dim")
M = Mref[0:6:2, 1].T
# TODO
# assert( np.array_equal(M.T,eigenpy.reflexV(M,verbose)) );
if verbose: print("===> Block Vector 0:6:2x1")
M = Mref[0:6:2,1:2]
assert( np.array_equal(M,eigenpy.reflexV(M,verbose)) );
if verbose:
print("===> Block Vector 0:6:2x1")
M = Mref[0:6:2, 1:2]
assert np.array_equal(M.squeeze(), eigenpy.reflexV(M, verbose))
if verbose: print("===> Block Vector 0:6:2x1 transpose")
M = Mref[0:6:2,1:2].T
if verbose:
print("===> Block Vector 0:6:2x1 transpose")
M = Mref[0:6:2, 1:2].T
# TODO
# assert( np.array_equal(M.T,eigenpy.reflexV(M,verbose)) );
if verbose: print("===> From Py to Eigen::Matrix3d")
if verbose: print("===> From Py to Eigen::Matrix3d")
if verbose: print("===> From Py to Eigen::Matrix3d")
if verbose:
print("===> From Py to Eigen::Matrix3d")
if verbose:
print("===> From Py to Eigen::Matrix3d")
if verbose:
print("===> From Py to Eigen::Matrix3d")
if verbose: print("===> Block Vector 0:3x0:6:2 ")
M = Mref[0:3,0:6:2]
assert( np.array_equal(M,eigenpy.reflex33(M,verbose)) );
if verbose:
print("===> Block Vector 0:3x0:6:2 ")
M = Mref[0:3, 0:6:2]
assert np.array_equal(M, eigenpy.reflex33(M, verbose))
if verbose: print("===> Block Vector 0:3x0:6:2 T")
M = Mref[0:3,0:6].T
if verbose:
print("===> Block Vector 0:3x0:6:2 T")
M = Mref[0:3, 0:6].T
# TODO
# try:
# assert( np.array_equal(M,eigenpy.reflex33(M,verbose)) );
# assert( np.array_equal(M,eigenpy.reflex33(M,verbose)) );
# except eigenpy.Exception as e:
# if verbose: print("As expected, got the following /ROW/ error:", e.message)
# if verbose: print("As expected, got the following /ROW/ error:", e.message)
if verbose: print("===> From Py to Eigen::Vector3d")
if verbose: print("===> From Py to Eigen::Vector3d")
if verbose: print("===> From Py to Eigen::Vector3d")
if verbose:
print("===> From Py to Eigen::Vector3d")
if verbose:
print("===> From Py to Eigen::Vector3d")
if verbose:
print("===> From Py to Eigen::Vector3d")
# TODO
# M = Mref[0:3,1:2]
# assert( np.array_equal(M,eigenpy.reflex3(M,verbose)) );
value = 2.0
mat1x1 = eigenpy.matrix1x1(value)
assert mat1x1.size == 1
assert mat1x1[0, 0] == value
vec1x1 = eigenpy.vector1x1(value)
assert vec1x1.size == 1
assert vec1x1[0] == value
# test registration of matrix6
mat6 = eigenpy.matrix6(0.0)
assert mat6.size == 36
# test RowMajor
mat = np.arange(0, 10).reshape(2, 5)
assert (eigenpy.asRowMajorFromColMajorMatrix(mat) == mat).all()
assert (eigenpy.asRowMajorFromRowMajorMatrix(mat) == mat).all()
vec = np.arange(0, 10)
assert (eigenpy.asRowMajorFromColMajorMatrix(vec) == vec).all()
assert (eigenpy.asRowMajorFromColMajorVector(vec) == vec).all()
assert (eigenpy.asRowMajorFromRowMajorMatrix(vec) == vec).all()
assert (eigenpy.asRowMajorFromRowMajorVector(vec) == vec).all()
# Test numpy -> Eigen -> numpy for all same type
def test_conversion(function, dtype):
input_array = np.array([1, 0], dtype=dtype)
assert input_array.dtype == dtype
output_array = function(input_array)
assert output_array.dtype == dtype
assert (output_array == input_array).all()
bool_t = np.dtype(np.bool_)
int8_t = np.dtype(np.int8)
uint8_t = np.dtype(np.uint8)
int16_t = np.dtype(np.int16)
uint16_t = np.dtype(np.uint16)
int32_t = np.dtype(np.int32)
uint32_t = np.dtype(np.uint32)
int64_t = np.dtype(np.int64)
uint64_t = np.dtype(np.uint64)
# On Windows long is a 32 bits integer but is a different type than int32.
long_t = np.dtype(np.int32 if platform.system() == "Windows" else np.int64)
ulong_t = np.dtype(np.uint32 if platform.system() == "Windows" else np.uint64)
longlong_t = np.dtype(np.longlong)
ulonglong_t = np.dtype(np.ulonglong)
float32_t = np.dtype(np.float32)
float64_t = np.dtype(np.float64)
complex64_t = np.dtype(np.complex64)
complex128_t = np.dtype(np.complex128)
complex256_t = np.dtype(np.clongdouble)
test_conversion(eigenpy.copyBoolToBool, bool_t)
test_conversion(eigenpy.copyInt8ToInt8, int8_t)
test_conversion(eigenpy.copyCharToChar, int8_t)
test_conversion(eigenpy.copyUCharToUChar, uint8_t)
test_conversion(eigenpy.copyInt16ToInt16, int16_t)
test_conversion(eigenpy.copyUInt16ToUInt16, uint16_t)
test_conversion(eigenpy.copyInt32ToInt32, int32_t)
test_conversion(eigenpy.copyUInt32ToUInt32, uint32_t)
test_conversion(eigenpy.copyInt64ToInt64, int64_t)
test_conversion(eigenpy.copyUInt64ToUInt64, uint64_t)
test_conversion(eigenpy.copyLongToLong, long_t)
test_conversion(eigenpy.copyULongToULong, ulong_t)
# On Windows long long is an int64_t alias.
# The numpy dtype match between longlong and int64.
# On Linux long long is a 64 bits integer but is a different type than int64_t.
# The numpy dtype doesn't match and it's not an issue since C++ type are different.
# On Mac long long is an int64_t and long alias.
# This is an issue because longlong numpy dtype is different than long numpy dtype
# but long and long long are the same type in C++.
# The test should pass thanks to the promotion code.
test_conversion(eigenpy.copyLongLongToLongLong, longlong_t)
test_conversion(eigenpy.copyULongLongToULongLong, ulonglong_t)
test_conversion(eigenpy.copyFloatToFloat, float32_t)
test_conversion(eigenpy.copyDoubleToDouble, float64_t)
# On Windows and Mac longdouble is 64 bits
test_conversion(eigenpy.copyLongDoubleToLongDouble, np.dtype(np.longdouble))
test_conversion(eigenpy.copyCFloatToCFloat, complex64_t)
test_conversion(eigenpy.copyCDoubleToCDouble, complex128_t)
# On Windows and Mac clongdouble is 128 bits
test_conversion(eigenpy.copyCLongDoubleToCLongDouble, complex256_t)
# Test numpy -> Eigen -> numpy promotion
def test_conversion_promotion(function, input_dtype, output_dtype):
input_array = np.array([1, 0], dtype=input_dtype)
assert input_array.dtype == input_dtype
output_array = function(input_array)
assert output_array.dtype == output_dtype
assert (output_array == input_array).all()
# Test bool to other type
test_conversion_promotion(eigenpy.copyInt8ToInt8, bool_t, int8_t)
test_conversion_promotion(eigenpy.copyUCharToUChar, bool_t, uint8_t)
test_conversion_promotion(eigenpy.copyInt16ToInt16, bool_t, int16_t)
test_conversion_promotion(eigenpy.copyUInt16ToUInt16, bool_t, uint16_t)
test_conversion_promotion(eigenpy.copyInt32ToInt32, bool_t, int32_t)
test_conversion_promotion(eigenpy.copyUInt32ToUInt32, bool_t, uint32_t)
test_conversion_promotion(eigenpy.copyInt64ToInt64, bool_t, int64_t)
test_conversion_promotion(eigenpy.copyUInt64ToUInt64, bool_t, uint64_t)
test_conversion_promotion(eigenpy.copyLongToLong, bool_t, long_t)
test_conversion_promotion(eigenpy.copyULongToULong, bool_t, ulong_t)
test_conversion_promotion(eigenpy.copyLongLongToLongLong, bool_t, int64_t)
test_conversion_promotion(eigenpy.copyULongLongToULongLong, bool_t, uint64_t)
# Test int8 to other type
test_conversion_promotion(eigenpy.copyInt16ToInt16, int8_t, int16_t)
test_conversion_promotion(eigenpy.copyInt16ToInt16, uint8_t, int16_t)
test_conversion_promotion(eigenpy.copyUInt16ToUInt16, uint8_t, uint16_t)
test_conversion_promotion(eigenpy.copyInt32ToInt32, int8_t, int32_t)
test_conversion_promotion(eigenpy.copyInt32ToInt32, uint8_t, int32_t)
test_conversion_promotion(eigenpy.copyUInt32ToUInt32, uint8_t, uint32_t)
test_conversion_promotion(eigenpy.copyInt64ToInt64, int8_t, int64_t)
test_conversion_promotion(eigenpy.copyInt64ToInt64, uint8_t, int64_t)
test_conversion_promotion(eigenpy.copyUInt64ToUInt64, uint8_t, uint64_t)
test_conversion_promotion(eigenpy.copyLongToLong, int8_t, long_t)
test_conversion_promotion(eigenpy.copyLongToLong, uint8_t, long_t)
test_conversion_promotion(eigenpy.copyULongToULong, uint8_t, ulong_t)
test_conversion_promotion(eigenpy.copyLongLongToLongLong, int8_t, int64_t)
test_conversion_promotion(eigenpy.copyLongLongToLongLong, uint8_t, int64_t)
test_conversion_promotion(eigenpy.copyULongLongToULongLong, uint8_t, uint64_t)
# Test int16 to other type
test_conversion_promotion(eigenpy.copyInt32ToInt32, int16_t, int32_t)
test_conversion_promotion(eigenpy.copyInt32ToInt32, uint16_t, int32_t)
test_conversion_promotion(eigenpy.copyUInt32ToUInt32, uint16_t, uint32_t)
test_conversion_promotion(eigenpy.copyInt64ToInt64, int16_t, int64_t)
test_conversion_promotion(eigenpy.copyInt64ToInt64, uint16_t, int64_t)
test_conversion_promotion(eigenpy.copyUInt64ToUInt64, uint16_t, uint64_t)
test_conversion_promotion(eigenpy.copyLongToLong, int16_t, long_t)
test_conversion_promotion(eigenpy.copyLongToLong, uint16_t, long_t)
test_conversion_promotion(eigenpy.copyULongToULong, uint16_t, ulong_t)
test_conversion_promotion(eigenpy.copyLongLongToLongLong, int16_t, int64_t)
test_conversion_promotion(eigenpy.copyLongLongToLongLong, uint16_t, int64_t)
test_conversion_promotion(eigenpy.copyULongLongToULongLong, uint16_t, uint64_t)
# Test int32 to other type
test_conversion_promotion(eigenpy.copyInt64ToInt64, int32_t, int64_t)
test_conversion_promotion(eigenpy.copyInt64ToInt64, uint32_t, int64_t)
test_conversion_promotion(eigenpy.copyUInt64ToUInt64, uint32_t, uint64_t)
test_conversion_promotion(eigenpy.copyLongToLong, int32_t, long_t)
test_conversion_promotion(eigenpy.copyLongToLong, uint32_t, long_t)
test_conversion_promotion(eigenpy.copyULongToULong, uint32_t, ulong_t)
test_conversion_promotion(eigenpy.copyLongLongToLongLong, int32_t, int64_t)
test_conversion_promotion(eigenpy.copyLongLongToLongLong, uint32_t, int64_t)
test_conversion_promotion(eigenpy.copyULongLongToULongLong, uint32_t, uint64_t)
# Test float to double
test_conversion_promotion(eigenpy.copyDoubleToDouble, float32_t, float64_t)
# Test complex to other type
test_conversion_promotion(eigenpy.copyCDoubleToCDouble, complex64_t, complex128_t)
test_conversion_promotion(
eigenpy.copyCLongDoubleToCLongDouble,
complex64_t,
complex256_t,
)
# Only Linux store complex double into 258 bits.
# Then, 128 bits complex can be promoted.
if platform.system() == "Linux":
test_conversion_promotion(
eigenpy.copyCLongDoubleToCLongDouble,
complex128_t,
complex256_t,
)
import multiple_registration # noqa
import numpy as np
import return_by_ref
from return_by_ref import Matrix, RowMatrix, Vector
def test_shared(mat):
m_ref = mat.ref()
m_ref.fill(0)
m_copy = mat.copy()
assert np.array_equal(m_ref, m_copy)
m_const_ref = mat.const_ref()
assert np.array_equal(m_const_ref, m_copy)
assert np.array_equal(m_const_ref, m_ref)
m_ref.fill(1)
assert not np.array_equal(m_ref, m_copy)
assert np.array_equal(m_const_ref, m_ref)
try:
m_const_ref.fill(2)
assert False
except Exception:
assert True
def test_not_shared(mat):
m_ref = mat.ref()
m_ref.fill(100.0)
m_copy = mat.copy()
assert not np.array_equal(m_ref, m_copy)
m_const_ref = mat.const_ref()
assert np.array_equal(m_const_ref, m_copy)
assert not np.array_equal(m_const_ref, m_ref)
m_ref.fill(10.0)
assert not np.array_equal(m_ref, m_copy)
assert not np.array_equal(m_const_ref, m_ref)
try:
m_const_ref.fill(2)
assert True
except Exception:
assert False
rows = 10
cols = 30
mat = Matrix(rows, cols)
row_mat = RowMatrix(rows, cols)
vec = Vector(rows, 1)
test_shared(mat)
test_shared(row_mat)
test_shared(vec)
return_by_ref.sharedMemory(False)
test_not_shared(mat)
test_not_shared(row_mat)
test_not_shared(vec)
import numpy as np
import eigenpy
dim = 100
rng = np.random.default_rng()
A = rng.random((dim, dim))
A = (A + A.T) * 0.5
es = eigenpy.SelfAdjointEigenSolver(A)
V = es.eigenvectors()
D = es.eigenvalues()
assert eigenpy.is_approx(A.dot(V), V.dot(np.diag(D)), 1e-6)
import numpy as np
import sparse_matrix
from scipy.sparse import csr_matrix
m = sparse_matrix.emptyMatrix()
assert m.shape == (0, 0)
v = sparse_matrix.emptyVector()
assert v.shape == (0, 0)
m = sparse_matrix.matrix1x1(2)
assert m.toarray() == np.array([2])
v = sparse_matrix.vector1x1(2)
assert v.toarray() == np.array([2])
rng = np.random.default_rng()
diag_values = rng.random(10)
diag_mat = sparse_matrix.diagonal(diag_values)
assert (diag_mat.toarray() == np.diag(diag_values)).all()
diag_mat_copy = sparse_matrix.copy(diag_mat)
assert (diag_mat_copy != diag_mat).nnz == 0
diag_mat_csr = csr_matrix(diag_mat)
assert (sparse_matrix.copy(diag_mat_csr) != diag_mat_csr).nnz == 0
# test zero matrix
zero_mat = csr_matrix(np.zeros((10, 1)))
zero_mat_copy = sparse_matrix.copy(zero_mat)
assert (zero_mat_copy != zero_mat).nnz == 0
import std_array
ints = std_array.get_arr_3_ints()
print(ints[0])
print(ints[1])
print(ints[2])
print(ints.tolist())
assert ints.tolist() == [1, 2, 3]
_ints_slice = ints[1:3]
print("Printing slice...")
for el in _ints_slice:
print(el)
ref = [1, 2, 3]
assert len(ref[1:2]) == 1 # sanity check
assert len(_ints_slice) == 2, f"Slice size should be 1, got {len(_ints_slice)}"
assert _ints_slice[0] == 2
assert _ints_slice[1] == 3
# Test that insert/delete is impossible with the slice operator
# prepend
try:
ints[0:0] = [0, 1]
except NotImplementedError:
pass
else:
assert False, "Insert value with slice operator should be impossible"
# append
try:
ints[10:12] = [0]
except NotImplementedError:
pass
else:
assert False, "Insert value with slice operator should be impossible"
# append
try:
ints[3:3] = [0]
except NotImplementedError:
pass
else:
assert False, "Insert value with slice operator should be impossible"
# Erase two elements and replace by one
try:
ints[1:3] = [0]
except NotImplementedError:
pass
else:
assert False, "Insert value with slice operator should be impossible"
# Erase two elements and replace by three
try:
ints[1:3] = [0, 1, 2]
except NotImplementedError:
pass
else:
assert False, "Insert value with slice operator should be impossible"
# Test that delete operator is not implemented
# Index delete
try:
del ints[0]
except NotImplementedError:
pass
else:
assert False, "del is not implemented"
# Slice delete
try:
del ints[1:3]
except NotImplementedError:
pass
else:
assert False, "del is not implemented"
# Slice delete
try:
del ints[1:3]
except NotImplementedError:
pass
else:
assert False, "del is not implemented"
# Test that append/extend are not implemented
# append
try:
ints.append(4)
except AttributeError:
pass
else:
assert False, "append is not implemented"
# extend
try:
ints.extend([4, 5])
except AttributeError:
pass
else:
assert False, "extend is not implemented"
# Test set_slice nominal case
ints[1:3] = [10, 20]
assert ints[1] == 10
assert ints[2] == 20
# print(ints.tolist())
vecs = std_array.get_arr_3_vecs()
assert len(vecs) == 3
print(vecs[0])
print(vecs[1])
print(vecs[2])
# slices do not work for Eigen objects...
# v2 = vecs[:]
# assert isinstance(v2, std_array.StdVec_VectorXd)
# assert len(v2) == 3
# print(v2.tolist())
# print(v2[0])
ts = std_array.test_struct()
assert len(ts.integs) == 3
assert len(ts.vecs) == 2
print(ts.integs[:].tolist())
print(ts.vecs[0])
print(ts.vecs[1])
ts.integs[:] = 111
print("Test of set_slice for std::array<int>:", ts.integs[:].tolist())
for el in ts.integs:
assert el == 111
ts.vecs[0][0] = 0.0
ts.vecs[1][0] = -243
print(ts.vecs[0])
print(ts.vecs[1])
from std_map import X, copy, copy_boost, copy_X, std_map_to_dict
t = {"one": 1.0, "two": 2.0}
t2 = {"one": 1, "two": 2, "three": 3}
assert std_map_to_dict(t) == t
assert std_map_to_dict(copy(t)) == t
m = copy_boost(t2)
assert m.todict() == t2
xmap_cpp = copy_X({"one": X(1), "two": X(2)})
print(xmap_cpp.todict())
x1 = xmap_cpp["one"]
x1.val = 11
print(xmap_cpp.todict())
assert xmap_cpp["one"].val == 11
assert xmap_cpp["two"].val == 2
from std_pair import copy, passthrough, std_pair_to_tuple
t = (1, 2.0)
assert std_pair_to_tuple(t) == t
assert copy(t) == t
assert passthrough(t) == t