|
| 1 | +"""Internal tools to aid in building MATLAB support. |
| 2 | +
|
| 3 | +Tensor classes can use these common tools, where matlab_support uses tensors. |
| 4 | +matlab_support can depend on this, but tensors and this shouldn't depend on it. |
| 5 | +Probably best for everything here to be private functions. |
| 6 | +""" |
| 7 | + |
| 8 | +# Copyright 2024 National Technology & Engineering Solutions of Sandia, |
| 9 | +# LLC (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the |
| 10 | +# U.S. Government retains certain rights in this software. |
| 11 | + |
| 12 | +import textwrap |
| 13 | +from typing import Optional, Tuple, Union |
| 14 | + |
| 15 | +import numpy as np |
| 16 | + |
| 17 | + |
| 18 | +def _matlab_array_str( |
| 19 | + array: np.ndarray, |
| 20 | + format: Optional[str] = None, |
| 21 | + name: Optional[str] = None, |
| 22 | + skip_name: bool = False, |
| 23 | +) -> str: |
| 24 | + """Convert numpy array to string more similar to MATLAB.""" |
| 25 | + if name is None: |
| 26 | + name = type(array).__name__ |
| 27 | + header_str = "" |
| 28 | + body_str = "" |
| 29 | + if len(array.shape) > 2: |
| 30 | + matlab_str = "" |
| 31 | + # Iterate over all possible slices (in Fortran order) |
| 32 | + for index in np.ndindex( |
| 33 | + array.shape[2:][::-1] |
| 34 | + ): # Skip the first two dimensions and reverse the order |
| 35 | + original_index = index[::-1] # Reverse the order back to the original |
| 36 | + # Construct the slice indices |
| 37 | + slice_indices: Tuple[Union[int, slice], ...] = ( |
| 38 | + slice(None), |
| 39 | + slice(None), |
| 40 | + *original_index, |
| 41 | + ) |
| 42 | + slice_data = array[slice_indices] |
| 43 | + matlab_str += f"{name}(:,:, {', '.join(map(str, original_index))}) =" |
| 44 | + matlab_str += "\n" |
| 45 | + array_str = _matlab_array_str(slice_data, format, name, skip_name=True) |
| 46 | + matlab_str += textwrap.indent(array_str, "\t") |
| 47 | + matlab_str += "\n" |
| 48 | + return matlab_str[:-1] # Trim extra newline |
| 49 | + elif len(array.shape) == 2: |
| 50 | + header_str += f"{name}(:,:) =" |
| 51 | + for row in array: |
| 52 | + if format is None: |
| 53 | + body_str += " ".join(f"{val}" for val in row) |
| 54 | + else: |
| 55 | + body_str += " ".join(f"{val:{format}}" for val in row) |
| 56 | + body_str += "\n" |
| 57 | + else: |
| 58 | + header_str += f"{name}(:) =" |
| 59 | + for val in array: |
| 60 | + if format is None: |
| 61 | + body_str += f"{val}" |
| 62 | + else: |
| 63 | + body_str += f"{val:{format}}" |
| 64 | + body_str += "\n" |
| 65 | + |
| 66 | + if skip_name: |
| 67 | + return body_str |
| 68 | + return header_str + "\n" + textwrap.indent(body_str[:-1], "\t") |
0 commit comments