1
0
mirror of https://github.com/TREX-CoE/trexio.git synced 2024-12-22 20:35:44 +01:00

Add state attrbitute and corresponding functions

+ remove useless try/except statements in the Python API
This commit is contained in:
q-posev 2022-04-13 16:38:29 +02:00
parent f0189cb8da
commit d234694f33

View File

@ -527,16 +527,10 @@ def string_of_error(return_code: int) -> str:
"""Decode the TREXIO exit code. """Decode the TREXIO exit code.
Argument is an integer return code that correspond to one of the TREXIO errors. Argument is an integer return code that correspond to one of the TREXIO errors.
Returns a string that contains description of TREXIO ~return_code~.
Returns string that contains description of TREXIO ~return_code~.
""" """
try: return pytr.trexio_string_of_error(return_code)
error_str = pytr.trexio_string_of_error(return_code)
except:
raise
return error_str
#+end_src #+end_src
** Back ends ** Back ends
@ -684,12 +678,15 @@ struct trexio_s {
back_end_t back_end; back_end_t back_end;
char mode; char mode;
bool one_based; bool one_based;
int32_t state;
char version[16]; char version[16];
char padding[6]; /* Ensures the proper alignment of back ends */
}; };
#+end_src #+end_src
*** TREXIO_File Python class
File class for the Python API is defined below.
Use of Python class make it more intuitive and more python-ic
to work with TREXIO files.
#+begin_src python :tangle basic_python.py #+begin_src python :tangle basic_python.py
class File: class File:
@ -707,6 +704,9 @@ class File:
mode: str mode: str
One of the currently supported TREXIO open modes. One of the currently supported TREXIO open modes.
For example, 'r' or 'w'. For example, 'r' or 'w'.
state: int
Active state of the file (needed to write determinant_coefficient).
Default is 0.
isOpen: bool isOpen: bool
Flag indicating whether the current object is still open for I/O Flag indicating whether the current object is still open for I/O
pytrexio_s: pytrexio_s:
@ -724,6 +724,7 @@ class File:
self.filename = filename self.filename = filename
self.mode = mode self.mode = mode
self.back_end = back_end self.back_end = back_end
self.state = 0
self.isOpen = False self.isOpen = False
self.exists = False self.exists = False
@ -759,6 +760,29 @@ class File:
raise Exception("TREXIO File object has not been opened.") raise Exception("TREXIO File object has not been opened.")
def set_state(self, state):
"""Set the state of the TREXIO File."""
if not isinstance(state, int):
raise TypeError("state argument has to be int")
rc = pytr.trexio_set_state(self.pytrexio_s, state)
if rc != TREXIO_SUCCESS:
raise Error(rc)
self.state = state
def get_state(self):
"""Get the state of the TREXIO File."""
rc, state = pytr.trexio_get_state(self.pytrexio_s)
if rc != TREXIO_SUCCESS:
raise Error(rc)
if state != self.state:
raise Exception("Inconsistent state of the TREXIO file.")
return self.state
def inquire(self): def inquire(self):
"""Inquire whether a TREXIO file exists.""" """Inquire whether a TREXIO file exists."""
self.exists = _inquire(self.filename) self.exists = _inquire(self.filename)
@ -774,7 +798,7 @@ class File:
pass pass
#+end_src #+end_src
** Polymorphism of the file handle ** TODO (Remove) : Polymorphism of the file handle
Polymorphism of the ~trexio_t~ type is handled by ensuring that the Polymorphism of the ~trexio_t~ type is handled by ensuring that the
corresponding types for all back ends can be safely casted to corresponding types for all back ends can be safely casted to
@ -939,6 +963,7 @@ trexio_open(const char* file_name, const char mode,
result->back_end = back_end_local; result->back_end = back_end_local;
result->mode = mode; result->mode = mode;
result->one_based = false; // Need to be flipped in Fortran interface result->one_based = false; // Need to be flipped in Fortran interface
result->state = 0; // By default the file corresponds to a ground state
int irc = pthread_mutex_init ( &(result->thread_lock), NULL); int irc = pthread_mutex_init ( &(result->thread_lock), NULL);
if (irc != 0) { if (irc != 0) {
if (rc_open != NULL) *rc_open = TREXIO_FAILURE; if (rc_open != NULL) *rc_open = TREXIO_FAILURE;
@ -1297,12 +1322,9 @@ def _close(trexio_file):
Parameter is a ~trexio_file~ object that has been created by a call to ~open~ function. Parameter is a ~trexio_file~ object that has been created by a call to ~open~ function.
""" """
try:
rc = pytr.trexio_close(trexio_file) rc = pytr.trexio_close(trexio_file)
if rc != TREXIO_SUCCESS: if rc != TREXIO_SUCCESS:
raise Error(rc) raise Error(rc)
except:
raise
#+end_src #+end_src
** File existence ** File existence
@ -1388,6 +1410,74 @@ def _inquire(file_name: str) -> bool:
raise Error(rc) raise Error(rc)
#+end_src #+end_src
** File state
~trexio_set_state~ set an existing ~trexio_t~ file handle to a given state.
~trexio_get_state~ returns current sate of the ~trexio_t~ file handle.
input parameters:
~file~ -- TREXIO file handle.
~state~ -- ~int32_t~ number of state.
output:
~trexio_exit_code~ exit code.
*** C
#+begin_src c :tangle prefix_front.h :exports none
trexio_exit_code trexio_set_state(trexio_t* file, const int32_t num);
trexio_exit_code trexio_get_state(trexio_t* file, int32_t* const num);
#+end_src
#+begin_src c :tangle prefix_front.c
trexio_exit_code
trexio_set_state (trexio_t* file, const int32_t num)
{
if (file == NULL) return TREXIO_INVALID_ARG_1;
file->state = num;
return TREXIO_SUCCESS;
}
trexio_exit_code
trexio_get_state (trexio_t* file, int32_t* const num)
{
if (file == NULL) return TREXIO_INVALID_ARG_1;
if (num == NULL) return TREXIO_INVALID_ARG_2;
*num = file->state;
return TREXIO_SUCCESS;
}
#+end_src
*** Fortran
#+begin_src f90 :tangle prefix_fortran.f90
interface
integer(trexio_exit_code) function trexio_set_state (trex_file, state) bind(C)
use, intrinsic :: iso_c_binding
import
integer(c_int64_t), intent(in), value :: trex_file
integer(c_int32_t), intent(in), value :: state
end function trexio_set_state
end interface
interface
integer(trexio_exit_code) function trexio_get_state (trex_file, state) bind(C)
use, intrinsic :: iso_c_binding
import
integer(c_int64_t), intent(in), value :: trex_file
integer(c_int32_t), intent(out) :: state
end function trexio_get_state
end interface
#+end_src
*** Python
See TREXIO File Python class.
* Templates for front end * Templates for front end
** Description ** Description
@ -1787,12 +1877,9 @@ def write_$group_num$(trexio_file, num_w: $group_num_py_dtype$) -> None:
- Exception from some other error (e.g. RuntimeError). - Exception from some other error (e.g. RuntimeError).
""" """
try:
rc = pytr.trexio_write_$group_num$(trexio_file.pytrexio_s, num_w) rc = pytr.trexio_write_$group_num$(trexio_file.pytrexio_s, num_w)
if rc != TREXIO_SUCCESS: if rc != TREXIO_SUCCESS:
raise Error(rc) raise Error(rc)
except:
raise
#+end_src #+end_src
#+begin_src python :tangle read_attr_num_front.py #+begin_src python :tangle read_attr_num_front.py
@ -1810,12 +1897,9 @@ def read_$group_num$(trexio_file) -> $group_num_py_dtype$:
- Exception from some other error (e.g. RuntimeError). - Exception from some other error (e.g. RuntimeError).
""" """
try:
rc, num_r = pytr.trexio_read_$group_num$(trexio_file.pytrexio_s) rc, num_r = pytr.trexio_read_$group_num$(trexio_file.pytrexio_s)
if rc != TREXIO_SUCCESS: if rc != TREXIO_SUCCESS:
raise Error(rc) raise Error(rc)
except:
raise
return num_r return num_r
#+end_src #+end_src
@ -1834,17 +1918,11 @@ def has_$group_num$(trexio_file) -> bool:
- Exception from some other error (e.g. RuntimeError). - Exception from some other error (e.g. RuntimeError).
""" """
try:
rc = pytr.trexio_has_$group_num$(trexio_file.pytrexio_s) rc = pytr.trexio_has_$group_num$(trexio_file.pytrexio_s)
if rc == TREXIO_FAILURE: if rc == TREXIO_FAILURE:
raise Error(rc) raise Error(rc)
except:
raise
if rc == TREXIO_SUCCESS: return rc == TREXIO_SUCCESS
return True
else:
return False
#+end_src #+end_src
** Templates for front end has/read/write a dataset of numerical data ** Templates for front end has/read/write a dataset of numerical data
@ -2553,44 +2631,32 @@ def read_$group_dset$(trexio_file, dim = None, doReshape = None, dtype = None):
if shape is None and doReshape: if shape is None and doReshape:
raise ValueError("Reshaping failure: shape is None.") raise ValueError("Reshaping failure: shape is None.")
try:
rc, dset_64 = pytr.trexio_read_safe_$group_dset$_64(trexio_file.pytrexio_s, dim)
rc, dset_64 = pytr.trexio_read_safe_$group_dset$_64(trexio_file.pytrexio_s, dim)
if rc != TREXIO_SUCCESS: if rc != TREXIO_SUCCESS:
raise Error(rc) raise Error(rc)
except:
raise
isConverted = False isConverted = False
dset_converted = None dset_converted = None
if dtype is not None: if dtype is not None:
try: try:
assert isinstance(dtype, type) assert isinstance(dtype, type)
except AssertionError: except AssertionError:
raise TypeError("dtype argument has to be an instance of the type class (e.g. np.float32).") raise TypeError("dtype argument has to be an instance of the type class (e.g. np.float32).")
if not dtype==np.int64 or not dtype==np.float64: if not dtype==np.int64 or not dtype==np.float64:
try:
dset_converted = np.array(dset_64, dtype=dtype) dset_converted = np.array(dset_64, dtype=dtype)
except:
raise
isConverted = True isConverted = True
# additional assert can be added here to check that read_safe functions returns numpy array of proper dimension # additional assert can be added here to check that read_safe functions returns numpy array of proper dimension
if doReshape: if doReshape:
try:
# in-place reshaping did not work so I have to make a copy # in-place reshaping did not work so I have to make a copy
if isConverted: if isConverted:
dset_reshaped = np.reshape(dset_converted, shape, order='C') dset_reshaped = np.reshape(dset_converted, shape, order='C')
else: else:
dset_reshaped = np.reshape(dset_64, shape, order='C') dset_reshaped = np.reshape(dset_64, shape, order='C')
except:
raise
if isConverted: if isConverted:
return dset_converted return dset_converted
@ -2614,17 +2680,11 @@ def has_$group_dset$(trexio_file) -> bool:
- Exception from some other error (e.g. RuntimeError). - Exception from some other error (e.g. RuntimeError).
""" """
try:
rc = pytr.trexio_has_$group_dset$(trexio_file.pytrexio_s) rc = pytr.trexio_has_$group_dset$(trexio_file.pytrexio_s)
if rc == TREXIO_FAILURE: if rc == TREXIO_FAILURE:
raise Error(rc) raise Error(rc)
except:
raise
if rc == TREXIO_SUCCESS: return rc == TREXIO_SUCCESS
return True
else:
return False
#+end_src #+end_src
** Templates for front end has/read/write a dataset of sparse data ** Templates for front end has/read/write a dataset of sparse data
@ -3245,12 +3305,9 @@ def read_$group_dset$_size(trexio_file) -> int:
- Exception from some other error (e.g. RuntimeError). - Exception from some other error (e.g. RuntimeError).
""" """
try:
rc, num_integral = pytr.trexio_read_$group_dset$_size(trexio_file.pytrexio_s) rc, num_integral = pytr.trexio_read_$group_dset$_size(trexio_file.pytrexio_s)
if rc != TREXIO_SUCCESS: if rc != TREXIO_SUCCESS:
raise Error(rc) raise Error(rc)
except:
raise
return num_integral return num_integral
#+end_src #+end_src
@ -3269,17 +3326,11 @@ def has_$group_dset$(trexio_file) -> bool:
- Exception from some other error (e.g. RuntimeError). - Exception from some other error (e.g. RuntimeError).
""" """
try:
rc = pytr.trexio_has_$group_dset$(trexio_file.pytrexio_s) rc = pytr.trexio_has_$group_dset$(trexio_file.pytrexio_s)
if rc == TREXIO_FAILURE: if rc == TREXIO_FAILURE:
raise Error(rc) raise Error(rc)
except:
raise
if rc == TREXIO_SUCCESS: return rc == TREXIO_SUCCESS
return True
else:
return False
#+end_src #+end_src
** Templates for front end has/read/write a dataset of strings ** Templates for front end has/read/write a dataset of strings
@ -3662,14 +3713,9 @@ def write_$group_dset$(trexio_file, dset_w: list) -> None:
max_str_length = len(max(dset_w, key=len)) + 1 max_str_length = len(max(dset_w, key=len)) + 1
try:
rc = pytr.trexio_write_$group_dset$(trexio_file.pytrexio_s, dset_w, max_str_length) rc = pytr.trexio_write_$group_dset$(trexio_file.pytrexio_s, dset_w, max_str_length)
if rc != TREXIO_SUCCESS: if rc != TREXIO_SUCCESS:
raise Error(rc) raise Error(rc)
except:
raise
#+end_src #+end_src
#+begin_src python :tangle read_dset_str_front.py #+begin_src python :tangle read_dset_str_front.py
@ -3704,22 +3750,15 @@ def read_$group_dset$(trexio_file, dim = None) -> list:
dim *= dims_list[i] dim *= dims_list[i]
try:
rc, dset_1d_r = pytr.trexio_read_$group_dset$_low(trexio_file.pytrexio_s, PYTREXIO_MAX_STR_LENGTH) rc, dset_1d_r = pytr.trexio_read_$group_dset$_low(trexio_file.pytrexio_s, PYTREXIO_MAX_STR_LENGTH)
if rc != TREXIO_SUCCESS: if rc != TREXIO_SUCCESS:
raise Error(rc) raise Error(rc)
except:
raise
try:
dset_full = dset_1d_r.split(pytr.TREXIO_DELIM) dset_full = dset_1d_r.split(pytr.TREXIO_DELIM)
dset_2d_r = [dset_full[i] for i in range(dim) if dset_full[i]] dset_2d_r = [dset_full[i] for i in range(dim) if dset_full[i]]
if not dset_2d_r: if not dset_2d_r:
raise ValueError(f"Output of {read_$group_dset$.__name__} function cannot be an empty list.") raise ValueError(f"Output of {read_$group_dset$.__name__} function cannot be an empty list.")
except:
raise
return dset_2d_r return dset_2d_r
#+end_src #+end_src
@ -3738,17 +3777,11 @@ def has_$group_dset$(trexio_file) -> bool:
- Exception from some other error (e.g. RuntimeError). - Exception from some other error (e.g. RuntimeError).
""" """
try:
rc = pytr.trexio_has_$group_dset$(trexio_file.pytrexio_s) rc = pytr.trexio_has_$group_dset$(trexio_file.pytrexio_s)
if rc == TREXIO_FAILURE: if rc == TREXIO_FAILURE:
raise Error(rc) raise Error(rc)
except:
raise
if rc == TREXIO_SUCCESS: return rc == TREXIO_SUCCESS
return True
else:
return False
#+end_src #+end_src
** Templates for front end has/read/write a single string attribute ** Templates for front end has/read/write a single string attribute
@ -3961,13 +3994,9 @@ def write_$group_str$(trexio_file, str_w: str) -> None:
max_str_length = len(str_w) + 1 max_str_length = len(str_w) + 1
try:
rc = pytr.trexio_write_$group_str$(trexio_file.pytrexio_s, str_w, max_str_length) rc = pytr.trexio_write_$group_str$(trexio_file.pytrexio_s, str_w, max_str_length)
if rc != TREXIO_SUCCESS: if rc != TREXIO_SUCCESS:
raise Error(rc) raise Error(rc)
except:
raise
#+end_src #+end_src
#+begin_src python :tangle read_attr_str_front.py #+begin_src python :tangle read_attr_str_front.py
@ -3985,13 +4014,9 @@ def read_$group_str$(trexio_file) -> str:
- Exception from some other error (e.g. RuntimeError). - Exception from some other error (e.g. RuntimeError).
""" """
try:
rc, str_r = pytr.trexio_read_$group_str$(trexio_file.pytrexio_s, PYTREXIO_MAX_STR_LENGTH) rc, str_r = pytr.trexio_read_$group_str$(trexio_file.pytrexio_s, PYTREXIO_MAX_STR_LENGTH)
if rc != TREXIO_SUCCESS: if rc != TREXIO_SUCCESS:
raise Error(rc) raise Error(rc)
except:
raise
return str_r return str_r
#+end_src #+end_src
@ -4010,17 +4035,11 @@ def has_$group_str$(trexio_file) -> bool:
- Exception from some other error (e.g. RuntimeError). - Exception from some other error (e.g. RuntimeError).
""" """
try:
rc = pytr.trexio_has_$group_str$(trexio_file.pytrexio_s) rc = pytr.trexio_has_$group_str$(trexio_file.pytrexio_s)
if rc == TREXIO_FAILURE: if rc == TREXIO_FAILURE:
raise Error(rc) raise Error(rc)
except:
raise
if rc == TREXIO_SUCCESS: return rc == TREXIO_SUCCESS
return True
else:
return False
#+end_src #+end_src
** Templates for front end delete an entire group (UNSAFE MODE) ** Templates for front end delete an entire group (UNSAFE MODE)