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
31 changes: 31 additions & 0 deletions doc/source/examples/ex_lsdyna_job.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
.. _example_lsdyna_job:

LS-DYNA Job Submission
======================

This example shows how to submit an LS-DYNA job to REP. Once submitted, minimal job information are serialized to a JSON file ``rep_job.json``.
This mimics what an application would need to store in order to subsequently monitor the job and download results.

The job consists of two tasks:

* The first task runs the actual LS-DYNA simulation
* The second task runs a little LS-PrePost script to post-process the results of the first task.

Usage:

.. code:: bash

python lsdyna_job.py submit
python lsdyna_job.py monitor
python lsdyna_job.py download

.. note::
The ``download`` action requires ``tqdm`` and ``humanize`` packages to show a progress bar during the result files download. You can install them with ``python -m pip install tqdm humanize``.

.. only:: builder_html

The project setup script as well as the data files can be downloaded here :download:`LS-DYNA Job Submission Example <../../../build/lsdyna_cylinder_plate.zip>`.

.. literalinclude:: ../../../examples/lsdyna_cylinder_plate/lsdyna_job.py
:language: python
:caption: lsdyna_job.py
30 changes: 30 additions & 0 deletions doc/source/examples/ex_mapdl_linked_analyses.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
.. _example_mapdl_linked_analyses:

MAPDL Linked Analyses Example
=========================================

This example shows how to submit an MAPDL linked analysis workflow (prestress-modal-harmonic)
as a multi-task job to REP. The script shows two possible ways to submit the individual tasks:

1. All-at-one: all 3 tasks are defined and included in the job definition before pushing it out to the server. When the job is created, it already has 3 tasks.

.. code:: bash

python project_setup.py

2. One-by-one: the first task is defined, pushed out to the server and then the job is created and submitted. Then, the second task is added to the job definition and the running job is synced to reflect the changes. The same for the third task.

.. code:: bash

python project_setup.py --incremental

In both cases, output files from upstream tasks are used as input of downstream ones.

.. only:: builder_html

The project setup script as well as the data files can be downloaded here :download:`MAPDL Linked Analyses Example <../../../build/mapdl_linked_analyses.zip>`.


.. literalinclude:: ../../../examples/mapdl_linked_analyses/project_setup.py
:language: python
:caption: project_setup.py
16 changes: 16 additions & 0 deletions doc/source/examples/ex_mapdl_tire_performance.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
.. _example_mapdl_tire_performance:

MAPDL Tire Performance
=======================

This example shows how to submit an MAPDL solver job to REP. The MAPDL model is the Tire-Performance Simulation example included
in the technology demonstration guide (td-57). Solution convergence (gst) and contact status (cnd) tracking files are periodically collected while the job is running.

.. only:: builder_html

The project setup script as well as the data files can be downloaded here :download:`MAPDL Tire Performance Example <../../../build/mapdl_tyre_performance.zip>`.


.. literalinclude:: ../../../examples/mapdl_tyre_performance/project_setup.py
:language: python
:caption: project_setup.py
177 changes: 7 additions & 170 deletions doc/source/examples/ex_motorbike_frame.rst
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
.. _example_mapdl_motorbike_frame:

Creating A Project
===============================
MAPDL Motorbike Frame - Project Creation
=========================================

This example shows how to create from scratch a DCS project consisting of an Ansys APDL beam model
This example shows how to create from scratch a REP project consisting of an Ansys APDL beam model
of a tubular steel trellis motorbike-frame.
After creating the project job_definition, 10 design points with randomly
chosen parameter values are created and set to pending.
Expand All @@ -26,171 +26,8 @@ by U. M. Fasel, O. Koenig, M. Wintermantel and P. Ermanni.

.. only:: builder_html

The project setup script as well as the data files can be downloaded here :download:`MAPDL Motorbike Frame Project <../../../mapdl_motorbike_frame.zip>`.
The project setup script as well as the data files can be downloaded here :download:`MAPDL Motorbike Frame Project <../../../build/mapdl_motorbike_frame.zip>`.

We shall now dissect the project setup script in detail.

Import modules and instantiate the DPS client
----------------------------------------------------

The script starts by importing some generic modules and some key ``ansys-dcs-client`` classes.
Next we connect to a DCS server running on the localhost with default username and password.

.. code-block:: python

import os
import random

from ansys.rep.client.jms import Client
from ansys.rep.client.jms.resource import (JobDefinition, Job, File,
FitnessDefinition, Project,
SuccessCriteria)

client = Client(rep_url="https://127.0.0.1:8443/rep", username="repadmin", password="repadmin")

Create an empty project and a job_definition
----------------------------------------------------

Once the client is available, we can define a new project and send it to the server.

.. code-block:: python

proj = Project(id="mapdl_motorbike_frame", display_name="MAPDL Motorbike Frame", priority=1, active=True)
proj = client.create_project(proj, replace=True)

