def freq_resp(): shutil.copyfile('PA13.LIB', '/tmp/PA13.LIB') shutil.copyfile('op27.cir', '/tmp/op27.cir') circuit = Circuit('Freq Response') circuit.include('/tmp/PA13.LIB') circuit.include('/tmp/op27.cir') circuit.subcircuit(PA13Amplifier(Z_1, Z_2)) circuit.subcircuit(OP27Amplifier(R_4, C_4)) # V_Ir input circuit.SinusoidalVoltageSource('input', 'vr', circuit.gnd, amplitude=0.05) circuit.R('r3', 'vir', 'vir2', Z_3) # Current controller stage circuit.X('curr', 'op27_amplifier', 'vir2', 'vr') # Voltage stage circuit.X('volt', 'pa13_amplifier', 'vr', 'vo') # Motor stage circuit.R('rm', 'vo', 'vm1', R_m) circuit.L('lm', 'vm1', 'vio', L_m) circuit.R('rs', 'vio', circuit.gnd, R_s) circuit.R('r5', 'vio', 'vir2', Z_5) simulator = circuit.simulator() # Force ngspice to have shorter time steps near sharp transitions simulator.options(trtol=0.0001) import pdb pdb.set_trace() analysis = simulator.ac( start_frequency=50e0, stop_frequency=5 * f_h, number_of_points=1000, # Lab manual suggests 20, might as well do more variation='dec') return analysis
def negative_clamper(v, r, c, f): print(v, r, c, f) circuit = Circuit('Negative Clamper') circuit.include('./app/circuits/libraries/diode/switching/1N4148.lib') source = circuit.SinusoidalVoltageSource('input', 'in', circuit.gnd, amplitude=u_V(float(v)), frequency=u_Hz(float(f))) circuit.C('C1', 'in', 'output', u_mF(float(c))) circuit.X('D1', '1N4148', 'output', circuit.gnd) circuit.R('load', 'output', circuit.gnd, u_Ohm(float(r))) simulator = circuit.simulator(temperature=25, nominal_temperature=25) analysis = simulator.transient(step_time=source.period / 200, end_time=source.period * 2) plt.close('all') plt.title('Negative Clamper') plt.xlabel('Time [s]') plt.ylabel('Voltage [V]') plt.grid() plt.plot(analysis['in']) plt.plot(analysis.output) plt.legend(('input', 'output'), loc=(.05, .1)) plt.tight_layout() return circuit, analysis, plt
def high_pass_rc_filter(v, r, c): circuit = Circuit('Low-Pass RC Filter') circuit.SinusoidalVoltageSource('input', 'in', circuit.gnd, amplitude=u_V(float(v))) C1 = circuit.C(1, 'in', 'out', u_uF(float(c))) R1 = circuit.R(1, 'out', circuit.gnd, u_kΩ(float(r))) break_frequency = 1 / (2 * math.pi * float(R1.resistance * C1.capacitance)) print("Break frequency = {:.1f} Hz".format(break_frequency)) simulator = circuit.simulator(temperature=25, nominal_temperature=25) analysis = simulator.ac(start_frequency=1 @ u_Hz, stop_frequency=1 @ u_MHz, number_of_points=10, variation='dec') # print(analysis.out) plt.close('all') figure, axes = plt.subplots(2, figsize=(20, 10)) plt.title("Bode Diagram of a Low-Pass RC Filter") bode_diagram( axes=axes, frequency=analysis.frequency, gain=20 * np.log10(np.absolute(analysis.out)), phase=np.angle(analysis.out, deg=False), marker='.', color='blue', linestyle='-', ) for ax in axes: ax.axvline(x=break_frequency, color='red') plt.tight_layout() return circuit, analysis, plt
def createCircuit(filter1o, filter2o): circuit = Circuit('Filter') circuit.include('Models/BasicOpamp.cir') circuit.include('Models/AD8619.cir') circuit.include('Models/TL084.cir') circuit.subcircuit(filter1o) circuit.subcircuit(filter2o) circuit.V('1', '5V', circuit.gnd, '5') circuit.V('2', 'VRef', circuit.gnd, '2.5') circuit.SinusoidalVoltageSource('In', 'In', 'VRef', amplitude=1) circuit.X('1', filter1o.name, 'In', 'out1o', 'VRef', '5V', circuit.gnd) circuit.X('2', filter2o.name, 'In', 'out2o', 'VRef', '5V', circuit.gnd) print(circuit) return circuit
def full_wave_rectifier(v, r, c, f): circuit = Circuit('Full-wave rectification') circuit.include('./app/circuits/libraries/diode/switching/1N4148.lib') source = circuit.SinusoidalVoltageSource('input', 'in', circuit.gnd, amplitude=u_V(float(v)), frequency=u_Hz(float(f))) circuit.X('D1', '1N4148', 'in', 'output_plus') circuit.R('load', 'output_plus', 'output_minus', u_Ω(float(r))) circuit.X('D2', '1N4148', 'output_minus', circuit.gnd) circuit.X('D3', '1N4148', circuit.gnd, 'output_plus') circuit.X('D4', '1N4148', 'output_minus', 'in') simulator = circuit.simulator(temperature=25, nominal_temperature=25) analysis = simulator.transient(step_time=source.period / 200, end_time=source.period * 2) plt.close('all') figure, (ax3, ax4) = plt.subplots(2, figsize=(20, 10)) ax3.set_title('Full-Wave Rectification') ax3.set_xlabel('Time [s]') ax3.set_ylabel('Voltage [V]') ax3.grid() ax3.plot(analysis['in']) ax3.plot(analysis.output_plus - analysis.output_minus) ax3.legend(('input', 'output'), loc=(.05, .1)) ax3.set_ylim(float(-source.amplitude * 1.1), float(source.amplitude * 1.1)) circuit.C('1', 'output_plus', 'output_minus', u_mF(float(c))) simulator = circuit.simulator(temperature=25, nominal_temperature=25) analysis = simulator.transient(step_time=source.period / 200, end_time=source.period * 2) ax4.set_title('Full-Wave Rectification with filtering') ax4.set_xlabel('Time [s]') ax4.set_ylabel('Voltage [V]') ax4.grid() ax4.plot(analysis['in']) ax4.plot(analysis.output_plus - analysis.output_minus) ax4.legend(('input', 'output'), loc=(.05, .1)) ax4.set_ylim(float(-source.amplitude * 1.1), float(source.amplitude * 1.1)) plt.tight_layout() return circuit, analysis, plt
def operational_amplifier(): circuit = Circuit('Operational Amplifier') # AC 1 PWL(0US 0V 0.01US 1V) circuit.SinusoidalVoltageSource('input', 'in', circuit.gnd, amplitude=10000000 @ u_V) circuit.subcircuit(BasicOperationalAmplifier()) circuit.X('op', 'BasicOperationalAmplifier', 'in', circuit.gnd, 'out') circuit.R('load', 'out', circuit.gnd, 470 @ u_Ω) circuit.R( 'R1', 'in', 'out', ) simulator = circuit.simulator(temperature=25, nominal_temperature=25) analysis = simulator.ac(start_frequency=1 @ u_Hz, stop_frequency=100 @ u_MHz, number_of_points=5, variation='dec') plt.close('all') figure, (ax1, ax2) = plt.subplots(2, figsize=(20, 10)) plt.title("Bode Diagram of an Operational Amplifier") bode_diagram( axes=(ax1, ax2), frequency=analysis.frequency, gain=20 * np.log10(np.absolute(analysis.out)), phase=np.angle(analysis.out, deg=False), marker='.', color='blue', linestyle='-', ) return circuit, analysis, plt
from PySpice.Spice.Netlist import Circuit from PySpice.Unit import * #################################################################################################### # r# We define four low-pass RLC filters with the following factor of quality: .5, 1, 2 and 4. #f# circuit_macros('low-pass-rlc-filter.m4') circuit1 = Circuit('Four double-pole Low-Pass RLC Filter') inductance = 10 @ u_mH capacitance = 1 @ u_uF circuit1.SinusoidalVoltageSource('input', 'in', circuit1.gnd, amplitude=1 @ u_V) #?# pulse 0 5 10 ms # Q = .5 circuit1.R(1, 'in', 1, 200 @ u_Ω) circuit1.L(1, 1, 'out5', inductance) circuit1.C(1, 'out5', circuit1.gnd, capacitance) # Q = 1 circuit1.R(2, 'in', 2, 100 @ u_Ω) circuit1.L(2, 2, 'out1', inductance) circuit1.C(2, 'out1', circuit1.gnd, capacitance) # Q = 2 circuit1.R(3, 'in', 3, 50 @ u_Ω) circuit1.L(3, 3, 'out2', inductance) circuit1.C(3, 'out2', circuit1.gnd, capacitance) # Q = 4
from PySpice.Doc.ExampleTools import find_libraries from PySpice.Probe.Plot import plot from PySpice.Spice.Library import SpiceLibrary from PySpice.Spice.Netlist import Circuit from PySpice.Unit import * libraries_path = find_libraries() spice_library = SpiceLibrary(libraries_path) figure1 = plt.figure(1, (20, 10)) circuit = Circuit('half-wave rectification') circuit.include(spice_library['1N4148']) source = circuit.SinusoidalVoltageSource('input', 'in', circuit.gnd, amplitude=10 @ u_V, frequency=50 @ u_Hz) circuit.X('D1', '1N4148', 'in', 'output') circuit.R('load', 'output', circuit.gnd, 100 @ u_Ω) simulator = circuit.simulator(temperature=25, nominal_temperature=25) analysis = simulator.transient(step_time=source.period / 200, end_time=source.period * 2) axe = plt.subplot(221) plt.title('Half-Wave Rectification') plt.xlabel('Time [s]') plt.ylabel('Voltage [V]') plt.grid() plot(analysis['in'], axis=axe)
#from PySpiceDvTools.LTSpiceServer import enableLtSpice circuit = Circuit('NonLineal Load Sim') ''' V1 A 0 SINE(0 220 50) D1 0 N001 Def D2 A N001 Def D3 N003 A Def D4 N003 0 Deg R1 N001 N002 27.5 L1 N002 N003 0.5 .MODEL Def D ''' circuit.SinusoidalVoltageSource('1', 'A', circuit.gnd, amplitude=220, frequency=50) subcir = BasicNonLinearLoad(r=27.5, l=0.5) circuit.subcircuit(subcir) circuit.X('1', 'BasicNonLinearLoad', 'A', circuit.gnd) print(circuit) print(subcir.getRValue()) print(subcir.getLValue()) simulator = circuit.simulator() #enableLtSpice(simulator) analysis = simulator.transient(step_time=1 @ u_ms, end_time=1 @ u_s)
#?# #o# #r# We found a dynamic resistance of @<@dynamic_resistance:.1f@>@ Ω. #################################################################################################### #r# #r# We will now drive the diode with a sinusoidal source and perform an AC analysis. #f# circuit_macros('diode-characteristic-curve-circuit-ac.m4') circuit = Circuit('Diode') circuit.include(spice_library['BAV21']) circuit.SinusoidalVoltageSource('input', 'in', circuit.gnd, dc_offset=dc_offset, offset=dc_offset, amplitude=ac_amplitude) R = circuit.R(1, 'in', 'out', 1 @ u_kΩ) circuit.D('1', 'out', circuit.gnd, model='BAV21') simulator = circuit.simulator(temperature=25, nominal_temperature=25) analysis = simulator.ac(start_frequency=10 @ u_kHz, stop_frequency=1 @ u_GHz, number_of_points=10, variation='dec') #r# Let plot the voltage across the diode and the dynamic resistance as a function of the frequency. figure = plt.figure(1, (20, 10))
from PySpice.Probe.Plot import plot from PySpice.Spice.Library import SpiceLibrary from PySpice.Spice.Netlist import Circuit from PySpice.Unit import * logger = Logging.setup_logging() libraries_path = find_libraries() spice_library = SpiceLibrary(libraries_path) circuit = Circuit('Transistor') circuit.V('power', 5, circuit.gnd, 15 @ u_V) source = circuit.SinusoidalVoltageSource('in', 'in', circuit.gnd, amplitude=.5 @ u_V, frequency=1 @ u_kHz) circuit.C(1, 'in', 2, 10 @ u_uF) circuit.R(1, 5, 2, 100 @ u_kΩ) circuit.R(2, 2, 0, 20 @ u_kΩ) circuit.R('C', 5, 4, 10 @ u_kΩ) circuit.BJT(1, 4, 2, 3, model='bjt') # Q is mapped to BJT ! circuit.model('bjt', 'npn', bf=80, cjc=pico(5), rb=100) circuit.R('E', 3, 0, 2 @ u_kΩ) circuit.C(2, 4, 'out', 10 @ u_uF) circuit.R('Load', 'out', 0, 1 @ u_MΩ) # .ac dec 5 10m 1G simulator = circuit.simulator(temperature=25, nominal_temperature=25)
dc_offset=5) skidl_SINV['p', 'n'] += net_1, net_2 skidl_circ = generate_netlist() print(skidl_circ) # In[49]: pyspice_circ = Circuit('') pyspice_circ.SinusoidalVoltageSource( '1', 'N1', 'N2', #transit sim statments offset=5, amplitude=5, frequency=5, delay=5, damping_factor=5, #ac sim statments ac_magnitude=5, dc_offset=5) print(pyspice_circ) # In[50]: netlist_comp_check(skidl_circ, pyspice_circ) # ## SinusoidalCurrentSource (AC) # #
figure1 = plt.figure(1, (20, 10)) circuit = Circuit('115/230V Rectifier') circuit.include(spice_library['1N4148']) on_115 = True # switch to select 115 or 230V if on_115: node_230 = circuit.gnd node_115 = 'node_115' amplitude = 115 @ u_V else: node_230 = 'node_230' node_115 = circuit.gnd amplitude = 230 @ u_V source = circuit.SinusoidalVoltageSource('input', 'in', circuit.gnd, amplitude=amplitude, frequency=50) # Fixme: rms circuit.X('D1', '1N4148', 'in', 'output_plus') circuit.X('D3', '1N4148', node_230, 'output_plus') circuit.X('D2', '1N4148', 'output_minus', node_230) circuit.X('D4', '1N4148', 'output_minus', 'in') circuit.C('1', 'output_plus', node_115, 1 @ u_mF) circuit.C('2', node_115, 'output_minus', 1 @ u_mF) circuit.R('load', 'output_plus', 'output_minus', 10 @ u_Ω) simulator = circuit.simulator(temperature=25, nominal_temperature=25) if on_115: simulator.initial_condition(node_115=0) analysis = simulator.transient(step_time=source.period / 200, end_time=source.period * 2)
def define_circuit(self): logger = Logging.setup_logging() circuit_lab = self.circuit circuit = Circuit(circuit_lab["name"]) # for complex circuit elements that requires SPICE library # libraries_path = find_libraries() python_file = os.path.abspath(sys.argv[0]) examples_root = parent_directory_of(python_file) libraries_path = os.path.join(examples_root, 'libraries') spice_library = SpiceLibrary(libraries_path) # return message message = "" # add all elements to the PySpice circuit for element in circuit_lab: if element == "V": for dc_voltage_source in circuit_lab["V"]: circuit.V( dc_voltage_source["id"], circuit.gnd if dc_voltage_source["node1"] == "gnd" else dc_voltage_source["node1"], circuit.gnd if dc_voltage_source["node2"] == "gnd" else dc_voltage_source["node2"], dc_voltage_source["value"] @ u_V) elif element == "VA": for ac_voltage_source in circuit_lab["VA"]: circuit.SinusoidalVoltageSource( ac_voltage_source["id"], circuit.gnd if ac_voltage_source["node1"] == "gnd" else ac_voltage_source["node1"], circuit.gnd if ac_voltage_source["node2"] == "gnd" else ac_voltage_source["node2"], amplitude=ac_voltage_source["amplitude"] @ u_V, frequency=ac_voltage_source["frequency"] @ u_Hz, offset=ac_voltage_source["offset"] @ u_V) elif element == "I": for dc_current_source in circuit_lab["I"]: circuit.I( dc_current_source["id"], circuit.gnd if dc_current_source["node1"] == "gnd" else dc_current_source["node1"], circuit.gnd if dc_current_source["node2"] == "gnd" else dc_current_source["node2"], dc_current_source["value"] @ u_A) elif element == "IA": for ac_current_source in circuit_lab["IA"]: circuit.SinusoidalCurrentSource( ac_current_source["id"], circuit.gnd if ac_current_source["node1"] == "gnd" else ac_current_source["node1"], circuit.gnd if ac_current_source["node2"] == "gnd" else ac_current_source["node2"], amplitude=ac_current_source["amplitude"] @ u_A, frequency=ac_current_source["frequency"] @ u_Hz, offset=ac_current_source["offset"] @ u_A) elif element == "R": for resistor in circuit_lab["R"]: circuit.R( resistor["id"], circuit.gnd if resistor["node1"] == "gnd" else resistor["node1"], circuit.gnd if resistor["node2"] == "gnd" else resistor["node2"], resistor["value"] @ u_Ω) elif element == "L": for inductor in circuit_lab["L"]: circuit.L( inductor["id"], circuit.gnd if inductor["node1"] == "gnd" else inductor["node1"], circuit.gnd if inductor["node2"] == "gnd" else inductor["node2"], inductor["value"] @ u_H) elif element == "C": for capacitor in circuit_lab["C"]: circuit.C( capacitor["id"], circuit.gnd if capacitor["node1"] == "gnd" else capacitor["node1"], circuit.gnd if capacitor["node2"] == "gnd" else capacitor["node2"], capacitor["value"] @ u_F) elif element == "D": for diode in circuit_lab["D"]: try: circuit.include(spice_library[diode["modelType"]]) circuit.X( diode["id"], diode["modelType"], circuit.gnd if diode["node1"] == "gnd" else diode["node1"], circuit.gnd if diode["node2"] == "gnd" else diode["node2"]) except KeyError as e: message += " " + str(e) elif element == "nBJT": for nBJT in circuit_lab["nBJT"]: try: circuit.include(spice_library[nBJT["modelType"]]) circuit.BJT(nBJT["id"], circuit.gnd if nBJT["node1"] == "gnd" else nBJT["node1"], circuit.gnd if nBJT["node2"] == "gnd" else nBJT["node2"], circuit.gnd if nBJT["node3"] == "gnd" else nBJT["node3"], model=nBJT["modelType"]) except KeyError as e: message += " " + str(e) elif element == "pBJT": for pBJT in circuit_lab["pBJT"]: try: circuit.include(spice_library[pBJT["modelType"]]) circuit.BJT(pBJT["id"], circuit.gnd if pBJT["node3"] == "gnd" else pBJT["node3"], circuit.gnd if pBJT["node2"] == "gnd" else pBJT["node2"], circuit.gnd if pBJT["node1"] == "gnd" else pBJT["node1"], model=pBJT["modelType"]) except KeyError as e: message += " " + str(e) elif element == "NMOS": for NMOS in circuit_lab["NMOS"]: try: circuit.include(spice_library[NMOS["modelType"]]) # nodes are: drain, gate, source, bulk circuit.MOSFET(NMOS["id"], circuit.gnd if NMOS["node4"] == "gnd" else NMOS["node4"], circuit.gnd if NMOS["node2"] == "gnd" else NMOS["node2"], circuit.gnd if NMOS["node3"] == "gnd" else NMOS["node3"], circuit.gnd if NMOS["node1"] == "gnd" else NMOS["node1"], model=NMOS["modelType"]) except KeyError as e: message += " " + str(e) elif element == "PMOS": for PMOS in circuit_lab["PMOS"]: try: circuit.include(spice_library[PMOS["modelType"]]) # nodes are: source, gate, drain, bulk circuit.MOSFET(PMOS["id"], circuit.gnd if PMOS["node1"] == "gnd" else PMOS["node1"], circuit.gnd if PMOS["node2"] == "gnd" else PMOS["node2"], circuit.gnd if PMOS["node3"] == "gnd" else PMOS["node3"], circuit.gnd if PMOS["node4"] == "gnd" else PMOS["node4"], model=PMOS["modelType"]) except KeyError as e: message += " " + str(e) # add ammeter as a 0 volt voltage source elif element == "AM": for ammeter in circuit_lab["AM"]: circuit.V( ammeter["id"], circuit.gnd if ammeter["node1"] == "gnd" else ammeter["node1"], circuit.gnd if ammeter["node2"] == "gnd" else ammeter["node2"], ammeter["value"] @ u_V) if not message: self.spice = circuit return message return "Undefined model type:" + message
class Circus: def __init__(self, elements_list, N_orig_comp,gene=None): self.elements_list = elements_list self.elements_names = list(elements_list.keys()) self.N_orig_comp = N_orig_comp self.create_node_list() if gene==None: self.generate_gene() else: self.gene=gene self.list_nodes_comps() self.add_jumpers() # self.draw_circuit() def create_node_list(self): self.node_list = ["Vin"] for i in range(0, self.N_orig_comp): n_node_list = ["n{}".format(i)][0] self.node_list.append(n_node_list) self.node_list.append("GND") def generate_gene(self): self.out = random.choice(self.node_list) while (self.out == 'Vin') or (self.out == 'GND'): self.out = random.choice(self.node_list) self.components = random.choices(self.elements_names, k=self.N_orig_comp) self.nodes = [] for comp in self.components: start = np.random.randint(1, self.N_orig_comp) end = np.random.randint(start + 1, self.N_orig_comp + 1) self.nodes.append(self.node_list[start]) self.nodes.append(self.node_list[end]) self.assemble_gene() def assemble_gene(self): self.gene = [self.out] for c, comp in enumerate(self.components): self.gene.append(self.nodes[2 * c]) self.gene.append(comp) self.gene.append(self.nodes[2 * c+1]) def list_nodes_comps(self): self.nodes=[] self.components=[] for i in range(self.N_orig_comp): self.nodes.append(self.gene[i*3+1]) self.components.append(self.gene[i*3+2]) self.nodes.append(self.gene[i*3+3]) def add_jumpers(self): #IMPORTANT COMMENT: this function add jumpers self.gene_jumper=copy.copy(self.gene) conns_circuit={} for i in range(self.N_orig_comp): node1=self.gene[i*3+1] component=self.gene[i*3+2] node2=self.gene[i*3+3] node=[node1,node2] node.sort() if (node1+node2 in conns_circuit): conns_circuit[node1+node2].append(component) else: conns_circuit[node1+node2]=[component] for n in range(len(self.node_list)-1): node1 = self.node_list[n] node2 = self.node_list[n+1] if node1+node2 not in conns_circuit: self.gene_jumper.append(node1) self.gene_jumper.append("jumper") self.gene_jumper.append(node2) def assemble_circuit(self): self.circuit = Circuit("pindamonhangaba") self.circuit.SinusoidalVoltageSource('input', 'Vin', self.circuit.gnd, [email protected]_kV) K=len(self.gene_jumper) troca=self.gene_jumper[0] new_gene=["out" if comp==troca else comp for comp in self.gene_jumper] for pos in range(1,K,3): # print(pos,self.gene[pos:pos+3]) pos1=new_gene[pos] pos2=new_gene[pos+2] component=new_gene[pos+1] if component=="jumper": func_add=self.circuit.R [email protected]_mΩ else: if (component[0] == "R"): func_add=self.circuit.R elif (component[0] == "C"): func_add=self.circuit.C elif (component[0] == "L"): func_add=self.circuit.L valor=self.elements_list[component][1] func_add(pos,pos1,pos2,valor) def mutation(self): for c in range(self.N_orig_comp): aux = random.randint(0, 100) if aux <= 5: self.components[c] = random.choice(self.elements_names) for n in range(self.N_orig_comp * 2): aux = random.randint(0, 100) if aux <= 5: self.nodes[n] = random.choice(self.node_list) self.assemble_gene()
libraries_path = find_libraries() spice_library = SpiceLibrary(libraries_path) #################################################################################################### from RingModulator import RingModulator #f# literal_include('RingModulator.py') #################################################################################################### circuit = Circuit('Ring Modulator') modulator = circuit.SinusoidalVoltageSource('modulator', 'in', circuit.gnd, amplitude=1 @ u_V, frequency=1 @ u_kHz) carrier = circuit.SinusoidalVoltageSource('carrier', 'carrier', circuit.gnd, amplitude=10 @ u_V, frequency=100 @ u_kHz) circuit.R('in', 'in', 1, 50 @ u_Ω) circuit.R('carrier', 'carrier', 2, 50 @ u_Ω) circuit.include(spice_library['1N4148']) circuit.subcircuit( RingModulator( outer_inductance=1 @ u_uH, inner_inductance=1 @ u_uH,