def test(): """Test NL AC analysis (API)""" cir = ahkab.Circuit('CS amplifier') mys = ahkab.time_functions.sin(0, 1, 60) cir.add_vsource('vin', '1', '0', dc_value=3, ac_value=1) cir.add_vsource('vdd', '3', '0', dc_value=30) cir.add_resistor('Rd', '3', '2', 10e3) cir.add_capacitor('Cd', '3', '2', 40e-12) cir.add_resistor('Rs', '4', '0', 1e3) cir.add_capacitor('Cs', '4', '0', 4e-6) cir.add_model('ekv', 'ekv0', {'TYPE':'n', 'VTO':.4, 'KP':1e-2}) cir.add_mos('m1', '2', '1', '4', '0', w=100e-6, l=1e-6, model_label='ekv0') print(cir) opa = ahkab.new_op(outfile='acnl', verbose=6) aca = ahkab.new_ac(1, 100e6, 10e3, outfile='acnl', verbose=6) r = ahkab.run(cir, [opa, aca])['ac'] testbench = testing.APITest('acnl', cir, [opa, aca], skip_on_travis=False, er=1e-3, ea=1e-5) testbench.setUp() testbench.test() if not cli: testbench.tearDown()
def test(): """Test NL AC analysis (API)""" cir = ahkab.Circuit('CS amplifier') mys = ahkab.time_functions.sin(0, 1, 60) cir.add_vsource('vin', '1', '0', dc_value=3, ac_value=1) cir.add_vsource('vdd', '3', '0', dc_value=30) cir.add_resistor('Rd', '3', '2', 10e3) cir.add_capacitor('Cd', '3', '2', 40e-12) cir.add_resistor('Rs', '4', '0', 1e3) cir.add_capacitor('Cs', '4', '0', 4e-6) cir.add_model('ekv', 'ekv0', {'TYPE': 'n', 'VTO': .4, 'KP': 1e-2}) cir.add_mos('m1', '2', '1', '4', '0', w=100e-6, l=1e-6, model_label='ekv0') print(cir) opa = ahkab.new_op(outfile='acnl', verbose=6) aca = ahkab.new_ac(1, 100e6, 10e3, outfile='acnl', verbose=6) r = ahkab.run(cir, [opa, aca])['ac'] testbench = testing.APITest('acnl', cir, [opa, aca], skip_on_travis=False, er=1e-3, ea=1e-5) testbench.setUp() testbench.test() if not cli: testbench.tearDown()
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 run_ac(circuit): """ :param circuit: ahkab circuit :return: results for AC analysis """ opa = ahkab.new_op() aca = ahkab.new_ac(ac_params['start'], ac_params['stop'], ac_params['pts']) return ahkab.run(circuit, [opa, aca])['ac']
def setUp(self): ttn = ahkab.Circuit('Twin-T Notch Stopband filter') ttn.add_vsource('V1', 'in', ttn.gnd, dc_value=1, ac_value=1) # 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.) aca = ahkab.new_ac(1e7, 1e10, 100, x0=None) self.r = ahkab.run(ttn, aca)['ac']
def setUp(self): ttn = ahkab.Circuit('Twin-T Notch Stopband filter') ttn.add_vsource('V1', 'in', ttn.gnd, dc_value=1, ac_value=1) # 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.) aca = ahkab.new_ac(1e7, 1e10, 100, x0=None) self.r = ahkab.run(ttn, aca)['ac']
def test(): """Test CCCS API""" # The circuit is: #test for transresitances #va 1 2 type=vdc vdc=.1 vac=1 #r1 1 0 .5k #r2 2 0 .5k #h1 3 4 va 5000 #r3 3 0 1k #r4 4 5 1k #l1 5 0 10u #c1 5 0 10u #.op #.ac start=50k stop=5e5 nsteps=1000 #.symbolic #.plot ac |v(5)| mycircuit = circuit.Circuit(title="Test CCVS API", filename=None) gnd = mycircuit.get_ground_node() mycircuit.add_resistor(part_id="R1", n1="1", n2=gnd, value=500) mycircuit.add_resistor(part_id="R2", n1="2", n2=gnd, value=500) mycircuit.add_vsource("VA", n1="1", n2='2', dc_value=0.1, ac_value=1.) mycircuit.add_ccvs('H1', n1='3', n2='4', source_id='VA', value=5000) mycircuit.add_resistor(part_id="R3", n1="3", n2=gnd, value=1e3) mycircuit.add_resistor(part_id="R4", n1="4", n2="5", value=1e3) mycircuit.add_inductor(part_id="L1", n1="5", n2=gnd, value=10e-6) mycircuit.add_capacitor(part_id="C1", n1="5", n2=gnd, value=10e-6) print(mycircuit) op_analysis = ahkab.new_op(outfile='hvsource_api', verbose=6) symb_analysis = ahkab.new_symbolic(outfile='hvsource_api', verbose=6) ac_analysis = ahkab.new_ac(outfile='hvsource_api', start=7957.747, stop=79577.471, points=1000, verbose=6) testbench = testing.APITest('hvsource', mycircuit, [op_analysis, symb_analysis, ac_analysis], skip_on_travis=False, er=1e-3, ea=1e-5) testbench.setUp() testbench.test() if not cli: testbench.tearDown()
def test(): """Test CCCS API""" # The circuit is: #test for transresitances #va 1 2 type=vdc vdc=.1 vac=1 #r1 1 0 .5k #r2 2 0 .5k #h1 3 4 va 5000 #r3 3 0 1k #r4 4 5 1k #l1 5 0 10u #c1 5 0 10u #.op #.ac start=50k stop=5e5 nsteps=1000 #.symbolic #.plot ac |v(5)| mycircuit = circuit.Circuit(title="Test CCVS API", filename=None) gnd = mycircuit.get_ground_node() mycircuit.add_resistor(part_id="R1", n1="1", n2=gnd, value=500) mycircuit.add_resistor(part_id="R2", n1="2", n2=gnd, value=500) mycircuit.add_vsource("VA", n1="1", n2='2', dc_value=0.1, ac_value=1.) mycircuit.add_ccvs('H1', n1='3', n2='4', source_id='VA', value=5000) mycircuit.add_resistor(part_id="R3", n1="3", n2=gnd, value=1e3) mycircuit.add_resistor(part_id="R4", n1="4", n2="5", value=1e3) mycircuit.add_inductor(part_id="L1", n1="5", n2=gnd, value=10e-6) mycircuit.add_capacitor(part_id="C1", n1="5", n2=gnd, value=10e-6) print(mycircuit) op_analysis = ahkab.new_op(outfile='hvsource_api', verbose=6) symb_analysis = ahkab.new_symbolic(outfile='hvsource_api', verbose=6) ac_analysis = ahkab.new_ac(outfile='hvsource_api', start=50e3, stop=500e3, points=1000, verbose=6) testbench = testing.APITest('hvsource', mycircuit, [op_analysis, symb_analysis, ac_analysis], skip_on_travis=False, er=1e-3, ea=1e-5) testbench.setUp() testbench.test() if not cli: testbench.tearDown()
gnd = mycircuit.get_ground_node() 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])
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])
def test(): """Test SVF Biquad""" mycircuit = Circuit(title="state variable filter") gnd = mycircuit.get_ground_node() buildsvf(mycircuit) mycircuit.add_vsource(part_id="V1", n1="in", n2=gnd, dc_value=5, ac_value=1) if cli: print(mycircuit) subs = {'E2':'E1', 'E3':'E1', 'R01':'R00', 'R02':'R00', 'R11':'R00', 'R10':'R00', 'C11':'C10', 'Rf2':'Rf1', 'Rin':'R00'} symbolic_sim = ahkab.new_symbolic(ac_enable=True, subs=subs, outfile='svf_biquad') ac_sim = ahkab.new_ac(start=0.1, stop=100e6, points=1000, x0=None, outfile='svf_biquad') testbench = testing.APITest('svf_biquad', mycircuit, [symbolic_sim, ac_sim], skip_on_travis=True, er=1e-3, ea=1e-5) testbench.setUp() testbench.test() if cli: r = ahkab.run(mycircuit, [symbolic_sim, ac_sim]) E = r['symbolic'][0].as_symbol('E1') out_hp = sympy.limit(r['symbolic'][0]['VU1o'], E, sympy.oo, '+') out_bp = sympy.limit(r['symbolic'][0]['VU2o'], E, sympy.oo, '+') out_lp = sympy.limit(r['symbolic'][0]['VU3o'], E, sympy.oo, '+') out_hp = out_hp.simplify() out_bp = out_bp.simplify() out_lp = out_lp.simplify() print("VU1o =", out_hp) print("VU2o =", out_bp) print("VU3o =", out_lp) w = sympy.Symbol('w') out_hp = out_hp.subs({r['symbolic'][0].as_symbol('RF1'):10e3, r['symbolic'][0].as_symbol('C10'):15e-9, r['symbolic'][0].as_symbol('V1'):1, r['symbolic'][0].as_symbol('s'):1j*w, }) out_bp = out_bp.subs({r['symbolic'][0].as_symbol('RF1'):10e3, r['symbolic'][0].as_symbol('C10'):15e-9, r['symbolic'][0].as_symbol('V1'):1, r['symbolic'][0].as_symbol('s'):1j*w, }) out_lp = out_lp.subs({r['symbolic'][0].as_symbol('RF1'):10e3, r['symbolic'][0].as_symbol('C10'):15e-9, r['symbolic'][0].as_symbol('V1'):1, r['symbolic'][0].as_symbol('s'):1j*w, }) out_lp = sympy.lambdify((w,), out_lp) out_bp = sympy.lambdify((w,), out_bp) out_hp = sympy.lambdify((w,), out_hp) ws = r['ac']['w'][::30] fig = plt.figure() plt.title(mycircuit.title) plt.subplot(211) plt.hold(True) plt.semilogx(r['ac']['w']/2./np.pi, 20*np.log10(np.abs(r['ac']['VU1o'])), label="HP output (AC)") plt.semilogx(r['ac']['w']/2./np.pi, 20*np.log10(np.abs(r['ac']['VU2o'])), label="BP output (AC)") plt.semilogx(r['ac']['w']/2./np.pi, 20*np.log10(np.abs(r['ac']['VU3o'])), label="LP output (AC)") plt.semilogx(ws/2./np.pi, 20*np.log10(np.abs(out_hp(ws))), 'v', label="HP output (SYMB)") plt.semilogx(ws/2./np.pi, 20*np.log10(np.abs(out_bp(ws))), 'v', label="BP output (SYMB)") plt.semilogx(ws/2./np.pi, 20*np.log10(np.abs(out_lp(ws))), 'v', label="LP output (SYMB)") plt.hold(False) plt.grid(True) plt.legend() plt.ylabel('Magnitude [dB]') plt.xlabel('Frequency [Hz]') plt.subplot(212) plt.hold(True) plt.semilogx(r['ac']['w']/2./np.pi, np.angle(r['ac']['VU1o']), label="HP output (AC)") plt.semilogx(r['ac']['w']/2./np.pi, np.angle(r['ac']['VU2o']), label="BP output (AC)") plt.semilogx(r['ac']['w']/2./np.pi, np.angle(r['ac']['VU3o']), label="LP output (AC)") plt.semilogx(ws/2./np.pi, np.angle(out_hp(ws)), 'v', label="HP output (SYMB)") plt.semilogx(ws/2./np.pi, np.angle(out_bp(ws)), 'v', label="BP output (SYMB)") plt.semilogx(ws/2./np.pi, np.angle(out_lp(ws)), 'v', label="LP output (SYMB)") plt.legend() plt.hold(False) plt.grid(True) #plt.ylim([0,1.2]) plt.ylabel('Phase [rad]') plt.xlabel('Frequency [Hz]') fig.savefig('ac_plot.png') else: testbench.tearDown()
from ahkab import new_ac, run from ahkab.circuit import Circuit from ahkab.plotting import plot_results # calls matplotlib for you import numpy as np import matplotlib.pyplot as plt # Define the circuit cir = Circuit('Butterworth 1kHz band-pass filter') cir.add_vsource('V1', 'n1', cir.gnd, dc_value=0., ac_value=1.) cir.add_resistor('R1', 'n1', 'n2', 50.) cir.add_inductor('L1', 'n2', 'n3', 0.245894) cir.add_capacitor('C1', 'n3', 'n4', 1.03013e-07) cir.add_inductor('L2', 'n4', cir.gnd, 9.83652e-05) cir.add_capacitor('C2', 'n4', cir.gnd, 0.000257513) cir.add_inductor('L3', 'n4', 'n5', 0.795775) cir.add_capacitor('C3', 'n5', 'n6', 3.1831e-08) cir.add_inductor('L4', 'n6', cir.gnd, 9.83652e-05) cir.add_capacitor('C4', 'n6', cir.gnd, 0.000257513) cir.add_capacitor('C5', 'n7', 'n8', 1.03013e-07) cir.add_inductor('L5', 'n6', 'n7', 0.245894) cir.add_resistor('R2', 'n8', cir.gnd, 50.) # Define the analysis ac1 = new_ac(.97e3, 1.03e3, 1e2, x0=None) # run it res = run(cir, ac1) # plot the results plot_results('5th order 1kHz Butterworth filter', [('|Vn8|',"")], res['ac'], outfilename='bpf_transfer_fn.png')
tr=1e-12, 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)
tr=1e-12, 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)
from ahkab.circuit import Circuit from ahkab.plotting import plot_results # calls matplotlib for you import numpy as np # Define the circuit cir = Circuit('Butterworth 1kHz band-pass filter') cir.add_vsource('V1', 'n1', cir.gnd, dc_value=0., ac_value=1.) cir.add_resistor('R1', 'n1', 'n2', 50.) cir.add_inductor('L1', 'n2', 'n3', 0.245894) cir.add_capacitor('C1', 'n3', 'n4', 1.03013e-07) cir.add_inductor('L2', 'n4', cir.gnd, 9.83652e-05) cir.add_capacitor('C2', 'n4', cir.gnd, 0.000257513) cir.add_inductor('L3', 'n4', 'n5', 0.795775) cir.add_capacitor('C3', 'n5', 'n6', 3.1831e-08) cir.add_inductor('L4', 'n6', cir.gnd, 9.83652e-05) cir.add_capacitor('C4', 'n6', cir.gnd, 0.000257513) cir.add_capacitor('C5', 'n7', 'n8', 1.03013e-07) cir.add_inductor('L5', 'n6', 'n7', 0.245894) cir.add_resistor('R2', 'n8', cir.gnd, 50.) # Define the analysis ac1 = new_ac(2. * np.pi * .97e3, 2. * np.pi * 1.03e3, 1e2, x0=None) # run it res = run(cir, ac1) # plot the results plot_results('5th order 1kHz Butterworth filter', [('|Vn8|', "")], res['ac'], outfilename='bpf_transfer_fn.png')
av = svf.add_vsource ao = lambda name, p, n: svf.add_vcvs("E"+name[1:], name+"o", gnd, p, n, 1e6) ao("u1", "u1p", "u1o") ar("R1", "in", "nR2", 10e3) ar("R2", "nR2", "u1p", 10e3) ac("C1", "u1o", "nR2", 1e-9) ac("C2", "u1p", gnd, 1e-9) av("V1", "in", gnd, 2.5, 1.0) buildsk(mycircuit) print(mycircuit) symbolic_sim = ahkab.new_symbolic(ac_enable=True, source='V1') ac_sim = ahkab.new_ac(start=10, stop=100e6, points=1000, x0=None) try: r = pickle.load(open("results-sallenkey.pk")) except: ahkab.queue(ac_sim, symbolic_sim) r = ahkab.run(mycircuit) pickle.dump(r, open("results-sallenkey.pk", "wb")) print r['symbolic'][0] print "Symbolic transfer functions:" printing.print_symbolic_transfer_functions(r['symbolic'][1]) # substitute the actual values to the symbols and plot V1 = r['symbolic'][0].as_symbol('V1') tf = r['symbolic'][0]['Vu1o']/V1
@author: Mahmoud """ import ahkab from ahkab import new_ac, run from ahkab.circuit import Circuit from ahkab.plotting import plot_results # calls matplotlib for you import numpy as np cir = Circuit('Butterworth 1kHz band-pass filter') cir.add_vsource('V1', 'n1', cir.gnd, dc_value=0., ac_value=1.) cir.add_resistor('R1', 'n1', 'n2', 50.) cir.add_inductor('L1', 'n2', 'n3', 0.245894) cir.add_capacitor('C1', 'n3', 'n4', 1.03013e-07) cir.add_inductor('L2', 'n4', cir.gnd, 9.83652e-05) cir.add_capacitor('C2', 'n4', cir.gnd, 0.000257513) cir.add_inductor('L3', 'n4', 'n5', 0.795775) cir.add_capacitor('C3', 'n5', 'n6', 3.1831e-08) cir.add_inductor('L4', 'n6', cir.gnd, 9.83652e-05) cir.add_capacitor('C4', 'n6', cir.gnd, 0.000257513) cir.add_capacitor('C5', 'n7', 'n8', 1.03013e-07) cir.add_inductor('L5', 'n6', 'n7', 0.245894) cir.add_resistor('R2', 'n8', cir.gnd, 50.) ac1 = new_ac(.97e3, 1.03e3, 1e2, x0=None, outfile=r"E:\New Text Document.txt ") res = run(cir, ac1) #ahkab.new_dc() #print(cir) #plot_results('5th order 1kHz Butterworth filter', [('|Vn8|',"")], res['ac'], # outfilename='bpf_transfer_fn.png')
if Type[0] == 'G': #--->Adding vccs<---# ac_circuit.add_vccs(Type,N1,N2,NS1,NS2,Value) vccs[vccsi]=X.split() vccsi+=1 else: if Type[0] == 'F': #--->Adding cccs<---# ac_circuit.add_cccs(Type,N1,N2,Vsource,Value) cccs[cccsi]=X.split() cccsi+=1 else: if Type[0] == 'I': #--->Adding independent current source<---# ac_circuit.add_isource(Type,Node1,Node2,dc_value = 0,ac_value = Value*(math.cos(math.radians(Phase))+math.sin(math.radians(Phase))*1j)) current_sources[ci]=X.split() ci+=1 ac = ahkab.new_ac(start = freq,stop = freq,points = 2,x0 = None) #setting the analysis res = ahkab.run(ac_circuit,ac) #runnung the ac ciruit array = res['ac'].values() #getting the result's values print() print("Values:") print(array) keys = res['ac'].keys() #getting the result's keys print() print("Keys:") print(keys) print() i=1 j=1 while j < len(keys): if(keys[i][0] != 'I'):
def test(): """Test SVF Biquad""" mycircuit = Circuit(title="state variable filter") gnd = mycircuit.get_ground_node() buildsvf(mycircuit) mycircuit.add_vsource(part_id="V1", n1="in", n2=gnd, dc_value=5, ac_value=1) if cli: printing.print_circuit(mycircuit) subs = symbolic.parse_substitutions(('E2=E1', 'E3=E1', 'R01=R00', 'R02=R00', 'R11=R00', 'R10=R00', 'C11=C10', 'Rf2=Rf1', 'Rin=R00')) symbolic_sim = ahkab.new_symbolic(ac_enable=True, subs=subs, outfile='svf_biquad') ac_sim = ahkab.new_ac(start=0.1, stop=100e6, points=1000, x0=None, outfile='svf_biquad') testbench = testing.APITest('svf_biquad', mycircuit, [symbolic_sim, ac_sim], skip_on_travis=True, er=1e-3, ea=1e-5) testbench.setUp() testbench.test() if cli: r = ahkab.run(mycircuit, [symbolic_sim, ac_sim]) E = r['symbolic'][0].as_symbol('E1') out_hp = sympy.limit(r['symbolic'][0]['VU1o'], E, sympy.oo, '+') out_bp = sympy.limit(r['symbolic'][0]['VU2o'], E, sympy.oo, '+') out_lp = sympy.limit(r['symbolic'][0]['VU3o'], E, sympy.oo, '+') out_hp = out_hp.simplify() out_bp = out_bp.simplify() out_lp = out_lp.simplify() print("VU1o =", out_hp) print("VU2o =", out_bp) print("VU3o =", out_lp) w = sympy.Symbol('w') out_hp = out_hp.subs({r['symbolic'][0].as_symbol('RF1'):10e3, r['symbolic'][0].as_symbol('C10'):15e-9, r['symbolic'][0].as_symbol('V1'):1, r['symbolic'][0].as_symbol('s'):1j*w, }) out_bp = out_bp.subs({r['symbolic'][0].as_symbol('RF1'):10e3, r['symbolic'][0].as_symbol('C10'):15e-9, r['symbolic'][0].as_symbol('V1'):1, r['symbolic'][0].as_symbol('s'):1j*w, }) out_lp = out_lp.subs({r['symbolic'][0].as_symbol('RF1'):10e3, r['symbolic'][0].as_symbol('C10'):15e-9, r['symbolic'][0].as_symbol('V1'):1, r['symbolic'][0].as_symbol('s'):1j*w, }) out_lp = sympy.lambdify((w,), out_lp, modules='numpy') out_bp = sympy.lambdify((w,), out_bp, modules='numpy') out_hp = sympy.lambdify((w,), out_hp, modules='numpy') ws = r['ac']['w'][::30] fig = plt.figure() plt.title(mycircuit.title) plt.subplot(211) plt.hold(True) plt.semilogx(r['ac']['w']/2./np.pi, 20*np.log10(np.abs(r['ac']['VU1o'])), label="HP output (AC)") plt.semilogx(r['ac']['w']/2./np.pi, 20*np.log10(np.abs(r['ac']['VU2o'])), label="BP output (AC)") plt.semilogx(r['ac']['w']/2./np.pi, 20*np.log10(np.abs(r['ac']['VU3o'])), label="LP output (AC)") plt.semilogx(ws/2./np.pi, 20*np.log10(np.abs(out_hp(ws))), 'v', label="HP output (SYMB)") plt.semilogx(ws/2./np.pi, 20*np.log10(np.abs(out_bp(ws))), 'v', label="BP output (SYMB)") plt.semilogx(ws/2./np.pi, 20*np.log10(np.abs(out_lp(ws))), 'v', label="LP output (SYMB)") plt.hold(False) plt.grid(True) plt.legend() plt.ylabel('Magnitude [dB]') plt.xlabel('Frequency [Hz]') plt.subplot(212) plt.hold(True) plt.semilogx(r['ac']['w']/2./np.pi, np.angle(r['ac']['VU1o']), label="HP output (AC)") plt.semilogx(r['ac']['w']/2./np.pi, np.angle(r['ac']['VU2o']), label="BP output (AC)") plt.semilogx(r['ac']['w']/2./np.pi, np.angle(r['ac']['VU3o']), label="LP output (AC)") plt.semilogx(ws/2./np.pi, np.angle(out_hp(ws)), 'v', label="HP output (SYMB)") plt.semilogx(ws/2./np.pi, np.angle(out_bp(ws)), 'v', label="BP output (SYMB)") plt.semilogx(ws/2./np.pi, np.angle(out_lp(ws)), 'v', label="LP output (SYMB)") plt.legend() plt.hold(False) plt.grid(True) #plt.ylim([0,1.2]) plt.ylabel('Phase [rad]') plt.xlabel('Frequency [Hz]') fig.savefig('ac_plot.png') else: testbench.tearDown()
ar("R2", "U3o", "U1n", 10e3) ar("R4", "U1o", "U2n", 10e3) ar("R5", "U2o", "U3n", 10e3) ar("R6", "U3n", "U3o", 10e3) ac("C1", "U1n", "U1o", 15e-9) ac("C2", "U2n", "U2o", 15e-9) ao("E1", gnd, "U1n") ao("E2", gnd, "U2n") ao("E3", gnd, "U3n") buildsvf(mycircuit) mycircuit.add_vsource("V1", n1="in", n2=gnd, dc_value=5, ac_value=1) print(mycircuit) ac_sim = new_ac(start=0.1, stop=100e6, points=1000, x0=None) try: r = pickle.load(open("results-ttb.pk")) except: subs = symbolic.parse_substitutions(('R2=R1', 'R3=R1', 'C2=C1', 'E2=E1', 'E3=E1', "R4=R1", "R5=R1", "R6=R1")) symbolic_sim = ahkab.new_symbolic(ac_enable=True, source=None, subs=subs) ahkab.queue(symbolic_sim) r = ahkab.run(mycircuit) pickle.dump(r, open("results-ttb.pk", "wb")) ahkab.queue(ac_sim) r.update(ahkab.run(mycircuit))
acvalue = m.rect(float(values[3]), Rad(float(values[4]))) mycircuit.add_isource(values[0], values[1], values[2], dc_value=0, ac_value=acvalue) #dc should not be zero? if values[0][0] == 'C': mycircuit.add_capacitor(values[0], values[1], values[2], float(values[3])) if values[0][0] == 'L': mycircuit.add_inductor(values[0], values[1], values[2], float(values[3])) if values[0][0] == 'R': mycircuit.add_resistor(values[0], values[1], values[2], float(values[3])) ac = new_ac(start=w, stop=w, points=2, x0=None) res = run(mycircuit, ac) #saving result in a file f = open("result.txt", "w") for result in res['ac'].keys(): f.write(str(result) + "=") f.write(str(res['ac'][result][0])) f.write('\n') #storing nodes voltages: voltage = [0 + 0j] for x in res['ac'].keys(): if x[0] == 'V': voltage.append(res['ac'][x][0]) #calculating power in each component: cirfile = open(filename, "r") impedance_z = complex(1, 0)
def score_ota(self, Indiv): # Use physical values for Width, Length and Resistance in Si Units minimalW = 1e-6 minimalL = 10e-9 minimalR = 10 W=(Indiv.gene_value('W1')+1)*minimalW L=(Indiv.gene_value('L1')+1)*minimalL R=(Indiv.gene_value('R1')+1)*minimalR ## Couple with spice simulator and extract GBW # Create new circuit ota = circuit.Circuit(title="Operational Transconductance Amplifier Circuit") # Reference ground gnd = ota.get_ground_node() n1 = ota.create_node('n1') # Top of current source n2 = ota.create_node('n2') # Output-, Drain of MOS1 (left) n3 = ota.create_node('n3') # Output+, Drain of MOS2 (right) n4 = ota.create_node('n4') # Power supply n5 = ota.create_node('n5') # Bias of gate + n6 = ota.create_node('n6') # Bias of gate - print 'variables' print W print L print R ota.add_resistor("R1", 'n4', 'n2', value=R) ota.add_resistor("R2", 'n4', 'n3', value=R) ota.add_capacitor('c1', n1='n2', n2=gnd, value=5e-12) ota.add_capacitor('c2', n1='n3', n2=gnd, value=5e-12) ota.add_model('ekv', 'nmos', dict(TYPE='n', VTO=.4, KP=10e-6)) ota.add_mos('m1', nd='n2', ng='n5', ns='n1', nb=gnd, model_label='nmos', w=W, l=L) ota.add_mos('m2', nd='n3', ng='n6', ns='n1', nb=gnd, model_label='nmos', w=W, l=L) Vac = 0.02 ota.add_vsource("V1", n1="n5", n2=gnd, dc_value=0.5, ac_value=Vac) ota.add_vsource("V2", n1="n6", n2=gnd, dc_value=0.5, ac_value=-Vac) ota.add_vsource("V3", n1="n4", n2=gnd, dc_value=2, ac_value=0) ota.add_isource('ib', n1='n1', n2=gnd, dc_value=1e-3) ac_analysis = ahkab.new_ac(start=1e6, stop=1e10, points=10) r = ahkab.run(ota, ac_analysis) Output = np.abs(r['ac']['VN3']-r['ac']['VN2']) ## Gain calculation Gain = Output[2]/Vac score = Gain ## Bandwidth calculation # Normalize the output to the low frequency value and convert to array norm_out = np.abs(Output)/np.abs(Output).max() # Convert to dB #norm_out_db = 20*np.log10(norm_out) # Convert angular frequencies to Hz and convert matrix to array frequencies = r['ac']['f'] #print r['ac'].keys() print norm_out print frequencies # call scipy to interpolate x1 = norm_out y1 = frequencies # Combine lists into list of tuples points = zip(x1, y1) # Sort list of tuples by x-value points = sorted(points, key=lambda point: point[0]) # Split list of tuples into two list of x values any y values x1, y1 = zip(*points) frequencies_interpolated = interpolate.interp1d(x1, y1) if 0.5 > min(x1): print frequencies_interpolated(0.5) Bandwidth = frequencies_interpolated(0.5) else: Bandwith = 0 score = Gain*Bandwidth print score return score
1e6) ao("u1", "u1p", "u1o") ar("R1", "in", "nR2", 10e3) ar("R2", "nR2", "u1p", 10e3) ac("C1", "u1o", "nR2", 1e-9) ac("C2", "u1p", gnd, 1e-9) av("V1", "in", gnd, 2.5, 1.0) buildsk(mycircuit) print(mycircuit) symbolic_sim = ahkab.new_symbolic(ac_enable=True, source='V1') ac_sim = ahkab.new_ac(start=10, stop=100e6, points=1000, x0=None) try: r = pickle.load(open("results-sallenkey.pk")) except: ahkab.queue(ac_sim, symbolic_sim) r = ahkab.run(mycircuit) pickle.dump(r, open("results-sallenkey.pk", "wb")) print r['symbolic'][0] print "Symbolic transfer functions:" printing.print_symbolic_transfer_functions(r['symbolic'][1]) # substitute the actual values to the symbols and plot V1 = r['symbolic'][0].as_symbol('V1') tf = r['symbolic'][0]['Vu1o'] / V1
sn.append(n1) en.append(n2) elif (words[0][0]=='F'): e_ip = words[0] n1 = words[1] n2 = words[2] v= words[3] value = float(words[4]) ac_circuit.add_cccs(e_ip, n1, n2, id(v),value) sympols.append(e_ip) impedence.append(0) sn.append(n1) en.append(n2) ac = ahkab.new_ac(start=freq, stop=freq, points=0,x0=None) res = ahkab.run(ac_circuit, ac) print(res['ac'].keys()) def check_v(e,n): if(e[n]=='0'): return 0 else: v = res['ac']['V{}'.format(e[n])] return v for l in range(len(sympols)): if(sympols[l][0]=='R'):
ElemID.append(Inputs[3]) VsID.append('V' + str(ccvsBatteryCount)) ccvsBatteryCount += 1 if (len(Inputs) == 6): i = 0 if LINE[0][0] == 'V': Circuit.add_ccvs(Inputs[0], Inputs[1], Inputs[2], LINE[0], float(Inputs[4])) else: while (i < len(ElemID)): if (ElemID[i] == Inputs[3]): Circuit.add_ccvs(Inputs[0], Inputs[1], Inputs[2], VsID[i], float(Inputs[4])) i += 1 File.close() ac = ahkab.new_ac(start=frequency, stop=frequency, points=2, x0=None) solution = ahkab.run(Circuit, ac) ######################################################################################################################## PowerList = [] File = open(NetlistName + ".txt", "r") Lines = File.readlines() File.close() File = open(NetlistName + ".txt", "r") ResultFile = open("OutputFile.txt", 'w') for line in File: Element = line.split() if len(Element) > 0: if Element[0][0] == 'R': if Element[2] != '0' and Element[1] != '0':