Next, a job_definition object is created.

.. code-block:: python

job_def = JobDefinition(name="JobDefinition.1", active=True)

File resources
----------------------------------------------------

The first step to fill the project job_definition is to define the files resources. Besides the name and type,
for each file we need to specify the ``evaluation_path``, i.e. the relative path under which the file instance
for a design point evaluation will be stored. Moreover, if the file needs to be uploaded to the server, we also need to provide the path to the local file
as ``src`` argument.

.. code-block:: python

cwd = os.path.dirname(__file__)
files = []
# Input File
files.append (File( name="mac",evaluation_path="motorbike_frame.mac",
type="text/plain", src=os.path.join(cwd, "motorbike_frame.mac") ) )
# Output Files
files.append( File( name="results", evaluation_path="motorbike_frame_results.txt", type="text/plain" ) )
files.append( File( name="img", evaluation_path="file000.jpg", type="image/jpeg", collect=True) )
files.append( File( name="img2", evaluation_path="file001.jpg", type="image/jpeg", collect=True) )
files.append( File( name="out", evaluation_path="file.out", type="text/plain", collect=True) )

File resources are then created on the server.

.. code-block:: python

files = proj.create_files(files)

# For convenience, we keep a reference to the input and result files.
mac_file = files[0]
result_file = files[1]

Parameters definition
--------------------------------------

Creating a parameter requires to first provide a parameter definition and then specify a parameter location.

.. code-block:: python

# Input params: Dimensions of three custom tubes
float_input_params=[]
for i in range(1,4):
pd = job_def.add_float_parameter_definition(name='tube%i_radius' %i, lower_limit=4.0, upper_limit=20.0,default=12.0 )
job_def.add_parameter_mapping(key_string='radius(%i)' % i, tokenizer="=", parameter_definition_name=pd.name, file_id=mac_file.id)
float_input_params.append(pd)
pd = job_def.add_float_parameter_definition(name='tube%i_thickness' %i,lower_limit=0.5, upper_limit=2.5, default=1.0 )
job_def.add_parameter_mapping(key_string='thickness(%i)' % i, tokenizer="=", parameter_definition_name=pd.name, file_id=mac_file.id)
float_input_params.append(pd)

# Input params: Custom types used for all the different tubes of the frame
str_input_params=[]
for i in range(1,22):
pd = job_def.add_string_parameter_definition(name="tube%s" %i, default="1", value_list=["1","2","3"] )
job_def.add_parameter_mapping(key_string='tubes(%i)' % i, tokenizer="=", parameter_definition_name=pd.name, file_id=mac_file.id)
str_input_params.append(pd)

# Output Parames
for pname in ["weight", "torsion_stiffness", "max_stress"]:
pd = job_def.add_float_parameter_definition(name=pname)
job_def.add_parameter_mapping(key_string=pname, tokenizer="=", parameter_definition_name=pd.name, file_id=result_file.id)

Process Step
--------------------------------------

In a process step, we specify which application should be executed, its requirements, which input and output files are linked to it, and optionally also the criteria for determining whether the process step completes successfully.

.. code-block:: python

# Process step
job_def.add_task_definition( name="MAPDL_run",
application_name="ANSYS Mechanical APDL",
application_version="20.1",
execution_command="\ %\ executable\ %\ -b -i \ %\file:mac\ %\ -o file.out",
max_execution_time=20.0,
cpu_core_usage=1,
execution_level=0,
memory=250,
disk_space=5,
input_file_ids=[f.id for f in files[:1]],
output_file_ids=[f.id for f in files[1:]],
success_criteria= SuccessCriteria(
return_code=0,
expressions= ["values['tube1_radius']>=4.0", "values['tube1_thickness']>=0.5"],
required_output_file_ids=[ f.id for f in files[2:] ],
require_all_output_files=False,
required_output_parameter_names=["02qPAKWH62wIdNjaD7Uo0l", "02qPAKWHB1fOcSEc27qUg9", "02qPAKWHBpZZG1DdoMvjbG"],
require_all_output_parameters=False
) )

Note that multiple process steps can be defined.

Fitness definition
--------------------------------------

In an optimization context, different type of fitness terms can be combined into a fitness definition object.

.. code-block:: python

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="max_stress", type="limit_constraint", weighting_factor=1.0,
expression="map_limit_constraint( values['max_stress'], 451.0, 50.0 )")
job_def.fitness_definition =fd


Submit the job_definition
--------------------------------------

The next step is to send the job_definition to the server.

.. code-block:: python

job_def = proj.create_job_definitions([job_def])[0]

Design Points
--------------------------------------

Finally, 10 design points with randomly chosen parameter values are created and set to pending.

.. code-block:: python

dps = []
for i in range(10):
values = { p.name : p.lower_limit + random.random()*(p.upper_limit-p.lower_limit) for p in float_input_params }
values.update({ p.name: random.choice(p.value_list) for p in str_input_params})
dps.append( Job( name=f"Job.{i}", values=values, eval_status="pending") )

