Skip to content

Commit

Permalink
add decorator in pyaedt_function_handler
Browse files Browse the repository at this point in the history
  • Loading branch information
gmalinve committed Mar 26, 2024
1 parent 58a5227 commit 9fd0110
Show file tree
Hide file tree
Showing 10 changed files with 40 additions and 99 deletions.
10 changes: 0 additions & 10 deletions _unittest/test_01_general_methods.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import pytest

from pyaedt.generic.DataHandlers import str_to_bool
from pyaedt.generic.general_methods import deprecated_alias
from pyaedt.generic.general_methods import number_aware_string_key


Expand All @@ -10,11 +9,6 @@ def desktop():
return


@deprecated_alias(t="n")
def operation(n, m):
return n + m


class TestClass(object):
def test_00_number_aware_string_key(self):
assert number_aware_string_key("C1") == ("C", 1)
Expand All @@ -36,7 +30,3 @@ def test_02_str_to_bool(self):
assert True in list(map(str_to_bool, test_list_1))
test_list_2 = ["Stop", "go", "run", "crawl", "False"]
assert False in list(map(str_to_bool, test_list_2))

def test_03_argument_decorator(self):
assert operation(n=2, m=3) == 5
assert operation(t=2, m=3) == 5
2 changes: 1 addition & 1 deletion examples/03-Maxwell/Maxwell2D_PMSynchronousMotor.py
Original file line number Diff line number Diff line change
Expand Up @@ -723,7 +723,7 @@ def create_cs_magnets(pm_id, cs_name, point_direction):
# formerly created when the section is applied.

