Maxwell 3D segmentation#

This example shows how to use the Magnet Segmentation Toolkit to segment your AEDT motor model.

Perform required imports#

Perform required imports.

[1]:

import shutil import tempfile from pathlib import Path from ansys.aedt.toolkits.common.utils import download_file from ansys.aedt.toolkits.magnet_segmentation.backend.api import ToolkitBackend

Initialize temporary folder and project settings#

Initialize a temporary folder to copy the input file into and specify project settings.

[2]:
URL_BASE = "https://raw.githubusercontent.com/ansys/example-data/master/toolkits/magnet_segmentation/"
AEDT_PROJECT = "e9_eMobility_IPM_3D"
URL = str(Path(URL_BASE) / (AEDT_PROJECT + ".aedt"))

temp_dir = tempfile.TemporaryDirectory(suffix=".ansys")
active_project = str(Path(temp_dir.name) / (AEDT_PROJECT + ".aedt"))
download_file(URL, active_project)
active_design = "e9_eMobility_IPM_3D_test"
---------------------------------------------------------------------------
InvalidURL                                Traceback (most recent call last)
Cell In[2], line 7
      5 temp_dir = tempfile.TemporaryDirectory(suffix=".ansys")
      6 active_project = str(Path(temp_dir.name) / (AEDT_PROJECT + ".aedt"))
----> 7 download_file(URL, active_project)
      8 active_design = "e9_eMobility_IPM_3D_test"

File C:\actions-runner\_work\magnet-segmentation-toolkit\magnet-segmentation-toolkit\.venv\Lib\site-packages\ansys\aedt\toolkits\common\utils.py:45, in download_file(url, local_filename)
     43 """Download a file from a URL into a local file."""
     44 download_timeout = DEFAULT_REQUESTS_TIMEOUT * 2
---> 45 with requests.get(url, stream=True, timeout=download_timeout) as r:
     46     r.raise_for_status()
     47     with open(local_filename, "wb") as f:

File C:\actions-runner\_work\magnet-segmentation-toolkit\magnet-segmentation-toolkit\.venv\Lib\site-packages\requests\api.py:73, in get(url, params, **kwargs)
     62 def get(url, params=None, **kwargs):
     63     r"""Sends a GET request.
     64
     65     :param url: URL for the new :class:`Request` object.
   (...)     70     :rtype: requests.Response
     71     """
---> 73     return request("get", url, params=params, **kwargs)

File C:\actions-runner\_work\magnet-segmentation-toolkit\magnet-segmentation-toolkit\.venv\Lib\site-packages\requests\api.py:59, in request(method, url, **kwargs)
     55 # By using the 'with' statement we are sure the session is closed, thus we
     56 # avoid leaving sockets open which can trigger a ResourceWarning in some
     57 # cases, and look like a memory leak in others.
     58 with sessions.Session() as session:
---> 59     return session.request(method=method, url=url, **kwargs)

File C:\actions-runner\_work\magnet-segmentation-toolkit\magnet-segmentation-toolkit\.venv\Lib\site-packages\requests\sessions.py:578, in Session.request(self, method, url, params, data, headers, cookies, files, auth, timeout, allow_redirects, proxies, hooks, stream, verify, cert, json)
    565 # Create the Request.
    566 req = Request(
    567     method=method.upper(),
    568     url=url,
   (...)    576     hooks=hooks,
    577 )
--> 578 prep = self.prepare_request(req)
    580 proxies = proxies or {}
    582 settings = self.merge_environment_settings(
    583     prep.url, proxies, stream, verify, cert
    584 )

File C:\actions-runner\_work\magnet-segmentation-toolkit\magnet-segmentation-toolkit\.venv\Lib\site-packages\requests\sessions.py:487, in Session.prepare_request(self, request)
    484     auth = get_netrc_auth(request.url)
    486 p = PreparedRequest()
--> 487 p.prepare(
    488     method=request.method.upper(),
    489     url=request.url,
    490     files=request.files,
    491     data=request.data,
    492     json=request.json,
    493     headers=merge_setting(
    494         request.headers, self.headers, dict_class=CaseInsensitiveDict
    495     ),
    496     params=merge_setting(request.params, self.params),
    497     auth=merge_setting(auth, self.auth),
    498     cookies=merged_cookies,
    499     hooks=merge_hooks(request.hooks, self.hooks),
    500 )
    501 return p

