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

.. only:: html

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

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

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

.. _sphx_glr_examples_03-Maxwell_Maxwell2D_Electrostatic.py:


Maxwell 2D Electrostatic analysis
---------------------------------
This example shows how you can use PyAEDT to create a Maxwell 2D electrostatic analysis.
It shows how to create the geometry, load material properties from an Excel file and
set up the mesh settings. Moreover, it focuses on post-processing operations, in particular how to
plot field line traces, relevant for an electrostatic analysis.

.. GENERATED FROM PYTHON SOURCE LINES 10-13

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

.. GENERATED FROM PYTHON SOURCE LINES 13-16

.. code-block:: Python


    import pyaedt








.. GENERATED FROM PYTHON SOURCE LINES 17-20

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

.. GENERATED FROM PYTHON SOURCE LINES 20-23

.. code-block:: Python


    aedt_version = "2024.1"








.. GENERATED FROM PYTHON SOURCE LINES 24-28

Initialize Maxwell 2D
~~~~~~~~~~~~~~~~~~~~~
Initialize Maxwell 2D, providing the version, path to the project, and the design
name and type.

.. GENERATED FROM PYTHON SOURCE LINES 28-35

.. code-block:: Python


    setup_name = 'MySetupAuto'
    solver = 'Electrostatic'
    design_name = 'Design1'
    project_name = pyaedt.generate_unique_project_name()
    non_graphical = False








.. GENERATED FROM PYTHON SOURCE LINES 36-39

Download .xlsx file
~~~~~~~~~~~~~~~~~~~
Set local temporary folder to export the .xlsx file to.

.. GENERATED FROM PYTHON SOURCE LINES 39-42

.. code-block:: Python


    file_name_xlsx = pyaedt.downloads.download_file("field_line_traces", "my_copper.xlsx")








.. GENERATED FROM PYTHON SOURCE LINES 43-46

Initialize dictionaries
~~~~~~~~~~~~~~~~~~~~~~~
Initialize dictionaries that contain all the definitions for the design variables.

.. GENERATED FROM PYTHON SOURCE LINES 46-64

.. code-block:: Python


    geom_params_circle = {
        'circle_x0': '-10mm',
        'circle_y0': '0mm',
        'circle_z0': '0mm',
        'circle_axis': 'Z',
        'circle_radius': '1mm'
    }

    geom_params_rectangle = {
        'r_x0': '1mm',
        'r_y0': '5mm',
        'r_z0': '0mm',
        'r_axis': 'Z',
        'r_dx': '-1mm',
        'r_dy': '-10mm'
    }








.. GENERATED FROM PYTHON SOURCE LINES 65-68

Launch Maxwell 2D
~~~~~~~~~~~~~~~~~
Launch Maxwell 2D and save the project.

.. GENERATED FROM PYTHON SOURCE LINES 68-77

.. code-block:: Python


    M2D = pyaedt.Maxwell2d(projectname=project_name,
                           specified_version=aedt_version,
                           designname=design_name,
                           solution_type=solver,
                           new_desktop_session=True,
                           non_graphical=non_graphical
                           )





.. 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 6756 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 78-81

Create object to access 2D modeler
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Create the object ``mod2D`` to access the 2D modeler easily.

.. GENERATED FROM PYTHON SOURCE LINES 81-86

.. code-block:: Python


    mod2D = M2D.modeler
    mod2D.delete()
    mod2D.model_units = "mm"








.. GENERATED FROM PYTHON SOURCE LINES 87-90

Define variables from dictionaries
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Define design variables from the created dictionaries.

.. GENERATED FROM PYTHON SOURCE LINES 90-96

.. code-block:: Python


    for k, v in geom_params_circle.items():
        M2D[k] = v
    for k, v in geom_params_rectangle.items():
        M2D[k] = v








.. GENERATED FROM PYTHON SOURCE LINES 97-100

Read materials from .xslx file
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Read materials from .xslx file into and set into design.

.. GENERATED FROM PYTHON SOURCE LINES 100-103

