You are on page 1of 6

PyMAPDL Cheat sheet

version:0.65.0 (stable)

Launching PyMAPDL Converting an existing APDL script to PyMAPDL format. Post-Processing Class
To launch PyMAPDL instance locally and exit it. This class is used for plotting and saving results to NumPy
inputfile='ansys_inputfile.inp'
arrays.
# To launch an instance pyscript='pyscript.py'
from ansys.mapdl.core import launch_mapdl mapdl.convert_script(inputfile, pyscript) mapdl.post1()
mapdl=launch_mapdl() mapdl.set(1, 2)
# To exit the instance # Plot the nodal equivalent stress
mapdl.exit()
MAPDL Class mapdl.post_processing.plot_nodal_eqv_stress()
Load a table from Python to MAPDL # Save nodal eqv. stresses to a Python array
To specify a jobname, number of processors, and working nod_eqv_stress=
directory. mapdl.load_table(name,array,var1='', var2='',
var3='', csysid='') mapdl.post_processing.nodal_eqv_stress()
# Plot contour legend using dictionary
jname='user_jobname'
To access from or write parameters to MAPDL database. mapdl.allsel()
path='<path of directory>'
sbar_kwargs={"color": "black",
mapdl=launch_mapdl(nproc=2, run_location=path,
# Save a parameter to a NumPy array nparray "title": "Equivalent Stress (psi)",
jobname=jname)
nparray=mapdl.parameters['displ_load'] "vertical": False,"n_labels": 6}
To connect to an existing instance of MAPDL at IP # Create a parameter from a NumPy array nparray mapdl.post_processing.plot_nodal_eqv_stress(
192.168.1.30 and port 50001. mapdl.parameters['exp_disp']=nparray cpos='xy', background='white',
edge_color='black', show_edges=True,
mapdl=launch_mapdl To access information using *GET and *VGET directly to scalar bar_args=sbar_kwargs, n_colors=9)
(start_instance=False, NumPy arrays.
ip='192.168.1.30', port=50001)
# Runs *GET command and returns a Python value
mapdl.get_value(entity='', entnum='', Plotting Class
To create and exit a pool of instances.
item1='', it1num='', Plotting is interpolated with PyVista by saving the resulting
# To create a pool of 10 instances item2='', it2num='', **kwargs) stress and storing wtihin the underlying UnstructuredGrid.
from ansys.mapdl.core import LocalMapdlPool
# Runs *VGET command and returns a Python array pl=pyvista.Plotter()
pool=mapdl.LocalMapdlPool(10)
mapdl.get_array(entity='', entnum='', pl0=mapdl.post_processing.plot_nodal_stress(
# To exit the pool
item1='', it1num='', item2='', return_plotter=True)
pool.exit()
it2num='', kloop='', **kwargs) pl.add(pl0.mesh)
pl.show()
PyMAPDL Language
PyMAPDL commands are Python statements that act as a Mesh Class
# Plot the currently selected elements
wrapper for APDL commands. For instance, ESEL, s, type, 1 is Store the finite element mesh as a VTK UnstructuredGrid
mapdl.eplot(show_node_numbering, vtk)
translated as data object.
# Plot the selected volumes
mapdl.esel('s', 'type', vmin=1) grid=mapdl.mesh.grid mapdl.vplot(nv1, nv2, ninc, degen, scale, ...)
# Display the selected areas
Commands that start with * or / have those characters Save element & node numbers to Python arrays. mapdl.aplot(na1, na2, ninc, degen, scale, ...)
removed. # Display the selected lines without
# Array of nodal coordinates # MAPDL plot symbols
mapdl.prep7() # /PREP7 nodes=mapdl.mesh.nodes mapdl.lplot(vtk=True, cpos='xy', line_width=10)
mapdl.get() # *GET # Save png file of line plot with MAPDL
# Save node numbers of selected nodes to array # coordinate symbol
In cases where removing * or / will cause conflict with other node_num=mapdl.mesh.nnum mapdl.psymb('CS', 1)
commands, a prefix "slash" or "star" is added. # Save node numbers of all nodes to array mapdl.lplot(vtk=False)
node_num_all=mapdl.mesh.nnum_all
mapdl.solu() # SOLU
mapdl.slashsolu() # /SOLU # Element numbs. of currently selected elements References from PyMAPDL Documentation
elem_num=mapdl.mesh.enum • Getting Started
mapdl.vget() # VGET # All element numbers incl. those not selected
mapdl.starvget() # *VGET elem_num_all=mapdl.mesh.enum_all • MAPDL Commands
• API Reference

Getting Started with PyMAPDL PyMAPDL on GitHub Visit mapdl.docs.pyansys.com


PyAEDT-API Cheat sheet
version:0.6.78 (stable)

Launching PyAEDT Creating boundaries Mesh Class


To launch HFSS instance locally and exit it In AEDT, open region is created as Mesh module manages the mesh functions in PyAEDT
# To launch an instance hfss.mesh.assign_initial_mesh_from_slider(level=6) #
import pyaedt hfss.create_open_region(Frequency="1GHz")
setting the slider level to 6
hfss = pyaedt.Hfss(specified_version="2023.1", # assign model resolutions
non_graphical=False, Assigning the radiation boundary to a box is as follows hfss.mesh.assign_model_resolution(names=[object1.name,
new_desktop_session=True, object2.name], defeature_length=None)
projectname="Project_name", hfss.assign_radiation_boundary_to_objects("airbox") # assigning the mesh length to the object1 faces
designname="Design_name") hfss.mesh.assign_length_mesh(names=object1.faces,
# To exit the instance isinside=False, maxlength=1, maxel=2000)
hfss.release_desktop()
Port definitions
Variable Class Common port types in HFSS are Lumped-port and Wave Analysis Class
guide-port. Pythonic way of defining the lumped-port is The solution setup (mysetup) in HFSS design is analyzed by call-
Creating a local and global variable in HFSS
ing the following Python command
hfss["dim"] = "1mm" # design variable box1 = hfss.modeler.create_box([0,0,50], [10,10,5], "
Box1","copper") hfss.analyze_setup("mysetup")
hfss["$dim"] = "1mm" # project variable
box2 = hfss.modeler.create_box([0,0,60], [10,10,5], "
hfss.variable_manager is the class handles all the variables. Box2","copper")
It contains a lot of properties and methods useful for variable port_L = hfss.lumped_port(signal="Box1", reference=" Post-processing Class
handling. Box2", integration_line=hfss.AxisDir.XNeg, Post-processing class has modules for creating and editing
impedance=50, name="LumpedPort", renormalize=True plots in AEDT. They are accessible through the post library
Material Class , deembed=False)
hfss.materials class is used to access the material library. A plotf = hfss.post.create_fieldplot_volume(object_list,
new material is added in HFSS as quantityname, setup_name, intrinsic_dict) # This
Pythonic way of defining Wave guide-port is call returns a FieldPlot object
my_mat = hfss.materials.add_material("myMat") my_data = hfss.post.get_solution_data(expression=
my_mat.permittivity = 3.5 port_W = hfss.wave_port("Box1","Box2",name="WavePort", trace_names) # This call returns a SolutionData
my_mat.conductivity = 450000 integration_line=1) object
my_mat.permeability = 1.5 standard_report = hfss.post.report_by_category.
standard("db(S(1,1))") # This call returns a new
Geometry Creation Setup Class standard report object
standard_report.create() # This call reate a report
hfss.modeler contains all properties and methods needed to Setup class is used to define the solution setup in the PyAEDT solution_data = standard_report.get_solution_data()
edit a modeler, including primitives methods and properties.
setup = hfss.create_setup("MySetup")
A box is drawn at (x_pos, y_pos, z_pos) position with (x_dim, setup.props["Frequency"] = "50MHz" Calling AEDT-API with PyAEDT
y_dim, z_dim) dimensions as setup["MaximumPasses"] = 10 Most of the critical functionalities are captured in PyAEDT.
hfss.create_linear_count_sweep(setupname="any",unit=" However, the missing features from AEDT-API method can be
box = hfss.modeler.create_box([x_pos,y_pos,z_pos], [ MHz",freqstart=0.1,freqstop=100,
x_dim,y_dim,z_dim],name="airbox", matname="air") converted to PyAEDT method.
num_of_freq_points=100, sweepname="sweep1",
sweep_type="Interpolating", save_fields=False) Example: AEDT-API module (Optimetrics), is accessible in
A spiral geometry made of "copper" is created as follows
PyAEDT as
ind = hfss.modeler.create_spiral( Parametric sweep and optimizations are accessed using fol-
internal_radius=rin, width=width, lowing classes omodule = hfss.odesign.GetModule("Optimetrics")
spacing=spacing, turns=Nr,
faces=Np, thickness=thickness, # returns the ParametericsSetups Class
material="copper",name="Inductor1") References from PyAEDT Documentation
hfss.parametrics
# returns the OptimizationSetups Class • Getting Started
box, ind are the Object3d objects, containing a lot of proper-
hfss.optimizations • User Guide
ties and methods related to that object including faces, ver-
tices, colors, and materials. • API Reference

Getting Started With AEDT Ansys Innovation Courses


PyAEDT EDB-API Cheat sheet
version:0.6.78 (stable)

Launching EDB-API using PyAEDT Simulation Configuration


# List of all nets in available in AEDB file
EDB manager manages the AEDB Database. An AEDB edb.nets.netlist These classes are the containers of simulation configuration
database is a folder that contains the database representing # To delete a net constructors for the EDB.
any part of a PCB. It can be opened and edited using the Edb edb.nets["net_name"].delete()
class.
# AC settings
# To launch an instance Vias and padstacks Sim_setup.ac_settings.start_freq = "100Hz"
import pyaedt sim_setup.ac_settings.stop_freq = "6GHz"
These containers contains the API references for padstack
edb = pyaedt.Edb(edbversion="2023.1", edbpath= sim_setup.ac_settings.step_freq = "10MHz"
management. The main padstack object is called directly from
aedb_path) main application using the property padstacks.
edb.save_edb() # Save the edb file # Batch solve
edb.close_edb() # exits the edb file # Creating a via sim_setup=edbapp.new_simulation_configuration()
edb.padstacks.place(position = [5e-3, 5e-3], "MyVia") sim_setup.solver_type sim_setup.SOLVER_TYPE.SiwaveSYZ
# To get the pad parameters sim_setup.batch_solve_settings.
Stackup and Layers edb.padstacks.get_pad_parameters() cutout_subdesign_expansion = 0.01
sim_setup.batch_solve_settings.do_cutout_subdesign =
These classes are the containers of the layer and stackup man- True
ager of the EDB API. Sources and Excitation sim_setup.use_default_cutout = False
These classes are the containers of sources methods of the sim_setup.batch_solve_settings.signal_nets =
# Adding a stackup layer
EDB for both HFSS and Siwave singl_net_list
edb.stakup.add_layer("Name")
sim_setup.batch_solve_settings.components =
# To get the names of the all layers # To get the Dictionary of EDB excitations component_list
edb.stackup.stackup_layers.keys() edb.excitations sim_setup.batch_solve_settings.power_nets =
# To create differential port power_nets_list
edb.hfss.create_differential_wave_port(
Modeler and primitives positive_primitive_id = trace_p[0].id, # Saving config file
These classes are the containers of primitives and all relative positive_points_on_edge = p1_points, sim_setup.export_json(os.path.join(project_path, "
methods. Primitives are planes, lines, rectangles, and circles. negative_primitive_id = trace_n[0].id, configuration.json"))
negative_points_on_edge = n1_points, name = " edbapp.build_simulation_project(sim_setup)
# Creating a polygon by defining points wave_port_1")
points = [[0.0, 1e-3], [0.0, 10e-3], [100e-3, 10e-3],
[100e-3, 1e-3], [0.0, 1e-3]] Simulation Setup
edb.modeler.create_polygon_from_points(points,
These classes are the containers of setup classes in EDB for
SiWave Manger
layer_name = "Name")
both HFSS and Siwave. Siwave is a specialized tool for power integrity, signal integrity,
# HFSS simulation setup and EMI analysis of IC packages and PCB. This tool solves
Components setup = edb.create_hfss_setup(name = "my_setup") power delivery systems and high-speed channels in electronic
devices. It can be accessed from PyAEDT in Windows only. All
Component class contains API references for net manage- setup.set_solution_single_frequency()
setups can be implemented through EDB API.
ment. The main component object is called directly from main setup.hfss_solver_settings.enhanced_low_freq_accuracy
application using the property components. = True
setup.hfss_solver_settings.order_basis = "first" from pyaedt.siwave import Siwave
# To get the list of components setup.adaptive_settings.add_adaptive_frequency_data("5 # this call returns the Edb class initialized on 2023
edb.components.components.keys() GHz",8,"0.01") R1
# To get the net information of a component siwave = Siwave(specified_version="2023.1")
edb.components.get_component_net_connection_info("Q13N siwave.open_project("pyproject.siw")
# SiWave Simulation setup
") siwave.export_element_data("mydata.txt")
setup = edb.siwave.add_siwave_dc_analysis(name = "
siwave.close_project()
myDCIR_4")
setup.use_dc_custom_settings = True
Nets setup.dc_slider_position = 0
The Net class contains API references for net management. setup.add_source_terminal_to_ground("V1", 1) References from PyAEDT Documentation
The main net object is called directly from main application solve_edb = edb.solve_siwave()
using the property nets. • EDB API

Getting Started With AEDT Ansys Innovation Courses


PyFluent Cheat sheet
Solver Settings Object Interface
version:0.13 (stable)

Launch Fluent locally Define materials Apply solution settings


The following method is used to start Fluent from Python in This example shows how you use Solver settings objects to PyFluent allows you to use Solver settings objects to apply
gRPC mode. define materials. solution settings, initialize, and solve.
This code starts Fluent in the background so that commands
can be sent to Fluent from the Python interpreter. solver.setup.materials.copy_database_material_by_name( solver.solution.initialization.hybrid_initialize()
type="fluid", name="water-liquid") solver.solution.run_calculation.iterate(
import ansys.fluent.core as pyfluent solver.setup.cell_zone_conditions.fluid["elbow-fluid" number_of_iterations=150)
solver = pyfluent.launch_fluent(mode = "solver", ].material = "water-liquid"
show_gui = True)

The solver object contains attributes such as file, setup, Define boundary conditions Post-Processing
solution, and results, which are also instances of settings The examples in this section show how you use Solver PyFluent allows you to post-process data with results object.
objects. settings objects to define boundary conditions. The following example shows you how to create and display
contours on a plane.
Import mesh in launched session solver.setup.boundary_conditions.velocity_inlet["cold-
The following examples show how to read the available mesh inlet"].vmag = { solver.results.graphics.contour["contour"] = {}
file in Fluent Session. "option": "constant or expression", solver.results.graphics.contour["contour"].
"constant": 0.4, print_state()
import_filename = 'example_file.msh.h5'
} solver.results.graphics.contour["contour"].field = "
solver.file.read(file_type="case", file_name=
solver.setup.boundary_conditions.velocity_inlet[ temperature"
import_filename)
"cold-inlet" solver.results.graphics.contour["contour"].
There are other specific APIs available for reading case files ].ke_spec = "Intensity and Hydraulic Diameter" surfaces_list = [
and reading case-data files. solver.setup.boundary_conditions.velocity_inlet["cold- "symmetry-xyplane",
inlet"].turb_intensity = 5 ]
# e.g., read_case(), read_case_data() solver.setup.boundary_conditions.velocity_inlet[
"cold-inlet"
import_filename = 'example_file.cas.h5' ].turb_hydraulic_diam = "4 [in]"
solver.file.read_case(file_type="case", file_name= solver.setup.boundary_conditions.velocity_inlet["cold-
Temperature Contour
import_filename) inlet"].t = {
"option": "constant or expression",
"constant": 293.15,
Enable heat transfer physics }
The following examples show how to enable heat transfer by
activating the energy equation.
Modify cell zone conditions
solver.setup.models.energy.enabled = True
The examples in this section show how you use Solver
Accessing the object state with using pprint settings objects to modify cell zone conditions.

>>> from pprint import pprint # Enabling Laminar Zone


>>> pprint(solver.setup.models.energy())
{'enabled': True, solver.setup.cell_zone_conditions.fluid["elbow-fluid"] References from PyAnsys Documentation
'inlet_diffusion': True, = {"laminar": True} • Getting Started
'kinetic_energy': False,
'pressure_work': False, • PyFluent Solver Settings Objects
'viscous_dissipation': False} • PyFluent Examples

Getting Started with PyFluent PyFluent on GitHub Visit


fluent.docs.pyansys.com
PyPrimeMesh Cheat sheet
version:0.3.0 (stable)

Launch PyPrimeMesh Client


# Create Curvature Size Control diag = prime.SurfaceSearch(model)
To launch and exit PyPrimeMesh server from Python in gRPC curvature_control = model.control_data. diag_params = prime.SurfaceDiagnosticSummaryParams(
mode. create_size_control(prime.SizingType.CURVATURE) model, scope=surface_scope,
control_name = "Curvature_Size_Control" compute_free_edges=True,
# Launch PyPrimeMesh Server,
curvature_control.set_suggested_name(control_name) )
from ansys.meshing import prime
# Define Scope diag_res = diag.get_surface_diagnostic_summary(
with prime.launch_prime(timeout = 20) as prime_client:
scope= prime.ScopeDefinition(model, evaluation_type= diag_params)
# The Client class gets the model parameter
prime.ScopeEvaluationType.LABELS, print("Number of free faces : ", diag_res.n_free_faces
model = prime_client.model
label_expression="*") )
#Define Script Here
curvature_control.set_scope(scope)
# Disconnect from server
prime_client.exit()
# Define Curvature Control parameter Surface Mesh Quality Metrics.
curvature_control.set_curvature_sizing_params(prime.
CurvatureSizingParams(model, normal_angle=18)) face_quality_measures = prime.FaceQualityMeasure.
To launch an instance of PyPrimeMesh at IP 127.0.0.1 and SKEWNESS
port 50055 with number of processes 4. quality = prime.SurfaceSearch(model)
quality_params = prime.SurfaceQualitySummaryParams(
with prime.launch_prime(ip = "127.0.0.1", port = Generate Wrapper Surface Mesh model=model,
50055, n_procs = 4) as prime_client: Generate Wrapper Surface Mesh. scope=surface_scope,
model = prime_client.model
face_quality_measures=[face_quality_measures],
mesher.wrap( quality_limit=[0.9],
min_size=0.2, max_size=1.0, )
Read and Write files input_parts="flange,pipe", print("Maximum surface skewness : ", qual_summary_res.
Read or Write files of different formats based on file use_existing_features=True, quality_results[0].max_quality)
extension. An example for the same can be seen below. recompute_remesh_sizes=True,
remesh_size_controls=[curvature_control],
# Import lucid class ) Generate Volume Mesh
from ansys.meshing.prime import lucid
Generate Volume Mesh.
# Define mesher object
mesher = lucid.Mesh(model) Generate Surface Mesh vol_scope = prime.ScopeDefinition(model,
# Read Mesh (*.msh) file part_expression="*")
mesh_file_name = r"sample1_mesh.msh" Generate Surface Mesh based on min, max size.
mesher.volume_mesh(volume_fill_type=prime.
mesher.read(mesh_file_name, append=False) VolumeFillType.HEXCOREPOLY,
surface_scope = prime.ScopeDefinition(model,
# Import CAD (*.step) file scope = vol_scope)
part_expression="*")
cad_file_name = r"sample2_CAD.stp"
mesher.surface_mesh(min_size=0.5, max_size=16,
mesher.read(cad_file_name, append=False)
generate_quads= True,
# Write Mesh (*.cdb) file
scope = surface_scope) Part Summary
cdb_file_name = r"sample3_case.cdb"
mesher.write(cdb_file_name)
Query for Part Summary.
Generate Surface Mesh based on size controls.
part = model.get_part_by_name("sample_part")
control_name = "Curvature_Size_Control" summary = part.get_summary(prime.PartSummaryParams(
Defining Size controls mesher.surface_mesh_with_size_controls( model))
Sets the global sizing parameters , control_name, print("Total number of cells: ",summary.n_cells)
surface_scope
# Define Global Size Controls
)
model.set_global_sizing_params(prime. References from PyAnsys Documentation
GlobalSizingParams(min = 0.5, max = 16.0, • PyPrimeMesh - Getting Started
growth_rate= 1.2))
Surface Mesh Analysis • PyPrimeMesh - User guide
Curvature size control definition. Surface Mesh Diagnostics. • PyPrimeMesh - Examples

Getting Started with PyPrimeMesh PyAnsys on GitHub Visit


prime.docs.pyansys.com
PyDPF-Core Cheat sheet
based on version:0.8.1 (stable) - API may be subjected to change

Importing a Model Read the Mesh Plot Contour Results


The DPF Model gives an overview of the result files content. Get mesh information, get the list of node IDs, get the list of Plot a Field on its mesh, show the minimum and maximum.
element IDs.
from ansys.dpf import core as dpf field_norm_disp.plot(show_max=True, show_min=True,
model = dpf.Model(r"D:\Path\to\my\file.rst") mesh = metadata.meshed_region
print(mesh) title='Field', text='Field plot')
print(model)
node_IDs = mesh.nodes.scoping.ids
element_IDs = mesh.elements.scoping.ids Take a screenshot from a specific camera position.
Fetching Metadata Get node and element using their IDs.
cpos = [(0.123, 0.095, 1.069), (-0.121, -0.149, 0.825)
Fetch all the results available in the results file. , (0.0, 0.0, 1.0)]
# Node ID 1
node = mesh.nodes.node_by_id(1) field.plot(off_screen=True, notebook=False, screenshot
metadata = model.metadata
# Element ID 1 ='field_plot.png', cpos=cpos)
print(metadata.result_info)
element = mesh.elements.element_by_id(1)
Print the time or frequency of the results.
Scope Results over Time/Space Workflows
print(metadata.time_freq_support)
Domains Combine operators to create Workflows.
Print available named selections. Scoping results over particular time IDs make data fetching
faster. disp_op = dpf.operators.result.displacement()
print(metadata.available_named_selections) max_fc_op = dpf.operators.min_max.min_max_fc(disp_op)
time_sets = [1, 3, 10] # Data for time IDs workflow = dpf.Workflow()
disp_op = model.results.displacement() workflow.add_operators([disp_op,max_fc_op])
disp_op.inputs.time_scoping(time_sets) workflow.set_input_name("data_sources", disp_op.inputs
Managing Data Sources .data_sources)
Manage result files by creating a DPF DataSources object Scoping over particular elements. workflow.set_output_name("min", max_fc_op.outputs.
from scratch or from a model. field_min)
eids = range(262, 272) # Element scoping
element_scoping = dpf.Scoping(ids=eids) workflow.set_output_name("max", max_fc_op.outputs.
from ansys.dpf import core as dpf field_max)
element_scoping.location = dpf.locations.elemental
data_src = dpf.DataSources(r"D:\Path\to\my\file.rst")
# or
s_y = dpf.operators.result.stress_Y() Use the workflow.
data_src = model.metadata.data_sources
s_y.inputs.mesh_scoping.connect(element_scoping)
data_src = dpf.data_sources.DataSources(r"D:\Path\to\
Retrieve a mesh from a scoping.
Read Results my\file.rst")
mesh_from_scoping_op = dpf.operators.mesh.from_scoping workflow.connect("data_sources", data_src)
Read displacement results by instantiating a displacement min = workflow.get_output("min", dpf.types.field)
(mesh, element_scoping)
operator and print the fields container. max = workflow.get_output("max", dpf.types.field)
cropped_mesh = mesh_from_scoping_op.outputs.mesh()
disp_op = model.results.displacement()
disp = disp_op.outputs.fields_container() Get a data Field
print(disp) References from PyDPF-Core Documentation
Apply operators and extract the resulting data Field.
• Getting Started
Get field by Time ID = 1. norm_op2 = dpf.operators.math.norm_fc()
disp = model.results.displacement() • Examples
disp_1 = disp.get_field_by_time_id(1).data norm_op2.inputs.connect(disp.outputs)
print(disp_1) field_norm_disp = norm_op2.outputs.fields_container() • API Reference
[0] • Operators Reference

Getting Started with PyDPF-Core PyDPF-Core on GitHub Visit


dpf.docs.pyansys.com

You might also like