File C:\actions-runner\_work\magnet-segmentation-toolkit\magnet-segmentation-toolkit\.venv\Lib\site-packages\requests\models.py:369, in PreparedRequest.prepare(self, method, url, headers, files, data, params, auth, cookies, hooks, json)
    366 """Prepares the entire request with the given parameters."""
    368 self.prepare_method(method)
--> 369 self.prepare_url(url, params)
    370 self.prepare_headers(headers)
    371 self.prepare_cookies(cookies)

File C:\actions-runner\_work\magnet-segmentation-toolkit\magnet-segmentation-toolkit\.venv\Lib\site-packages\requests\models.py:446, in PreparedRequest.prepare_url(self, url, params)
    440     raise MissingSchema(
    441         f"Invalid URL {url!r}: No scheme supplied. "
    442         f"Perhaps you meant https://{url}?"
    443     )
    445 if not host:
--> 446     raise InvalidURL(f"Invalid URL {url!r}: No host supplied")
    448 # In general, we want to try IDNA encoding the hostname if the string contains
    449 # non-ASCII characters. This allows users to automatically get the correct IDNA
    450 # behaviour. For strings containing only ASCII characters, we need to also verify
    451 # it doesn't start with a wildcard (*), before allowing the unencoded hostname.
    452 if not unicode_is_ascii(host):

InvalidURL: Invalid URL 'https:\\raw.githubusercontent.com\\ansys\\example-data\\master\\toolkits\\magnet_segmentation\\e9_eMobility_IPM_3D.aedt': No host supplied

Initialize toolkit#

Initialize the toolkit.

[3]:
toolkit = ToolkitBackend()

Get toolkit properties#

Get the toolkit properties.

[4]:
properties = toolkit.get_properties()

Initialize properties#

Initialize a dictionary of properties.

[5]:
properties["aedt_version"] = "2026.1"
properties["active_project"] = AEDT_PROJECT
properties["active_design"] = active_design
properties["design_list"] = {AEDT_PROJECT: [active_design]}
properties["is_skewed"] = False
properties["rotor_material"] = "M250-35A_20C"
properties["stator_material"] = "M250-35A_20C"
properties["magnets_material"] = "N30UH_65C"
properties["magnet_segments_per_slice"] = 2
properties["rotor_slices"] = 2
properties["apply_mesh_sheets"] = False
# properties["mesh_sheets_number"] = 3
properties["skew_angle"] = "2deg"
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[5], line 3
      1 properties["aedt_version"] = "2026.1"
      2 properties["active_project"] = AEDT_PROJECT
----> 3 properties["active_design"] = active_design
      4 properties["design_list"] = {AEDT_PROJECT: [active_design]}
      5 properties["is_skewed"] = False

NameError: name 'active_design' is not defined

Set non-graphical mode#

Set non-graphical mode. The default value is False.

[6]:
properties["non_graphical"] = False

Set properties#

Set properties.

[7]:
toolkit.set_properties(properties)
INFO - Updating internal properties.
[7]:
(True, 'Properties were updated successfully.')

Initialize AEDT#

Launch a new AEDT session.

[8]:
toolkit.launch_aedt()
INFO - AEDT is released.
[8]:
True

Open project#

Open the project.

[9]:
toolkit.open_project(active_project)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
File C:\actions-runner\_work\magnet-segmentation-toolkit\magnet-segmentation-toolkit\.venv\Lib\site-packages\ansys\aedt\core\internal\grpc_plugin_dll_class.py:116, in AedtObjWrapper.__Invoke__(self, funcName, argv)
    115     self.dllapi.recreate_application(True)
--> 116 ret = _retry_ntimes(
    117     settings.number_of_grpc_api_retries,
    118     self.dllapi.AedtAPI.InvokeAedtObjMethod,
    119     self.objectID,
    120     funcName,
    121     argv,
    122 )  # Call C function
    123 if ret and isinstance(ret, (AedtObjWrapper, AedtPropServer)):

