Skip to content
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

Incorporated pathlib.Path compatibility #99

Merged
merged 3 commits into from
Jan 28, 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
24 changes: 20 additions & 4 deletions ansys/mapdl/reader/archive.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import os
import logging
from functools import wraps
import pathlib
from typing import Union

import numpy as np
from pyvista._vtk import (VTK_TETRA, VTK_QUADRATIC_TETRA, VTK_PYRAMID,
Expand Down Expand Up @@ -37,7 +39,7 @@ class Archive(Mesh):

Parameters
----------
filename : string
filename : string, pathlib.Path
Filename of block formatted cdb file

read_parameters : bool, optional
Expand Down Expand Up @@ -113,9 +115,9 @@ def __init__(self, filename, read_parameters=False,
verbose=False, name=''):
"""Initializes an instance of the archive class."""
self._read_parameters = read_parameters
self._filename = filename
self._filename = pathlib.Path(filename)
self._name = name
self._raw = _reader.read(filename, read_parameters=read_parameters,
self._raw = _reader.read(self.filename, read_parameters=read_parameters,
debug=verbose)
super().__init__(self._raw['nnum'],
self._raw['nodes'],
Expand All @@ -136,6 +138,20 @@ def __init__(self, filename, read_parameters=False,
self._grid = self._parse_vtk(allowable_types,
force_linear, null_unallowed)

@property
def filename(self) -> str:
"""String form of the filename. Accepts ``pathlib.Path`` and string objects when set."""
return str(self._filename)
Comment on lines +142 to +144
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agree with this for backwards compatibility.


@property
def pathlib_filename(self) -> pathlib.Path:
"""Return the ``pathlib.Path`` version of the filename. This property can not be set."""
return self._filename

@filename.setter
def filename(self, value: Union[str, pathlib.Path]):
self._filename = pathlib.Path(value)

@property
def raw(self): # pragma: no cover
raise AttributeError('The `raw` attribute has been depreciated. Access'
Expand Down Expand Up @@ -262,7 +278,7 @@ def save_as_archive(filename, grid, mtype_start=1, etype_start=1,

Parameters
----------
filename : str
filename : str, pathlib.Path
Filename to write archive file.

grid : vtk.UnstructuredGrid
Expand Down
16 changes: 8 additions & 8 deletions ansys/mapdl/reader/common.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Methods common to binary files"""
import struct
import os
import pathlib
from typing import Union
from collections import Counter

import numpy as np
Expand All @@ -24,7 +25,6 @@
45: 'Component Mode Synthesis Matrices (CMS) File'}



# c *** standard usage of the block number (buffers) and file unit number(FUN)
# c for the ansys files
# c
Expand Down Expand Up @@ -61,9 +61,9 @@
# c ASI -> ASIRSTNM FUN66 9 asi results


class AnsysBinary():
class AnsysBinary:
"""ANSYS binary file class"""
filename = None
filename: Union[str, pathlib.Path] = None

# read only file handle
_cfile = None
Expand Down Expand Up @@ -120,7 +120,7 @@ def read_binary(filename, **kwargs):

Parameters
----------
filename : str
filename : str, pathlib.Path
Filename to read.

**kwargs : keyword arguments
Expand Down Expand Up @@ -148,9 +148,9 @@ def read_binary(filename, **kwargs):
- Jobname.RMG A magnetic analysis
- Jobname.RFL A FLOTRAN analysis (a legacy results file)
"""
if not os.path.isfile(filename):
raise FileNotFoundError('%s is not a file or cannot be found' %
str(filename))
filename = pathlib.Path(filename)
if not filename.is_file():
raise FileNotFoundError(f'{filename} is not a file or cannot be found')

file_format = read_standard_header(filename)['file format']

Expand Down
1 change: 1 addition & 0 deletions ansys/mapdl/reader/cyclic_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -1645,6 +1645,7 @@ def animate_nodal_solution(self, rnum, comp='norm',
plotter.camera_position = cpos

if movie_filename:
movie_filename = str(movie_filename)
if movie_filename.strip()[-3:] == 'gif':
plotter.open_gif(movie_filename)
else:
Expand Down
4 changes: 3 additions & 1 deletion ansys/mapdl/reader/dis_result.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import glob
import os
from functools import wraps
from typing import Union
import pathlib

import pyvista as pv
import numpy as np
Expand All @@ -17,7 +19,7 @@
from ansys.mapdl.reader._rst_keys import element_index_table_info


def find_dis_files(main_file):
def find_dis_files(main_file: Union[str, pathlib.Path]):
"""Find the individual distributed result files given a main result file"""
basename = os.path.basename(main_file)
jobname = basename[:basename.rfind('0')]
Expand Down
32 changes: 24 additions & 8 deletions ansys/mapdl/reader/emat.py
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,8 @@
c kygrf global restoring force matrix calculate key

"""
import pathlib

import numpy as np

from ansys.mapdl.reader.common import read_table, parse_header
Expand All @@ -334,7 +336,7 @@ class EmatFile(object):

Parameters
----------
filename : str
filename : str, pathlib.Path
File to open. Generally ends in ``*.emat``.

Examples
Expand All @@ -350,12 +352,26 @@ def __init__(self, filename):
self._nnum = None
self._eeqv = None
self._enum = None
self.filename = filename
self._filename = pathlib.Path(filename)
self.read_header()

@property
def filename(self):
"""String form of the filename. Accepts ``pathlib.Path`` and string objects when set."""
return str(self._filename)

@property
def pathlib_filename(self):
"""Return the ``pathlib.Path`` version of the filename. This property can not be set."""
return self._filename

@filename.setter
def filename(self, value):
self._filename = pathlib.Path(value)

def read_header(self):
"""Read standard emat file header"""
with open(self.filename, 'rb') as f:
with open(self.pathlib_filename, 'rb') as f:
f.seek(103*4)
self.header = parse_header(read_table(f), EMAT_HEADER_KEYS)

Expand Down Expand Up @@ -402,15 +418,15 @@ def read_element_matrix_header(self, f_index):
lower triangular form.

"""
with open(self.filename, 'rb') as f:
with open(self.pathlib_filename, 'rb') as f:
f.seek(4*f_index)
return parse_header(read_table(f), ELEMENT_HEADER_KEYS)

@property
def element_matrices_index_table(self):
"""Return element matrices index table"""
if self._element_matrices_index_table is None:
with open(self.filename, 'rb') as f:
with open(self.pathlib_filename, 'rb') as f:
f.seek(self.header['ptrIDX']*4)
self._element_matrices_index_table = read_table(f)
return self._element_matrices_index_table
Expand All @@ -435,7 +451,7 @@ def neqv(self):
for storage to the actual node number.
"""
if self._neqv is None:
with open(self.filename, 'rb') as f:
with open(self.pathlib_filename, 'rb') as f:
f.seek(self.header['ptrBAC']*4)
self._neqv = read_table(f)
return self._neqv
Expand All @@ -459,7 +475,7 @@ def eeqv(self):
table equates the order number used to the actual element.
"""
if self._eeqv is None:
with open(self.filename, 'rb') as f:
with open(self.pathlib_filename, 'rb') as f:
f.seek(self.header['ptrElm']*4)
self._eeqv = read_table(f)
return self._eeqv
Expand Down Expand Up @@ -540,7 +556,7 @@ def read_element(self, index, stress=True, mass=True,
reference number given by ``dof_idx``.
"""
element_data = {}
with open(self.filename, 'rb') as fobj:
with open(self.pathlib_filename, 'rb') as fobj:
# seek to the position of the element table in the file
fobj.seek(self.element_matrices_index_table[index]*4)

Expand Down
29 changes: 21 additions & 8 deletions ansys/mapdl/reader/full.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@

"""
import os
import pathlib
import warnings
from typing import Union

import numpy as np

Expand Down Expand Up @@ -68,7 +70,7 @@ class FullFile(AnsysBinary):

"""

def __init__(self, filename):
def __init__(self, filename: Union[str, pathlib.Path]):
"""Loads full header on initialization.

See ANSYS programmer's reference manual full header section
Expand All @@ -86,13 +88,10 @@ def __init__(self, filename):
self._m = None
self._dof_ref = None

self.filename = filename
self._filename = pathlib.Path(filename)
self._standard_header = read_standard_header(self.filename)
self._header = parse_header(self.read_record(103), SYMBOLIC_FULL_HEADER_KEYS)

# if not self._header['fun04'] < 0:
# raise NotImplementedError("Unable to read a frontal assembly full file")

# Check if lumped (item 11)
if self._header['lumpm']:
raise NotImplementedError("Unable to read a lumped mass matrix")
Expand All @@ -101,6 +100,20 @@ def __init__(self, filename):
if self._header['keyuns']:
raise NotImplementedError("Unable to read an unsymmetric mass/stiffness matrix")

@property
def filename(self):
"""String form of the filename. Accepts ``pathlib.Path`` and string objects when set."""
return str(self._filename)

@property
def pathlib_filename(self):
"""Return the ``pathlib.Path`` version of the filename. This property can not be set."""
return self._filename

@filename.setter
def filename(self, value):
self._filename = pathlib.Path(value)

@property
def k(self):
"""Stiffness Matrix corresponding to sorted DOF.
Expand Down Expand Up @@ -221,8 +234,8 @@ def load_km(self, as_sparse=True, sort=False):
Constrained DOF can be accessed from ``const``, which returns
the node number and DOF constrained in ANSYS.
"""
if not os.path.isfile(self.filename):
raise Exception('%s not found' % self.filename)
if not self.pathlib_filename.is_file():
raise Exception('%s not found' % self.pathlib_filename)

if as_sparse:
try:
Expand All @@ -242,7 +255,7 @@ def load_km(self, as_sparse=True, sort=False):
ptrDOF = self._header['ptrDOF'] # pointer to DOF info

# DOF information
with open(self.filename, 'rb') as f:
with open(self.pathlib_filename, 'rb') as f:
read_table(f, skip=True) # standard header
read_table(f, skip=True) # full header
read_table(f, skip=True) # number of degrees of freedom
Expand Down
4 changes: 2 additions & 2 deletions ansys/mapdl/reader/mesh.py
Original file line number Diff line number Diff line change
Expand Up @@ -558,7 +558,7 @@ def save(self, filename, binary=True, force_linear=False, allowable_types=[],

Parameters
----------
filename : str
filename : str, pathlib.Path
Filename of output file. Writer type is inferred from
the extension of the filename.

Expand Down Expand Up @@ -593,7 +593,7 @@ def save(self, filename, binary=True, force_linear=False, allowable_types=[],
grid = self._parse_vtk(allowable_types=allowable_types,
force_linear=force_linear,
null_unallowed=null_unallowed)
return grid.save(filename, binary=binary)
return grid.save(str(filename), binary=binary)

@property
def n_node(self):
Expand Down
Loading