Skip to main content

Python wrapper for OpenMagnetics

Project description

PyOpenMagnetics - Python Wrapper for OpenMagnetics

Python License: MIT

🤖 For AI Assistants: If you're an AI assistant helping with this library, please read AGENTS.md FIRST before continuing with this README. It contains essential information about:

  • Correct import procedures (this package requires special handling)
  • ⚠️ Using API methods instead of manual calculations (CRITICAL)
  • Required field specifications for converter topologies
  • Troubleshooting common API errors
  • Complete working examples

⚠️ AVOID MANUAL MODE: Always use process_flyback(), calculate_advised_magnetics(), and other API methods rather than doing manual calculations. The MKF engine handles complex magnetic effects that manual calculations cannot.

PyOpenMagnetics is a Python wrapper for MKF (Magnetics Knowledge Foundation), the simulation engine of OpenMagnetics, providing a comprehensive toolkit for designing and analyzing magnetic components such as transformers and inductors.

Features

  • 🧲 Core Database: Access to extensive database of core shapes, materials, and manufacturers
  • 🔌 Winding Design: Automatic winding calculations with support for various wire types (round, litz, rectangular, planar)
  • 📊 Loss Calculations: Core losses (Steinmetz), winding losses (DC, skin effect, proximity effect)
  • 🎯 Design Adviser: Automated recommendations for optimal magnetic designs
  • 📈 Signal Processing: Harmonic analysis, waveform processing
  • 🖼️ Visualization: SVG plotting of cores, windings, magnetic fields
  • 🔧 SPICE Export: Export magnetic components as SPICE subcircuits

Installation

From PyPI (recommended)

pip install PyOpenMagnetics

From Source

git clone https://github.com/OpenMagnetics/PyOpenMagnetics.git
cd PyOpenMagnetics
pip install .

⚠️ Import Instructions

Important: The compiled extension module may require special import handling:

import importlib.util

# Option 1: Direct loading (recommended)
so_path = '/path/to/PyOpenMagnetics.cpython-311-x86_64-linux-gnu.so'
spec = importlib.util.spec_from_file_location('PyOpenMagnetics', so_path)
PyOpenMagnetics = importlib.util.module_from_spec(spec)
spec.loader.exec_module(PyOpenMagnetics)

# Option 2: Create __init__.py (see AGENTS.md for details)

# Verify installation
PyOpenMagnetics.load_databases({})
print(f"✓ Loaded {len(PyOpenMagnetics.get_core_materials())} materials")
print(f"✓ Loaded {len(PyOpenMagnetics.get_core_shapes())} shapes")

See AGENTS.md for complete import instructions and troubleshooting.

Quick Start

Basic Example: Creating a Core

import PyOpenMagnetics

# Find a core shape by name
shape = PyOpenMagnetics.find_core_shape_by_name("E 42/21/15")

# Find a core material by name
material = PyOpenMagnetics.find_core_material_by_name("3C95")

# Create a core with gapping
core_data = {
    "functionalDescription": {
        "shape": shape,
        "material": material,
        "gapping": [{"type": "subtractive", "length": 0.001}],  # 1mm gap
        "numberStacks": 1
    }
}

# Calculate complete core data
core = PyOpenMagnetics.calculate_core_data(core_data, False)
print(f"Effective area: {core['processedDescription']['effectiveParameters']['effectiveArea']} m²")

Design Adviser: Get Magnetic Recommendations

import PyOpenMagnetics

