Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
4 changes: 2 additions & 2 deletions pyttb/cp_als.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ def cp_als(
# Compute the matrix of coefficients for linear system
Y = np.prod(UtU, axis=2, where=[i != n for i in range(N)])
# don't try to solve linear system with Y = 0
if (Y == np.zeros(Y.shape)).all():
if (Y == 0).all():
Unew = np.zeros(Unew.shape)
else:
Unew = np.linalg.solve(Y.T, Unew.T).T
Expand All @@ -213,7 +213,7 @@ def cp_als(
weights = np.maximum(np.max(np.abs(Unew), 0), 1) # max-norm

# if weights are 0, do not divide
if not (weights == np.zeros(weights.shape)).all():
if not (weights == 0).all():
Unew = Unew / weights

U[n] = Unew
Expand Down
33 changes: 4 additions & 29 deletions pyttb/ktensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -614,31 +614,6 @@ def double(self) -> np.ndarray:
"""
return self.full().double()

def end(self, k: Optional[int] = None) -> int:
"""
Last index of indexing expression for :class:`pyttb.ktensor`.

Parameters
----------
k:
Dimension for subscripted indexing

Returns
-------
Final index

Examples
--------
>>> K = ttb.ktensor.from_function(np.ones, (2, 3, 4), 2)
>>> print(K.end(2))
3
"""

if k is not None: # Subscripted indexing
return self.shape[k] - 1
# For linear indexing
return int(np.prod(self.shape) - 1)

def extract(
self, idx: Optional[Union[int, tuple, list, np.ndarray]] = None
) -> ktensor:
Expand Down Expand Up @@ -893,7 +868,7 @@ def full(self) -> ttb.tensor:
[[5. 6.]
[7. 8.]]
>>> print(K.full()) # doctest: +NORMALIZE_WHITESPACE
tensor of shape 2 x 2
tensor of shape (2, 2)
data[:, :] =
[[29. 39.]
[63. 85.]]
Expand Down Expand Up @@ -976,7 +951,7 @@ def isequal(self, other: ttb.ktensor) -> bool:
if (self.weights != other.weights).any():
return False
for k in range(self.ndims):
if not (self.factor_matrices[k] == other.factor_matrices[k]).all():
if not np.array_equal(self.factor_matrices[k], other.factor_matrices[k]):
return False
return True

Expand Down Expand Up @@ -1032,7 +1007,7 @@ def issymmetric(
for j in range(i + 1, self.ndims):
if self.factor_matrices[i].shape != self.factor_matrices[j].shape:
diffs[i, j] = np.inf
elif (self.factor_matrices[i] == self.factor_matrices[j]).all():
elif np.array_equal(self.factor_matrices[i], self.factor_matrices[j]):
diffs[i, j] = 0
else:
diffs[i, j] = np.linalg.norm(
Expand Down Expand Up @@ -1771,7 +1746,7 @@ def tolist(self, mode: Optional[int] = None) -> List[np.ndarray]:
assert False, "Input parameter'mode' must be in the range of self.ndims"

# all weights are equal to 1
if (self.weights == np.ones(self.weights.shape)).all():
if np.array_equal(self.weights, np.ones(self.weights.shape)):
return self.factor_matrices.copy()

lsgn = np.sign(self.weights)
Expand Down
20 changes: 3 additions & 17 deletions pyttb/sptensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -429,7 +429,7 @@ def collapse(
size=newsize[0],
func=fun,
)
return np.zeros((newsize[0], 1))
return np.zeros((newsize[0],))

# Create Result
if self.subs.size > 0:
Expand Down Expand Up @@ -533,19 +533,6 @@ def elemfun(self, function_handle: Callable[[np.ndarray], np.ndarray]) -> sptens
return ttb.sptensor.from_data(np.array([]), np.array([]), self.shape)
return ttb.sptensor.from_data(self.subs[idx, :], vals[idx], self.shape)

def end(self, k: Optional[int] = None) -> int:
"""
Last index of indexing expression for sparse tensor

Parameters
----------
k:
Dimension for subscript indexing
"""
if k is not None:
return self.shape[k] - 1
return int(np.prod(self.shape) - 1)

def extract(self, searchsubs: np.ndarray) -> np.ndarray:
"""
Extract value for a sptensor.
Expand Down Expand Up @@ -1102,7 +1089,7 @@ def scale(self, factor: np.ndarray, dims: Union[float, np.ndarray]) -> sptensor:
assert False, "Size mismatch in scale"
return ttb.sptensor.from_data(
self.subs,
self.vals * factor[self.subs[:, dims].transpose()[0]],
self.vals * factor[self.subs[:, dims].transpose()[0]][:, None],
self.shape,
)
assert False, "Invalid scaling factor"
Expand Down Expand Up @@ -2553,8 +2540,7 @@ def __repr__(self): # pragma: no cover
s += (" x ").join([str(int(d)) for d in self.shape])
return s

s = "Sparse tensor of shape "
s += (" x ").join([str(int(d)) for d in self.shape])
s = f"Sparse tensor of shape {self.shape}"
s += f" with {nz} nonzeros \n"

# Stop insane printouts
Expand Down
21 changes: 1 addition & 20 deletions pyttb/tenmat.py
Original file line number Diff line number Diff line change
Expand Up @@ -243,22 +243,6 @@ def double(self) -> np.ndarray:
"""
return self.data.astype(np.float_).copy()

def end(self, k: int) -> int:
"""
Last index of indexing expression for tenmat

Parameters
----------
k:
Dimension for subscripted indexing

Returns
-------
Index
"""

return self.data.shape[k] - 1

@property
def ndims(self) -> int:
"""Return the number of dimensions of a tenmat"""
Expand Down Expand Up @@ -498,10 +482,7 @@ def __repr__(self):
"""
s = ""
s += "matrix corresponding to a tensor of shape "
if self.data.size == 0:
s += str(self.shape)
else:
s += (" x ").join([str(int(d)) for d in self.tshape])
s += str(self.tshape)
s += "\n"

s += "rindices = "
Expand Down
30 changes: 3 additions & 27 deletions pyttb/tensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -335,29 +335,6 @@ def exp(self) -> tensor:
"""
return ttb.tensor.from_data(np.exp(self.data))

def end(self, k: Optional[int] = None) -> int:
"""
Last index of indexing expression for tensor

Parameters
----------
k:
Dimension for subscripted indexing

Examples
--------
>>> X = ttb.tensor.from_data(np.ones((2,2)))
>>> X.end() # linear indexing
3
>>> X.end(0)
1
"""

if k is not None: # Subscripted indexing
return self.shape[k] - 1
# For linear indexing
return np.prod(self.shape) - 1

def find(self) -> Tuple[np.ndarray, np.ndarray]:
"""
FIND Find subscripts of nonzero elements in a tensor.
Expand Down Expand Up @@ -1462,12 +1439,12 @@ def __getitem__(self, item):
1.0
>>> # produces a tensor of order 1 and size 1
>>> X[1,1,1,:] # doctest: +NORMALIZE_WHITESPACE
tensor of shape 1
tensor of shape (1,)
data[:] =
[1.]
>>> # produces a tensor of size 2 x 2 x 1
>>> X[0:2,[2, 3],1,:] # doctest: +NORMALIZE_WHITESPACE
tensor of shape 2 x 2 x 1
tensor of shape (2, 2, 1)
data[0, :, :] =
[[1.]
[1.]]
Expand Down Expand Up @@ -1862,8 +1839,7 @@ def __repr__(self):
return s

s = ""
s += "tensor of shape "
s += (" x ").join([str(int(d)) for d in self.shape])
s += f"tensor of shape {self.shape}"
s += "\n"

if self.ndims == 1:
Expand Down
6 changes: 3 additions & 3 deletions tests/test_import_export_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ def test_import_data_array(sample_array):
data_filename = os.path.join(os.path.dirname(__file__), "data", "matrix.tns")
X = ttb.import_data(data_filename)

assert (M == X).all()
assert np.array_equal(M, X)


@pytest.mark.indevelopment
Expand Down Expand Up @@ -230,14 +230,14 @@ def test_export_data_array(sample_array):
ttb.export_data(M, data_filename)

X = ttb.import_data(data_filename)
assert (M == X).all()
assert np.array_equal(M, X)
os.unlink(data_filename)

data_filename = os.path.join(os.path.dirname(__file__), "data", "matrix_int.out")
ttb.export_data(M, data_filename, fmt_data="%d")

X = ttb.import_data(data_filename)
assert (M == X).all()
assert np.array_equal(M, X)
os.unlink(data_filename)


Expand Down
10 changes: 5 additions & 5 deletions tests/test_khatrirao.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,9 @@ def test_khatrirao():
[64, 125, 216],
]
)
assert (ttb.khatrirao(*[A, A, A]) == answer).all()
assert (ttb.khatrirao(*[A, A, A], reverse=True) == answer).all()
assert (ttb.khatrirao(A, A, A) == answer).all()
assert np.array_equal(ttb.khatrirao(*[A, A, A]), answer)
assert np.array_equal(ttb.khatrirao(*[A, A, A], reverse=True), answer)
assert np.array_equal(ttb.khatrirao(A, A, A), answer)

# Test case where inputs are column vectors
a_1 = np.array([[1], [1], [1], [1]])
Expand All @@ -40,8 +40,8 @@ def test_khatrirao():
a_2[3, 0] * np.ones((16, 1)),
)
)
assert (ttb.khatrirao(*[a_2, a_1, a_1]) == result).all()
assert (ttb.khatrirao(a_2, a_1, a_1) == result).all()
assert np.array_equal(ttb.khatrirao(*[a_2, a_1, a_1]), result)
assert np.array_equal(ttb.khatrirao(a_2, a_1, a_1), result)

with pytest.raises(AssertionError) as excinfo:
ttb.khatrirao(a_2, a_1, np.ones((2, 2, 2)))
Expand Down
Loading