dps = job_def.create_jobs(dps)
.. literalinclude:: ../../../examples/mapdl_motorbike_frame/project_setup.py
:language: python
:caption: project_setup.py
15 changes: 15 additions & 0 deletions doc/source/examples/ex_motorbike_frame_query.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
.. _example_mapdl_motorbike_frame_query:

MAPDL Motorbike Frame - Project Query
=========================================

This example builds upon the example :ref:`example_mapdl_motorbike_frame`. It shows how to query resources of an existing project and how to download output files.

.. only:: builder_html

The project setup script as well as the data files can be downloaded here :download:`MAPDL Motorbike Frame Project <../../../build/mapdl_motorbike_frame.zip>`.


.. literalinclude:: ../../../examples/mapdl_motorbike_frame/project_query.py
:language: python
:caption: project_query.py
17 changes: 17 additions & 0 deletions doc/source/examples/ex_python_two_bar.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
.. _example_python_two_bar:

Python Two-Bar Truss Example
=========================================

This example shows how to create a REP project solving a Two-Bar Truss problem with Python.

For the original problem descriptions you can refer to R.L. Fox, *Optimization Methods in Engineering Design*, Addison Wesley, 1971.
See e.g. https://apmonitor.com/me575/uploads/Main/optimization_book.pdf

.. only:: builder_html

The project setup script as well as the data files can be downloaded here :download:`Python Two-Bar Truss Example <../../../build/python_two_bar_truss_problem.zip>`.

.. literalinclude:: ../../../examples/python_two_bar_truss_problem/project_setup.py
:language: python
:caption: project_setup.py
41 changes: 38 additions & 3 deletions doc/source/examples/index.rst
Original file line number Diff line number Diff line change
@@ -1,11 +1,46 @@
.. _examples:

Examples
===========================
========

Here you can find some examples showing how to interact with a REP server in Python using the ``ansys-rep-client``.
Examples consist of a Python script plus some data files (e.g. solver input files).
Many of the Python scripts can be executed with the following command line arguments:

* ``-n``, ``--name``: name of the REP project
* ``-U``, ``--url``: url or the REP server (default: https://localhost:8443/rep)
* ``-u``, ``--username``: REP username (default: repadmin)
* ``-p``, ``--password``: REP password (default: repadmin)

A link to download all the required resources is available at each example page.

You can also download the entire set of examples :download:`Download All Examples <../../../build/pyrep_examples.zip>`.

.. toctree::
:hidden:
:maxdepth: 3

ex_motorbike_frame
ex_download
ex_adding_file
ex_motorbike_frame_query
ex_mapdl_tire_performance
ex_mapdl_linked_analyses
ex_lsdyna_job
ex_python_two_bar

.. list-table::
:header-rows: 1

* - Name
- Description
* - :ref:`example_mapdl_motorbike_frame`
- Create from scratch a REP project consisting of an Ansys APDL beam model of a tubular steel trellis motorbike-frame. This example shows how to create a parameter study and submit design points.
* - :ref:`example_mapdl_motorbike_frame_query`
- Query an existing project and download output files.
* - :ref:`example_mapdl_tire_performance`
- Submit an MAPDL analysis as a single job. Solution convergence and contacts tracking files are periodically collected.
* - :ref:`example_mapdl_linked_analyses`
- Submit an MAPDL linked analysis workflow as a multi-task job to REP.
* - :ref:`example_lsdyna_job`
- Submit, monitor and download results of an LS-DYNA job.
* - :ref:`example_python_two_bar`
- Create a REP project solving a Two-Bar Truss problem with Python.
6 changes: 3 additions & 3 deletions doc/source/quickstart.rst
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ of a tubular steel trellis motorbike-frame.

.. only:: builder_html

The project setup script as well as the data files can be downloaded here :download:`MAPDL Motorbike Frame Project <../../mapdl_motorbike_frame.zip>`.
The project setup script as well as the data files can be downloaded here :download:`MAPDL Motorbike Frame Project <../../build/mapdl_motorbike_frame.zip>`.
To create the project you only need to run the `project_setup` script:

::
Expand Down Expand Up @@ -177,10 +177,10 @@ Query a specific project and set its failed design points (if any) to pending.
failed_jobs = project_api.update_jobs(failed_jobs)


Modify a project job_definition
Modify a job definition
-----------------------------------

Query an existing project job_definition, modify it and send it back to the server.
Query an existing job definition, modify it and send it back to the server.

.. code-block:: python

Expand Down
4 changes: 2 additions & 2 deletions examples/mapdl_motorbike_frame/project_query.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""
Example to query things from a project.
Example to query resources from a project.

- Query values from evaluated jobs,computing some simple statistics on parameter values.
- Query values from evaluated jobs, computing some simple statistics on parameter values.
- Download files from the project

"""
Expand Down
Loading