# Define design requirements
inputs = {
    "designRequirements": {
        "magnetizingInductance": {
            "minimum": 100e-6,  # 100 µH minimum
            "nominal": 110e-6   # 110 µH nominal
        },
        "turnsRatios": [{"nominal": 5.0}]  # 5:1 turns ratio
    },
    "operatingPoints": [
        {
            "name": "Nominal",
            "conditions": {"ambientTemperature": 25},
            "excitationsPerWinding": [
                {
                    "name": "Primary",
                    "frequency": 100000,  # 100 kHz
                    "current": {
                        "waveform": {
                            "data": [0, 1.0, 0],
                            "time": [0, 5e-6, 10e-6]
                        }
                    },
                    "voltage": {
                        "waveform": {
                            "data": [50, 50, -50, -50],
                            "time": [0, 5e-6, 5e-6, 10e-6]
                        }
                    }
                }
            ]
        }
    ]
}

# Process inputs (adds harmonics and validation)
processed_inputs = PyOpenMagnetics.process_inputs(inputs)

# Get magnetic recommendations
# core_mode: "available cores" (stock cores) or "standard cores" (all standard shapes)
result = PyOpenMagnetics.calculate_advised_magnetics(processed_inputs, 5, "standard cores")

# Result format: {"data": [{"mas": {...}, "scoring": float, "scoringPerFilter": {...}}, ...]}
for i, item in enumerate(result["data"]):
    mag = item["mas"]["magnetic"]
    core = mag["core"]["functionalDescription"]
    print(f"{i+1}. {core['shape']['name']} - {core['material']['name']} (score: {item['scoring']:.3f})")

Calculate Core Losses

import PyOpenMagnetics

# Define core and operating point
core_data = {...}  # Your core definition
operating_point = {
    "name": "Nominal",
    "conditions": {"ambientTemperature": 25},
    "excitationsPerWinding": [
        {
            "frequency": 100000,
            "magneticFluxDensity": {
                "processed": {
                    "peakToPeak": 0.2,  # 200 mT peak-to-peak
                    "offset": 0
                }
            }
        }
    ]
}

losses = PyOpenMagnetics.calculate_core_losses(core_data, operating_point, "IGSE")
print(f"Core losses: {losses['coreLosses']} W")

Winding a Coil

import PyOpenMagnetics

# Define coil requirements
coil_functional_description = [
    {
        "name": "Primary",
        "numberTurns": 50,
        "numberParallels": 1,
        "wire": "Round 0.5 - Grade 1"
    },
    {
        "name": "Secondary",
        "numberTurns": 10,
        "numberParallels": 3,
        "wire": "Round 1.0 - Grade 1"
    }
]

# Wind the coil on the core
result = PyOpenMagnetics.wind(core_data, coil_functional_description, bobbin_data, [1, 1], [])
print(f"Winding successful: {result.get('windingResult', 'unknown')}")

Flyback Converter Wizard

PyOpenMagnetics includes a complete flyback converter design wizard. See flyback.py for a full example:

from flyback import design_flyback, create_mas_inputs, get_advised_magnetics

# Define flyback specifications
specs = {
    "input_voltage_min": 90,
    "input_voltage_max": 375,
    "outputs": [{"voltage": 12, "current": 2, "diode_drop": 0.5}],
    "switching_frequency": 100000,
    "max_duty_cycle": 0.45,
    "efficiency": 0.85,
    "current_ripple_ratio": 0.4,
    "force_dcm": False,
    "safety_margin": 0.85,
    "ambient_temperature": 40,
    "max_drain_source_voltage": None,
}

# Calculate magnetic requirements
design = design_flyback(specs)
print(f"Required inductance: {design['min_inductance']*1e6:.1f} µH")
print(f"Turns ratio: {design['turns_ratios'][0]:.2f}")

# Create inputs for PyOpenMagnetics
inputs = create_mas_inputs(specs, design)

# Get recommended magnetics
magnetics = get_advised_magnetics(inputs, max_results=5)

API Reference

Database Access

Function Description
get_core_materials() Get all available core materials
get_core_shapes() Get all available core shapes
get_wires() Get all available wires
get_bobbins() Get all available bobbins
find_core_material_by_name(name) Find core material by name
find_core_shape_by_name(name) Find core shape by name
find_wire_by_name(name) Find wire by name

Core Calculations