File C:\actions-runner\_work\magnet-segmentation-toolkit\magnet-segmentation-toolkit\.venv\Lib\site-packages\ansys\aedt\core\generic\general_methods.py:613, in _retry_ntimes(n, function, *args, **kwargs)
    612 if "__name__" in dir(function):
--> 613     raise AttributeError(f"Error in Executing Method {function.__name__}.")
    614 else:

AttributeError: Error in Executing Method InvokeAedtObjMethod.

During handling of the above exception, another exception occurred:

GrpcApiError                              Traceback (most recent call last)
Cell In[9], line 1
----> 1 toolkit.open_project(active_project)

File C:\actions-runner\_work\magnet-segmentation-toolkit\magnet-segmentation-toolkit\.venv\Lib\site-packages\ansys\aedt\toolkits\common\backend\api.py:743, in AEDTCommon.open_project(self, project_name)
    741     return True
    742 elif not os.path.exists(project_name + ".lock") and self.desktop and project_name:
--> 743     self.desktop.odesktop.OpenProject(project_name)
    744     logger.debug("Project {} is opened".format(project_name))
    745     self.__save_project_info()

File C:\actions-runner\_work\magnet-segmentation-toolkit\magnet-segmentation-toolkit\.venv\Lib\site-packages\ansys\aedt\core\internal\grpc_plugin_dll_class.py:138, in AedtObjWrapper.__GetObjMethod__.<locals>.DynamicFunc(self, *args)
    137 def DynamicFunc(self, *args):
--> 138     return self.__Invoke__(funcName, args)

File C:\actions-runner\_work\magnet-segmentation-toolkit\magnet-segmentation-toolkit\.venv\Lib\site-packages\ansys\aedt\core\internal\grpc_plugin_dll_class.py:129, in AedtObjWrapper.__Invoke__(self, funcName, argv)
    127 pyaedt_logger.debug("Failed to execute gRPC AEDT command:")
    128 pyaedt_logger.debug(f"{funcName}({argv})")
--> 129 raise GrpcApiError(f"Failed to execute gRPC AEDT command: {funcName}")

GrpcApiError: Failed to execute gRPC AEDT command: OpenProject

Connect design#

Connect or create a new design.

[10]:
toolkit.connect_design()
INFO - Updating internal properties.
INFO - Toolkit is connected to AEDT design.
[10]:
True

Apply segmentation#

Apply segmentation and assign the relative coordinate system.

