-
Notifications
You must be signed in to change notification settings - Fork 14
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* Internal: Try new link checker * Internal: Add codespell and fix typos. * Internal: See if codespell precommit finds config. * Internal: Found config. Now enable reading it * MATLAB: Add initial support for more matlab support. Closes #350
- Loading branch information
1 parent
c3249ad
commit 81e5217
Showing
6 changed files
with
172 additions
and
0 deletions.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
"""Partial support of MATLAB users in PYTTB.""" |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
"""A limited number of utilities to support users coming from MATLAB.""" | ||
|
||
# Copyright 2024 National Technology & Engineering Solutions of Sandia, | ||
# LLC (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the | ||
# U.S. Government retains certain rights in this software. | ||
|
||
from typing import Optional, Union | ||
|
||
import numpy as np | ||
|
||
from pyttb.tensor import tensor | ||
|
||
from .matlab_utilities import _matlab_array_str | ||
|
||
PRINT_CLASSES = Union[tensor, np.ndarray] | ||
|
||
|
||
def matlab_print( | ||
data: Union[tensor, np.ndarray], | ||
format: Optional[str] = None, | ||
name: Optional[str] = None, | ||
): | ||
"""Print data in a format more similar to MATLAB. | ||
Arguments | ||
--------- | ||
data: Object to print | ||
format: Numerical formatting | ||
""" | ||
if not isinstance(data, (tensor, np.ndarray)): | ||
raise ValueError( | ||
f"matlab_print only supports inputs of type {PRINT_CLASSES} but got" | ||
f" {type(data)}." | ||
) | ||
if isinstance(data, np.ndarray): | ||
print(_matlab_array_str(data, format, name)) | ||
return | ||
print(data._matlab_str(format, name)) |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,68 @@ | ||
"""Internal tools to aid in building MATLAB support. | ||
Tensor classes can use these common tools, where matlab_support uses tensors. | ||
matlab_support can depend on this, but tensors and this shouldn't depend on it. | ||
Probably best for everything here to be private functions. | ||
""" | ||
|
||
# Copyright 2024 National Technology & Engineering Solutions of Sandia, | ||
# LLC (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the | ||
# U.S. Government retains certain rights in this software. | ||
|
||
import textwrap | ||
from typing import Optional, Tuple, Union | ||
|
||
import numpy as np | ||
|
||
|
||
def _matlab_array_str( | ||
array: np.ndarray, | ||
format: Optional[str] = None, | ||
name: Optional[str] = None, | ||
skip_name: bool = False, | ||
) -> str: | ||
"""Convert numpy array to string more similar to MATLAB.""" | ||
if name is None: | ||
name = type(array).__name__ | ||
header_str = "" | ||
body_str = "" | ||
if len(array.shape) > 2: | ||
matlab_str = "" | ||
# Iterate over all possible slices (in Fortran order) | ||
for index in np.ndindex( | ||
array.shape[2:][::-1] | ||
): # Skip the first two dimensions and reverse the order | ||
original_index = index[::-1] # Reverse the order back to the original | ||
# Construct the slice indices | ||
slice_indices: Tuple[Union[int, slice], ...] = ( | ||
slice(None), | ||
slice(None), | ||
*original_index, | ||
) | ||
slice_data = array[slice_indices] | ||
matlab_str += f"{name}(:,:, {', '.join(map(str, original_index))}) =" | ||
matlab_str += "\n" | ||
array_str = _matlab_array_str(slice_data, format, name, skip_name=True) | ||
matlab_str += textwrap.indent(array_str, "\t") | ||
matlab_str += "\n" | ||
return matlab_str[:-1] # Trim extra newline | ||
elif len(array.shape) == 2: | ||
header_str += f"{name}(:,:) =" | ||
for row in array: | ||
if format is None: | ||
body_str += " ".join(f"{val}" for val in row) | ||
else: | ||
body_str += " ".join(f"{val:{format}}" for val in row) | ||
body_str += "\n" | ||
else: | ||
header_str += f"{name}(:) =" | ||
for val in array: | ||
if format is None: | ||
body_str += f"{val}" | ||
else: | ||
body_str += f"{val:{format}}" | ||
body_str += "\n" | ||
|
||
if skip_name: | ||
return body_str | ||
return header_str + "\n" + textwrap.indent(body_str[:-1], "\t") |
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
# Copyright 2024 National Technology & Engineering Solutions of Sandia, | ||
# LLC (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the | ||
# U.S. Government retains certain rights in this software. | ||
|
||
import numpy as np | ||
import pytest | ||
|
||
from pyttb import matlab_support, tensor | ||
|
||
|
||
def test_matlab_printing_negative(): | ||
with pytest.raises(ValueError): | ||
matlab_support.matlab_print("foo") | ||
|
||
|
||
def test_np_printing(): | ||
"""These are just smoke tests since formatting needs manual style verification.""" | ||
# Check different dimensionality support | ||
one_d_array = np.ones((1,)) | ||
matlab_support.matlab_print(one_d_array) | ||
two_d_array = np.ones((1, 1)) | ||
matlab_support.matlab_print(two_d_array) | ||
three_d_array = np.ones((1, 1, 1)) | ||
matlab_support.matlab_print(three_d_array) | ||
|
||
# Check name and format | ||
matlab_support.matlab_print(one_d_array, format="5.1f", name="X") | ||
matlab_support.matlab_print(two_d_array, format="5.1f", name="X") | ||
matlab_support.matlab_print(three_d_array, format="5.1f", name="X") | ||
|
||
|
||
def test_dense_printing(): | ||
"""These are just smoke tests since formatting needs manual style verification.""" | ||
# Check different dimensionality support | ||
example = tensor(np.arange(16), shape=(2, 2, 2, 2)) | ||
# 4D | ||
matlab_support.matlab_print(example) | ||
# 2D | ||
matlab_support.matlab_print(example[:, :, 0, 0]) | ||
# 1D | ||
matlab_support.matlab_print(example[:, 0, 0, 0]) | ||
|
||
# Check name and format | ||
matlab_support.matlab_print(example, format="5.1f", name="X") |