Skip to content
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
1 change: 1 addition & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ repos:
rev: v2.1.0
hooks:
- id: codespell
exclude: .mac

# For now we disable some of these checks, can be reenabled later
# - repo: https://github.com/pycqa/pydocstyle
Expand Down
13 changes: 9 additions & 4 deletions ansys/rep/client/auth/authenticate.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,8 @@ def get_oidc_response(

if r.status_code != 200:
raise RuntimeError(
f"Failed to retrieve access token for client {client_id} from {token_url} using {grant_type} grant, status code {r.status_code}: {r.content.decode()}"
f"""Failed to retrieve access token for client {client_id} from {token_url}
using {grant_type} grant, status code {r.status_code}: {r.content.decode()}"""
)

return r.json()
Expand Down Expand Up @@ -88,7 +89,8 @@ def authenticate(
password (str): Password
refresh_token (str, optional): Refresh token.
timeout (float, optional): Timeout in seconds. Defaults to 10.
scope (str, optional): String containing one or more requested scopes. Defaults to 'dps dpdb ansft monitor'.
scope (str, optional): String containing one or more requested scopes.
Defaults to 'dps dpdb ansft monitor'.
client_id (str, optional): The client type. Defaults to 'external'.

Returns:
Expand Down Expand Up @@ -129,7 +131,8 @@ def authenticate(

raise_for_status(r)
# if r.status_code != 200:
# # raise ClientError(f"Failed to retrieve access token for client {client_id} from {token_url} using {grant_type} grant, status code {r.status_code}: {r.content.decode()}", **d)
# raise ClientError(f"Failed to retrieve access token for client {client_id} from
# {token_url} using {grant_type} grant, status code {r.status_code}: {r.content.decode()}", **d)

return r.json()

Expand All @@ -151,7 +154,9 @@ def authenticate(
# with requests.Session() as session:
# # Disable SSL certificate verification and warnings about it
# session.verify = False
# requests.packages.urllib3.disable_warnings(requests.packages.urllib3.exceptions.InsecureRequestWarning)
# requests.packages.urllib3.disable_warnings(
# requests.packages.urllib3.exceptions.InsecureRequestWarning
# )

# # Set basic content type
# session.headers.update({'content-type': 'application/x-www-form-urlencoded'})
Expand Down
2 changes: 1 addition & 1 deletion ansys/rep/client/auth/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ class Client(object):

Users with admin rights (such as the default ``repadmin`` user) can create new
users as well as modify or delete existing ones. Non-admin users are only allowed
to query the list of exisiting users.
to query the list of existing users.

Args:
rep_url (str): The base path for the server to call, e.g. "https://127.0.0.1/dcs".
Expand Down
10 changes: 7 additions & 3 deletions ansys/rep/client/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,16 @@

class REPError(RequestException):
def __init__(self, *args, **kwargs):
"""Base class for all rep related errors. Derives from :class:`requests.exceptions.RequestException`.
"""Base class for all rep related errors.
Derives from :class:`requests.exceptions.RequestException`.

Example:
>>> from ansys.rep.client import REPError
>>> from ansys.rep.client.jms import Client
>>> try:
>>> client = Client(rep_url="https://127.0.0.1/dcs/", username="repadmin", password="wrong_psw")
>>> client = Client(rep_url="https://127.0.0.1/dcs/",
username="repadmin",
password="wrong_psw")
>>> except REPError as e:
>>> print(e)
400 Client Error: invalid_grant for: POST https://127.0.0.1/dcs/auth/api/oauth/token
Expand All @@ -41,7 +44,8 @@ def __init__(self, *args, **kwargs):


def raise_for_status(response, *args, **kwargs):
"""Hook function to automatically check HTTP errors. Mimics requests.Response.raise_for_status()"""
"""Hook function to automatically check HTTP errors.
Mimics requests.Response.raise_for_status()"""
if 400 <= response.status_code < 600:

r_content = {}
Expand Down
27 changes: 18 additions & 9 deletions ansys/rep/client/jms/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@
class Client(object):
"""A python interface to the Design Point Service API.

Uses the provided credentials to create and store an authorized :class:`requests.Session` object.
Uses the provided credentials to create and store
an authorized :class:`requests.Session` object.

The following authentication workflows are supported:

Expand All @@ -42,7 +43,8 @@ class Client(object):
- Access token: no authentication needed.

Args:
rep_url (str): The base path for the server to call, e.g. "https://127.0.0.1/dcs".
rep_url (str): The base path for the server to call,
e.g. "https://127.0.0.1/dcs".
username (str): Username (Optional)
password (str): Password (Optional)
refresh_token (str): Refresh Token (Optional)
Expand Down Expand Up @@ -105,7 +107,8 @@ def __init__(
self._unauthorized_max_retry = 1

def _auto_refresh_token(self, response, *args, **kwargs):
"""Hook function to automatically refresh the access token and re-send the request in case of unauthorized error"""
"""Hook function to automatically refresh the access token and
re-send the request in case of unauthorized error"""
if (
response.status_code == 401
and self.unauthorized_num_retry < self._unauthorized_max_retry
Expand Down Expand Up @@ -160,9 +163,11 @@ def archive_project(self, project, path, include_job_files=True):
"""Archive an existing project and save it to disk

Args:
project (:class:`ansys.rep.client.jms.Project`): A Project object (only the id field is needed).
project (:class:`ansys.rep.client.jms.Project`): A Project object
(only the id field is needed).
path (str): Where to save the archive locally.
include_job_files (bool, optional): Whether to include design point files in the archive. True by default.
include_job_files (bool, optional): Whether to include design point files in the
archive. True by default.

Returns:
str: The path to the archive.
Expand Down Expand Up @@ -190,29 +195,33 @@ def update_evaluators(self, evaluators, as_objects=True):
return update_evaluators(self, evaluators, as_objects=as_objects)

def get_task_definition_templates(self, as_objects=True, **query_params):
"""Return a list of task definition templates, optionally filtered by given query parameters"""
"""Return a list of task definition templates,
optionally filtered by given query parameters"""
return get_task_definition_templates(self, as_objects=as_objects, **query_params)

def create_task_definition_templates(self, templates):
"""Create new task definition templates

Args:
templates (list of :class:`ansys.rep.client.jms.TaskDefinitionTemplate`): A list of task definition templates
templates (list of :class:`ansys.rep.client.jms.TaskDefinitionTemplate`):
A list of task definition templates
"""
return create_task_definition_templates(self, templates)

def update_task_definition_templates(self, templates):
"""Update existing task definition templates

Args:
templates (list of :class:`ansys.rep.client.jms.TaskDefinitionTemplate`): A list of task definition templates
templates (list of :class:`ansys.rep.client.jms.TaskDefinitionTemplate`):
A list of task definition templates
"""
return update_task_definition_templates(self, templates)

def delete_task_definition_templates(self, templates):
"""Delete existing task definition templates

Args:
templates (list of :class:`ansys.rep.client.jms.TaskDefinitionTemplate`): A list of task definition templates
templates (list of :class:`ansys.rep.client.jms.TaskDefinitionTemplate`):
A list of task definition templates
"""
return delete_task_definition_templates(self, templates)
2 changes: 1 addition & 1 deletion ansys/rep/client/jms/resource/algorithm.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ class Algorithm(Object):
"""Algorithm resource.

Args:
project (:class:`ansys.rep.client.jms.Project`, optional): A Project object. Defaults to None.
project (:class:`ansys.rep.client.jms.Project`, optional): Project object. Defaults to None.
**kwargs: Arbitrary keyword arguments, see the Algorithm schema below.

Example:
Expand Down
6 changes: 4 additions & 2 deletions ansys/rep/client/jms/resource/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@ def __init__(self, **kwargs):
# If property k is provided as init parameter
if k in kwargs.keys():
setattr(self, k, kwargs[k])
# Else we set it this value as missing. That way marshmallow will ignore it on serialization
# Else we set it this value as missing.
# That way marshmallow will ignore it on serialization
elif not hasattr(self, k):
setattr(self, k, missing)

Expand All @@ -54,7 +55,8 @@ def __repr__(self):
self.__class__.__name__,
",".join(["%s=%r" % (k, getattr(self, k)) for k in self.declared_fields()]),
)
# return "%s(%s)" % (self.__class__.__name__, ",".join(["%s=%r" %(k,v) for k,v in self.__dict__.items()]) )
# return "%s(%s)" % (self.__class__.__name__,
# ",".join(["%s=%r" %(k,v) for k,v in self.__dict__.items()]) )

def __str__(self):
return "%s(\n%s\n)" % (
Expand Down
3 changes: 2 additions & 1 deletion ansys/rep/client/jms/resource/file.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ class File(Object):
"""File resource.

Args:
project (:class:`ansys.rep.client.jms.Project`, optional): A project resource. Defaults to None.
project (:class:`ansys.rep.client.jms.Project`, optional): Project resource.
Defaults to None.
src (str, optional): Path to the local file. Defaults to None.
**kwargs: Arbitrary keyword arguments, see the File schema below.

Expand Down
33 changes: 25 additions & 8 deletions ansys/rep/client/jms/resource/fitness_definition.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,25 @@ class FitnessTermDefinition(Object):
Example:

>>> # A fitness term of type objective
>>> ft1 = FitnessTermDefinition(name="weight", type="design_objective", weighting_factor=1.0,
expression="map_design_objective( values['weight'], 7.5, 5.5)")
>>> ft1 = FitnessTermDefinition(name="weight",
type="design_objective",
weighting_factor=1.0,
expression="map_design_objective(values['weight'],7.5,5.5)"
)
>>> # A fitness term of type target constraint
>>> ft2 = FitnessTermDefinition(name="torsional_stiffness", type="target_constraint", weighting_factor=0.8,
expression="map_target_constraint( values['torsion_stiffness'], 1313.0, 5.0, 30.0 )" )
>>> ft2 = FitnessTermDefinition(name="torsional_stiffness",
type="target_constraint",
weighting_factor=0.8,
expression="map_target_constraint(
values['torsion_stiffness'], 1313.0, 5.0, 30.0)"
)
>>> # A fitness term of type limit constraint
>>> ft3 = FitnessTermDefinition(name="max_stress", type="limit_constraint", weighting_factor=0.6,
expression="map_limit_constraint( values['max_stress'], 451.0, 50.0 )")
>>> ft3 = FitnessTermDefinition(name="max_stress",
type="limit_constraint",
weighting_factor=0.6,
expression="map_limit_constraint(
values['max_stress'], 451.0, 50.0 )"
)
"""

class Meta:
Expand All @@ -59,8 +70,14 @@ class FitnessDefinition(Object):
>>> fd = FitnessDefinition(error_fitness=10.0)
>>> fd.add_fitness_term(name="weight", type="design_objective", weighting_factor=1.0,
expression="map_design_objective( values['weight'], 7.5, 5.5)")
>>> fd.add_fitness_term(name="torsional_stiffness", type="target_constraint", weighting_factor=1.0,
expression="map_target_constraint( values['torsion_stiffness'], 1313.0, 5.0, 30.0 )" )
>>> fd.add_fitness_term(name="torsional_stiffness",
type="target_constraint",
weighting_factor=1.0,
expression="map_target_constraint(
values['torsion_stiffness'],
1313.0,
5.0,
30.0 )" )

The FitnessDefinition schema has the following fields:

Expand Down
2 changes: 1 addition & 1 deletion ansys/rep/client/jms/resource/job.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ class Job(Object):
"""Job resource.

Args:
project (:class:`ansys.rep.client.jms.Project`, optional): A Project object. Defaults to None.
project (:class:`ansys.rep.client.jms.Project`, optional): Project object. Defaults to None.
**kwargs: Arbitrary keyword arguments, see the Job schema below.

Example:
Expand Down
10 changes: 7 additions & 3 deletions ansys/rep/client/jms/resource/job_definition.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,17 @@ class JobDefinition(Object):
"""JobDefinition resource.

Args:
project (:class:`ansys.rep.client.jms.Project`, optional): A Project object. Defaults to None.
project (:class:`ansys.rep.client.jms.Project`, optional): A Project object.
Defaults to None.
**kwargs: Arbitrary keyword arguments, see the JobDefinition schema below.

Example:

>>> job_def = JobDefinition(name="JobDefinition.1", active=True)
>>> job_def.add_float_parameter_definition(name='tube_radius', lower_limit=4.0, upper_limit=20.0,default=12.0 )
>>> job_def.add_float_parameter_definition(name='tube_radius',
lower_limit=4.0,
upper_limit=20.0,
default=12.0 )

The JobDefinition schema has the following fields:

Expand All @@ -41,7 +45,7 @@ def __init__(self, project=None, **kwargs):
super(JobDefinition, self).__init__(**kwargs)

def get_jobs(self, **query_params):
"""Return a list of desing points, optionally filtered by given query parameters"""
"""Return a list of design points, optionally filtered by given query parameters"""
return get_objects(self.project, Job, job_definition=self, **query_params)

def create_jobs(self, jobs):
Expand Down
4 changes: 3 additions & 1 deletion ansys/rep/client/jms/resource/license_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@ class LicenseContext(Object):
Example:

>>> lc = LicenseContext(
environment={"ANSYS_HPC_PARAMETRIC_ID": "my_id", "ANSYS_HPC_PARAMETRIC_SERVER":"my_server" })
environment={"ANSYS_HPC_PARAMETRIC_ID": "my_id",
"ANSYS_HPC_PARAMETRIC_SERVER":"my_server" }
)
)

The LicenseContext schema has the following fields:
Expand Down
23 changes: 17 additions & 6 deletions ansys/rep/client/jms/resource/parameter_definition.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,13 @@ class FloatParameterDefinition(ParameterDefinition):

Example:

>>> # A continuos parameter
>>> pd1 = FloatParameterDefinition(name='param_1', lower_limit=4.0, upper_limit=20.0, default=12.0 )
>>> # A continuous parameter
>>> pd1 = FloatParameterDefinition(name='param_1', lower_limit=4.0,
upper_limit=20.0, default=12.0)
>>> # In case of e.g. a manifacturing variable which can only take some values
>>> pd2 = FloatParameterDefinition(name='param_2', value_list=[4.7, 12.0, 15.5, 20.0], default=12.0)
>>> pd2 = FloatParameterDefinition(name='param_2',
value_list=[4.7, 12.0, 15.5, 20.0],
default=12.0)

The FloatParameterDefinition schema has the following fields:

Expand All @@ -68,8 +71,14 @@ class IntParameterDefinition(ParameterDefinition):

Example:

>>> pd1 = IntParameterDefinition(name='ply_angle', value_list=[-60, -45, 0, 45, 60], default=0)
>>> pd2 = IntParameterDefinition(name='number_of_layers', lower_limit=1, upper_limit=5, default=2, step=1)
>>> pd1 = IntParameterDefinition(name='ply_angle',
value_list=[-60, -45, 0, 45, 60],
default=0)
>>> pd2 = IntParameterDefinition(name='number_of_layers',
lower_limit=1,
upper_limit=5,
default=2,
step=1)

The IntParameterDefinition schema has the following fields:

Expand Down Expand Up @@ -117,7 +126,9 @@ class StringParameterDefinition(ParameterDefinition):

Example:

>>> pd = StringParameterDefinition(name='DiameterDistribution', value_list=['Constant', 'Uniform', 'Log-Normal'], default='Constant')
>>> pd = StringParameterDefinition(name='DiameterDistribution',
value_list=['Constant', 'Uniform', 'Log-Normal'],
default='Constant')

The StringParameterDefinition schema has the following fields:

Expand Down
4 changes: 3 additions & 1 deletion ansys/rep/client/jms/resource/parameter_mapping.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@ class ParameterMapping(Object):

Example:

>>> pl = ParameterMapping(key_string='radius(0)', tokenizer="=", parameter_definition_name="tube_radius")
>>> pl = ParameterMapping(key_string='radius(0)',
tokenizer="=",
parameter_definition_name="tube_radius")

The ParameterMapping schema has the following fields:

Expand Down
3 changes: 2 additions & 1 deletion ansys/rep/client/jms/resource/project.py
Original file line number Diff line number Diff line change
Expand Up @@ -479,7 +479,8 @@ def _monitor_operation(client, location, interval=1.0):
op = r.json()["operations"][0]
done = op["finished"]
log.info(
f"Operation {op['name']} - progress={op['progress'] * 100.0}%, succeded={op['succeeded']}, finished={op['finished']}"
f"""Operation {op['name']} - progress={op['progress'] * 100.0}%,
succeeded={op['succeeded']}, finished={op['finished']}"""
)
time.sleep(interval)

Expand Down
2 changes: 1 addition & 1 deletion ansys/rep/client/jms/resource/selection.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ class Selection(Object):
"""Selection resource.

Args:
project (:class:`ansys.rep.client.jms.Project`, optional): A Project object. Defaults to None.
project (:class:`ansys.rep.client.jms.Project`, optional): Project object. Defaults to None.
**kwargs: Arbitrary keyword arguments, see the Selection schema below.

Example:
Expand Down
2 changes: 1 addition & 1 deletion ansys/rep/client/jms/resource/task.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ class Task(Object):
"""Task resource.

Args:
project (:class:`ansys.rep.client.jms.Project`, optional): A Project object. Defaults to None.
project (:class:`ansys.rep.client.jms.Project`, optional): Project object. Defaults to None.
**kwargs: Arbitrary keyword arguments, see the Task schema below.

The Task schema has the following fields:
Expand Down
3 changes: 2 additions & 1 deletion ansys/rep/client/jms/resource/task_definition.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,8 @@ class TaskDefinition(Object):
name="MAPDL_run",
application_name="ANSYS Mechanical APDL",
application_version="20.1",
execution_command="%executable% -b -i %file:mac% -o file.out -np %resource:num_cores%",
execution_command="%executable% -b -i %file:mac%
-o file.out -np %resource:num_cores%",
max_execution_time=20.0,
cpu_core_usage=1,
execution_level=0,
Expand Down
Loading