Pyleecan Simulation Framework

repository·master·Indexed 42 days ago

https://github.com/eomys/pyleecan

An open-source, multiphysic simulation framework for the design and optimization of electrical machines and drives. Version 1.0.0 supports non-linear magnetostatic analysis via FEMM, loss modeling, electrical modeling for PMSM and SCIM, and 2D/3D mesh generation via GMSH. It includes a GUI and API for various topologies (SPMSM, IPMSM, SCIM, DFIM, WRSM, SRM, SynRM) and provides tools for constrained global optimization and Motor-CAD file conversion via the ConvertMC class.

Tokens
18.4K
Snippets
49
Records
61
Agent score
53%

What's inside Pyleecan

  1. Overview of Pyleecan simulation framework

    master

    Pyleecan is a unified, flexible simulation framework designed for the multiphysic design and optimization of electrical machines and drives. It is an open-source project (Apache V2 license) intended for researchers, R&D engineers, and teachers to support reproducible research in electrical engineering.

    Key capabilities include:

    • Non-linear magnetostatic analysis: Fully coupled with FEMM (Windows only) to support sliding band and symmetries.
    • Loss modeling: Includes several models based on FEMM coupling output.
    • Electrical modeling: Solves equivalent circuits for PMSM and SCIM machines.
    • Meshing: Coupled with GMSH for 2D/3D finite element mesh generation.
    • Optimization: Coupled with two multiobjective optimization libraries for machine design.
    • Parameter Sweeps: Enables variable speed simulations via parameter sweeps.
  2. Supported electrical machine topologies in Pyleecan

    master

    Pyleecan provides a Graphical User Interface (GUI) and modeling capabilities for various 2D radial flux topologies, including:

    • SPMSM (Surface Permanent Magnet Synchronous Machine)
    • IPMSM (Interior Permanent Magnet Synchronous Machine)
    • SCIM (Squirrel Cage Induction Machine)
    • DFIM (Doubly Fed Induction Machine)
    • WRSM (Wound Rotor Synchronous Machine)
    • SRM (Switched Reluctance Machine)
    • SynRM (Synchronous Reluctance Machine)

    Advanced geometry features include importing slots or holes from DXF files, support for Star of Slot Winding (via swat-em), user-defined windings, and complex geometry modeling (notches, uneven bore/yoke shapes, and multi-lamination machines).

  3. Define a machine using scripting mode

    master

    For complex or exotic topologies, you can define machines directly in Python by composing various lamination, slot, winding, and machine classes.

    Key components include:

    • Machine classes: e.g., MachineUD, MachineIPMSM.
    • Lamination classes: e.g., LamSlotWind (for stators with windings), LamSlot (for rotors/stators without windings), LamHole (for rotors with magnet holes).
    • Slot classes: e.g., SlotW11, SlotW22.
    • Winding classes: e.g., WindingCW2LT, WindingDW1L.
    • Conductor classes: e.g., CondType11.
    • Shaft and Frame: Shaft and Frame classes.
    from pyleecan.Classes.MachineUD import MachineUD
    from pyleecan.Classes.LamSlotWind import LamSlotWind
    from pyleecan.Classes.LamSlot import LamSlot
    from pyleecan.Classes.WindingCW2LT import WindingCW2LT
    from pyleecan.Classes.SlotW10 import SlotW10
    from pyleecan.Classes.SlotW22 import SlotW22
    from numpy import pi
    
    machine = MachineUD()
    
    # Example: Defining an outer stator
    Rext = 170e-3
    W1 = 30e-3
    lam1 = LamSlotWind(Rext=Rext, Rint=Rext - W1, is_internal=False, is_stator=True)
    lam1.slot = SlotW22(
        Zs=12, W0=2 * pi / 12 * 0.75, W2=2 * pi / 12 * 0.75, H0=0, H2=W1 * 0.65
    )
    lam1.winding = WindingCW2LT(qs=3, p=3)
    
    machine.lam_list = [lam1]
    machine.plot()
  4. Run simulations across multiple operating points with VarLoadCurrent

    master

    To run a simulation over a range of operating points (e.g., varying current angle $\Phi_0$ or $I_d/I_q$), use the VarLoadCurrent class. This creates a 'multi-simulation' that returns an XOutput object.

    Steps:

    1. Define a single simulation (Simu1) with an InputCurrent object.
    2. Create a VarLoadCurrent object.
    3. Define an OP_matrix where each row is an operating point. The columns depend on type_OP_matrix:
      • type_OP_matrix = 0: (N0, I0, Phi0)
      • type_OP_matrix = 1: (N0, Id, Iq)
    4. Copy the original simulation and assign the var_simu property to the VarLoadCurrent instance.
    5. Run the simulation.

    XOutput Results: Results are stored in Xout.xoutput_dict. You can access specific results using Xout["key"].result (e.g., Xout["Phi0"].result).

    from pyleecan.Classes.VarLoadCurrent import VarLoadCurrent
    
    # 1. Setup VarLoadCurrent
    varload = VarLoadCurrent(is_torque=True, is_reuse_femm_file=True)
    varload.type_OP_matrix = 0 # Matrix format: N0, I0, Phi0
    
    # 2. Create OP_matrix (example: 5 points)
    import numpy as np
    OP_matrix = np.zeros((5, 4))
    OP_matrix[:, 0] = 2000 # N0
    OP_matrix[:, 1] = 250 / np.sqrt(2) # I0
    OP_matrix[:, 2] = np.linspace(60*np.pi/180, 180*np.pi/180, 5) # Phi0
    OP_matrix[:, 3] = [79, 125, 160, 192, 237] # Reference torque
    
    varload.OP_matrix = OP_matrix
    
    # 3. Run multi-simulation
    simu_vop = simu_op.copy()
    simu_vop.var_simu = varload
    Xout_vop = simu_vop.run()
    
    # 4. Access results
    print(Xout_vop["Phi0"].result)
  5. Install Pyleecan and dependencies

    master

    To use Pyleecan for advanced meshing and simulation, follow these setup steps:

    1. Install Anaconda.
    2. In the Anaconda Prompt, run: pip install pyleecan.
    3. Install the latest version of FEMM (Windows only).
    4. For meshing capabilities, install gmsh: pip install gmsh.
    5. Launch Jupyter Notebook via Anaconda Navigator to run tutorials and notebooks.
    pip install pyleecan
    pip install gmsh
  6. Save and plot FEMM simulation results using MeshSolution

    master

    To capture Finite Element (FE) results from a FEMM simulation into a Pyleecan MeshSolution object, set the is_get_mesh attribute to True on the magnetic module before running the simulation.

    Once the simulation is complete, you can use the MeshSolution object to:

    • Plot the mesh: out_femm.mag.meshsolution.plot_mesh()
    • Extract specific groups: Use group_names (e.g., "stator" or ["airgap", "stator_windings"]) or intersection syntax (e.g., ["stator", "/", "airgap"]).
    • Plot electromagnetic solutions: Use plot_contour(label="B") for field contours or plot_glyph(label="B") for vector/arrow plots.
    • Extract field data: Use get_field(label='B') to retrieve the raw data arrays.
    # Enable saving of FEMM mesh and results
    simu_femm.mag.is_get_mesh = True
    
    # Run simulation
    out_femm = simu_femm.run()
    
    # Plotting examples
    out_femm.mag.meshsolution.plot_mesh(group_names="stator")
    out_femm.mag.meshsolution.plot_contour(label="B")
    out_femm.mag.meshsolution.plot_glyph(label="B", group_names="stator")
  7. Install Pyleecan

    master

    To install Pyleecan, use pip within an Anaconda environment. If you are on Windows and intend to use FEMM coupling, you must also install the latest version of FEMM.

    pip install pyleecan
  8. Start the Pyleecan GUI

    master

    The Graphical User Interface (GUI) allows you to create or load machines and save them in JSON format. You can launch it from a Jupyter Notebook or a terminal.

    From Jupyter Notebook:

    %run -m pyleecan

    From a Terminal:

    Path/to/python.exe -m pyleecan

    Note: On Anaconda, you may need to set the system variable QT_QPA_PLATFORM_PLUGIN_PATH to your PySide2 plugins directory.

    # Start Pyleecan GUI from the Jupyter Notebook
    %run -m pyleecan
  9. Import external meshes using MeshVTK

    master

    To use meshes generated by external tools like Gmsh, it is recommended to convert them to the .vtk format (using libraries like meshio). Once converted, you can load them into Pyleecan using the MeshVTK class, which relies on pyvista for visualization.

    Workflow:

    1. Generate .msh file with Gmsh.
    2. Convert .msh to .vtk using meshio.
    3. Load .vtk into MeshVTK.
    4. Wrap in MeshSolution.
    import meshio
    from pyleecan.Classes.MeshVTK import MeshVTK
    from pyleecan.Classes.MeshSolution import MeshSolution
    
    # 1. Convert msh to vtk
    m = meshio.Mesh.read('my_mesh.msh')
    m.write('my_mesh.vtk')
    
    # 2. Import into Pyleecan
    mesh_import = MeshVTK(path='.', name='my_mesh')
    MSol_import = MeshSolution(mesh=[mesh_import])
    MSol_import.plot_mesh()
  10. How to solve constrained global optimization problems

    master

    Pyleecan solves constrained global optimization problems by separating the problem definition from the solver. To perform an optimization, you must define an OptiProblem object which encapsulates:

    1. A Reference Simulation: A base simulation object (e.g., Simu1) that serves as a template. Each optimization iteration copies this simulation and applies new design variable values.
    2. Design Variables: Parameters to vary, defined via OptiDesignVarInterval (for continuous variables) or OptiDesignVarSet (for discrete variables).
    3. Objective Functions: The metrics to minimize, defined using OptiObjective objects.
    4. Constraints (Optional): Limits on the search space, defined using OptiConstraint objects.
    5. Evaluation Function: A function (defaults to simu.run) that executes the simulation for a given set of variables and returns the results.
    from pyleecan.Classes.OptiProblem import OptiProblem
    
    # Problem creation
    my_prob = OptiProblem(
        simu=simu_ref, 
        design_var=my_design_var, 
        obj_func=my_obj,
        constraint = my_constraint,
        eval_func = None # Defaults to simu.run
    )
  11. Understand the Converter architecture

    master

    The converter follows a three-step pipeline to transform data between software (e.g., Motor-CAD to Pyleecan):

    1. Dictionary Creation: The source file (like a .mot file) is parsed into a nested dictionary structure. This dictionary maps section headers (e.g., [Dimensions]) to key-value pairs. A secondary unit_dict is created to manage unit conversions.
    2. Rule Selection: The converter scans the machine/dictionary to identify and build a rules_list. This list contains the specific logic required to map parameters between the two environments.
    3. Rule Execution: The converter iterates through the rules_list in a precise order to populate the Pyleecan machine object properties or the target software's dictionary.

    This architecture is designed to be reusable for other software by simply changing the dictionary mapping and the rules.

  12. Use Air-Gap Surface Force (AGSF) transfer for magnetic force computation

    master

    The Air-Gap Surface Force (AGSF) method computes equivalent magnetic pressure in the air-gap using the Maxwell Stress Tensor (MST). To resolve the conflict between numerical error in the middle of the air-gap and MST accuracy at the stator bore radius, Pyleecan provides an AGSF transfer law. This allows you to compute the AGSF at the stator bore radius based on the AGSF calculated in the middle of the air-gap.

    To use this feature, configure a ForceMT object within your simulation and set the following parameters:

    • is_agsf_transfer=True: Enables the transfer law.
    • max_wavenumber_transfer: Sets the maximum wavenumber used for the transfer (e.g., 70 or 100).
    • Rsbo_enforced_transfer: Specifies the target radius (stator bore radius) where the transferred force should be applied.
    # Create a simulation instance with transfer enabled
    simu_transfer = simu.copy()
    simu_transfer.force.is_agsf_transfer = True
    simu_transfer.force.max_wavenumber_transfer = 70
    
    # When running, specify the target radius (e.g., stator bore radius)
    simu_transfer.force.Rsbo_enforced_transfer = Rag
    
    # Run the simulation
    out_transfer = simu_transfer.run()