def run(self, state=None, action=None, stepsize=None, **kwargs): """ Runs a simulation for the specified time. Passes simulation results to postprocess(). Args: state (list/tuple/ndarray): A vector of state variables that are used to change self.netlist and self.circuit action (list/tuple/ndarray): A vector of action variables that are used to change self.netlist and self.circuit stepsize (float): Time over which to run simulation. Defaults to self.timestep if None. Returns: A vector of state variables describing the new state. """ stepsize = self.stepsize if stepsize is None else stepsize if state is not None or action is not None: self.set_state(state, action) # Setting initial conditions to either Operating Point or values # provided to the class. x0 = 'op' if len(self.ic) == 0 else ahkab.new_x0(self.circuit, self.ic) tran = ahkab.new_tran(tstart=0, tstop=stepsize, tstep=self.timestep,\ x0=x0, method=ahkab.transient.TRAP) res = ahkab.run(self.circuit, tran)['tran'] return self.postprocess(state, action, res)
def test(): """Test pulse and sin API""" step = devices.pulse(v1=0, v2=1, td=500e-9, tr=1e-12, pw=1, tf=1e-12, per=2) damped_sin = devices.sin(vo=0, va=1, td=500e-9, freq=15e3, theta=5e3, phi=90.) exp = devices.exp(v1=.5, v2=-.05, td1=0, tau1=20e-6, td2=400e-6, tau2=20e-6) mycircuit = circuit.Circuit(title="Butterworth Example circuit", filename=None) gnd = mycircuit.get_ground_node() mycircuit.add_resistor(part_id="R1", n1="n1", n2="n2", value=600) mycircuit.add_inductor(part_id="L1", n1="n2", n2="n3", value=15.24e-3) mycircuit.add_capacitor(part_id="C1", n1="n3", n2=gnd, value=119.37e-9) mycircuit.add_inductor(part_id="L2", n1="n3", n2="n4", value=61.86e-3) mycircuit.add_capacitor(part_id="C2", n1="n4", n2=gnd, value=155.12e-9) mycircuit.add_resistor(part_id="R2", n1="n4", n2=gnd, value=1.2e3) mycircuit.add_vsource("V1", n1="n1", n2='n5', dc_value=3.3333, ac_value=.33333, function=step) mycircuit.add_vsource("V2", n1="n5", n2='n6', dc_value=3.3333, ac_value=.33333, function=damped_sin) mycircuit.add_vsource("V3", n1="n6", n2=gnd, dc_value=3.3333, ac_value=.33333, function=exp) op_analysis = ahkab.new_op(outfile='time_functions') ac_analysis = ahkab.new_ac(start=1e3, stop=1e5, points=100, outfile='time_functions') tran_analysis = ahkab.new_tran(tstart=0, tstop=1.2e-3, tstep=1e-6, x0=None, outfile='time_functions') testbench = testing.APITest('time_functions', mycircuit, [op_analysis, ac_analysis, tran_analysis], skip_on_travis=True, er=1e-3, ea=1e-5) testbench.setUp() testbench.test() if cli: r = ahkab.run(mycircuit, an_list=[op_analysis, ac_analysis, tran_analysis]) fig = plt.figure() plt.title(mycircuit.title + " - TRAN Simulation") plt.plot(r['tran']['T'], r['tran']['VN1'], label="Input voltage") plt.hold(True) plt.plot(r['tran']['T'], r['tran']['VN4'], label="output voltage") plt.legend() plt.hold(False) plt.grid(True) #plt.ylim([0,1.2]) plt.ylabel('Step response') plt.xlabel('Time [s]') fig.savefig('tran_plot.png') fig = plt.figure() plt.subplot(211) plt.semilogx(r['ac']['w'], np.abs(r['ac']['Vn4']), 'o-') plt.ylabel('abs(V(n4)) [V]') plt.title(mycircuit.title + " - AC Simulation") plt.subplot(212) plt.grid(True) plt.semilogx(r['ac']['w'], np.angle(r['ac']['Vn4']), 'o-') plt.xlabel('Angular frequency [rad/s]') plt.ylabel('arg(V(n4)) [rad]') fig.savefig('ac_plot.png') else: testbench.tearDown()
def test(): """Test pulse and sin API""" step = time_functions.pulse(v1=0, v2=1, td=500e-9, tr=1e-12, pw=1, tf=1e-12, per=2) damped_sin = time_functions.sin(vo=0, va=1, td=500e-9, freq=15e3, theta=5e3, phi=90.) exp = time_functions.exp(v1=.5, v2=-.05, td1=0, tau1=20e-6, td2=400e-6, tau2=20e-6) mycircuit = circuit.Circuit(title="Butterworth Example circuit", filename=None) gnd = mycircuit.get_ground_node() mycircuit.add_resistor(part_id="R1", n1="n1", n2="n2", value=600) mycircuit.add_inductor(part_id="L1", n1="n2", n2="n3", value=15.24e-3) mycircuit.add_capacitor(part_id="C1", n1="n3", n2=gnd, value=119.37e-9) mycircuit.add_inductor(part_id="L2", n1="n3", n2="n4", value=61.86e-3) mycircuit.add_capacitor(part_id="C2", n1="n4", n2=gnd, value=155.12e-9) mycircuit.add_resistor(part_id="R2", n1="n4", n2=gnd, value=1.2e3) mycircuit.add_vsource("V1", n1="n1", n2='n5', dc_value=3.3333, ac_value=.33333, function=step) mycircuit.add_vsource("V2", n1="n5", n2='n6', dc_value=3.3333, ac_value=.33333, function=damped_sin) mycircuit.add_vsource("V3", n1="n6", n2=gnd, dc_value=3.3333, ac_value=.33333, function=exp) op_analysis = ahkab.new_op(outfile='time_functions') ac_analysis = ahkab.new_ac(start=1e3, stop=1e5, points=100, outfile='time_functions') tran_analysis = ahkab.new_tran(tstart=0, tstop=1.2e-3, tstep=1e-6, x0=None, outfile='time_functions') testbench = testing.APITest('time_functions', mycircuit, [op_analysis, ac_analysis, tran_analysis], skip_on_travis=True, er=1e-3, ea=1e-5) testbench.setUp() testbench.test() if cli: r = ahkab.run(mycircuit, an_list=[op_analysis, ac_analysis, tran_analysis]) fig = plt.figure() plt.title(mycircuit.title + " - TRAN Simulation") plt.plot(r['tran']['T'], r['tran']['VN1'], label="Input voltage") plt.hold(True) plt.plot(r['tran']['T'], r['tran']['VN4'], label="output voltage") plt.legend() plt.hold(False) plt.grid(True) #plt.ylim([0,1.2]) plt.ylabel('Step response') plt.xlabel('Time [s]') fig.savefig('tran_plot.png') fig = plt.figure() plt.subplot(211) plt.semilogx(r['ac']['w'], np.abs(r['ac']['Vn4']), 'o-') plt.ylabel('abs(V(n4)) [V]') plt.title(mycircuit.title + " - AC Simulation") plt.subplot(212) plt.grid(True) plt.semilogx(r['ac']['w'], np.angle(r['ac']['Vn4']), 'o-') plt.xlabel('Angular frequency [rad/s]') plt.ylabel('arg(V(n4)) [rad]') fig.savefig('ac_plot.png') else: testbench.tearDown()
def processFunc(ec): ec.setCircuit() returnHighFunctioning = False try: tran = ahkab.new_tran(tstart=0., tstop=ec.electricWorld.t, tstep=ec.electricWorld.t / 2, method='trap') ahkab.run(ec.circuit, tran)['tran'] returnHighFunctioning = True except: pass if returnHighFunctioning: tran = ahkab.new_tran(tstart=0., tstop=ec.electricWorld.t, tstep=ec.electricWorld.tstep, method='trap') return ahkab.run(ec.circuit, tran)['tran']
def setUp(self): ttn = ahkab.Circuit('Twin-T Notch Stopband filter') rect_wave = ahkab.time_functions.pulse(v1=-1, v2=+1, td=0, tr=10e-6, pw=90e-6, tf=10e-6, per=200e-6) ttn.add_vsource('V1', 'in', ttn.gnd, dc_value=1, ac_value=1, function=rect_wave) # first path ttn.add_capacitor('C1', 'in', 'n1', 2.2e-12) ttn.add_capacitor('C2', 'n1', 'out', 2.2e-12) ttn.add_resistor('R1', 'n1', ttn.gnd, 1e3) # second path ttn.add_resistor('R2', 'in', 'n2', 2e3) ttn.add_resistor('R3', 'n2', 'out', 2e3) ttn.add_capacitor('C3', 'n2', ttn.gnd, 2*2.2e-12) ttn.add_vcvs('E1', 'outb', ttn.gnd, 'out', ttn.gnd, 1.) # create a simulation object and run it! # using no step control, we know EXACTLY what the time # axis looks like. Easier for testing. tra = ahkab.new_tran(0, 50e-6, tstep=5e-6, x0=None, use_step_control=False) self.r = ahkab.run(ttn, tra)['tran']
mycircuit.add_resistor("R1", n1="n1", n2="n2", value=600) mycircuit.add_inductor("L1", n1="n2", n2="n3", value=15.24e-3) mycircuit.add_capacitor("C1", n1="n3", n2=gnd, value=119.37e-9) mycircuit.add_inductor("L2", n1="n3", n2="n4", value=61.86e-3) mycircuit.add_capacitor("C2", n1="n4", n2=gnd, value=155.12e-9) mycircuit.add_resistor("R2", n1="n4", n2=gnd, value=1.2e3) voltage_step = time_functions.pulse(v1=0, v2=1, td=500e-9, tr=1e-12, pw=1, tf=1e-12, per=2) mycircuit.add_vsource("V1", n1="n1", n2=gnd, dc_value=5, ac_value=1, function=voltage_step) print mycircuit op_analysis = ahkab.new_op() ac_analysis = ahkab.new_ac(start=1e3, stop=1e5, points=100) tran_analysis = ahkab.new_tran(tstart=0, tstop=1.2e-3, tstep=1e-6, x0=None) r = ahkab.run(mycircuit, an_list=[op_analysis, ac_analysis, tran_analysis]) import pylab fig = pylab.figure() pylab.title(mycircuit.title + " - TRAN Simulation") pylab.plot(r['tran']['T'], r['tran']['VN1'], label="Input voltage") pylab.hold(True) pylab.plot(r['tran']['T'], r['tran']['VN4'], label="output voltage") pylab.legend() pylab.hold(False) pylab.grid(True) pylab.ylim([0,1.2]) pylab.ylabel('Step response')
tr=1e-12, pw=1, tf=1e-12, per=2) mycircuit.add_vsource("V1", n1="n1", n2=gnd, dc_value=5, ac_value=1, function=voltage_step) print mycircuit op_analysis = ahkab.new_op() ac_analysis = ahkab.new_ac(start=1e3, stop=1e5, points=100) tran_analysis = ahkab.new_tran(tstart=0, tstop=1.2e-3, tstep=1e-6, x0=None) r = ahkab.run(mycircuit, an_list=[op_analysis, ac_analysis, tran_analysis]) import pylab fig = pylab.figure() pylab.title(mycircuit.title + " - TRAN Simulation") pylab.plot(r['tran']['T'], r['tran']['VN1'], label="Input voltage") pylab.hold(True) pylab.plot(r['tran']['T'], r['tran']['VN4'], label="output voltage") pylab.legend() pylab.hold(False) pylab.grid(True) pylab.ylim([0, 1.2]) pylab.ylabel('Step response')
pw=0.5e-9, tf=1e-12, per=1) # voltage_step = time_functions.pulse(v1=0, v2=1, td=1e-12, tr=1e-15, pw=1, tf=1e-15, per=1) mycircuit.add_vsource("V1", n1="n1", n2=gnd, dc_value=0, ac_value=0.1, function=voltage_step) print mycircuit op_analysis = ahkab.new_op() ac_analysis = ahkab.new_ac(start=1e8, stop=5e10, points=1e2) tran_analysis = ahkab.new_tran(tstart=0, tstop=1e-9, tstep=1e-12, x0=None) # tran_analysis = ahkab.new_tran(tstart=0, tstop=10e-9, tstep=10e-12, x0=None) r = ahkab.run(mycircuit, an_list=[op_analysis, ac_analysis, tran_analysis]) # r = ahkab.run(mycircuit, an_list=[ac_analysis, tran_analysis]) import pylab fig = pylab.figure() pylab.title(mycircuit.title + " - TRAN Simulation") pylab.plot(r['tran']['T'], r['tran']['VN1'], label="Input voltage") pylab.hold(True) pylab.plot(r['tran']['T'], r['tran']['VN3'], label="output voltage") pylab.legend() pylab.hold(False) pylab.grid(True)
pw=1, tf=1e-12, per=2) # voltage_step = time_functions.pulse(v1=0, v2=1, td=0.1e-6, tr=1e-12, pw=0.5e-6, tf=1e-12, per=1.0e-6) mycircuit.add_vsource("V1", n1="n1", n2=gnd, dc_value=0, ac_value=0.1, function=voltage_step) print mycircuit # op_analysis = ahkab.new_op() ac_analysis = ahkab.new_ac(start=1e6, stop=1e11, points=1e2) tran_analysis = ahkab.new_tran(tstart=0, tstop=14e-6, tstep=0.1e-6, x0=None) # r = ahkab.run(mycircuit, an_list=[op_analysis, ac_analysis, tran_analysis]) r = ahkab.run(mycircuit, an_list=[ac_analysis, tran_analysis]) import pylab fig = pylab.figure() pylab.title(mycircuit.title + " - TRAN Simulation") pylab.plot(r['tran']['T'] * 1e6, r['tran']['VN1'], label="Input voltage") pylab.hold(True) pylab.plot(r['tran']['T'] * 1e6, r['tran']['VN2'], label="output voltage") pylab.legend() pylab.hold(False) pylab.grid(True) pylab.ylim([0, 2.0])
def test(): """Full wave rectifier test circuit""" cir = assemble() ## define analyses op1 = ahkab.new_op(outfile='rectifier') tran1 = ahkab.new_tran(0, 200e-3, 1e-4, outfile='rectifier', verbose=0+cli*6) # set the options sim_opts = {} sim_opts.update({'gmin':1e-7}) sim_opts.update({'nl_voltages_lock':False}) sim_opts.update({'nl_voltages_lock_factor':20}) sim_opts.update({'iea':1e-1}) sim_opts.update({'default_tran_method':'TRAP'}) sim_opts.update({'hmin':1e-20}) sim_opts.update({'transient_max_nr_iter':200}) ## create a testbench testbench = testing.APITest('rectifier', cir, [op1, tran1], skip_on_travis=True, sim_opts=sim_opts, ea=1e-1, er=1.) ## setup and test testbench.setUp() testbench.test() ## this section is recommended. If something goes wrong, you may call the ## test from the cli and the plots to video in the following will allow ## for quick inspection if cli: ## re-run the test to grab the results cir = assemble() res = ahkab.run(cir, an_list=[op1, tran1]) # print-out for good measure print("OP Results:") print(list(res['op'].items())) ## plot and save interesting data fig = plt.figure() plt.title(cir.title + " inputs") plt.plot(res['tran'].get_x(), res['tran']['VINA']-res['tran']['VINB'], label='Transf. input') plt.hold(True) plt.plot(res['tran'].get_x(), res['tran']['vint1'], label='Transformer output #1') plt.plot(res['tran'].get_x(), res['tran']['vint2'], label='Transformer output #2') plt.hold(False) plt.grid(True) plt.legend() plt.ylabel('Voltage [V]') plt.xlabel('Time [s]') fig.savefig('rectf1_plot.png') fig = plt.figure() plt.title(cir.title + " outputs") plt.plot(res['tran'].get_x(), res['tran']['vint4']-res['tran']['vint3'], label="output voltage") plt.legend() plt.grid(True) plt.ylabel('Voltage [V]') plt.xlabel('Time [s]') fig.savefig('rectf2_plot.png') else: testbench.tearDown()
c.add_inductor('L3', 'n3', c.gnd, L) c.add_capacitor('C3', 'n3', c.gnd, C) # tank4 c.add_inductor('L4', 'n4', c.gnd, L) c.add_capacitor('C4', 'n4', c.gnd, C) # Interferência destrutiva x0 = ahkab.new_x0(c, { 'V(n1)': -0.2 / C, 'V(n2)': -0.1 / C, 'V(n3)': 0.1 / C, 'V(n4)': 0.2 / C }) tran = ahkab.new_tran(tstart=0.0, tstop=(L * C)**0.5 * 100, tstep=1e-3, x0=x0, outfile='results') res = ahkab.run(c, tran)['tran'] plt.plot(res.get_x(), res['VN1']) plt.plot(res.get_x(), res['VN2']) plt.plot(res.get_x(), res['VN3']) plt.plot(res.get_x(), res['VN4']) plt.savefig('interferencia.png') plt.show() # Sincronização x0 = ahkab.new_x0(c, { 'V(n1)': 0.1 / C, 'V(n2)': 0.2 / C, 'V(n3)': 0.3 / C, 'V(n4)': 0.4 / C
def CircuitAnalysis(components, parameters): for i in components: if 'r' in i[0]: if (i[2] == '0'): cir.add_resistor(i[0], gnd, i[3], i[1]) elif (i[3] == '0'): cir.add_resistor(i[0], i[2], gnd, i[1]) else: cir.add_resistor(i[0], i[2], i[3], i[1]) elif 'c' in i[0]: if (i[2] == '0'): cir.add_capacitor(i[0], gnd, i[3], i[1]) elif (i[3] == '0'): cir.add_capacitor(i[0], i[2], gnd, i[1]) else: cir.add_capacitor(i[0], i[2], i[3], i[1]) elif 'i' in i[0]: if (i[2] == '0'): cir.add_inductor(i[0], gnd, i[3], i[1]) elif (i[3] == '0'): cir.add_inductor(i[0], i[2], gnd, i[1]) else: cir.add_inductor(i[0], i[2], i[3], i[1]) elif 'vdc' in i[0]: if (i[2] == '0'): cir.add_vsource(i[0], gnd, i[3], i[1]) elif (i[3] == '0'): cir.add_vsource(i[0], i[2], gnd, i[1]) else: cir.add_vsource(i[0], i[2], i[3], i[1]) elif 'vac' in i[0]: mys = lambda t: 1 if not t else i[1] * math.sin(math.pi * i[ 4] / 180 + 2 * math.pi * i[5] * t) if (i[2] == '0'): cir.add_vsource(i[0], gnd, i[3], 1, function=mys) elif (i[3] == '0'): cir.add_vsource(i[0], gnd, i[3], 1, function=mys) else: cir.add_vsource(i[0], gnd, i[3], 1, function=mys) if parameters[1] == 'V': node1 = '' node2 = '' for i in components: if parameters[0] == i[0]: node1 = components[2] node2 = components[3] if node1 == '0': node1 = gnd elif node2 == '0': node2 = gnd break tran_analysis = new_tran(0, 100, 10000, x0=None) r = run(cir, tran_analysis) fig = plt.figure() plt.plot(r['tran']['T'], (r['tran']['V' + node1] - r['tran']['V' + node2]), label="Voltage across component") plt.legend() plt.plot() plt.grid(True) plt.ylabel('Voltage') plt.xlabel('Time [s]') fig.savefig('Volatge.png') elif parameters[1] == 'I': node1 = '' node2 = '' r = 0 i = 0 c = 0 for i in components: if parameters[0] == i[0]: node1 = components[2] node2 = components[3] if node1 == '0': node1 = gnd elif node2 == '0': node2 = gnd if 'r' in parameters[0]: r = components[1] elif 'c' in parameters[0]: c = components[1] elif 'i' in parameters[0]: i = components[1] break tran_analysis = new_tran(0, 100, 10000, x0=None) r = run(cir, tran_analysis) fig = plt.figure() plt.plot(r['tran']['T'], I(parameters[0]), label="Current across component") plt.legend() plt.plot() plt.grid(True) plt.ylabel('Current') plt.xlabel('Time [s]') fig.savefig('Current.png')
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License v2 # along with ahkab. If not, see <http://www.gnu.org/licenses/>. from __future__ import unicode_literals, print_function, division import numpy as np import ahkab cir = ahkab.Circuit('Test FOUR and FFT') #mys = lambda t: 1 if not t else math.sin(math.pi*1e4*t)/(math.pi*1e4*t) mys = ahkab.time_functions.sin(vo=0, va=1, freq=10e3) cir.add_resistor('R1', 'n1', cir.gnd, 1e3) cir.add_vsource('V1', 'n1', cir.gnd, 1, function=mys) tr = ahkab.new_tran(0, 1e-3, 1e-5, x0=None) r = ahkab.run(cir, tr)['tran'] def test_fourier(): """Test fourier.fourier() and printing.print_fourier()""" fs, F, THD = ahkab.fourier.fourier('vn1', r, 10e3) fs_ref = np.array([0., 10000., 20000., 30000., 40000., 50000., 60000., 70000., 80000., 90000.]) assert np.allclose(fs, fs_ref) assert np.argmax(abs(F)) == 1 assert len(F) == len(fs) == 10 assert abs(F[0]) < 1 assert THD < .1 ahkab.printing.print_fourier('vn1', fs, F, THD)
def test(): """Full wave rectifier test circuit""" cir = assemble() ## define analyses op1 = ahkab.new_op(outfile='rectifier') tran1 = ahkab.new_tran(0, 200e-3, 1e-4, outfile='rectifier', verbose=0 + cli * 6) # set the options sim_opts = {} sim_opts.update({'gmin': 1e-7}) sim_opts.update({'nl_voltages_lock': False}) sim_opts.update({'nl_voltages_lock_factor': 20}) sim_opts.update({'iea': 1e-1}) sim_opts.update({'default_tran_method': 'TRAP'}) sim_opts.update({'hmin': 1e-20}) sim_opts.update({'transient_max_nr_iter': 200}) ## create a testbench testbench = testing.APITest('rectifier', cir, [op1, tran1], skip_on_travis=True, sim_opts=sim_opts, ea=1e-1, er=1.) ## setup and test testbench.setUp() testbench.test() ## this section is recommended. If something goes wrong, you may call the ## test from the cli and the plots to video in the following will allow ## for quick inspection if cli: ## re-run the test to grab the results cir = assemble() res = ahkab.run(cir, an_list=[op1, tran1]) # print-out for good measure print("OP Results:") print(list(res['op'].items())) ## plot and save interesting data fig = plt.figure() plt.title(cir.title + " inputs") plt.plot(res['tran'].get_x(), res['tran']['VINA'] - res['tran']['VINB'], label='Transf. input') plt.hold(True) plt.plot(res['tran'].get_x(), res['tran']['vint1'], label='Transformer output #1') plt.plot(res['tran'].get_x(), res['tran']['vint2'], label='Transformer output #2') plt.hold(False) plt.grid(True) plt.legend() plt.ylabel('Voltage [V]') plt.xlabel('Time [s]') fig.savefig('rectf1_plot.png') fig = plt.figure() plt.title(cir.title + " outputs") plt.plot(res['tran'].get_x(), res['tran']['vint4'] - res['tran']['vint3'], label="output voltage") plt.legend() plt.grid(True) plt.ylabel('Voltage [V]') plt.xlabel('Time [s]') fig.savefig('rectf2_plot.png') else: testbench.tearDown()
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License v2 # along with ahkab. If not, see <http://www.gnu.org/licenses/>. from __future__ import unicode_literals, print_function, division import numpy as np import ahkab cir = ahkab.Circuit('Test FOUR and FFT') #mys = lambda t: 1 if not t else math.sin(math.pi*1e4*t)/(math.pi*1e4*t) mys = ahkab.time_functions.sin(vo=0, va=1, freq=10e3) cir.add_resistor('R1', 'n1', cir.gnd, 1e3) cir.add_vsource('V1', 'n1', cir.gnd, 1, function=mys) tr = ahkab.new_tran(0, 1e-3, 1e-5, x0=None) r = ahkab.run(cir, tr)['tran'] def test_fourier(): """Test fourier.fourier() and printing.print_fourier()""" fs, F, THD = ahkab.fourier.fourier('vn1', r, 10e3) fs_ref = np.array([ 0., 10000., 20000., 30000., 40000., 50000., 60000., 70000., 80000., 90000. ]) assert np.allclose(fs, fs_ref) assert np.argmax(abs(F)) == 1 assert len(F) == len(fs) == 10 assert abs(F[0]) < 1 assert THD < .1