Skip to content

Commit

Permalink
update handling of "drfunc" checks during cla.DR_Def.add and improve …
Browse files Browse the repository at this point in the history
…error messages
  • Loading branch information
twmacro committed Jul 4, 2022
1 parent dffb657 commit bba2554
Show file tree
Hide file tree
Showing 3 changed files with 72 additions and 30 deletions.
19 changes: 12 additions & 7 deletions pyyeti/cla/_utilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

__all__ = [
"_is_valid_identifier",
"_compile_strfunc",
"get_drfunc",
"_merge_uf_reds",
"_get_rpt_headers",
Expand Down Expand Up @@ -43,6 +44,16 @@ def _is_valid_identifier(name):
return name.isidentifier() and not iskeyword(name)


def _compile_strfunc(s, get_psd):
# build function and return it:
strfunc = "def _func(sol, nas, Vars, se):\n return " + s.strip()
g = globals()
exec(strfunc, g)
if get_psd:
return g["_func"], None
return g["_func"]


def get_drfunc(filename, funcname, get_psd=False):
"""
Get data recovery function(s)
Expand Down Expand Up @@ -78,13 +89,7 @@ def get_drfunc(filename, funcname, get_psd=False):
return func, psdfunc
return func

# build function and return it:
strfunc = "def _func(sol, nas, Vars, se):\n return " + funcname.strip()
g = globals()
exec(strfunc, g)
if get_psd:
return g["_func"], None
return g["_func"]
return _compile_strfunc(funcname, get_psd)


def _merge_uf_reds(old, new, method="replace"):
Expand Down
54 changes: 37 additions & 17 deletions pyyeti/cla/dr_def.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,12 @@
from types import SimpleNamespace
import warnings
import copyreg
import re
import numpy as np
import pandas as pd
import xlsxwriter
from pyyeti.nastran import n2p
from ._utilities import _merge_uf_reds, _is_valid_identifier, get_drfunc
from ._utilities import _merge_uf_reds, _is_valid_identifier, _compile_strfunc


# FIXME: We need the str/repr formatting used in Numpy < 1.14.
Expand Down Expand Up @@ -214,28 +215,46 @@ def _add_drms(d1, d2):
curdrms[se] = {}
_add_drms(curdrms[se], newdrms)

def _check_for_drfunc(self, filename, funcname):
def _check_for_drfunc(self, name, filename, funcname):
def _get_msg():
s0 = f'When checking for the data recovery function "{funcname}",'
s0 = f'When checking `drfunc` for category "{name}",'
s1 = (
"This can be safely ignored if you plan to "
"implement the data recovery functions later."
)
return s0, s1

try:
get_drfunc(filename, funcname)
except (FileNotFoundError, ImportError, SyntaxError) as e:
s0, s1 = _get_msg()
msg = (
f'{s0} import of "{filename}" failed. {s1}\nThe exception was: '
f"{type(e).__name__}: {e!s}"
)
warnings.warn(msg, RuntimeWarning)
except AttributeError:
s0, s1 = _get_msg()
msg = f'{s0} "{funcname}" not found in: {filename}. {s1}'
warnings.warn(msg, RuntimeWarning)
if _is_valid_identifier(funcname):
try:
# search for "def funcname("
with open(filename, "r") as fin:
for line in fin:
if re.match(rf" *def +{funcname} *\(", line):
break
else:
s0, s1 = _get_msg()
msg = (
f'{s0} function "{funcname}" not found in: '
f"{filename}. {s1}"
)
warnings.warn(msg, RuntimeWarning)
except FileNotFoundError as e:
s0, s1 = _get_msg()
msg = (
f'{s0} could not open "{filename}". {s1}\nThe exception was: '
f"{type(e).__name__}: {e!s}"
)
warnings.warn(msg, RuntimeWarning)
else:
try:
_compile_strfunc(funcname, False)
except SyntaxError as e:
s0, s1 = _get_msg()
msg = (
f'{s0} failed to compile string: "{funcname}".\n'
f"The exception was: {type(e).__name__}: {e!s}"
)
warnings.warn(msg, RuntimeWarning)

@staticmethod
def _get_pv(pv, name, length):
Expand Down Expand Up @@ -327,7 +346,8 @@ def _handle_defaults(self, name):
callerdir = os.path.dirname(calling_file)
ns.drfile = os.path.join(callerdir, drfile)
self._drfilemap[drfile] = ns.drfile
self._check_for_drfunc(ns.drfile, ns.drfunc)

self._check_for_drfunc(name, ns.drfile, ns.drfunc)

# ensure uf_reds has no None values:
ns.uf_reds = _merge_uf_reds((1, 1, 1, 1), ns.uf_reds)
Expand Down
29 changes: 23 additions & 6 deletions tests/test_cla.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ def _():
desc = "S/C Internal Accelerations"
units = "m/sec^2, rad/sec^2"
labels = _get_labels(rows, name)
drfunc = "no func"
drfunc = "no-func"
drdefs.add(**locals())

@cla.DR_Def.addcat
Expand All @@ -202,7 +202,7 @@ def _():
desc = "S/C Internal Loads"
units = "N, N-m"
labels = _get_labels(rows, name)
drfunc = "no func"
drfunc = "no-func"
drdefs.add(**locals())

# for checking, make a pandas DataFrame to summarize data
Expand Down Expand Up @@ -1400,7 +1400,8 @@ def _():
with assert_warns(RuntimeWarning) as cm:
cla.DR_Def.addcat(_)
the_warning = str(cm.warning)
for s in ("ATM45", "import of", "failed."):
# for s in ("ATM45", "import of", "failed."):
for s in ("ATM45", "could not open "):
assert s in the_warning

def _():
Expand Down Expand Up @@ -1617,6 +1618,22 @@ def _():
}
assert drdefs["ATM"].srsconv == 2.0

def _():
name = "ATM2"
desc = "First set of accelerations"
labels = 4
drfunc = "blah *"
drdefs.add(**locals())

with assert_warns(RuntimeWarning) as cm:
cla.DR_Def.addcat(_)
the_warning = str(cm.warning)
for s in ("ATM2", "failed to compile string"):
assert s in the_warning
from pyyeti.pp import PP

assert drdefs["ATM2"].srsQs is None


def test_event_add():
# ext_name = 'FLAC'
Expand Down Expand Up @@ -3208,11 +3225,11 @@ def _():
def test_set_dr_order():
drdefs0 = cla.DR_Def()
for name, nrows in (("atm0", 12), ("ltm0", 30), ("dtm0", 9)):
drdefs0.add(name=name, labels=nrows, drfunc="no func")
drdefs0.add(name=name, labels=nrows, drfunc="no-func")

drdefs1 = cla.DR_Def()
for name, nrows in (("atm1", 12), ("ltm1", 30), ("dtm1", 9)):
drdefs1.add(name=name, labels=nrows, drfunc="no func")
drdefs1.add(name=name, labels=nrows, drfunc="no-func")

DR = cla.DR_Event()
DR.add(None, drdefs0)
Expand Down Expand Up @@ -3768,7 +3785,7 @@ def _():
desc = "S/C Internal Accelerations"
units = "m/sec^2, rad/sec^2"
labels = [f"{name} Row {i+1:6d}" for i in range(nrows)]
drfunc = "no func"
drfunc = "no-func"
drdefs.add(**locals())

# prepare results data structure:
Expand Down

0 comments on commit bba2554

Please sign in to comment.