今天介绍在python中使用PySpice来进行电路仿真分析,这不是完全的python来进行,而是使用了ngspice这个开源的软件来进行分析。

首先是安装ngspice,参考网址:Ngspice, the open source Spice circuit simulator​ngspice.sourceforge.net

这里简单介绍一下:

【1】在windows下,可以直接下载:http://sourceforge.net/projects/ngspice/files/ng-spice-rework/31/ngspice-31_64.zip​sourceforge.net

下载完就安装,另外,如果想让pyspice使用ngspice的动态链接库的模式,必须到:Browse /ng-spice-rework/31 at SourceForge.net​sourceforge.net

下载:ngspice-30_dll_64.zip 文件,并解压缩到C:\Program Files\Spice64_dll目录。

当然也可以使用GUI版本,具体参考上面的网页。

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

【2】在linux下,可以下载源码自己编译,但是我自己编译有不少问题,如果在Ubuntu下,可以直接下载二进制的编译好的版本:

【2.1】在Ubuntu 18.04,可以安装ngspice 2.7:

sudo apt update

sudo apt install ngspice

【2.2】在Ubuntu 19.10,会安装ngspice 3.0,安装命令同上。

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

【3】接下来安装PySpice,为了解决其中一些相互冲突的包,推荐用anaconda创建一个新的环境并安装相关的包:

conda create -n spice

conda activate spice

conda install python ipython numpy scipy matplotlib -y

pip install pyspice

另外,例子是不会被安装的,而且其中也包含了很重要的元器件库的文件,所以还需要下载源程序文件,其中包括了例子和元器件库文件:

cd ~

mkdir ngspice

cd ngspice

git clone https://github.com/FabriceSalvaire/PySpice.git

注意例子现在安装在~/ngspice/PySpice/examples/下,元器件库安装在~/ngspice/PySpice/examples/libraries下,这个在后面的程序中可以设置。

如果是在windows下,修改为对应的路径。

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

【4】接下来,编写个简单的程序测试一下:

下面的例子主要是分析二极管的特性曲线,参考网页:8.4.2. Diode Characteristic Curve​pyspice.fabrice-salvaire.fr

程序: demo1.py:

import numpy as np

import matplotlib.pyplot as plt

import matplotlib.ticker as ticker

import PySpice.Logging.Logging as Logging

logger = Logging.setup_logging()

from PySpice.Spice.Netlist import Circuit

from PySpice.Spice.Library import SpiceLibrary

from PySpice.Unit import *

from PySpice.Physics.SemiConductor import ShockleyDiode

import PySpice

#设置ngspice是以subprocess的形式来使用

PySpice.Spice.Simulation.CircuitSimulator.DEFAULT_SIMULATOR = 'ngspice-subprocess'

#元器件库所在的目录

libraries_path = "~/ngspice/PySpice/examples/libraries"

spice_library = SpiceLibrary(libraries_path)

circuit = Circuit('Diode Characteristic Curve')

circuit.include(spice_library['1N4148']) #导入二极管元件:1N4148

circuit.V('input', 'in', circuit.gnd, 10@u_V)

circuit.R(1, 'in', 'out', 1@u_Ω) # not required for simulation

circuit.X('D1', '1N4148', 'out', circuit.gnd)

# Fixme: Xyce ???

temperatures = [0, 25, 100]@u_Degree

analyses = {}

#分析不同温度下的二极管的特性

for temperature in temperatures:

#创建仿真器

simulator = circuit.simulator(temperature=temperature,

nominal_temperature=temperature)

#进行直流分析:DC, 电压从-2V -- 5V, 步进: 0.01V

analysis = simulator.dc(Vinput=slice(-2, 5, .01))

analyses[float(temperature)] = analysis

silicon_forward_voltage_threshold = .7

shockley_diode = ShockleyDiode(Is=4e-9, degree=25)

def two_scales_tick_formatter(value, position):

if value >= 0:

return '{}mA'.format(value)

else:

return '{}nA'.format(value/100)

formatter = ticker.FuncFormatter(two_scales_tick_formatter)

figure = plt.figure(1, (20, 10))

axe = plt.subplot(121)

axe.set_title('1N4148 Characteristic Curve ')

axe.set_xlabel('Voltage [V]')

axe.set_ylabel('Current')

axe.grid()

axe.set_xlim(-2, 2)

axe.axvspan(-2, 0, facecolor='green', alpha=.2)

axe.axvspan(0, silicon_forward_voltage_threshold, facecolor='blue', alpha=.1)

axe.axvspan(silicon_forward_voltage_threshold, 2, facecolor='blue', alpha=.2)

axe.set_ylim(-500, 750) # Fixme: round

axe.yaxis.set_major_formatter(formatter)

Vd = analyses[25].out

# compute scale for reverse and forward region

forward_region = Vd >= 0@u_V

reverse_region = np.invert(forward_region)

scale = reverse_region*1e11 + forward_region*1e3

for temperature in temperatures:

analysis = analyses[float(temperature)]

axe.plot(Vd, - analysis.Vinput * scale)

axe.plot(Vd, shockley_diode.I(Vd) * scale, 'black')

axe.legend(['@{}°C'.format(temperature)

for temperature in temperatures] + ['Shockley Diode Model Is = 4 nA'],

loc=(.02,.8))

axe.axvline(x=0, color='black')

axe.axhline(y=0, color='black')

axe.axvline(x=silicon_forward_voltage_threshold, color='red')

axe.text(-1, -100, 'Reverse Biased Region', ha='center', va='center')

axe.text( 1, -100, 'Forward Biased Region', ha='center', va='center')

axe = plt.subplot(122)

axe.set_title('Resistance @ 25 °C')

axe.grid()

axe.set_xlim(-2, 3)

axe.axvspan(-2, 0, facecolor='green', alpha=.2)

axe.axvspan(0, silicon_forward_voltage_threshold, facecolor='blue', alpha=.1)

axe.axvspan(silicon_forward_voltage_threshold, 3, facecolor='blue', alpha=.2)

analysis = analyses[25]

static_resistance = -analysis.out / analysis.Vinput

dynamic_resistance = np.diff(-analysis.out) / np.diff(analysis.Vinput)

axe.semilogy(analysis.out, static_resistance, basey=10)

axe.semilogy(analysis.out[10:-1], dynamic_resistance[10:], basey=10)

axe.axvline(x=0, color='black')

axe.axvline(x=silicon_forward_voltage_threshold, color='red')

axe.axhline(y=1, color='red')

axe.text(-1.5, 1.1, 'R limitation = 1 Ω', color='red')

axe.legend(['{}Resistance'.format(x) for x in ('Static', 'Dynamic')], loc=(.05,.2))

axe.set_xlabel('Voltage [V]')

axe.set_ylabel('Resistance [Ω]')

plt.tight_layout()

plt.show()

然后在spice环境下,运行:

conda activate spice

python demo1.py

结果:

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