def run_simulator(): global n, sfreq, samp, netdict global a0, f0 a0 = 1000 f0 = 10 circ_state = [] x = 0 y = 0 fig = plt.figure(1) ax = fig.add_subplot(211) ax1 = fig.add_subplot(212) plt.subplots_adjust(left=0.25, bottom=0.25) r = run(netdict['Circuit'], netdict['Opa'])['op'] line = [None] * (len(r.results.keys())) for n in range(len(line)): line[n], = ax.plot(x, y) l2, = ax1.plot(x, y) axcolor = 'lightgoldenrodyellow' axfreq = plt.axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor) axamp = plt.axes([0.25, 0.15, 0.65, 0.03], axisbg=axcolor) sfreq = Slider(axfreq, 'Freq', 0.01, 20.0, valinit=f0) samp = Slider(axamp, 'Amp', 0.1, 1500.0, valinit=a0) def update(val): a0 = samp.val f0 = sfreq.val sfreq.on_changed(update) samp.on_changed(update) for i in range(10000): r = run(netdict['Circuit'], netdict['Opa'])['op'] netdict = update_memristor_vals_from_oprun(netdict, r) netdict = update_memristor_states(netdict) netdict = update_circrvals_from_memres(netdict) circ_state.append(r) for p in range(len(r.results.keys()) - 1): x = np.concatenate((line[p].get_xdata(), [i])) y = np.concatenate( (line[p].get_ydata(), [r.results['VN' + str(p)]])) line[p].set_data(x, y) ax.relim() ax.autoscale_view() plt.pause(0.001) newv = samp.val * np.sin(2 * np.pi * sfreq.val * i * Tao) set_cir_voltage('V1', newv, netdict) x = np.concatenate((l2.get_xdata(), [i])) y = np.concatenate((l2.get_ydata(), [get_cir_voltage('V1', netdict)])) l2.set_data(x, y) ax1.relim() ax1.autoscale_view()
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 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 score_resistiveDivider(self, Indiv): # Avoid shortcircuited resistances by making minimal resistance = 1 R1=Indiv.gene_value('R1')+1 R2=Indiv.gene_value('R2')+1 # This circuit has a trivial solution: R1 = min(int)+1 and R2 = max(int)+1 mycircuit = circuit.Circuit(title="Resistive Divider Circuit") # Reference ground gnd = mycircuit.get_ground_node() # This makes sure nodes are uniquely defined n1 = mycircuit.create_node('n1') n2 = mycircuit.create_node('n2') # Add the resistors to the schematic mycircuit.add_resistor("R1", 'n1', 'n2', value=R1) mycircuit.add_resistor("R2", 'n2', gnd, value=R2) # Add a voltage source mycircuit.add_vsource("V1", n1="n1", n2=gnd, dc_value=1, ac_value=1) # Resistors are passives with a flat frequency characteristic so an operating point (op) analysis is enough op_analysis = ahkab.new_op() # Start the simulation and store the result in <result> result = ahkab.run(mycircuit, op_analysis) # The figure of merit to maximize is the voltage at the intermediate node between R1 and R2 score = result['op']['VN2']*100 return score
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 run_sym(circuit, source, print_tf=False) -> Dict[str, sp.Expr]: """ :param circuit: ahkab circuit :param source: name of the source for analysis :param print_tf: print transfer function, poles, & zeros? :return: results for symbolic analysis """ if not isinstance(source, str): raise ValueError('Source name must be a string! e.g. \'V1\'') r, tf = ahkab.run(circuit, ahkab.new_symbolic(source=source, verbose=0))['symbolic'] tfs = tf['VOUT/' + str(source)] if print_tf: print("DC gain: {} dB".format( 20 * sp.log(tf['VOUT/' + str(source)]['gain0'], 10))) print("Transfer function:") sp.pprint(tfs['gain']) for i, z in enumerate(tfs['zeros']): print("Zero #{}:".format(i)) sp.pprint(z) for i, p in enumerate(tfs['poles']): print("Pole #{}:".format(i)) sp.pprint(p) return tfs
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 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 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 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 test_op_solution(): """Test results.op_solution""" ######### CIRCUIT ############## 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.) # set up the OP and run opa = ahkab.new_op() r = ahkab.run(ttn, opa)['op'] ####### CHECKS ########### # str representation print(str(r)) r.keys() # 'sd' is not an existing key try: r['sd'] assert False except KeyError: pass # fallback on default assert r.get('sd', 1e3) == 1e3 assert r.get('VN1') == 0 # the important part is not the value np.allclose(r.asmatrix(), np.array([[ 1.00000000e+00], [ 0.00000000e+00], [ 1.00000000e+00], [ 1.00000000e+00], [ 1.00000000e+00], [ 1.01736171e-20], [ 0.00000000e+00]]), rtol=1e-3) r.print_short() set(list(zip(*r.items()))[0]) == set(r.keys()) set(list(zip(*r.items()))[1]) == set(r.values()) # iterator keys = set() values = set() for k, v in r: keys |= {k} values |= {float(v)} assert keys == set(r.keys()) assert values == set(r.values())
def test_op_solution(): """Test results.op_solution""" ######### CIRCUIT ############## 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.) # set up the OP and run opa = ahkab.new_op() r = ahkab.run(ttn, opa)['op'] ####### CHECKS ########### # str representation print(str(r)) r.keys() # 'sd' is not an existing key try: r['sd'] assert False except KeyError: pass # fallback on default assert r.get('sd', 1e3) == 1e3 assert r.get('VN1') == 0 # the important part is not the value np.allclose(r.asmatrix(), np.array([[1.00000000e+00], [0.00000000e+00], [1.00000000e+00], [1.00000000e+00], [1.00000000e+00], [1.01736171e-20], [0.00000000e+00]]), rtol=1e-3) r.print_short() set(list(zip(*r.items()))[0]) == set(r.keys()) set(list(zip(*r.items()))[1]) == set(r.values()) # iterator keys = set() values = set() for k, v in r: keys |= {k} values |= {float(v)} assert keys == set(r.keys()) assert values == set(r.values())
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 setUp(self): ttn = ahkab.Circuit('Twin-T Notch Stopband filter') ttn.add_vsource('V1', 'in', ttn.gnd, dc_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.) sa = ahkab.new_symbolic(source=None) self.r = ahkab.run(ttn, sa)['symbolic'][0]
def PDN_circuit(args): logging.basicConfig(filename='PDN.log',filemode='w', level=logging.INFO) #args = parser.parse_args() if len(args.currents) == 0: raise ValueError("input currents should not be empty") mycircuit = circuit.Circuit(title="PDN circuit") gnd = mycircuit.get_ground_node() v_nodes = [] c_nodes = [] inter_nodes = [] _NODE_COUNT = args.cores ROW_SIZE = args.rsize # declare Vdd nodes for i in range(_NODE_COUNT): v_nodes.append(mycircuit.create_node('nv'+str(i))) c_nodes.append(mycircuit.create_node('nc'+str(i))) inter_nodes.append(mycircuit.create_node('ni'+str(i))) # subcircuit for Metal layer parasitics (MLP) and cores # The values to the cores are obtained as command line inputs. for i in range(_NODE_COUNT): mycircuit.add_resistor("Rb"+str(i), n1=v_nodes[i] , n2=inter_nodes[i] , value = 40e-3) mycircuit.add_inductor("Lb"+str(i), n1=inter_nodes[i] , n2=c_nodes[i] , value = 0.5e-11) mycircuit.add_capacitor("Cb"+str(i), n1=c_nodes[i] , n2=gnd , value = 1.6e-6) mycircuit.add_isource("Ib"+str(i), n1=c_nodes[i] , n2=gnd , dc_value = args.currents[i]) # 0.1e-3) # connection between cores if (i+1)%ROW_SIZE != 0: if i%2 == 0: mycircuit.add_resistor("Rcc"+str(i), n1=c_nodes[i] ,n2=c_nodes[i+1] ,value = 50e-3) if (i+ROW_SIZE) < _NODE_COUNT: if (i/ROW_SIZE)%2 == 0: mycircuit.add_resistor("Rcc"+str(i+_NODE_COUNT), n1=c_nodes[i] ,n2=c_nodes[i+ROW_SIZE] ,value = 50e-3) mycircuit.add_vsource("V"+str(i), n1=v_nodes[i], n2=gnd, dc_value=args.voltages[i]) # OP analysis op_analysis = ahkab.new_op() r = ahkab.run(mycircuit, an_list=[op_analysis]) # print r['op'].results with open('vdd_out.log', 'w') as v_out: for i in range(_NODE_COUNT): gvdd = r['op'].results['vnv'+str(i)] cvdd = r['op'].results['vnc'+str(i)] if gvdd > 0: F_normal = float((gvdd-0.30)*(gvdd-0.30)/gvdd) F_dip = float((cvdd-0.30)*(cvdd-0.30)/cvdd) print ("Node %d : current: %f, Grid Vdd is %f, Core Vdd is %f, variation is %f percent" % (i, args.currents[i], gvdd , cvdd, 100*(gvdd-cvdd)/gvdd)) v_out.write(str(cvdd)+' ') return r
def setUp(self): ttn = ahkab.Circuit('Twin-T Notch Stopband filter') ttn.add_vsource('V1', 'in', ttn.gnd, dc_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.) sa = ahkab.new_symbolic(source=None) self.r = ahkab.run(ttn, sa)['symbolic'][0]
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.) # setup analysis and simulate dca = ahkab.new_dc(-5, 5, 100, 'V1') self.r = ahkab.run(ttn, dca)['dc']
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.) # setup analysis and simulate dca = ahkab.new_dc(-5, 5, 100, 'V1') self.r = ahkab.run(ttn, dca)['dc']
def _run_test(ref_run=False): MINNODES = 6 MAXNODES = 14 STEP = 1 times = [] x = list(range(max((2, MINNODES)), MAXNODES, STEP)) for circuit_nodes in x: # build the circuit mycir = ahkab.Circuit('R2R symbolic test with %d nodes' % circuit_nodes) n1 = '1' gnd = mycir.gnd mycir.add_vsource('VS', n1, gnd, dc_value=10e3) subs = {} for n in range(1, circuit_nodes): n1 = str(n) n2 = str(n + 1) mycir.add_resistor("R%dh1" % n, n1, n2, value=2.6e3) mycir.add_resistor("R%dh2" % n, n1, n2, value=2.6e3) mycir.add_resistor("R%dv" % n, n2, gnd, value=2.6e3) subs.update({"R%dh1" % n: 'R', "R%dh2" % n: 'R', "R%dv" % n: 'R'}) n1 = str(circuit_nodes) mycir.add_resistor("R%dve" % circuit_nodes, n1, gnd, value=2.6e3) subs.update({"R%dve" % circuit_nodes: 'R'}) # define analysis s = ahkab.new_symbolic(subs=subs) start = time.time() r = ahkab.run(mycir, s)['symbolic'][0] stop = time.time() times.append((stop - start)) print("Solving with %d nodes took %f s" % (circuit_nodes, times[-1])) # check the values too VS = r.as_symbol('VS') out_test = r['V' + str(circuit_nodes)] / VS out_th = 1. / (2**(circuit_nodes - 1)) assert .5 * abs(out_th - out_test) / (out_th + out_test) < 1e-3 x = numpy.array(x, dtype=numpy.int64) times = numpy.array(times, dtype=numpy.float64) if ref_run: numpy.savetxt(os.path.join(reference_path, 'r2r_symbolic_ref.csv'), numpy.concatenate((x.reshape( (-1, 1)), times.reshape((-1, 1))), axis=1), delimiter=',') save_boxid(os.path.join(reference_path, 'r2r_symbolic_ref.boxid')) return x, times
def setUp(self): ######### CIRCUIT ############## 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.) # set up the OP and run opa = ahkab.new_op() self.r = ahkab.run(ttn, opa)['op']
def _run_test(ref_run=False): MINNODES = 6 MAXNODES = 14 STEP = 1 times = [] x = list(range(max((2, MINNODES)), MAXNODES, STEP)) for circuit_nodes in x: # build the circuit mycir = ahkab.Circuit('R2R symbolic test with %d nodes' % circuit_nodes) n1 = '1' gnd = mycir.gnd mycir.add_vsource('VS', n1, gnd, dc_value=10e3) subs = {} for n in range(1, circuit_nodes): n1 = str(n) n2 = str(n + 1) mycir.add_resistor("R%dh1" % n, n1, n2, value=2.6e3) mycir.add_resistor("R%dh2" % n, n1, n2, value=2.6e3) mycir.add_resistor("R%dv" % n, n2, gnd, value=2.6e3) subs.update({"R%dh1" % n: 'R', "R%dh2" % n: 'R', "R%dv" % n: 'R'}) n1 = str(circuit_nodes) mycir.add_resistor("R%dve" % circuit_nodes, n1, gnd, value=2.6e3) subs.update({"R%dve" % circuit_nodes: 'R'}) # define analysis s = ahkab.new_symbolic(subs=subs) start = time.time() r = ahkab.run(mycir, s)['symbolic'][0] stop = time.time() times.append((stop - start)) print("Solving with %d nodes took %f s" % (circuit_nodes, times[-1])) # check the values too VS = r.as_symbol('VS') out_test = r['V' + str(circuit_nodes)] / VS out_th = 1./(2**(circuit_nodes - 1)) assert .5*abs(out_th - out_test)/(out_th + out_test) < 1e-3 x = numpy.array(x, dtype=numpy.int64) times = numpy.array(times, dtype=numpy.float64) if ref_run: numpy.savetxt(os.path.join(reference_path, 'r2r_symbolic_ref.csv'), numpy.concatenate((x.reshape((-1, 1)), times.reshape((-1, 1))), axis=1), delimiter=',') save_boxid(os.path.join(reference_path, 'r2r_symbolic_ref.boxid')) return x, times
def take_decision_circuit(observations, parameters): observations = normalize_observations(observations) observations.append(1) # The bias paramter is multiplied by 1 (or -1) # Multiply observations that have indicies in the array negative_weights by -1 to compensate for the paramters by multiplied by -1 for i in range(len(observations)): if i in negative_weights: observations[i] *= -1 # Creating an opamp circuit that adds the input voltages; resistors are used as the paramters (actually 1/parameters) mycir = ahkab.Circuit('Simple Example Circuit') add_op_amp(mycir, "_opamp1") mycir.add_vsource("V1", "v1_r1", mycir.gnd, observations[0]) mycir.add_vsource("V2", "v2_r2", mycir.gnd, observations[1]) mycir.add_vsource("V3", "v3_r3", mycir.gnd, observations[2]) mycir.add_vsource("V4", "v4_r4", mycir.gnd, observations[3]) mycir.add_resistor("R1", "inverting_input_opamp1", "v1_r1", value=1 / parameters[0] * 1000) mycir.add_resistor("R2", "inverting_input_opamp1", "v2_r2", value=1 / parameters[1] * 1000) mycir.add_resistor("R3", "inverting_input_opamp1", "v3_r3", value=1 / parameters[2] * 1000) mycir.add_resistor("R4", "inverting_input_opamp1", "v4_r4", value=1 / parameters[3] * 1000) mycir.add_resistor("over", "inverting_input_opamp1", "output_opamp1", value=1000) opa = ahkab.new_op() r = ahkab.run(mycir, opa)['op'] # output is multiplied by -1 because the opamp inverts the output signal jump_prob = r["VOUTPUT_OPAMP1"][0][0] * -1 if jump_prob > 2.5: return 1 else: return 0
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']
def setUp(self): ttn = ahkab.Circuit('PSS Linear circuit') sin_wave = ahkab.time_functions.sin(vo=0, va=2, td=0, freq=1e6, theta=0, phi=0.) ttn.add_vsource('VIN', 'in', ttn.gnd, dc_value=5, function=sin_wave) ttn.add_resistor('R1', 'in', 'n1', 10e3) ttn.add_resistor('R2', 'n1', 'out', 20e3) ttn.add_resistor('R3', 'n2', ttn.gnd, 10e3) ttn.add_resistor('R4', 'n3', ttn.gnd, 20e3) ttn.add_resistor('R5', 'n3', 'out', 40e3) ttn.add_capacitor('C1', 'n1', 'n2', 31.83e-12) ttn.add_capacitor('C2', 'n1', 'n2', 15.91e-12) ttn.add_vcvs('E1', 'out', ttn.gnd, 'n2', 'n3', 1e6) # create a simulation object and run it! op = ahkab.new_op() pssa = ahkab.new_pss(1e-6, points=60) self.r = ahkab.run(ttn, [op, pssa])['pss']
def test_pz_solution(): """Test results.pz_solution""" # Numeric test, not to run on PYPY if py3compat.PYPY: raise SkipTest bpf = ahkab.Circuit('RLC bandpass') bpf.add_inductor('L1', 'in', 'n1', 1e-6) bpf.add_capacitor('C1', 'n1', 'out', 2.2e-12) bpf.add_resistor('R1', 'out', bpf.gnd, 13) bpf.add_vsource('V1', 'in', bpf.gnd, dc_value=1, ac_value=1) pza = ahkab.new_pz('V1', ('out', bpf.gnd), x0=None, shift=1e3) r = ahkab.run(bpf, pza)['pz'] str(r) np.allclose(r['p0']+r['p1'], -1034507*2, rtol=1e-3) np.allclose(abs(r['p0']-r['p1']), 107297253*2, rtol=1e-3) np.allclose(r['z0'], 0, rtol=1.) assert set(r.keys()) == {u'p0', u'p1', u'z0'} assert r['p0'] == r.get('p0') for i in {u'p0', u'p1', u'z0'}: assert i in r assert r.has_key(i) set(list(zip(*r.items()))[0]) == {u'p0', u'p1', u'z0'} set(list(zip(*r.items()))[1]) == set(r.values()) i = 0 for k, v in r: i += 1 assert v in r.values() assert k in r.keys() assert i == 3
def test_pz_solution(): """Test results.pz_solution""" # Numeric test, not to run on PYPY if py3compat.PYPY: raise SkipTest bpf = ahkab.Circuit('RLC bandpass') bpf.add_inductor('L1', 'in', 'n1', 1e-6) bpf.add_capacitor('C1', 'n1', 'out', 2.2e-12) bpf.add_resistor('R1', 'out', bpf.gnd, 13) bpf.add_vsource('V1', 'in', bpf.gnd, dc_value=1, ac_value=1) pza = ahkab.new_pz('V1', ('out', bpf.gnd), x0=None, shift=1e3) r = ahkab.run(bpf, pza)['pz'] str(r) np.allclose(r['p0'] + r['p1'], -1034507 * 2, rtol=1e-3) np.allclose(abs(r['p0'] - r['p1']), 107297253 * 2, rtol=1e-3) np.allclose(r['z0'], 0, rtol=1.) assert set(r.keys()) == {u'p0', u'p1', u'z0'} assert r['p0'] == r.get('p0') for i in {u'p0', u'p1', u'z0'}: assert i in r assert r.has_key(i) set(list(zip(*r.items()))[0]) == {u'p0', u'p1', u'z0'} set(list(zip(*r.items()))[1]) == set(r.values()) i = 0 for k, v in r: i += 1 assert v in r.values() assert k in r.keys() assert i == 3
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()
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)) # TU1o is bandpass output tf = r['symbolic'][0]['VU1o']/r['symbolic'][0].as_symbol('V1') locals().update(ahkabHelpers.getMapping(tf)) tf = sympy.limit(tf, E1, sympy.oo, '+') tf = ahkabHelpers.reduceTF(tf, mycircuit) sRate = 44.1e3
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')
mycir = ahkab.Circuit('Simple Circuit') mycir.add_resistor('R1', 'n1', mycir.gnd, value=5) mycir.add_vsource('V1', 'n2', 'n1', dc_value=8) mycir.add_resistor('R2', 'n2', mycir.gnd, value=2) mycir.add_vsource('V2', 'n3', 'n2', dc_value=4) mycir.add_resistor('R3', 'n3', mycir.gnd, value=4) mycir.add_resistor('R4', 'n001', 'n3', value=1) mycir.add_vsource('V3', 'n4', mycir.gnd, dc_value=10) mycir.add_resistor('R5', 'n2', 'n4', value=4) mycir.add_resistor('R6','n4','n001',value=10) opa = ahkab.new_op() # Assembles an OP analysis and returns the analysis object. r = ahkab.run(mycir, opa)['op'] #print(r) # print('---------------------------------------------') # a = mycir.get_nodes_number() # print(a) # print('----------------------------------------------') #print the output to a file with open('test_file.txt', 'w') as f: print(r, file=f) with open('test_file.txt', 'r') as f: data = f.read()#.replace('\n', '') print(data)
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') pylab.xlabel('Time [s]') fig.savefig('tran_plot.png')
if thisline[3] == '0': mycircuit.add_vsource('zerovolt' + thisline[0][1], n1=gnd, n2=thisline[4], dc_value=0, ac_value=0) mycircuit.add_cccs(thisline[0], n1=thisline[1], n2=thisline[2], source_id='zerovolt' + thisline[0][1], value=float(thisline[5])) CCCS_ARR += thisline ac = ahkab.new_ac(start=frequency, stop=frequency, points=0, x0=None) res = ahkab.run(mycircuit, ac) myarr = res['ac'].keys() f.write('\n\n____________Active_Power____________\n\n') i = 1 while i < len(ResArray): node1 = 'v' node2 = 'v' value = 0 # f.write("\npow(") # f.write(ResArray[i] + ')=') i = i + 1 node1 = node1 + ResArray[i]
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()
from ahkab import new_dc, run from ahkab.circuit import Circuit from ahkab.plotting import plot_results, show_plots # calls matplotlib for you import scipy as np from ahkab.components.TunnelJunction import * # Define the circuit tjm = TunnelJunctionModel("tjm") cir = Circuit('Scanning Tunnel Microscope IV') cir.add_model("diode", "ddd", {"IS": 0.000139 * 3 * 2.5, "N": 160}) cir.add_vsource('V1', 'n1', cir.gnd, dc_value=1., ac_value=0.) cir.add_diode('D1', 'n1', 'n2', "ddd") cir.add_resistor('R1', 'n1', 'n3', 1.) tj = TunnelJunction('tj1', cir.add_node('n2'), cir.add_node(cir.gnd), tjm, d=10) cir.append(tj) dc1 = new_dc(-2.1, 3, 1e2, source="V1") res = run(cir, dc1) plot_results('Scanning Tunnel Microscope IV', [('I(V1)', '')], res['dc']) show_plots()
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
if (L[0][0]) == "H": list_names_H.append(L[0]) list_nodes_H.append((L[1], L[2])) list_values_H.append(L[4]) if L[1] == "0": circ.add_cccs(L[0], circ.gnd, concat(L[2]), L[3], sconverti(L[4])) continue if L[2] == "0": circ.add_cccs(L[0], concat(L[1]), circ.gnd, L[3], sconverti(L[4])) continue circ.add_cccs(L[0], concat(L[1]), concat(L[2]), L[3], sconverti(L[4])) ac = ahkab.new_ac(start=freq, stop=freq, points=2, x0=None) r = ahkab.run(circ, ac) for i in r['ac']: print(i[0] + "= ", i[1][1]) File.close() output = open("output of powers", "w") # The active resistor power values RPS = 0 for i, node in enumerate(List_nodes_R): v1 = 0 v2 = 0 if node[0] != '0': v1 = r['ac']['v' + node[0]][0] if node[1] != '0':
# Defining the voltage square wave function ( all times are in seconds) # v1 = square wave low value # v2 = square wave high value # td = delay time to the first ramp # tr = rise time from v1 to v2 # pw = pulse width # tf = fall time from v2 to v1 # per = periodicity interval 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) ac_analysis = ahkab.new_ac(start=1e3, stop=1e5, points=100) r = ahkab.run(mycircuit, ac_analysis) print('------------------------------------------------------------------------') print(r) print('------------------------------------------------------------------------') print(r['ac']) print(r['ac'].keys()) print('----------------------------------------------------------------------------') print(np.abs(r['ac']['Vn4'])) fig = plt.figure() plt.subplot(211) plt.semilogx(r['ac']['f'], np.abs(r['ac']['Vn4']), 'o-') plt.ylabel('abs(V(n4)) [V]') plt.title(mycircuit.title + " - AC Simulation")
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()
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 tf = ahkabHelpers.reduceTF(tf, mycircuit) evalTF = sympy.lambdify(ahkabHelpers.getMapping(tf)['s'], tf) out = map(evalTF, 1j*r['ac']['w'][::50]) Vu1o_symb_mag = np.abs(out)
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') pylab.xlabel('Time [s]') fig.savefig('tran_plot.png')
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('Simple circuit') cir.add_vsource('V1', 'n1', cir.gnd, dc_value=5) cir.add_resistor('R1', 'n1', 'n2', 50) res = run(cir) print res print type(res)
ac("Cin", "in", gnd, 100e-3) al("L1", "in", "s1", 47e-6) ac("C1", "s1", "da", 10e-6) al("L2", "da", gnd, 47e-6) ac("C2", "dc", gnd, 100e-3) #circuit.add_inductor_coupling("K1", "L1", "L2", 0.99) buildsepic(mycircuit) print(mycircuit) symbolic_sim = ahkab.new_symbolic() try: r = pickle.load(open("results-sepic.pk")) except: r = ahkab.run(mycircuit, (symbolic_sim,)) pickle.dump(r, open("results-sepic.pk", "wb")) print mycircuit print r['symbolic'][0] tf = r['symbolic'][0]['I[L1]']/r['symbolic'][0]['Vin'] tf = ahkabHelpers.reduceTF(tf, mycircuit) import compensators print compensators.drawBode(tf) from pylab import savefig savefig('sepic.png')
netdict = generate_network(mem_pars, net_pars) global a0, f0 a0 = 1000 f0 = 10 circ_state = [] x = 0 y = 0 fig = plt.figure(1) ax = fig.add_subplot(211) ax1 = fig.add_subplot(212) plt.subplots_adjust(left=0.25, bottom=0.25) r = run(netdict['Circuit'], netdict['Opa'])['op'] line = [None] * (len(r.results.keys())) for n in range(len(line)): line[n], = ax.plot(x, y) l2, = ax1.plot(x, y) axcolor = 'lightgoldenrodyellow' axfreq = plt.axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor) axamp = plt.axes([0.25, 0.15, 0.65, 0.03], axisbg=axcolor) sfreq = Slider(axfreq, 'Freq', 0.01, 20.0, valinit=f0) samp = Slider(axamp, 'Amp', 0.1, 1500.0, valinit=a0) def update(val):
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'): print(keys[i])
import pdb from ahkab import netlist_parser, circuit, ac import ahkab import numpy as np import os, sys """ bpf = ahkab.Circuit('RLC bandpass') bpf.add_inductor('L1', 'in', 'n1', 1e-6) bpf.add_capacitor('C1', 'n1', 'out', 2.2e-12) bpf.add_resistor('R1', 'out', bpf.gnd, 13) # we also give V1 an AC value since we wish to run an AC simulation # in the following bpf.add_vsource('V1', 'in', bpf.gnd, dc_value=1, ac_value=1) """ fspice = sys.argv[1] parsed = netlist_parser.parse_circuit(fspice) cir = parsed[0] cir.add_vsource('V1', 'in', cir.gnd, dc_value=1, ac_value=1) out = 'n8' pza = ahkab.new_pz('V1', (out, cir.gnd), x0=None, shift=1e3) r = ahkab.run(cir, pza)['pz'] print('Singularities:') for x, _ in r: print "* %s = %+g %+gj Hz" % (x, np.real(r[x]), np.imag(r[x])) pdb.set_trace()
lista_de_análisis[1]['outfile'] = "simulación dc.tsv" # %% [markdown] # > **Pregunta:** escribe el código Python necesario para identificar qué análisis de `lista_de_análisis` # son de tipo `dc` ó `tran` y sólo añadir la propiedad `outfile` en estos casos. # Aquí tenéis un post de Stackoverflow con algo de [ayuda](https://stackoverflow.com/questions/49194107/how-to-find-index-of-a-dictionary-key-value-within-a-list-python). # Un poco más de ayuda: el siguiente código (sí, una única línea) devuelve el índice de la simulación que es de tipo `dc`. Para simplificar un poco el ejercicio, suponed que, como máximo, habrá un análisis de tipo `tran` y/o `dc`. # %% [i for i, d in enumerate(lista_de_análisis) if "dc" in d.values()][0] # %% [markdown] # Una vez que ya hemos separado netlists de simulaciones, ahora ejecutamos las segundas (¡todas a la vez!) gracias al método `.run` de Ahkab: # %% resultados = ahkab.run(circuito, lista_de_análisis) # %% [markdown] # ### Resultados de la simulación `.dc` # Imprimimos información sobre la simulación de tipo `.dc`: # %% print(resultados['dc']) # %% [markdown] # Veamos qué variables podemos dibujar para el caso del análisis `dc`. # %% print(resultados['dc'].keys()) # %% [markdown]
# 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)
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'): v=abs((check_v(en,l)-check_v(sn,l)))
from ahkab import new_dc, run from ahkab.circuit import Circuit from ahkab.plotting import plot_results, show_plots # calls matplotlib for you import scipy as np from ahkab.components.TunnelJunction import * # Define the circuit tjm=TunnelJunctionModel("tjm") cir = Circuit('Scanning Tunnel Microscope IV') cir.add_model("diode","ddd",{"IS":0.000139*3*2.5,"N":160}) cir.add_vsource('V1','n1', cir.gnd, dc_value=1., ac_value=0.) cir.add_diode('D1','n1','n2',"ddd") cir.add_resistor('R1', 'n1', 'n3', 1.) tj=TunnelJunction('tj1',cir.add_node('n2'),cir.add_node(cir.gnd),tjm,d=10) cir.append(tj) dc1 = new_dc(-2.1,3, 1e2, source="V1") res = run(cir, dc1) plot_results('Scanning Tunnel Microscope IV', [('I(V1)','')], res['dc']) show_plots()