.. code-block:: Python


    mats = M2D.materials.import_materials_from_excel(file_name_xlsx)





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

 .. code-block:: none

    C:\actions-runner\_work\pyaedt\pyaedt\.venv\lib\site-packages\pyaedt\modules\MaterialLib.py:907: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]`
      and val[keys.index(prop)]
    C:\actions-runner\_work\pyaedt\pyaedt\.venv\lib\site-packages\pyaedt\modules\MaterialLib.py:908: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]`
      and not (isinstance(val[keys.index(prop)], float) and math.isnan(val[keys.index(prop)]))
    C:\actions-runner\_work\pyaedt\pyaedt\.venv\lib\site-packages\pyaedt\modules\MaterialLib.py:910: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]`
      props[prop] = float(val[keys.index(prop)])




.. GENERATED FROM PYTHON SOURCE LINES 104-108

Create design geometries
~~~~~~~~~~~~~~~~~~~~~~~~
Create rectangle and a circle and assign the material read from the .xlsx file.
Create two new polylines and a region.

.. GENERATED FROM PYTHON SOURCE LINES 108-127

.. code-block:: Python


    rect = mod2D.create_rectangle(origin=['r_x0', 'r_y0', 'r_z0'],
                                  sizes=['r_dx', 'r_dy', 0],
                                  name='Ground', matname=mats[0])
    rect.color = (0, 0, 255)  # rgb
    rect.solve_inside = False

    circle = mod2D.create_circle(position=['circle_x0', 'circle_y0', 'circle_z0'], radius='circle_radius',
                                 num_sides='0', is_covered=True, name='Electrode', matname=mats[0])
    circle.color = (0, 0, 255)  # rgb
    circle.solve_inside = False

    poly1_points = [[-9, 2, 0], [-4, 2, 0], [2, -2, 0],[8, 2, 0]]
    poly2_points = [[-9, 0, 0], [9, 0, 0]]
    poly1_id = mod2D.create_polyline(points=poly1_points, segment_type='Spline', name='Poly1')
    poly2_id = mod2D.create_polyline(points=poly2_points, name='Poly2')
    mod2D.split([poly1_id, poly2_id], 'YZ', sides='NegativeOnly')
    mod2D.create_region([20, 100, 20, 100])





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

 .. code-block:: none


    <pyaedt.modeler.cad.object3d.Object3d object at 0x0000022600FCC970>



.. GENERATED FROM PYTHON SOURCE LINES 128-131

Define excitations
~~~~~~~~~~~~~~~~~~
Assign voltage excitations to rectangle and circle.

.. GENERATED FROM PYTHON SOURCE LINES 131-135

.. code-block:: Python


    M2D.assign_voltage(rect.id, amplitude=0, name='Ground')
    M2D.assign_voltage(circle.id, amplitude=50e6, name='50kV')





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

 .. code-block:: none


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



.. GENERATED FROM PYTHON SOURCE LINES 136-139

Create initial mesh settings
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Assign a surface mesh to the rectangle.

.. GENERATED FROM PYTHON SOURCE LINES 139-142

.. code-block:: Python


    M2D.mesh.assign_surface_mesh_manual(assignment=['Ground'], surface_deviation=0.001)





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

 .. code-block:: none


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



.. GENERATED FROM PYTHON SOURCE LINES 143-146

Create, validate and analyze the setup
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Create, update, validate and analyze the setup.

.. GENERATED FROM PYTHON SOURCE LINES 146-153

.. code-block:: Python


    setup = M2D.create_setup(name=setup_name)
    setup.props['PercentError'] = 0.5
    setup.update()
    M2D.validate_simple()
    M2D.analyze_setup(setup_name)





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

 .. code-block:: none


    True



.. GENERATED FROM PYTHON SOURCE LINES 154-158

Evaluate the E Field tangential component
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Evaluate the E Field tangential component along the given polylines.
Add these operations to the Named Expression list in Field Calculator.

.. GENERATED FROM PYTHON SOURCE LINES 158-172

.. code-block:: Python


    fields = M2D.ofieldsreporter
    fields.CalcStack("clear")
    fields.EnterQty("E")
    fields.EnterEdge("Poly1")
    fields.CalcOp("Tangent")
    fields.CalcOp("Dot")
    fields.AddNamedExpression("e_tan_poly1", "Fields")
    fields.EnterQty("E")
    fields.EnterEdge("Poly2")
    fields.CalcOp("Tangent")
    fields.CalcOp("Dot")
    fields.AddNamedExpression("e_tan_poly2", "Fields")








.. GENERATED FROM PYTHON SOURCE LINES 173-178

Create Field Line Traces Plot
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Create Field Line Traces Plot specifying as seeding faces
the ground, the electrode and the region
and as ``In surface objects`` only the region.

.. GENERATED FROM PYTHON SOURCE LINES 178-182

.. code-block:: Python


    plot = M2D.post.create_fieldplot_line_traces(seeding_faces=["Ground", "Electrode", "Region"],
                                                 in_volume_tracing_objs="Region", plot_name="LineTracesTest")








.. GENERATED FROM PYTHON SOURCE LINES 183-187

Update Field Line Traces Plot
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Update field line traces plot.
Update seeding points number, line style and line width.

.. GENERATED FROM PYTHON SOURCE LINES 187-193

.. code-block:: Python


    plot.SeedingPointsNumber = 20
    plot.LineStyle = "Cylinder"
    plot.LineWidth = 3
    plot.update()





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

 .. code-block:: none


    True



.. GENERATED FROM PYTHON SOURCE LINES 194-198

Export field line traces plot
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Export field line traces plot.
For field lint traces plot, the export file format is ``.fldplt``.

.. GENERATED FROM PYTHON SOURCE LINES 198-201

.. code-block:: Python


    M2D.post.export_field_plot(plot_name="LineTracesTest", output_dir=M2D.toolkit_directory, file_format="fldplt")





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

 .. code-block:: none


    'D:/Temp/pyaedt_prj_0XX/Project_YJM.pyaedt\\LineTracesTest.fldplt'



.. GENERATED FROM PYTHON SOURCE LINES 202-205

Export the mesh field plot
~~~~~~~~~~~~~~~~~~~~~~~~~~
Export the mesh in ``aedtplt`` format.

.. GENERATED FROM PYTHON SOURCE LINES 205-208

.. code-block:: Python


    M2D.post.export_mesh_obj(setup=M2D.nominal_adaptive)





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

 .. code-block:: none


    'D:/Temp/pyaedt_prj_0XX/Project_YJM.pyaedt\\Design1\\Mesh_BWOK7T.aedtplt'



.. GENERATED FROM PYTHON SOURCE LINES 209-212

Save project and close AEDT
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Save the project and close AEDT.

.. GENERATED FROM PYTHON SOURCE LINES 212-215

.. code-block:: Python


    M2D.save_project()
    M2D.release_desktop()




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

 .. code-block:: none


    True




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

   **Total running time of the script:** (1 minutes 12.346 seconds)


.. _sphx_glr_download_examples_03-Maxwell_Maxwell2D_Electrostatic.py:

.. only:: html

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

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

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

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

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


.. only:: html

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

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