Skip to main content

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 .

Build provenance

The build compiles MKF by globbing its .cpp files directly into the extension, tracking MKF/MAS main, and builds the Kirchhoff converter-model library (libKirchhoffApi.so) as an ExternalProject. The exact engine commits a wheel was compiled from are baked into the package:

import PyOpenMagnetics
print(PyOpenMagnetics.__mkf_commit__)  # MKF SHA this wheel was built from
print(PyOpenMagnetics.__mas_commit__)  # MAS SHA this wheel was built from

A clean rebuild:

rm -rf build && pip install . --no-deps -v

Importing and error handling

import PyOpenMagnetics works like any other package. Since v1.7.0 every engine failure raises PyOpenMagnetics.EngineError (a RuntimeError subclass) — functions never return error strings or {"data": "<error>"} objects:

import PyOpenMagnetics

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

try:
    PyOpenMagnetics.find_core_shape_by_name("No Such Shape")
except PyOpenMagnetics.EngineError as e:
    print(f"Engine error: {e}")

The only exception is the plotting family, which returns a discriminated union {"success": bool, "error": str, ...} that callers branch on.

See AGENTS.md for more usage guidance.

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. "type" is mandatory; shape/material accept
# either the objects fetched above or plain name strings.
core_data = {
    "functionalDescription": {
        "type": "two-piece set",
        "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

# A complete core (see "Creating a Core" above)
core = PyOpenMagnetics.calculate_core_data({
    "functionalDescription": {
        "type": "two-piece set",
        "shape": "E 42/21/15",
        "material": "3C95",
        "gapping": [{"type": "subtractive", "length": 0.0005}],
        "numberStacks": 1
    }
}, True)

# A wound coil on that core
bobbin = PyOpenMagnetics.create_basic_bobbin(core, True)
coil = PyOpenMagnetics.wind({
    "bobbin": bobbin,
    "functionalDescription": [{
        "name": "Primary",
        "numberTurns": 20,
        "numberParallels": 1,
        "isolationSide": "primary",
        "wire": "Round 0.5 - Grade 1"
    }]
}, 1, [1.0], [0], [])

# Inputs with the excitation waveforms (see the Design Adviser example)
inputs = PyOpenMagnetics.process_inputs({
    "designRequirements": {
        "magnetizingInductance": {"nominal": 100e-6},
        "turnsRatios": []
    },
    "operatingPoints": [{
        "name": "Nominal",
        "conditions": {"ambientTemperature": 25},
        "excitationsPerWinding": [{
            "name": "Primary",
            "frequency": 100000,
            "current": {"waveform": {"data": [-1, 1, -1], "time": [0, 5e-6, 10e-6]}},
            "voltage": {"waveform": {"data": [50, 50, -50, -50], "time": [0, 5e-6, 5e-6, 10e-6]}}
        }]
    }]
})

models = {"coreLosses": "IGSE", "reluctance": "ZHANG"}
losses = PyOpenMagnetics.calculate_core_losses(core, coil, inputs, models)
print(f"Core losses: {losses['coreLosses']} W")

Winding a Coil

import PyOpenMagnetics

# core from calculate_core_data(...) as above
bobbin = PyOpenMagnetics.create_basic_bobbin(core, True)

coil_spec = {
    "bobbin": bobbin,
    "functionalDescription": [
        {
            "name": "Primary",
            "numberTurns": 50,
            "numberParallels": 1,
            "isolationSide": "primary",
            "wire": "Round 0.5 - Grade 1"
        },
        {
            "name": "Secondary",
            "numberTurns": 10,
            "numberParallels": 3,
            "isolationSide": "secondary",
            "wire": "Round 1.00 - Grade 1"
        }
    ]
}

# wind(coil, repetitions, proportion_per_winding, pattern, margin_pairs)
coil = PyOpenMagnetics.wind(coil_spec, 1, [0.5, 0.5], [0, 1], [])
print(f"Wound {len(coil['turnsDescription'])} turns")

Converter-Based Design

The converter surface builds complete MAS Inputs straight from converter specifications (the Kirchhoff topology designer sizes inductance, turns ratios and waveforms). See examples/converter_design_example.py for the full flow:

import PyOpenMagnetics

flyback_specs = {
    "inputVoltage": {"minimum": 185, "maximum": 265},
    "desiredInductance": 800e-6,      # optional pin; omit to let Kirchhoff size it
    "desiredTurnsRatios": [13.5],     # optional pin
    "efficiency": 0.88,
    "operatingPoints": [{
        "outputVoltages": [12.0],
        "outputCurrents": [2.0],
        "switchingFrequency": 100000,
        "ambientTemperature": 40
    }]
}

inputs = PyOpenMagnetics.process_converter("flyback", flyback_specs)
processed = PyOpenMagnetics.process_inputs(inputs)
result = PyOpenMagnetics.calculate_advised_magnetics(processed, 5, "standard cores")
for item in result["data"]:
    print(item["mas"]["magnetic"]["manufacturerInfo"]["reference"], item["scoring"])

A TAS-shaped spec (an object with designRequirements / operatingPoints[].outputs) is also accepted and passed to Kirchhoff untouched.

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, coil, inputs, models) Calculate core losses

Winding Functions

Function Description
wind(coil, repetitions, proportions, pattern, margins) 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. The converter spec is either the legacy flat shape shown in "Converter-Based Design" above (inputVoltage, optional desiredInductance/desiredTurnsRatios/efficiency/ currentRippleRatio, and operatingPoints[] with outputVoltages[]/ outputCurrents[]/switchingFrequency/ambientTemperature) or a TAS-shaped spec, which is passed through untouched. Failures raise PyOpenMagnetics.EngineError.

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:

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.7.3.tar.gz (686.8 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.7.3-cp313-cp313-win_amd64.whl (11.5 MB view details)

Uploaded CPython 3.13Windows x86-64

pyopenmagnetics-1.7.3-cp313-cp313-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl (14.1 MB view details)

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

pyopenmagnetics-1.7.3-cp312-cp312-win_amd64.whl (11.5 MB view details)

Uploaded CPython 3.12Windows x86-64

pyopenmagnetics-1.7.3-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl (14.1 MB view details)

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

pyopenmagnetics-1.7.3-cp311-cp311-win_amd64.whl (11.5 MB view details)

Uploaded CPython 3.11Windows x86-64

pyopenmagnetics-1.7.3-cp311-cp311-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl (14.1 MB view details)

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

pyopenmagnetics-1.7.3-cp310-cp310-win_amd64.whl (11.5 MB view details)

Uploaded CPython 3.10Windows x86-64

pyopenmagnetics-1.7.3-cp310-cp310-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl (14.1 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.7.3.tar.gz.

File metadata

  • Download URL: pyopenmagnetics-1.7.3.tar.gz
  • Upload date:
  • Size: 686.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/7.0.0 CPython/3.13.14

File hashes

Hashes for pyopenmagnetics-1.7.3.tar.gz
Algorithm Hash digest
SHA256 a64de3567ea20dddf0ec2ad5d904cb962ad3bc4a2de4730e868a8c512ef840a4
MD5 9f89072fbd3dd13e08e6b86700b20b52
BLAKE2b-256 8a4ee959bd5644840cce9d95a7667ead0262dd28f561c44969cf3535f4b87d50

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for pyopenmagnetics-1.7.3-cp313-cp313-win_amd64.whl
Algorithm Hash digest
SHA256 f5815d3937a6fa5e537ec18e7678f07d46a4fd5580f0fd13b5ce14e082dffdfb
MD5 ca1e3c61d70deaf798c520015f04f451
BLAKE2b-256 8f84231de3513dcc9dfb23aad26ae5b7b19c70ee10acfc43b5d26d27e77976d1

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for pyopenmagnetics-1.7.3-cp313-cp313-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl
Algorithm Hash digest
SHA256 3cdbd33cb1bee4d6f3b3ef9bd765842afc8f1d4628308822b7a244712d1c768d
MD5 6a09df33c68cb641bce8ca528196861b
BLAKE2b-256 229ac56485dcfb702f46889cc4086398eaaea90a3a2afc63f7d9df432d519c8c

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for pyopenmagnetics-1.7.3-cp312-cp312-win_amd64.whl
Algorithm Hash digest
SHA256 3e3a1ed797c25328fdd0930e9277fb4bd3a7e0129514b57acf3b12756548a342
MD5 e1afab80e138262061f10c6dc3895e81
BLAKE2b-256 7c66c6d8b16db99e31b0bb7c2ac55b58e2143c10f436b63d9b3809f19c29e9e1

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for pyopenmagnetics-1.7.3-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl
Algorithm Hash digest
SHA256 12c358ea5780faba1b361fb21126ead5515bc1c185fc75cae34a867537e3318d
MD5 31dd58fb61bd65af3459ffd390cba72a
BLAKE2b-256 7d9d964402d20f1f78f27e5177546b0e9a0f268ff63666036c27a61451562ac6

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for pyopenmagnetics-1.7.3-cp311-cp311-win_amd64.whl
Algorithm Hash digest
SHA256 b5d1ca5ba21c328395bdd8ba98509da487671e6070b99c276556dc329c1d8a2c
MD5 5eb2a17907766bbe50b7f5e310864537
BLAKE2b-256 e36547e37927b93d1462dc96b3c9e9b187d96947eec678e22f7aa347843463cd

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for pyopenmagnetics-1.7.3-cp311-cp311-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl
Algorithm Hash digest
SHA256 b8c3ec0967c41a2166893d9d92da0f5490ae3fc4cf02da3ebfc372b7451a2d8e
MD5 95c7d477be7a4fd3e4d150cf6052b650
BLAKE2b-256 8b85348f8bebffd3782f0d62445ca44e502ca81f7caf44b3c208e0b36ef8228d

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for pyopenmagnetics-1.7.3-cp310-cp310-win_amd64.whl
Algorithm Hash digest
SHA256 9dd591a2dafb7eea1996d86d4d2f6a1946931f38c8c46a2e9543946fc91624e5
MD5 682e1c913e39d23ca1bd001fd6a57a0a
BLAKE2b-256 c8ffd6a0549635978d001a2fc3cef20ccb234f53f433c774ade46bcd7b93d7e0

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for pyopenmagnetics-1.7.3-cp310-cp310-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl
Algorithm Hash digest
SHA256 c108161692d711d109912b6067338004bd451420a5bc6f19758459637060e0e7
MD5 be42b2a85cc0b5987743906ebea2ec76
BLAKE2b-256 7f687d01bc978ac86ed550d0b44b3080e517673e876e5b8bb668edc18bff42e2

See more details on using hashes here.

Release history Release notifications | RSS feed

1.7.15

11 files

1.7.14

1 file

1.7.13

11 files

1.7.12

11 files

1.7.11

11 files

1.7.10

11 files

1.7.9

6 files

1.7.8

11 files

1.7.7

11 files

1.7.6

11 files

1.7.5

11 files

1.7.4

9 files

This release

1.7.3 This release

9 files

1.7.2

9 files

1.7.1

9 files

1.7.0

9 files

1.6.6

9 files

1.6.5

9 files

1.6.4

9 files

1.6.3

9 files

1.6.2

9 files

1.6.1

9 files

1.6.0

5 files

1.5.1

5 files

1.5.0

5 files

1.4.6

9 files

1.4.5

9 files

1.4.4

9 files

1.4.3

9 files

1.4.2

9 files

1.4.1

9 files

1.4.0

11 files

1.3.13

9 files

1.3.12

9 files

1.3.10

5 files

1.3.9

5 files

1.3.8

8 files

1.3.6

13 files

1.3.5

5 files

1.3.4

5 files

1.3.3

5 files

1.3.2

5 files

1.3.1

5 files

1.3.0

13 files

1.2.2

13 files

1.2.1

13 files

1.2.0

13 files

1.1.5

13 files

1.1.4

13 files

1.1.3

13 files

1.1.2

13 files

1.1.0

13 files

1.0.2

12 files

1.0.1

12 files

1.0.0

5 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page