[11]:
toolkit.segmentation()
INFO - AEDT is released.
INFO - Toolkit is connected to AEDT design.
PyAEDT ERROR: **************************************************************
PyAEDT ERROR:   File "<frozen runpy>", line 198, in _run_module_as_main
PyAEDT ERROR:   File "<frozen runpy>", line 88, in _run_code
PyAEDT ERROR:   File "C:\actions-runner\_work\_tool\Python\3.12.10\x64\Lib\asyncio\base_events.py", line 645, in run_forever
PyAEDT ERROR:     self._run_once()
PyAEDT ERROR:   File "C:\actions-runner\_work\_tool\Python\3.12.10\x64\Lib\asyncio\base_events.py", line 1999, in _run_once
PyAEDT ERROR:     handle._run()
PyAEDT ERROR:   File "C:\actions-runner\_work\_tool\Python\3.12.10\x64\Lib\asyncio\events.py", line 88, in _run
PyAEDT ERROR:     self._context.run(self._callback, *self._args)
PyAEDT ERROR:   File "C:\Users\ansys\AppData\Local\Temp\ipykernel_6164\450086471.py", line 1, in <module>
PyAEDT ERROR:     toolkit.segmentation()
PyAEDT ERROR:   File "C:\actions-runner\_work\magnet-segmentation-toolkit\magnet-segmentation-toolkit\.venv\Lib\site-packages\ansys\aedt\toolkits\magnet_segmentation\backend\workflows\aedt.py", line 74, in segmentation
PyAEDT ERROR:     if self.aedtapp["HalfAxial"] == "1":
PyAEDT ERROR:   File "C:\actions-runner\_work\magnet-segmentation-toolkit\magnet-segmentation-toolkit\.venv\Lib\site-packages\ansys\aedt\core\application\design.py", line 329, in __getitem__
PyAEDT ERROR:     return self.variable_manager[variable_name].expression
PyAEDT ERROR:   File "C:\actions-runner\_work\magnet-segmentation-toolkit\magnet-segmentation-toolkit\.venv\Lib\site-packages\ansys\aedt\core\application\variables.py", line 768, in __getitem__
PyAEDT ERROR:     return self.variables[variable_name]
PyAEDT ERROR:            ~~~~~~~~~~~~~~^^^^^^^^^^^^^^^
PyAEDT ERROR: 'halfaxial' on __getitem__
PyAEDT ERROR: Method arguments:
PyAEDT ERROR:     variable_name = HalfAxial
PyAEDT ERROR: **************************************************************
PyAEDT ERROR: **************************************************************
PyAEDT ERROR:   File "<frozen runpy>", line 198, in _run_module_as_main
PyAEDT ERROR:   File "<frozen runpy>", line 88, in _run_code
PyAEDT ERROR:   File "C:\actions-runner\_work\_tool\Python\3.12.10\x64\Lib\asyncio\base_events.py", line 645, in run_forever
PyAEDT ERROR:     self._run_once()
PyAEDT ERROR:   File "C:\actions-runner\_work\_tool\Python\3.12.10\x64\Lib\asyncio\base_events.py", line 1999, in _run_once
PyAEDT ERROR:     handle._run()
PyAEDT ERROR:   File "C:\actions-runner\_work\_tool\Python\3.12.10\x64\Lib\asyncio\events.py", line 88, in _run
PyAEDT ERROR:     self._context.run(self._callback, *self._args)
PyAEDT ERROR:   File "C:\Users\ansys\AppData\Local\Temp\ipykernel_6164\450086471.py", line 1, in <module>
PyAEDT ERROR:     toolkit.segmentation()
PyAEDT ERROR:   File "C:\actions-runner\_work\magnet-segmentation-toolkit\magnet-segmentation-toolkit\.venv\Lib\site-packages\ansys\aedt\toolkits\magnet_segmentation\backend\workflows\aedt.py", line 74, in segmentation
PyAEDT ERROR:     if self.aedtapp["HalfAxial"] == "1":
PyAEDT ERROR:   File "C:\actions-runner\_work\magnet-segmentation-toolkit\magnet-segmentation-toolkit\.venv\Lib\site-packages\ansys\aedt\core\application\design.py", line 329, in __getitem__
PyAEDT ERROR:     return self.variable_manager[variable_name].expression
PyAEDT ERROR:            ~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^
PyAEDT ERROR:   File "C:\actions-runner\_work\magnet-segmentation-toolkit\magnet-segmentation-toolkit\.venv\Lib\site-packages\ansys\aedt\core\application\variables.py", line 768, in __getitem__
PyAEDT ERROR:     return self.variables[variable_name]
PyAEDT ERROR:            ~~~~~~~~~~~~~~^^^^^^^^^^^^^^^
PyAEDT ERROR: 'halfaxial' on __getitem__
PyAEDT ERROR: Method arguments:
PyAEDT ERROR:     variable_name = HalfAxial
PyAEDT ERROR: **************************************************************
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
Cell In[11], line 1
----> 1 toolkit.segmentation()

File C:\actions-runner\_work\magnet-segmentation-toolkit\magnet-segmentation-toolkit\.venv\Lib\site-packages\ansys\aedt\toolkits\magnet_segmentation\backend\workflows\aedt.py:74, in AEDTWorkflow.segmentation(self)
     71 self.connect_design()
     73 # Requirements: Design needs  a design variable "HalfAxial"
---> 74 if self.aedtapp["HalfAxial"] == "1":
     75     self.aedtapp["HalfAxial"] = "0"
     77 for obj in self.aedtapp.modeler.unclassified_objects:

