.. DO NOT EDIT.
.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY.
.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE:
.. "examples\06-Multiphysics\Hfss_Icepak_Coupling.py"
.. LINE NUMBERS ARE GIVEN BELOW.

.. only:: html

    .. note::
        :class: sphx-glr-download-link-note

        :ref:`Go to the end <sphx_glr_download_examples_06-Multiphysics_Hfss_Icepak_Coupling.py>`
        to download the full example code.

.. rst-class:: sphx-glr-example-title

.. _sphx_glr_examples_06-Multiphysics_Hfss_Icepak_Coupling.py:


Multiphysics: HFSS-Icepak multiphysics analysis
------------------------------------------------
This example shows how you can create a project from scratch in HFSS and Icepak (linked to HFSS).
This includes creating a setup, solving it, and creating postprocessing outputs.

To provide the advanced postprocessing features needed for this example, the ``numpy``,
``matplotlib``, and ``pyvista`` packages must be installed on the machine.

This examples runs only on Windows using CPython.

.. GENERATED FROM PYTHON SOURCE LINES 13-16

Perform required imports
~~~~~~~~~~~~~~~~~~~~~~~~
Perform required imports.

.. GENERATED FROM PYTHON SOURCE LINES 16-21

.. code-block:: Python


    import os
    import pyaedt
    from pyaedt.generic.pdf import AnsysReport








.. GENERATED FROM PYTHON SOURCE LINES 22-25

Set AEDT version
~~~~~~~~~~~~~~~~
Set AEDT version.

.. GENERATED FROM PYTHON SOURCE LINES 25-28

.. code-block:: Python


    aedt_version = "2024.1"








.. GENERATED FROM PYTHON SOURCE LINES 29-33

Set non-graphical mode
~~~~~~~~~~~~~~~~~~~~~~
Set non-graphical mode. 
You can set ``non_graphical`` either to ``True`` or ``False``.

.. GENERATED FROM PYTHON SOURCE LINES 33-36

.. code-block:: Python


    non_graphical = False








.. GENERATED FROM PYTHON SOURCE LINES 37-40

Open project
~~~~~~~~~~~~
Open the project.

.. GENERATED FROM PYTHON SOURCE LINES 40-45

.. code-block:: Python


    NewThread = True

    project_file = pyaedt.generate_unique_project_name()








.. GENERATED FROM PYTHON SOURCE LINES 46-50

Launch AEDT and initialize HFSS
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Launch AEDT and initialize HFSS. If there is an active HFSS design, the ``aedtapp``
object is linked to it. Otherwise, a new design is created.

.. GENERATED FROM PYTHON SOURCE LINES 50-57

.. code-block:: Python


    aedtapp = pyaedt.Hfss(projectname=project_file,
                          specified_version=aedt_version,
                          non_graphical=non_graphical,
                          new_desktop_session=NewThread
                          )





