You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决运行magpylib示例时报错AttributeError: module 'magpylib' has no attribute 'source'

问题原因

你安装的是magpylib v4及以上版本,你运行的示例代码是magpylib v3及更早版本的旧API,版本API不兼容是报错的根本原因。

解决方案

这里提供两种可行方案,任选其一即可:

方案1:降级到v3版本直接运行原有代码

直接执行对应包管理命令安装兼容的旧版本:

  • pip用户执行:pip install magpylib==3.0.5
  • Anaconda用户执行:conda install magpylib=3.0.5

安装完成后直接运行你手头的示例代码即可正常运行。

方案2:修改代码适配v4版本新API

v4版本对API结构做了较大调整,修改后的适配代码如下:

# 导入依赖
import numpy as np
import matplotlib.pyplot as plt
import magpylib as magpy

# 创建磁铁
magnet1 = magpy.magnet.Box(magnetization=(0,0,600), dimension=(3,3,3), position=(-4,0,3))
magnet2 = magpy.magnet.Cylinder(magnetization=(0,0,500), dimension=(3,5), position=(0,0,0))

# 操作磁铁
magnet1.rotate_from_angax(45, [0,1,0], anchor=(0,0,0), degrees=True)
magnet2.move((5,0,-4))

# 收集磁铁对象
pmc = magpy.Collection(magnet1, magnet2)

# 展示系统几何结构
pmc.show()

# 计算网格上的B场
xs = np.linspace(-10,10,20)
zs = np.linspace(-10,10,20)
pos_grid = np.array([[(x,0,z) for x in xs] for z in zs])
Bs = magpy.getB(pmc, pos_grid)

# 使用matplotlib展示场分布
fig, ax = plt.subplots()
X,Y = np.meshgrid(xs,zs)
U,V = Bs[:,:,0], Bs[:,:,2]
ax.streamplot(X, Y, U, V, color=np.log(U**2+V**2), density=1.5)
plt.show()

修改说明:

  • 磁铁对象的导入路径从magpy.source.magnet简化为magpy.magnet
  • 参数名做了语义化调整:mag改为magnetization、dim改为dimension、pos改为position
  • 旋转方法从rotate调整为rotate_from_angax,新增degrees=True参数明确传入单位为角度
  • 系统展示方法从displaySystem改为show
  • B场计算支持直接传入网格位置数组,运算效率更高

内容的提问来源于stack exchange,提问作者Emil_K

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 08:36:03