Function Description
calculate_core_data(core, process) Calculate complete core data
calculate_core_gapping(core, gapping) Calculate gapping configuration
calculate_inductance_from_number_turns_and_gapping(...) Calculate inductance
calculate_core_losses(core, operating_point, model) Calculate core losses

Winding Functions

Function Description
wind(core, coil, bobbin, pattern, layers) Wind coils on a core
calculate_winding_losses(...) Calculate total winding losses
calculate_ohmic_losses(...) Calculate DC losses
calculate_skin_effect_losses(...) Calculate skin effect losses
calculate_proximity_effect_losses(...) Calculate proximity effect losses

Design Adviser

Function Description
calculate_advised_cores(inputs, max_results) Get recommended cores
calculate_advised_magnetics(inputs, max, mode) Get complete designs
process_inputs(inputs) Process and validate inputs

Visualization

Function Description
plot_core(core, ...) Generate SVG of core
plot_sections(magnetic, ...) Plot winding sections
plot_layers(magnetic, ...) Plot winding layers
plot_turns(magnetic, ...) Plot individual turns
plot_field(magnetic, ...) Plot magnetic field

Settings

Function Description
get_settings() Get current settings
set_settings(settings) Configure settings
reset_settings() Reset to defaults

SPICE Export

Function Description
export_magnetic_as_subcircuit(magnetic, ...) Export as SPICE model

Converter Topologies

All 24 power topologies are exposed with a uniform API. Use the generic process_converter("<topology>", converter, use_ngspice) (also accepts "advanced_<topology>"), or the per-topology functions below.

Function family Description
process_converter(name, json, use_ngspice=True) Universal dispatch for every topology
design_magnetics_from_converter(name, json, max_results, core_mode, ...) Converter → advised magnetic designs (single call)
calculate_<t>_inputs(json) Build MAS inputs (basic mode) for topology <t>
calculate_advanced_<t>_inputs(json) Build MAS inputs (advanced mode)
simulate_<t>_ideal_waveforms(json) ngspice ideal-waveform simulation
generate_<t>_ngspice_circuit(json, input_voltage_index=0, operating_point_index=0) Generate ngspice netlist

<t>flyback, buck, boost, single_switch_forward, two_switch_forward, active_clamp_forward, push_pull, isolated_buck, isolated_buck_boost, cuk, sepic, zeta, four_switch_buck_boost, weinberg, llc, cllc, clllc, src, dab, psfb, pshb, ahb, vienna. PFC is basic-only (calculate_pfc_inputs, generate_pfc_ngspice_circuit(json, dc_resistance=0.1, simulation_time=0.02, time_step=1e-8)); common-/differential-mode chokes use the cmc / dmc families. See AGENTS.md §11 for the full per-topology parity matrix.

Core Materials

PyOpenMagnetics includes materials from major manufacturers:

  • TDK/EPCOS: N27, N49, N87, N95, N97, etc.
  • Ferroxcube: 3C90, 3C94, 3C95, 3F3, 3F4, etc.
  • Fair-Rite: Various ferrite materials
  • Magnetics Inc.: Powder cores (MPP, High Flux, Kool Mu)
  • Micrometals: Iron powder cores

Core Shapes

Supported shape families include:

  • E cores: E, EI, EFD, EQ, ER
  • ETD/EC cores: ETD, EC
  • PQ/PM cores: PQ, PM
  • RM cores: RM, RM/ILP
  • Toroidal: Various sizes
  • Pot cores: P, PT
  • U/UI cores: U, UI, UR
  • Planar: E-LP, EQ-LP, etc.

Wire Types

  • Round enamelled wire: Various AWG and IEC sizes
  • Litz wire: Multiple strand configurations
  • Rectangular wire: For high-current applications
  • Foil: For planar magnetics
  • Planar PCB: For integrated designs

Configuration

Use set_settings() to configure:

