tlmfoundationcosmetics.com

Visualizing Magnetic Fields in Python: A Matplotlib Guide

Written on

Understanding the Biot-Savart Law

In this article, we will explore the visualization of magnetic fields generated by electric currents through the application of the Biot-Savart law. Additionally, we will present Python code snippets to demonstrate how to create magnetic field plots for various current configurations.

The Biot-Savart Law Explained

The Biot-Savart law articulates how a magnetic field is established by a wire carrying an electric current. Specifically, it indicates that the magnetic field at a certain location is directly related to the current and the segment's length, while inversely related to the distance from the segment to that location. The mathematical representation of the law is as follows:

B⃗ = (μ₀ / 4π) ∫ (I * dl⃗ × r̂) / r²

Here, B⃗ denotes the magnetic field vector at a position r, μ₀ represents the permeability of free space, I is the current flowing through the wire, dl⃗ is an infinitesimal segment of the wire, r' is the vector connecting the segment to the point r, and the integral covers the entire wire.

By utilizing the Biot-Savart law, we can determine the magnetic field at any point around a current-carrying wire. For a straight wire, the magnetic field can be computed using the formula:

B = (μ₀ * I) / (2 * π * r)

where I is the current in the wire, r is the distance from the wire to the observation point, and ẑ is the unit vector in the direction of the wire (the z-axis).

Visualizing Magnetic Field Lines

To illustrate the magnetic field, we can leverage Python along with the Matplotlib library to generate plots of the field lines. Below is an example code snippet for a straight wire:

import numpy as np

import matplotlib.pyplot as plt

# Define current strength and position

I = 1.0 # Current strength

x_c = 0.0 # x-coordinate of the current

y_c = 0.0 # y-coordinate of the current

# Create a mesh grid of points

x, y = np.meshgrid(np.linspace(-2, 2, 200), np.linspace(-2, 2, 200))

# Calculate the magnetic field components

r = np.sqrt((x - x_c) ** 2 + (y - y_c) ** 2)

B_x = I * (y - y_c) / r ** 3

B_y = -I * (x - x_c) / r ** 3

# Generate the plot for magnetic field lines

fig, ax = plt.subplots(figsize=(8, 8))

ax.streamplot(x, y, B_x, B_y, color='blue', linewidth=1, density=1, arrowstyle='->')

# Add the wire to the plot

circle = plt.Circle((x_c, y_c), 0.1, color='red')

ax.add_artist(circle)

# Set limits and labels for the plot

ax.set_xlim(-2, 2)

ax.set_ylim(-2, 2)

ax.set_xlabel('x')

ax.set_ylabel('y')

# Display the plot

plt.show()

This code initializes the current strength and location, along with creating a mesh grid of points for magnetic field calculations. It computes the magnetic field components and visualizes them using the streamplot function from Matplotlib. A red circle represents the wire, with appropriate axis limits and labels.

We can observe that the field lines form circular patterns around the wire.

Next, we can extend this visualization to 3D using the quiver function from Matplotlib:

import numpy as np

import matplotlib.pyplot as plt

from mpl_toolkits.mplot3d import Axes3D

# Define current strength and position

I = 1.0 # Current strength

x_c = 0.0 # x-coordinate of the current

y_c = 0.0 # y-coordinate of the current

# Create a mesh grid of points

x, y, z = np.meshgrid(np.linspace(-2, 2, 20),

np.linspace(-2, 2, 20),

[0])

# Calculate the magnetic field components

r = np.sqrt((x - x_c) ** 2 + (y - y_c) ** 2 + (z) ** 2)

B_x = I * (y - y_c) / r ** 3

B_y = -I * (x - x_c) / r ** 3

B_z = np.zeros_like(r)

# Create the figure and axes

fig = plt.figure(figsize=(8, 8))

ax = fig.add_subplot(111, projection='3d')

# Generate the quiver plot for the magnetic field

ax.quiver(x, y, z, B_x, B_y, B_z, length=0.2, normalize=True)

# Plot the wire carrying the current

z_wire = np.linspace(-2, 2, 50)

x_wire = np.zeros_like(z_wire)

y_wire = np.zeros_like(z_wire)

ax.plot(x_wire, y_wire, z_wire, lw=3, color='red')

# Set limits and labels for the plot

ax.set_xlim(-2, 2)

ax.set_ylim(-2, 2)

ax.set_zlim(-2, 2)

ax.set_xlabel('x')

ax.set_ylabel('y')

ax.set_zlabel('z')

# Display the plot

plt.show()

