Skip to content

Fix load_table #1402

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Aug 25, 2022
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
59 changes: 28 additions & 31 deletions src/ansys/mapdl/core/mapdl.py
Original file line number Diff line number Diff line change
Expand Up @@ -2827,11 +2827,9 @@ def load_array(self, name, array):
os.remove(filename)

def load_table(self, name, array, var1="", var2="", var3="", csysid=""):
"""Load a table from Python to MAPDL.
"""Load a table from Python to into MAPDL.

Uses ``TREAD`` to transfer the table.
It should be noticed that PyMAPDL when query a table, it will return
the table but not its axis (meaning it will return ``table[1:,1:]``).
Uses :func:`tread <Mapdl.tread>` to transfer the table.

Parameters
----------
Expand All @@ -2841,21 +2839,20 @@ def load_table(self, name, array, var1="", var2="", var3="", csysid=""):
containing only letters, numbers, and underscores.
Examples: ``"ABC" "A3X" "TOP_END"``.

array : np.ndarray or List
List as a table or ``numpy`` array.
array : numpy.ndarray or List
List as a table or :class:`numpy.ndarray` array.

var1 : str, optional
Variable name corresponding to the first dimension (row).
Default Row
Default ``"Row"``.

A primary variable (listed below) or can be an independent
parameter. If specifying an independent parameter, then
you must define an additional table for the independent
parameter. The additional table must have the same name as
the independent parameter and may be a function of one or
more primary variables or another independent
parameter. All independent parameters must relate to a
primary variable.
parameter. If specifying an independent parameter, then you must
define an additional table for the independent parameter. The
additional table must have the same name as the independent
parameter and may be a function of one or more primary variables or
another independent parameter. All independent parameters must
relate to a primary variable.

- ``"TIME"``: Time
- ``"FREQ"``: Frequency
Expand Down Expand Up @@ -2888,6 +2885,9 @@ def load_table(self, name, array, var1="", var2="", var3="", csysid=""):

Examples
--------
Transfer a table to MAPDL. The first column is time values and must be
ascending in order.

>>> my_conv = np.array([[0, 0.001],
[120, 0.001],
[130, 0.005],
Expand All @@ -2896,7 +2896,12 @@ def load_table(self, name, array, var1="", var2="", var3="", csysid=""):
[1000, 0.002]])
>>> mapdl.load_table('MY_TABLE', my_conv, 'TIME')
>>> mapdl.parameters['MY_TABLE']
array([0.0001, 0.0001, 0.0005, 0.0005, 0.0002, 0.0002])
array([[0.001],
[0.001],
[0.005],
[0.005],
[0.002],
[0.002]])
"""
if not isinstance(array, np.ndarray):
raise ValueError("The table should be a Numpy array")
Expand All @@ -2909,7 +2914,7 @@ def load_table(self, name, array, var1="", var2="", var3="", csysid=""):
self.dim(
name,
"TABLE",
imax=array.shape[0] - 1,
imax=array.shape[0],
jmax=array.shape[1] - 1,
kmax="",
var1=var1,
Expand All @@ -2922,34 +2927,26 @@ def load_table(self, name, array, var1="", var2="", var3="", csysid=""):
f"Expecting only a 2D table, but input contains\n{array.ndim} dimensions"
)

if not np.all(array[0, :-1] <= array[0, 1:]):
raise ValueError(
"The underlying ``TREAD`` command requires that the axis 0 is in ascending order."
)
if not np.all(array[:-1, 0] <= array[1:, 0]):
raise ValueError(
"The underlying ``TREAD`` command requires that the axis 1 is in ascending order."
"The underlying ``TREAD`` command requires that the first column is in "
"ascending order."
)

# weird bug where MAPDL ignores the first row when there are greater than 2 columns
if array.shape[1] > 2:
array = np.vstack((array[0], array))

base_name = random_string() + ".txt"
filename = os.path.join(tempfile.gettempdir(), base_name)

if array.shape[1] == 2:
# two-columns bug.
# If there is two columns, the header is also read as part of the table values,
# for this case, we are not going to write it to the file.
array = array[1:, :]

np.savetxt(filename, array, header="File generated by PyMAPDL:load_table")

if not self._local:
self.upload(filename, progress_bar=False)
filename = base_name
# skip the first line its a header we wrote in np.savetxt
self.tread(name, filename, nskip=1, mute=True)

if self._local: # pragma: no cover
os.remove(filename)

def _display_plot(self, *args, **kwargs): # pragma: no cover
raise NotImplementedError("Implemented by child class")

Expand Down
27 changes: 4 additions & 23 deletions tests/test_mapdl.py
Original file line number Diff line number Diff line change
Expand Up @@ -780,35 +780,16 @@ def test_cyclic_solve(mapdl, cleared):
)
def test_load_table(mapdl, dim_rows, dim_cols):
my_conv = np.random.rand(dim_rows, dim_cols)
my_conv[:, 0] = np.arange(dim_rows)
my_conv[0, :] = np.arange(dim_cols)

mapdl.load_table("my_conv", my_conv)
if (
dim_cols == 2
): # because mapdl output arrays with shape (x,1) not (X,) See issue: #883
assert np.allclose(
mapdl.parameters["my_conv"], my_conv[1:, 1].reshape((dim_rows - 1, 1)), 1e-7
)
else:
assert np.allclose(mapdl.parameters["my_conv"], my_conv[1:, 1:], 1e-7)

my_conv[:, 0] = np.arange(dim_rows) # "time" values

def test_load_table_error_ascending_row(mapdl):
my_conv = np.ones((3, 3))
my_conv[0, 1] = 4
with pytest.raises(
ValueError, match="requires that the axis 0 is in ascending order."
):
mapdl.load_table("my_conv", my_conv)
mapdl.load_table("my_conv", my_conv, "TIME")
assert np.allclose(mapdl.parameters["my_conv"], my_conv[:, 1:], 1e-7)


def test_load_table_error_ascending_row(mapdl):
my_conv = np.ones((3, 3))
my_conv[1, 0] = 4
with pytest.raises(
ValueError, match="requires that the axis 1 is in ascending order."
):
with pytest.raises(ValueError, match="requires that the first column is in"):
mapdl.load_table("my_conv", my_conv)


Expand Down