settings = PyOpenMagnetics.get_settings()
settings["coilAllowMarginTape"] = True
settings["coilWindEvenIfNotFit"] = False
settings["painterNumberPointsX"] = 50
PyOpenMagnetics.set_settings(settings)

Contributing

Contributions are welcome! Please see the OpenMagnetics organization for contribution guidelines.

Documentation

Quick Start

  • llms.txt - Comprehensive API reference optimized for AI assistants and quick lookup
  • examples/ - Practical example scripts for common design workflows
  • PyOpenMagnetics.pyi - Type stubs for IDE autocompletion

Tutorials

Reference

Validation

License

This project is licensed under the MIT License - see the LICENSE file for details.

Related Projects

References

  • Maniktala, S. "Switching Power Supplies A-Z", 2nd Edition
  • Basso, C. "Switch-Mode Power Supplies", 2nd Edition
  • McLyman, C. "Transformer and Inductor Design Handbook"

Support

For questions and support:

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pyopenmagnetics-1.4.2.tar.gz (685.1 kB view details)

Uploaded Source

Built Distributions

If you're not sure about the file name format, learn more about wheel file names.

pyopenmagnetics-1.4.2-cp313-cp313-win_amd64.whl (11.4 MB view details)

Uploaded CPython 3.13Windows x86-64

pyopenmagnetics-1.4.2-cp313-cp313-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl (12.9 MB view details)

Uploaded CPython 3.13manylinux: glibc 2.24+ x86-64manylinux: glibc 2.28+ x86-64

pyopenmagnetics-1.4.2-cp312-cp312-win_amd64.whl (11.4 MB view details)

Uploaded CPython 3.12Windows x86-64

pyopenmagnetics-1.4.2-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl (12.9 MB view details)

Uploaded CPython 3.12manylinux: glibc 2.24+ x86-64manylinux: glibc 2.28+ x86-64

pyopenmagnetics-1.4.2-cp311-cp311-win_amd64.whl (11.4 MB view details)

Uploaded CPython 3.11Windows x86-64

pyopenmagnetics-1.4.2-cp311-cp311-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl (12.9 MB view details)

Uploaded CPython 3.11manylinux: glibc 2.24+ x86-64manylinux: glibc 2.28+ x86-64

pyopenmagnetics-1.4.2-cp310-cp310-win_amd64.whl (11.4 MB view details)

Uploaded CPython 3.10Windows x86-64

pyopenmagnetics-1.4.2-cp310-cp310-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl (12.9 MB view details)

Uploaded CPython 3.10manylinux: glibc 2.24+ x86-64manylinux: glibc 2.28+ x86-64

File details

Details for the file pyopenmagnetics-1.4.2.tar.gz.

File metadata

  • Download URL: pyopenmagnetics-1.4.2.tar.gz
  • Upload date:
  • Size: 685.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for pyopenmagnetics-1.4.2.tar.gz
Algorithm Hash digest
SHA256 beab59c4fe3f2fc4f9f43342daef2318c6054e109eba0ba3ba05248c381aaf04
MD5 248aa6c6264a31ac08fdb5e4fdb2db66
BLAKE2b-256 82fbdc40e54f43180a5b20fff70370dae247e25fdad5fa8ed906a883d857b4ce

See more details on using hashes here.

File details

Details for the file pyopenmagnetics-1.4.2-cp313-cp313-win_amd64.whl.

File metadata

File hashes

Hashes for pyopenmagnetics-1.4.2-cp313-cp313-win_amd64.whl
Algorithm Hash digest
SHA256 70ce38316d45898ab34a7843da7e050f8526bf71db3a2273b31437c7a2868054
MD5 c835323d2b3070a9532b3a653163d7d7
BLAKE2b-256 7962af36672cd1710a94247d94c6e617257fb77ab6c06d828d39b23beeb2fb37

See more details on using hashes here.

File details

Details for the file pyopenmagnetics-1.4.2-cp313-cp313-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl.