This example sets up the current strength, position, and a mesh grid for magnetic field calculations in 3D. It calculates the magnetic field components and creates a 3D quiver plot to visualize the field. A red line represents the current-carrying wire, with defined plot limits and axis labels.

Exploring Multiple Current-Carrying Wires

To visualize the magnetic field produced by multiple current-carrying wires, we can modify our approach. Below is a code snippet designed for two parallel wires. The plotting code is encapsulated in a function to enable easy plotting of different configurations:

import numpy as np

import matplotlib.pyplot as plt

def plot_parallel_wires(I_1, x_c1, y_c1, I_2, x_c2, y_c2):

# Create mesh grid of points

x, y = np.meshgrid(np.linspace(-2, 2, 200), np.linspace(-2, 2, 200))

# Calculate magnetic field components due to the first current

r1 = np.sqrt((x - x_c1) ** 2 + (y - y_c1) ** 2)

B_x1 = I_1 * (y - y_c1) / r1 ** 3

B_y1 = -I_1 * (x - x_c1) / r1 ** 3

# Calculate magnetic field components due to the second current

r2 = np.sqrt((x - x_c2) ** 2 + (y - y_c2) ** 2)

B_x2 = I_2 * (y - y_c2) / r2 ** 3

B_y2 = -I_2 * (x - x_c2) / r2 ** 3

# Combine magnetic field contributions

B_x = B_x1 + B_x2

B_y = B_y1 + B_y2

# Generate the plot for magnetic field lines

fig, ax = plt.subplots(figsize=(8, 8))

ax.streamplot(x, y, B_x, B_y, color='blue', linewidth=1, density=1, arrowstyle='->')

# Add the wires to the plot

circle1 = plt.Circle((x_c1, y_c1), 0.1, color='red')

ax.add_artist(circle1)

circle2 = plt.Circle((x_c2, y_c2), 0.1, color='red')

ax.add_artist(circle2)

# Set limits and labels for the plot

ax.set_xlim(-2, 2)

ax.set_ylim(-2, 2)

ax.set_xlabel('x')

ax.set_ylabel('y')

# Display the plot

plt.show()

To visualize two parallel wires carrying current in the same direction, you would call:

plot_parallel_wires(1.0, -1.0, 0.0, 1.0, 1.0, 0.0)

Conversely, for wires with currents flowing in opposite directions, you would use:

plot_parallel_wires(1.0, -1.0, 0.0, -1.0, 1.0, 0.0)

The latter scenario demonstrates the magnetic field lines characteristic of a ring current.

In conclusion, Matplotlib offers robust capabilities for visualizing magnetic fields and other vector fields. With these tools, we can create detailed visual representations of magnetic field lines and streamlines while incorporating current-carrying wires as visual elements. Such visualizations enhance our understanding of intricate electromagnetic phenomena and find applications across physics, engineering, and various other domains.

Visual Model of the Magnetic Field

This video provides a comprehensive overview of building a visual model of magnetic fields using Python, focusing on practical applications and examples.

Understanding Magnetic Field Visualization

This lesson covers how to visualize the magnetic field generated by a moving point charge using Python, offering insights into the underlying physics.

Share the page:

Twitter Facebook Reddit LinkIn

-----------------------

Recent Post:

Unraveling the Abyss: A Lovecraftian Tale of Recursive Horror

A chilling exploration of recursion and its dark implications in a Lovecraftian context.

Understanding the Limitations of Fitness Trackers

Exploring how fitness trackers can mislead our understanding of well-being.

Rediscovering Minimalism: The Kilobyte’s Gambit in Chess Coding

The Kilobyte's Gambit showcases how chess can be played using just 1KB of code, highlighting the importance of clean programming in today's tech landscape.

Strategies for Rapidly Growing Your Startup: A Comprehensive Guide

Discover effective strategies to accelerate the growth of your startup with actionable tips and insights.

Mastering the Art of Freelancing: Balancing Multiple Projects

Discover effective strategies for managing multiple freelance projects while maintaining balance and efficiency.

Exploring Near-Death Experiences: Insights and Implications

Discover the impact of near-death experiences on beliefs about life and death, and the psychological changes they may induce.

The Future of Autonomous Vehicles: A Glimpse into 2030

Discover how autonomous vehicles are transforming transportation by 2030, enhancing mobility and redefining our relationship with driving.

Bitcoin's Historic Adoption in Africa Amidst Global Conflicts

The Central African Republic adopts Bitcoin as legal tender, raising questions about its implications amidst geopolitical tensions.