File C:\actions-runner\_work\magnet-segmentation-toolkit\magnet-segmentation-toolkit\.venv\Lib\site-packages\ansys\aedt\core\generic\general_methods.py:252, in _function_handler_wrapper.<locals>.wrapper(*args, **kwargs)
    250     msg = msg.capitalize()
    251 _exception(sys.exc_info(), user_function, args, kwargs, msg)
--> 252 return raise_exception_or_return_false(e)

File C:\actions-runner\_work\magnet-segmentation-toolkit\magnet-segmentation-toolkit\.venv\Lib\site-packages\ansys\aedt\core\generic\general_methods.py:214, in raise_exception_or_return_false(e)
    211         for v in list(_desktop_sessions.values())[:]:
    212             v.release_desktop(close_projects=v.close_on_exit, close_on_exit=v.close_on_exit)
--> 214     raise e
    215 elif "__init__" in str(e):  # pragma: no cover
    216     return

File C:\actions-runner\_work\magnet-segmentation-toolkit\magnet-segmentation-toolkit\.venv\Lib\site-packages\ansys\aedt\core\generic\general_methods.py:227, in _function_handler_wrapper.<locals>.wrapper(*args, **kwargs)
    225 try:
    226     settings.time_tick = time.time()
--> 227     out = user_function(*args, **kwargs)
    228     _log_method(user_function, args, kwargs)
    229     return out

File C:\actions-runner\_work\magnet-segmentation-toolkit\magnet-segmentation-toolkit\.venv\Lib\site-packages\ansys\aedt\core\application\design.py:329, in Design.__getitem__(self, variable_name)
    327 @pyaedt_function_handler()
    328 def __getitem__(self, variable_name: str) -> str:
--> 329     return self.variable_manager[variable_name].expression

File C:\actions-runner\_work\magnet-segmentation-toolkit\magnet-segmentation-toolkit\.venv\Lib\site-packages\ansys\aedt\core\generic\general_methods.py:252, in _function_handler_wrapper.<locals>.wrapper(*args, **kwargs)
    250     msg = msg.capitalize()
    251 _exception(sys.exc_info(), user_function, args, kwargs, msg)
--> 252 return raise_exception_or_return_false(e)

File C:\actions-runner\_work\magnet-segmentation-toolkit\magnet-segmentation-toolkit\.venv\Lib\site-packages\ansys\aedt\core\generic\general_methods.py:214, in raise_exception_or_return_false(e)
    211         for v in list(_desktop_sessions.values())[:]:
    212             v.release_desktop(close_projects=v.close_on_exit, close_on_exit=v.close_on_exit)
--> 214     raise e
    215 elif "__init__" in str(e):  # pragma: no cover
    216     return

File C:\actions-runner\_work\magnet-segmentation-toolkit\magnet-segmentation-toolkit\.venv\Lib\site-packages\ansys\aedt\core\generic\general_methods.py:227, in _function_handler_wrapper.<locals>.wrapper(*args, **kwargs)
    225 try:
    226     settings.time_tick = time.time()
--> 227     out = user_function(*args, **kwargs)
    228     _log_method(user_function, args, kwargs)
    229     return out

File C:\actions-runner\_work\magnet-segmentation-toolkit\magnet-segmentation-toolkit\.venv\Lib\site-packages\ansys\aedt\core\application\variables.py:768, in VariableManager.__getitem__(self, variable_name)
    766 @pyaedt_function_handler()
    767 def __getitem__(self, variable_name):
--> 768     return self.variables[variable_name]

KeyError: 'HalfAxial'

Apply skew angle#

Apply the skew angle to rotor slices.

[12]:
toolkit.apply_skew()
INFO - AEDT is released.
[12]:
False

Validate and analyze design#

Uncomment the line to validate and analyze the design.

toolkit.validate_and_analyze()

Create magnet loss report#

Uncomment the lines to create magnet loss report and compute average value.

magnet_loss = toolkit.get_magnet_loss() print(f”Average magnet loss: {magnet_loss} W”)

Save and release AEDT#

Save and release AEDT.

toolkit.save_project()

[13]:
toolkit.release_aedt(True, True)
INFO - AEDT is released.
[13]:
True

Remove temporary folder#

Remove the temporary folder.

[14]:
shutil.rmtree(temp_dir.name, ignore_errors=True)