File metadata

File hashes

Hashes for pyopenmagnetics-1.4.2-cp313-cp313-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl
Algorithm Hash digest
SHA256 1854f5edd49edb9d6db08e9f53cbc839a8ea499bf2b7ebf59dc145d5721a6ef8
MD5 e8b3fa2f4333a8b649c8515322b41591
BLAKE2b-256 640e10310bcaf60bf8ee046176d4636109547539c27b6412b030f59082fca5c1

See more details on using hashes here.

File details

Details for the file pyopenmagnetics-1.4.2-cp312-cp312-win_amd64.whl.

File metadata

File hashes

Hashes for pyopenmagnetics-1.4.2-cp312-cp312-win_amd64.whl
Algorithm Hash digest
SHA256 3cbadd3043050eea4c5f4486f6e1947c68c9b84f9c5bf342c9b90ad33c3081a3
MD5 c82d389b5bb5b943f011be80331b574d
BLAKE2b-256 1276206afe479bf556c7e86fbb946e8048c6258a4bf242e2357e8456b7d12e3d

See more details on using hashes here.

File details

Details for the file pyopenmagnetics-1.4.2-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl.

File metadata

File hashes

Hashes for pyopenmagnetics-1.4.2-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl
Algorithm Hash digest
SHA256 94cb75150334f43cf05a5c903f3803577efa787ddb123b8ff249672f23b207a7
MD5 d380fe34989b9b5957025db5011b3dc8
BLAKE2b-256 f7f7ef0c748441b6fa392883536cd423aa98e0891df3d7ace44e7c360324a023

See more details on using hashes here.

File details

Details for the file pyopenmagnetics-1.4.2-cp311-cp311-win_amd64.whl.

File metadata

File hashes

Hashes for pyopenmagnetics-1.4.2-cp311-cp311-win_amd64.whl
Algorithm Hash digest
SHA256 71604eebed956b132421c4e343fcbca5f984f02835bdf0cd80e9be81643d468f
MD5 81755d3052fa1aa57b40b9070a6a65db
BLAKE2b-256 a674f942d8aa74ce3c0d6a47a13dc75647dd97064ecb480847a9e82d6a6812a0

See more details on using hashes here.

File details

Details for the file pyopenmagnetics-1.4.2-cp311-cp311-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl.

File metadata

File hashes

Hashes for pyopenmagnetics-1.4.2-cp311-cp311-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl
Algorithm Hash digest
SHA256 cd49122e5c747401a0f7d8f07105bf1ec94424f396a66b532ac177a5db2d7218
MD5 00a9cf642f0c98ad87dfa61ba09dea3c
BLAKE2b-256 fdc8233232f475ce06b80a800e1b2362f4bde5fd5d71284edf28be88d524c0b4

See more details on using hashes here.

File details

Details for the file pyopenmagnetics-1.4.2-cp310-cp310-win_amd64.whl.

File metadata

File hashes

Hashes for pyopenmagnetics-1.4.2-cp310-cp310-win_amd64.whl
Algorithm Hash digest
SHA256 688582979496e684a1f62ac700607657602efbb4d1a2915951e25e3152a60889
MD5 7622ccb0785c5d6dc5899ed8f078016d
BLAKE2b-256 8e9580f36fd45fdf5cd46631ab500b20a87b8c99c76f32881e75e1c57b09082f

See more details on using hashes here.

File details

Details for the file pyopenmagnetics-1.4.2-cp310-cp310-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl.

File metadata

File hashes

Hashes for pyopenmagnetics-1.4.2-cp310-cp310-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl
Algorithm Hash digest
SHA256 2b357f0441b40435f5da6f103416930f89154693876db46a808fecc2a8e78516
MD5 28147b457d8b6b454e91d5613a23a4aa
BLAKE2b-256 5c6f9821525b672e83d0dce5fbb6d6cf4dd307f7e3fc2179764c270e141ad503

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page