.. rst-class:: sphx-glr-script-out

 .. code-block:: none

    C:\actions-runner\_work\_tool\Python\3.10.9\x64\lib\subprocess.py:1072: ResourceWarning: subprocess 1156 is still running
      _warn("subprocess %s is still running" % self.pid,
    C:\actions-runner\_work\pyaedt\pyaedt\.venv\lib\site-packages\pyaedt\generic\settings.py:383: ResourceWarning: unclosed file <_io.TextIOWrapper name='D:\\Temp\\pyaedt_ansys.log' mode='a' encoding='cp1252'>
      self._logger = val




.. GENERATED FROM PYTHON SOURCE LINES 58-63

Initialize variable settings
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Initialize variable settings. You can initialize a variable simply by creating
it as a list object. If you enter the prefix ``$``, the variable is created for
the project. Otherwise, the variable is created for the design.

.. GENERATED FROM PYTHON SOURCE LINES 63-68

.. code-block:: Python


    aedtapp["$coax_dimension"] = "100mm"
    udp = aedtapp.modeler.Position(0, 0, 0)
    aedtapp["inner"] = "3mm"








.. GENERATED FROM PYTHON SOURCE LINES 69-75

Create coaxial and cylinders
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Create a coaxial and three cylinders. You can apply parameters
directly using the :func:`pyaedt.modeler.Primitives3D.Primitives3D.create_cylinder`
method. You can assign a material directly to the object creation action.
Optionally, you can assign a material using the :func:`assign_material` method.

.. GENERATED FROM PYTHON SOURCE LINES 75-84

.. code-block:: Python


    # TODO: How does this work when two truesurfaces are defined?
    o1 = aedtapp.modeler.create_cylinder(orientation=aedtapp.PLANE.ZX, origin=udp, radius="inner", height="$coax_dimension",
                                         num_sides=0, name="inner")
    o2 = aedtapp.modeler.create_cylinder(orientation=aedtapp.PLANE.ZX, origin=udp, radius=8, height="$coax_dimension",
                                         num_sides=0, material="teflon_based")
    o3 = aedtapp.modeler.create_cylinder(orientation=aedtapp.PLANE.ZX, origin=udp, radius=10, height="$coax_dimension",
                                         num_sides=0, name="outer")








.. GENERATED FROM PYTHON SOURCE LINES 85-88

Assign colors
~~~~~~~~~~~~~
Assign colors to each primitive.

.. GENERATED FROM PYTHON SOURCE LINES 88-95

.. code-block:: Python


    o1.color = (255, 0, 0)
    o2.color = (0, 255, 0)
    o3.color = (255, 0, 0)
    o3.transparency = 0.8
    aedtapp.modeler.fit_all()








.. GENERATED FROM PYTHON SOURCE LINES 96-100

Assign materials
~~~~~~~~~~~~~~~~
Assign materials. You can assign materials either directly when creating the primitive,
which was done for ``id2``, or after the object is created.

.. GENERATED FROM PYTHON SOURCE LINES 100-104

.. code-block:: Python


    o1.material_name = "Copper"
    o3.material_name = "Copper"








.. GENERATED FROM PYTHON SOURCE LINES 105-109

Perform modeler operations
~~~~~~~~~~~~~~~~~~~~~~~~~~
Perform modeler operations. You can subtract, add, and perform other operations
using either the object ID or object name.

.. GENERATED FROM PYTHON SOURCE LINES 109-113

.. code-block:: Python


    aedtapp.modeler.subtract(o3, o2, True)
    aedtapp.modeler.subtract(o2, o1, True)





.. rst-class:: sphx-glr-script-out

 .. code-block:: none


    True



.. GENERATED FROM PYTHON SOURCE LINES 114-119

Perform mesh operations
~~~~~~~~~~~~~~~~~~~~~~~
Perform mesh operations. Most mesh operations are available.
After a mesh is created, you can access a mesh operation to
edit or review parameter values.

.. GENERATED FROM PYTHON SOURCE LINES 119-124

.. code-block:: Python


    aedtapp.mesh.assign_initial_mesh_from_slider(level=6)
    aedtapp.mesh.assign_model_resolution(assignment=[o1.name, o3.name], defeature_length=None)
    aedtapp.mesh.assign_length_mesh(assignment=o2.faces, inside_selection=False, maximum_length=1, maximum_elements=2000)





.. rst-class:: sphx-glr-script-out

 .. code-block:: none


    <pyaedt.modules.Mesh.MeshOperation object at 0x00000226687A6230>



.. GENERATED FROM PYTHON SOURCE LINES 125-131

Create excitations
~~~~~~~~~~~~~~~~~~
Create excitations. The ``create_wave_port_between_objects`` method automatically
identifies the closest faces on a predefined direction and creates a sheet to cover
the faces. It also assigns a port to this face. If ``add_pec_cap=True``, the method
creates a PEC cap.

.. GENERATED FROM PYTHON SOURCE LINES 131-140

.. code-block:: Python


    aedtapp.wave_port(assignment="inner", reference="outer", create_port_sheet=True, create_pec_cap=True,
                      integration_line=1, name="P1")
    aedtapp.wave_port(assignment="inner", reference="outer", create_port_sheet=True, create_pec_cap=True,
                      integration_line=4, name="P2")

    port_names = aedtapp.get_all_sources()
    aedtapp.modeler.fit_all()








.. GENERATED FROM PYTHON SOURCE LINES 141-146

Create setup
~~~~~~~~~~~~
Create a setup. A setup is created with default values. After its creation,
you can change values and update the setup. The ``update`` method returns a Boolean
value.

.. GENERATED FROM PYTHON SOURCE LINES 146-153

.. code-block:: Python


    aedtapp.set_active_design(aedtapp.design_name)
    setup = aedtapp.create_setup("MySetup")
    setup.props["Frequency"] = "1GHz"
    setup.props["BasisOrder"] = 2
    setup.props["MaximumPasses"] = 1








.. GENERATED FROM PYTHON SOURCE LINES 154-157

Create sweep
~~~~~~~~~~~~
Create a sweep. A sweep is created with default values.

.. GENERATED FROM PYTHON SOURCE LINES 157-161

.. code-block:: Python


    sweepname = aedtapp.create_linear_count_sweep(setup="MySetup", units="GHz", start_frequency=0.8, stop_frequency=1.2,
                                                  num_of_freq_points=401, sweep_type="Interpolating")








.. GENERATED FROM PYTHON SOURCE LINES 162-167

Create Icepak model
~~~~~~~~~~~~~~~~~~~
Create an Icepak model. After an HFSS setup is ready, link this model to an Icepak
project and run a coupled physics analysis. The :func:`FieldAnalysis3D.copy_solid_bodies_from`
method imports a model from HFSS with all material settings.

.. GENERATED FROM PYTHON SOURCE LINES 167-171

.. code-block:: Python


    ipkapp = pyaedt.Icepak()
    ipkapp.copy_solid_bodies_from(aedtapp)





.. rst-class:: sphx-glr-script-out

 .. code-block:: none


    True



.. GENERATED FROM PYTHON SOURCE LINES 172-175

Link sources to EM losses
~~~~~~~~~~~~~~~~~~~~~~~~~
Link sources to the EM losses.

.. GENERATED FROM PYTHON SOURCE LINES 175-180

.. code-block:: Python


    surfaceobj = ["inner", "outer"]
    ipkapp.assign_em_losses(design=aedtapp.design_name, setup="MySetup", sweep="LastAdaptive", map_frequency="1GHz",
                            surface_objects=surfaceobj, parameters=["$coax_dimension", "inner"])





.. rst-class:: sphx-glr-script-out

 .. code-block:: none


    <pyaedt.modules.Boundary.BoundaryObject object at 0x00000226687715D0>



.. GENERATED FROM PYTHON SOURCE LINES 181-184

Edit gravity setting
~~~~~~~~~~~~~~~~~~~~
Edit the gravity setting if necessary because it is important for a fluid analysis.

.. GENERATED FROM PYTHON SOURCE LINES 184-187

.. code-block:: Python


    ipkapp.edit_design_settings(aedtapp.GRAVITY.ZNeg)





.. rst-class:: sphx-glr-script-out

 .. code-block:: none


    True



.. GENERATED FROM PYTHON SOURCE LINES 188-195

Set up Icepak project
~~~~~~~~~~~~~~~~~~~~~
Set up the Icepak project. When you create a setup, default settings are applied.
When you need to change a property of the setup, you can use the ``props``
command to pass the correct value to the property. The ``update`` function
applies the settings to the setup. The setup creation process is identical
for all tools.

.. GENERATED FROM PYTHON SOURCE LINES 195-199

.. code-block:: Python


    setup_ipk = ipkapp.create_setup("SetupIPK")
    setup_ipk.props["Convergence Criteria - Max Iterations"] = 3








.. GENERATED FROM PYTHON SOURCE LINES 200-204

Edit or review mesh parameters
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Edit or review the mesh parameters. After a mesh is created, you can access
a mesh operation to edit or review parameter values.

.. GENERATED FROM PYTHON SOURCE LINES 204-210

.. code-block:: Python


    airbox = ipkapp.modeler.get_obj_id("Region")
    ipkapp.modeler[airbox].display_wireframe = True
    airfaces = ipkapp.modeler.get_object_faces(airbox)
    ipkapp.assign_openings(airfaces)





.. rst-class:: sphx-glr-script-out

 .. code-block:: none


    <pyaedt.modules.Boundary.BoundaryObject object at 0x00000226687702B0>



.. GENERATED FROM PYTHON SOURCE LINES 211-216

Close and open projects
~~~~~~~~~~~~~~~~~~~~~~~
Close and open the projects to ensure that the HFSS - Icepak coupling works
correctly in AEDT versions 2019 R3 through 2021 R1. Closing and opening projects
can be helpful when performing operations on multiple projects.

.. GENERATED FROM PYTHON SOURCE LINES 216-224

.. code-block:: Python


    aedtapp.save_project()
    aedtapp.close_project(aedtapp.project_name)
    aedtapp = pyaedt.Hfss(project_file)
    ipkapp = pyaedt.Icepak()
    ipkapp.solution_type = ipkapp.SOLUTIONS.Icepak.SteadyTemperatureAndFlow
    ipkapp.modeler.fit_all()








.. GENERATED FROM PYTHON SOURCE LINES 225-228

Solve Icepak project
~~~~~~~~~~~~~~~~~~~~
Solve the Icepak project and the HFSS sweep.

.. GENERATED FROM PYTHON SOURCE LINES 228-234

.. code-block:: Python


    setup1 = ipkapp.analyze_setup("SetupIPK")
    aedtapp.save_project()
    aedtapp.modeler.fit_all()
    aedtapp.analyze_setup("MySetup")





.. rst-class:: sphx-glr-script-out

 .. code-block:: none


    True



.. GENERATED FROM PYTHON SOURCE LINES 235-238

Generate field plots and export
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Generate field plots on the HFSS project and export them as images.

.. GENERATED FROM PYTHON SOURCE LINES 238-255

.. code-block:: Python


    cutlist = [pyaedt.constants.GLOBALCS.XY, pyaedt.constants.GLOBALCS.ZX, pyaedt.constants.GLOBALCS.YZ]
    vollist = [o2.name]
    setup_name = "MySetup : LastAdaptive"
    quantity_name = "ComplexMag_E"
    quantity_name2 = "ComplexMag_H"
    intrinsic = {"Freq": "1GHz", "Phase": "0deg"}
    surflist = aedtapp.modeler.get_object_faces("outer")
    plot1 = aedtapp.post.create_fieldplot_surface(surflist, quantity_name2, setup_name, intrinsic)

    results_folder = os.path.join(aedtapp.working_directory, "Coaxial_Results_NG")
    if not os.path.exists(results_folder):
        os.mkdir(results_folder)

    aedtapp.post.plot_field_from_fieldplot(plot1.name, project_path=results_folder, mesh_plot=False, image_format="jpg",
                                           view="isometric", show=False, plot_cad_objs=False, log_scale=False)




.. image-sg:: /examples/06-Multiphysics/images/sphx_glr_Hfss_Icepak_Coupling_001.png
   :alt: Hfss Icepak Coupling
   :srcset: /examples/06-Multiphysics/images/sphx_glr_Hfss_Icepak_Coupling_001.png
   :class: sphx-glr-single-img


.. rst-class:: sphx-glr-script-out

 .. code-block:: none


    <pyaedt.generic.plot.ModelPlotter object at 0x0000022668780AF0>



.. GENERATED FROM PYTHON SOURCE LINES 256-259

Generate animation from field plots
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Generate an animation from field plots using PyVista.

.. GENERATED FROM PYTHON SOURCE LINES 259-281

.. code-block:: Python


    import time

    start = time.time()
    cutlist = ["Global:XY"]
    phases = [str(i * 5) + "deg" for i in range(18)]

    animated = aedtapp.post.plot_animated_field(quantity="Mag_E", assignment=cutlist, plot_type="CutPlane",
                                                setup=aedtapp.nominal_adaptive,
                                                intrinsics={"Freq": "1GHz", "Phase": "0deg"}, variation_variable="Phase",
                                                variations=phases, show=False, log_scale=True, export_gif=False,
                                                export_path=results_folder)
    animated.gif_file = os.path.join(aedtapp.working_directory, "animate.gif")
    # animated.camera_position = [0, 0, 300]
    # animated.focal_point = [0, 0, 0]
    # Set off_screen to False to visualize the animation.
    # animated.off_screen = False
    animated.animate()

    endtime = time.time() - start
    print("Total Time", endtime)




.. image-sg:: /examples/06-Multiphysics/images/sphx_glr_Hfss_Icepak_Coupling_002.gif
   :alt: Hfss Icepak Coupling
   :srcset: /examples/06-Multiphysics/images/sphx_glr_Hfss_Icepak_Coupling_002.gif
   :class: sphx-glr-single-img


.. rst-class:: sphx-glr-script-out

 .. code-block:: none

    C:\actions-runner\_work\pyaedt\pyaedt\.venv\lib\site-packages\pyvista\plotting\plotter.py:4644: PyVistaDeprecationWarning: This method is deprecated and will be removed in a future version of PyVista. Directly modify the scalars of a mesh in-place instead.
      warnings.warn(
    Total Time 14.705658912658691




.. GENERATED FROM PYTHON SOURCE LINES 282-286

Create Icepak plots and export
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Create Icepak plots and export them as images using the same functions that
were used early. Only the quantity is different.

.. GENERATED FROM PYTHON SOURCE LINES 286-295

.. code-block:: Python


    quantity_name = "Temperature"
    setup_name = ipkapp.existing_analysis_sweeps[0]
    intrinsic = ""
    surflist = ipkapp.modeler.get_object_faces("inner") + ipkapp.modeler.get_object_faces("outer")
    plot5 = ipkapp.post.create_fieldplot_surface(surflist, "SurfTemperature")

    aedtapp.save_project()





.. rst-class:: sphx-glr-script-out

 .. code-block:: none


    True



.. GENERATED FROM PYTHON SOURCE LINES 296-299

Generate plots outside of AEDT
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Generate plots outside of AEDT using Matplotlib and NumPy.

.. GENERATED FROM PYTHON SOURCE LINES 299-307

.. code-block:: Python


    trace_names = aedtapp.get_traces_for_plot(category="S")
    cxt = ["Domain:=", "Sweep"]
    families = ["Freq:=", ["All"]]
    my_data = aedtapp.post.get_solution_data(expressions=trace_names)
    my_data.plot(trace_names, "db20", x_label="Frequency (Ghz)", y_label="SParameters(dB)", title="Scattering Chart",
                 snapshot_path=os.path.join(results_folder, "Touchstone_from_matplotlib.jpg"))




.. image-sg:: /examples/06-Multiphysics/images/sphx_glr_Hfss_Icepak_Coupling_003.png
   :alt: Scattering Chart
   :srcset: /examples/06-Multiphysics/images/sphx_glr_Hfss_Icepak_Coupling_003.png
   :class: sphx-glr-single-img


.. rst-class:: sphx-glr-script-out

 .. code-block:: none

    No artists with labels found to put in legend.  Note that artists whose label start with an underscore are ignored when legend() is called with no argument.

    <Figure size 2000x1000 with 1 Axes>



.. GENERATED FROM PYTHON SOURCE LINES 308-311

Generate pdf report
~~~~~~~~~~~~~~~~~~~
Generate a pdf report with output of simultion.

.. GENERATED FROM PYTHON SOURCE LINES 311-330

.. code-block:: Python

    report = AnsysReport(version=aedt_version, design_name=aedtapp.design_name, project_name=aedtapp.project_name)
    report.create()
    report.add_section()
    report.add_chapter("Hfss Results")
    report.add_sub_chapter("Field Plot")
    report.add_text("This section contains Field plots of Hfss Coaxial.")
    report.add_image(os.path.join(results_folder, plot1.name + ".jpg"), "Coaxial Cable")
    report.add_page_break()
    report.add_sub_chapter("S Parameters")
    report.add_chart(my_data.intrinsics["Freq"], my_data.data_db20(), "Freq", trace_names[0], "S-Parameters")
    report.add_image(os.path.join(results_folder, "Touchstone_from_matplotlib.jpg"), "Touchstone from Matplotlib")
    report.add_section()
    report.add_chapter("Icepak Results")
    report.add_sub_chapter("Temperature Plot")
    report.add_text("This section contains Multiphysics temperature plot.")
    report.add_toc()
    # report.add_image(os.path.join(results_folder, plot5.name+".jpg"), "Coaxial Cable Temperatures")
    report.save_pdf(results_folder, "AEDT_Results.pdf")





.. rst-class:: sphx-glr-script-out

 .. code-block:: none


    'D:/Temp/pyaedt_prj_OW9/Project_AQ4.pyaedt\\HFSS_XLU\\Coaxial_Results_NG\\AEDT_Results.pdf'



.. GENERATED FROM PYTHON SOURCE LINES 331-334

Close project and release AEDT
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Close the project and release AEDT.

.. GENERATED FROM PYTHON SOURCE LINES 334-336

.. code-block:: Python


    aedtapp.release_desktop()




.. rst-class:: sphx-glr-script-out

 .. code-block:: none


    True




.. rst-class:: sphx-glr-timing

   **Total running time of the script:** (3 minutes 11.097 seconds)


.. _sphx_glr_download_examples_06-Multiphysics_Hfss_Icepak_Coupling.py:

.. only:: html

  .. container:: sphx-glr-footer sphx-glr-footer-example

    .. container:: sphx-glr-download sphx-glr-download-jupyter

      :download:`Download Jupyter notebook: Hfss_Icepak_Coupling.ipynb <Hfss_Icepak_Coupling.ipynb>`

    .. container:: sphx-glr-download sphx-glr-download-python

      :download:`Download Python source code: Hfss_Icepak_Coupling.py <Hfss_Icepak_Coupling.py>`


.. only:: html

 .. rst-class:: sphx-glr-signature

    `Gallery generated by Sphinx-Gallery <https://sphinx-gallery.github.io>`_