faces_reg = mod2D.get_object_faces(object_list[1].name) # Region
plot1 = M2D.post.create_fieldplot_surface(objlist=faces_reg, quantityName='Flux_Lines', intrinsic_dict={
plot1 = M2D.post.create_fieldplot_surface(objlist=faces_reg, quantityName='Flux_Lines', intrinsics={
"Time": M2D.variable_manager.variables["StopTime"].evaluated_value}, plot_name="Flux_Lines")

##########################################################
Expand Down
6 changes: 3 additions & 3 deletions examples/03-Maxwell/Maxwell3DTeam7.py
Original file line number Diff line number Diff line change
Expand Up @@ -424,9 +424,9 @@

surf_list = m3d.modeler.get_object_faces("Plate")
intrinsic_dict = {"Freq": "200Hz", "Phase": "0deg"}
m3d.post.create_fieldplot_surface(surf_list, "Mag_J", intrinsic_dict=intrinsic_dict, plot_name="Mag_J")
m3d.post.create_fieldplot_surface(surf_list, "Mag_B", intrinsic_dict=intrinsic_dict, plot_name="Mag_B")
m3d.post.create_fieldplot_surface(surf_list, "Mesh", intrinsic_dict=intrinsic_dict, plot_name="Mesh")
m3d.post.create_fieldplot_surface(surf_list, "Mag_J", intrinsics=intrinsic_dict, plot_name="Mag_J")
m3d.post.create_fieldplot_surface(surf_list, "Mag_B", intrinsics=intrinsic_dict, plot_name="Mag_B")
m3d.post.create_fieldplot_surface(surf_list, "Mesh", intrinsics=intrinsic_dict, plot_name="Mesh")

####################################################################################################
# Release AEDT and clean up temporary directory
Expand Down
2 changes: 1 addition & 1 deletion examples/03-Maxwell/Maxwell3D_Team3_bath_plate.py
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,7 @@

ladder_plate = m3d.modeler.objects_by_name["LadderPlate"]
intrinsic_dict = {"Freq": "50Hz", "Phase": "0deg"}
m3d.post.create_fieldplot_surface(ladder_plate.faces, "Mag_J", intrinsic_dict=intrinsic_dict, plot_name="Mag_J")
m3d.post.create_fieldplot_surface(ladder_plate.faces, "Mag_J", intrinsics=intrinsic_dict, plot_name="Mag_J")

###############################################################################
# Release AEDT
Expand Down
65 changes: 19 additions & 46 deletions pyaedt/generic/general_methods.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
import datetime
import difflib
import fnmatch
import functools
from functools import update_wrapper
import inspect
import itertools
Expand All @@ -22,9 +21,6 @@
import tempfile
import time
import traceback
from typing import Callable
from typing import Dict
import warnings

from pyaedt.aedt_logger import pyaedt_logger
from pyaedt.generic.constants import CSS4_COLORS
Expand Down Expand Up @@ -202,8 +198,10 @@ def _check_types(arg):
return ""


def _function_handler_wrapper(user_function):
def _function_handler_wrapper(user_function, **deprecated_kwargs):
def wrapper(*args, **kwargs):
if deprecated_kwargs and kwargs:
rename_kwargs(user_function.__name__, kwargs, deprecated_kwargs)
if not settings.enable_error_handler:
result = user_function(*args, **kwargs)
return result
Expand Down Expand Up @@ -236,7 +234,20 @@ def wrapper(*args, **kwargs):
return wrapper


def pyaedt_function_handler(direct_func=None):
def rename_kwargs(func_name, kwargs, aliases):
"""Helper function for deprecating function arguments."""
for alias, new in aliases.items():
if alias in kwargs:
if new in kwargs:
raise TypeError(
f"{func_name} received both {alias} and {new} as arguments!"
f" {alias} is deprecated, use {new} instead."
)
pyaedt_logger.warning(f"`{alias}` is deprecated as an argument to `{func_name}`; use" f" `{new}` instead.")
kwargs[new] = kwargs.pop(alias)


def pyaedt_function_handler(direct_func=None, **deprecated_kwargs):
"""Provides an exception handler, logging mechanism, and argument converter for client-server
communications.
Expand All @@ -246,13 +257,13 @@ def pyaedt_function_handler(direct_func=None):
"""
if callable(direct_func):
user_function = direct_func
wrapper = _function_handler_wrapper(user_function)
wrapper = _function_handler_wrapper(user_function, **deprecated_kwargs)
return update_wrapper(wrapper, user_function)
elif direct_func is not None:
raise TypeError("Expected first argument to be a callable, or None")

def decorating_function(user_function):
wrapper = _function_handler_wrapper(user_function)
wrapper = _function_handler_wrapper(user_function, **deprecated_kwargs)
return update_wrapper(wrapper, user_function)

return decorating_function
Expand Down Expand Up @@ -2090,41 +2101,3 @@ def developer_forum(self):
# property = Property

online_help = Help()


def deprecated_alias(**aliases: str) -> Callable:
"""Decorator for deprecated function and method arguments.
Use as follows:
@deprecated_alias(old_arg='new_arg')
def myfunc(new_arg):
...
"""

def deco(f: Callable):
@functools.wraps(f)
def wrapper(*args, **kwargs):
rename_kwargs(f.__name__, kwargs, aliases)
return f(*args, **kwargs)

return wrapper

return deco


def rename_kwargs(func_name: str, kwargs: Dict[str, str], aliases: Dict[str, str]):
"""Helper function for deprecating function arguments."""
for alias, new in aliases.items():
if alias in kwargs:
if new in kwargs:
raise TypeError(
f"{func_name} received both {alias} and {new} as arguments!"
f" {alias} is deprecated, use {new} instead."
)
warnings.warn(
message=(f"`{alias}` is deprecated as an argument to `{func_name}`; use" f" `{new}` instead."),
category=DeprecationWarning,
)
kwargs[new] = kwargs.pop(alias)
8 changes: 2 additions & 6 deletions pyaedt/generic/pdf.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,14 +49,10 @@ class ReportSpec:


class AnsysReport(FPDF):
def __init__(
self, version="2023R2", design_name="design1", project_name="AnsysProject", template_json_file=None, **kwargs
):
def __init__(self, version="2023R2", design_name="design1", project_name="AnsysProject", tempplate_json_file=None):
super().__init__()
self.report_specs = ReportSpec()
if "tempplate_json_file" in kwargs.keys():
template_json_file = kwargs["tempplate_json_file"]
self.read_template(template_json_file)
self.read_template(tempplate_json_file)
self.report_specs.ansys_version = version
self.report_specs.design_name = design_name
self.report_specs.project_name = project_name
Expand Down
20 changes: 4 additions & 16 deletions pyaedt/icepak.py
Original file line number Diff line number Diff line change
Expand Up @@ -224,11 +224,10 @@ def assign_grille(
free_loss_coeff=True,
free_area_ratio=0.8,
external_temp="AmbientTemp",
external_pressure="AmbientPressure",
expternal_pressure="AmbientPressure",
x_curve=["0", "1", "2"],
y_curve=["0", "1", "2"],
boundary_name=None,
**kwargs,
):
"""Assign grille to a face or list of faces.
Expand All @@ -241,17 +240,9 @@ def assign_grille(
the free loss coefficient is not used.
free_area_ratio : float, str
Free loss coefficient value. The default is ``0.8``.
resistance_type : int, optional
Type of the resistance. Options are:
- ``0`` for ``"Perforated Thin Vent"``
- ``1`` for ``"Circular Metal Wire Screen"``
- ``2`` for ``"Two-Plane Screen Cyl. Bars"``
The default is ``0`` for ``"Perforated Thin Vent"``.
external_temp : str, optional
External temperature. The default is ``"AmbientTemp"``.
external_pressure : str, optional
expternal_pressure : str, optional
External pressure. The default is ``"AmbientPressure"``.
x_curve : list, optional
List of X curves in m_per_sec. The default is ``["0", "1", "2"]``.
Expand All @@ -271,9 +262,6 @@ def assign_grille(
>>> oModule.AssignGrilleBoundary
"""
if "expternal_pressure" in kwargs:
self.logger.warning("``expternal_pressure`` is deprecated, please use ``external_pressure`` instead.")
external_pressure = kwargs["expternal_pressure"]
if boundary_name is None:
boundary_name = generate_unique_name("Grille")

Expand All @@ -286,12 +274,12 @@ def assign_grille(
props["Pressure Loss Type"] = "Coeff"
props["Free Area Ratio"] = str(free_area_ratio)
props["External Rad. Temperature"] = external_temp
props["External Total Pressure"] = external_pressure
props["External Total Pressure"] = expternal_pressure

else:
props["Pressure Loss Type"] = "Curve"
props["External Rad. Temperature"] = external_temp
props["External Total Pressure"] = external_pressure
props["External Total Pressure"] = expternal_pressure

props["X"] = x_curve
props["Y"] = y_curve
Expand Down
10 changes: 3 additions & 7 deletions pyaedt/modeler/cad/Primitives.py
Original file line number Diff line number Diff line change
Expand Up @@ -4562,8 +4562,7 @@ def import_3d_cad(
create_group=True,
separate_disjoints_lumped_object=False,
import_free_surfaces=False,
point_coincidence_tolerance=1e-6,
**kwargs,
point_coicidence_tolerance=1e-6,
):
"""Import a CAD model.
Expand Down Expand Up @@ -4593,7 +4592,7 @@ def import_3d_cad(
Either to automatically separate disjoint parts. The default is ``False``.
import_free_surfaces : bool, optional
Either to import free surfaces parts. The default is ``False``.
point_coincidence_tolerance : float, optional
point_coicidence_tolerance : float, optional
Tolerance on point. Default is ``1e-6``.
Returns
Expand All @@ -4606,9 +4605,6 @@ def import_3d_cad(
>>> oEditor.Import
"""
if "point_coicidence_tolerance" in kwargs:
self.logger.warning("point_coicidence_tolerance is deprecated, please use instead.")
point_coincidence_tolerance = kwargs["point_coicidence_tolerance"]
if str(healing) in ["0", "1"]:
warnings.warn(
"Assigning `0` or `1` to `healing` option is deprecated. Assign `True` or `False` instead.",
Expand All @@ -4624,7 +4620,7 @@ def import_3d_cad(
vArg1.append("CreateGroup:="), vArg1.append(create_group)
vArg1.append("STLFileUnit:="), vArg1.append("Auto")
vArg1.append("MergeFacesAngle:="), vArg1.append(-1)
vArg1.append("PointCoincidenceTol:="), vArg1.append(point_coincidence_tolerance)
vArg1.append("PointCoincidenceTol:="), vArg1.append(point_coicidence_tolerance)
vArg1.append("CreateLightweightPart:="), vArg1.append(create_lightweigth_part)
vArg1.append("ImportMaterialNames:="), vArg1.append(import_materials)
vArg1.append("SeparateDisjointLumps:="), vArg1.append(separate_disjoints_lumped_object)
Expand Down
14 changes: 6 additions & 8 deletions pyaedt/modules/PostProcessor.py
Original file line number Diff line number Diff line change
Expand Up @@ -3076,18 +3076,17 @@ def _create_fieldplot_line_traces(
else:
return False

@pyaedt_function_handler()
@deprecated_alias(IntrinsincDict="intrinsics")
@pyaedt_function_handler(objlist="objects", quantityName="quantity")
def create_fieldplot_line(
self, objlist, quantityName, setup_name=None, intrinsics=None, plot_name=None, field_type="DC R/L Fields"
self, objects, quantity, setup_name=None, intrinsics=None, plot_name=None, field_type="DC R/L Fields"
):
"""Create a field plot of the line.
Parameters
----------
objlist : list
objects : list
List of polyline to plot.
quantityName : str
quantity : str
Name of the quantity to plot.
setup_name : str, optional
Name of the setup. The default is ``None`` which automatically take ``nominal_adaptive`` setup.
Expand Down Expand Up @@ -3117,7 +3116,7 @@ def create_fieldplot_line(
self.logger.info("Plot {} exists. returning the object.".format(plot_name))
return self.field_plots[plot_name]
return self._create_fieldplot(
objlist, quantityName, setup_name, intrinsics, "Line", plot_name, field_type=field_type
objects, quantity, setup_name, intrinsics, "Line", plot_name, field_type=field_type
)

@pyaedt_function_handler()
Expand Down Expand Up @@ -3346,8 +3345,7 @@ def create_fieldplot_surface(
new_obj_list, quantityName, setup_name, intrinsics, "FacesList", plot_name, field_type=field_type
)

@pyaedt_function_handler()
@deprecated_alias(IntrinsincDict="intrinsics")
@pyaedt_function_handler(IntrinsincDict="intrinsics")
def create_fieldplot_cutplane(
self,
objlist,
Expand Down
2 changes: 1 addition & 1 deletion pyaedt/modules/solutions.py
Original file line number Diff line number Diff line change
Expand Up @@ -2632,7 +2632,7 @@ class FieldPlot:
"""

@deprecated_alias(IntrinsincList="intrinsics")
@pyaedt_function_handler(IntrinsincList="intrinsics")
def __init__(
self,
postprocessor,
Expand Down

0 comments on commit 9fd0110

Please sign in to comment.