Exemple #1
1
 def test_transformer(self):
     import os
     from PySpice.Spice.Netlist import Circuit
     circuit = Circuit('Diode Characteristic Curve')
     circuit.L('primary', 'Vlp', 'Vdrain', '{l_trf}')
     circuit.C('resonance', 'Vlv', 'Vdrain', '{cap_r}')
     circuit.L('secondary', 'Vls', 'ghv', '{Ls}')
     circuit.R('secondary', 'Vls', 1, 5.15)
     circuit.K('flyback', 'Lprimary', 'Lsecondary', 1)
Exemple #2
0
    def test_spinit(self):

        from PySpice.Spice.Netlist import Circuit
        import PySpice.Unit as U

        circuit = Circuit('Astable Multivibrator')

        source = circuit.V('cc', 'vcc', circuit.gnd, 15 @ U.u_V)
        circuit.R(1, 'output', 'comparator', 1 @ U.u_kΩ)
        circuit.C(1, 'comparator', circuit.gnd, 100 @ U.u_nF)
        circuit.R(2, 'output', 'reference', 100 @ U.u_kΩ)
        circuit.R(3, 'vcc', 'reference', 100 @ U.u_kΩ)
        circuit.R(4, 'reference', circuit.gnd, 100 @ U.u_kΩ)
        circuit.NonLinearVoltageSource(1,
                                       'output',
                                       circuit.gnd,
                                       expression='V(reference, comparator)',
                                       table=((-U.micro(1), 0),
                                              (U.micro(1), source.dc_value)))

        simulator = circuit.simulator(temperature=25, nominal_temperature=25)
        simulator.initial_condition(
            comparator=0)  # Fixme: simulator.nodes.comparator == 0
        analysis = simulator.transient(step_time=1 @ U.u_us,
                                       end_time=500 @ U.u_us)

        if (len(analysis.output)) < 500:
            raise NameError('Simualtion failed')
Exemple #3
0
    def __init__(self, name):
        Circuit.__init__(self, name)
        libraries_path = 'C:\\Users\\micha\\PycharmProjects\\circuit_model\\component_libraries\\transistor'
        spice_library = SpiceLibrary(libraries_path)
        self.include(spice_library['ptm65nm_nmos'])
        self.include(spice_library['ptm65nm_pmos'])

        # input pair
        self.MOSFET(1, "vd_l", "inp", "vtail", self.gnd, model='ptm65nm_nmos', width=5e-6, length=0.65e-6)
        self.MOSFET(2, "vd_r", "inn", "vtail", self.gnd, model='ptm65nm_nmos', width=5e-6, length=0.65e-6)

        # active load
        self.MOSFET(3, "vd_l", "vd_l", "vdd", "vdd", model='ptm65nm_pmos', width=2.5e-6, length=0.65e-6)
        self.MOSFET(4, "vd_r", "vd_l", "vdd", "vdd", model='ptm65nm_pmos', width=2.5e-6, length=0.65e-6)

        # tail current
        self.MOSFET(5, "vtail", "vbias", self.gnd, self.gnd, model='ptm65nm_nmos', width=5e-6, length=1e-6)
        # input current mirror
        self.MOSFET(6, "vbias", "vbias", self.gnd, self.gnd, model='ptm65nm_nmos', width=5e-6, length=1e-6)

        # sources
        self.I(1, "vdd", "vbias", 1e-6)

        # load
        self.R('load', 'vd_r', self.gnd, 1e9)
        self.C('load', 'vd_r', self.gnd, 5e-12)
    def test(self):

        self._test_spice_declaration(
            Resistor(Circuit(''), '1', 'n1', 'n2', 100),
            'R1 n1 n2 100'.lower())
        self._test_spice_declaration(
            Resistor(Circuit(''), '1', 'n1', 'n2', kilo(1)),
            'R1 n1 n2 1k'.lower())
        self._test_spice_declaration(
            Resistor(Circuit(''),
                     '1',
                     'n1',
                     'n2',
                     kilo(1),
                     ac=kilo(2),
                     multiplier=2,
                     scale=1.5,
                     temperature=25,
                     device_temperature=26,
                     noisy=True),
            'R1 n1 n2 1k ac=2k dtemp=26 m=2 noisy=1 scale=1.5 temp=25'.lower())
        self._test_spice_declaration(
            Resistor(Circuit(''), '1', 'n1', 'n2', kilo(1), noisy=False),
            'R1 n1 n2 1k'.lower())

        self._test_spice_declaration(
            XSpiceElement(Circuit(''), '1', 1, 0, model='cap'),
            'A1 1 0 cap'.lower())
class AM_circuit():
	
	'''
	translate a netlist into ngSpice elements
	'''
	
	def __init__(self):
		pass
	
	def load_netlist(self,netlistfile):
		'''
		class method to build a circuit model from a netlist
		netlistfile=path/filename that contains a valid spice netlist
		'''
		with open(netlistfile,'r',encoding='utf-8') as f:
			self.netlist = [item.strip() for item in f.readlines()[:-1]]
			self.circuitname = self.netlist[0].lstrip('.title').strip()
			self.instantiate_circuit()
	
	def instantiate_circuit(self):
		'''
		class method that instantiates a circuit model from an inherited netlist
		'''
		self.circuit = Circuit(self.circuitname)
		for line in self.netlist[1:]:
			try:
				self.add_circuit_element_from_netlist_line(line)
			except:
				print(traceback.format_exc())
		
	def add_circuit_element_from_netlist_line(self,line):
		'''
		class method to parse a line from a netlist and add RC components to a circuit model
		line=text string from netlist
		'''
		line = line.split(' ')
		if 'R' in line[0]:
			self.circuit.Resistor(line[0].lstrip('R'),line[1],line[2],kilo(float(line[3].rstrip('k'))))
		
		if 'C' in line[0]:
			self.circuit.Capacitor(line[0].lstrip('C'),line[1],line[2],float(line[3])@u_uF)
		
		if 'I' in line[0]:
			self.circuit.CurrentSource(line[0].lstrip('I'),line[1],line[2],line[3])
	
	def get_nodal_voltages(self,analysis):
		'''
		class method to retrieve nodal voltages from a circuit analysis
		analysis:circuit analysis (simulator.operating_point(), etc.)
		returns:list
		'''
		nvs = {}
		for key in analysis.nodes.keys():
			nvs[int(key)-1] = analysis[key].T.tolist()[0]
		
		return(nvs)
	def instantiate_circuit(self):
		'''
		class method that instantiates a circuit model from an inherited netlist
		'''
		self.circuit = Circuit(self.circuitname)
		for line in self.netlist[1:]:
			try:
				self.add_circuit_element_from_netlist_line(line)
			except:
				print(traceback.format_exc())
Exemple #7
0
def create_circuit(genome, config):
    libraries_path = '/home/alan/ngspice/libraries'  # os.path.join(os.path.dirname(os.path.dirname(__file__)), 'libraries')
    spice_library = SpiceLibrary(libraries_path)

    circuit = Circuit('NEAT')
    circuit.include(spice_library['1N4148'])

    Vbase = circuit.V('base', 'input1', circuit.gnd, 2)
    Vcc = circuit.V('cc', 'input2', circuit.gnd, 5)
    Vgnd = circuit.V('gnd', 'input3', circuit.gnd, 0)
    #circuit.R('test1', 'node0', circuit.gnd, 1e6)
    #circuit.R('test2', 'node0', 'input1', 1e6)
    ridx = 1
    xidx = 1
    for key, c in iteritems(genome.connections):
        if c.component == 'resistor':
            pin0, pin1 = get_pins(key)
            R = 10**c.value
            circuit.R(ridx, pin1, pin0, R)
            ridx += 1
        elif c.component == 'diode':
            pin0, pin1 = get_pins(key)
            circuit.X(xidx, '1N4148', pin1, pin0)
            xidx += 1

    return circuit
Exemple #8
0
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 test_spinit(self):

        from PySpice.Spice.Netlist import Circuit
        import PySpice.Unit as U

        circuit = Circuit('Test')

        # Fixme: On Windows
        #   Supplies reduced to   2.5749% Supplies reduced to   1.7100% Warning: source stepping failed
        #   doAnalyses: Too many iterations without convergence
        source = circuit.V('cc', 'vcc', circuit.gnd, 15 @ U.u_V)
        circuit.R(1, 'output', 'comparator', 1 @ U.u_kΩ)
        circuit.C(1, 'comparator', circuit.gnd, 100 @ U.u_nF)
        circuit.R(2, 'output', 'reference', 100 @ U.u_kΩ)
        circuit.R(3, 'vcc', 'reference', 100 @ U.u_kΩ)
        circuit.R(4, 'reference', circuit.gnd, 100 @ U.u_kΩ)
        # circuit.NonLinearVoltageSource(1, 'output', circuit.gnd,
        #                                expression='V(reference, comparator)',
        #                                table=((-U.micro(1), 0),
        #                                       (U.micro(1), source.dc_value))
        # )

        simulator = circuit.simulator(temperature=25, nominal_temperature=25)
        simulator.initial_condition(
            comparator=0)  # Fixme: simulator.nodes.comparator == 0
        analysis = simulator.transient(step_time=1 @ U.u_us,
                                       end_time=500 @ U.u_us)

        if (len(analysis.output)) < 500:
            raise NameError('Simualtion failed')
Exemple #10
0
def init():
    logger = Logging.setup_logging()
    # libraries_path = find_libraries()
    libraries_path = '/home/anurag/Workspace/DTU/CourseProj/AE/website/DTU-VLAB/dtuvlab/lab/simulations/libraries'
    print(libraries_path)
    spice_library = SpiceLibrary(libraries_path)
    print(spice_library)
    circuit = Circuit('Diode Characteristic Curve')
    circuit.include(spice_library['1N4148'])
    print(spice_library['1N4148'])
    return circuit
Exemple #11
0
def nmos_characteristics(Vd, Vg):
    circuit = Circuit('NMOS Input Characteristic')
    circuit.include(
        './app/circuits/libraries/transistor/ptm_65nm_nmos_bulk.mod')

    # Define the DC supply voltage value
    Vdd = float(Vd)

    # Instanciate circuit elements
    Vgate = circuit.V('gate', 'gatenode', circuit.gnd, u_V(float(Vg)))
    Vdrain = circuit.V('drain', 'vdd', circuit.gnd, u_V(Vdd))
    # M <name> <drain node> <gate node> <source node> <bulk/substrate node>
    circuit.MOSFET(1,
                   'vdd',
                   'gatenode',
                   circuit.gnd,
                   circuit.gnd,
                   model='ptm65nm_nmos')

    simulator = circuit.simulator(temperature=25, nominal_temperature=25)
    analysis = simulator.dc(Vdrain=slice(0, Vdd, .01))

    figure, ax = plt.subplots(figsize=(20, 10))

    ax.plot(analysis['vdd'], u_A(-analysis.Vdrain))
    ax.legend('NMOS characteristic')
    ax.grid()
    ax.set_xlabel('Vds [V]')
    ax.set_ylabel('Id [A]')

    return circuit, analysis, plt
def make_database_core(w=2000,V=12,R=10,L=3,C=320):
    threshold = 4
    circuit = Circuit('RLC-series')
    circuit.V('1',0,1, f'DC 0 AC {V} SIN(0 {V} {w})')
    circuit.R('1',  1, 2,R@u_kΩ)
    circuit.L('1',  2, 3,L@u_H)
    circuit.X('diodus','D1N4148', 2, 3)
    circuit.include(spice_library['D1N4148']) 
    circuit.C('1',  3, 0,C@u_nF)
    dt = 2*np.pi/w*4
    tau = 2*np.pi/w*4
    simulator = circuit.simulator(temperature=25, nominal_temperature=25)
    analysis = simulator.transient(step_time=dt@u_ms, end_time=tau@u_s)
    auxiliar = analysis['2']-analysis['3']
    return [w,V,R,L,C,int(float(max(auxiliar))>threshold)]
Exemple #13
0
def current_divider(i, r1, r2):
    circuit = Circuit('Current Divider')
    circuit.I('input', 1, circuit.gnd, u_A(float(i)))  # Fixme: current value
    circuit.R(1, 1, circuit.gnd, u_kOhm(float(r1)))
    circuit.R(2, 1, circuit.gnd, u_kOhm(float(r2)))

    for resistance in (circuit.R1, circuit.R2):
        resistance.minus.add_current_probe(circuit)  # to get positive value

    simulator = circuit.simulator(temperature=25, nominal_temperature=25)
    analysis = simulator.operating_point()
    output = {}
    for node in analysis.branches.values():
        output[str(node)] = str(round(float(node), 2)) + "A"

    return circuit, analysis, output
Exemple #14
0
    def test_raw_spice(self):

        spice_declaration = """
.title Voltage Divider

R2 out 0 1kOhm
vinput in 0 10v
r1 in out 9kohm
"""
        # .end

        circuit = Circuit('Voltage Divider')
        circuit.V('input', 'in', circuit.gnd, '10V')
        circuit.R(1, 'in', 'out', raw_spice='9kOhm')
        circuit.raw_spice += 'R2 out 0 1kOhm'
        self._test_spice_declaration(circuit, spice_declaration)
Exemple #15
0
def create_test_circuit(fet_type, iparam, fet_L, fet_W, coner_path):
    c = Circuit('gm_id')
    c.include(
        '/home/tclarke/skywater-pdk/libraries/sky130_fd_pr/latest/models/corners/tt.spice'
    )
    fet_L = 0.15
    fet_W = 1

    # create the circuit
    c.V('gg', 1, c.gnd, 0 @ u_V)
    c.V('dd', 2, c.gnd, 1.8 @ u_V)
    c.X('M1',
        fet_type,
        2,
        1,
        c.gnd,
        c.gnd,
        L=fet_L,
        W=fet_W,
        ad="'W*0.29'",
        pd="'2*(W+0.29)'",
        as_="'W*0.29'",
        ps="'2*(W+0.29)'",
        nrd="'0.29/W'",
        nrs="'0.29/W'",
        sa=0,
        sb=0,
        sd=0,
        nf=1,
        mult=1)
    return c
def simulate_RLC(w=2000,V=2,R=10,L=3,C=320,**kwargs):

    circuit = Circuit('Name me please')
    circuit.R('1',  1, 2,R@u_kΩ)
    circuit.L('1',  2, 3,L@u_H)
    circuit.C('1',  3, 0,C@u_nF)
    #circuit.V('1',  circuit.gnd,1 ,f'SIN(0 {V} {w})')
    circuit.V('1',0,1, f'DC 0 AC {V} SIN(0 {V} {w})')
    dt = 2*np.pi/w*4
    tf = 5/w
    simulator = circuit.simulator(temperature=25, nominal_temperature=25)
    #analysis = simulator.transient(step_time=0.1@u_ms, end_time=tf@u_s)
    analysis = simulator.transient(step_time=dt@u_ms, end_time=tf@u_s)

    if kwargs.get('view',False):
        #print(str(circuit))
        fig = plt.figure(figsize=(20,4))  # create a figure object
        ax = fig.add_subplot(1, 1, 1)
        plt.plot(analysis['1']-analysis['2'],label='R')
        plt.plot(analysis['2']-analysis['3'],label='L')
        ax.plot(analysis['3'],label='C')
        #ax.set_ylim(-int(V*1.1)-10,int(V*1.1)+10)
        ax.legend()
        ax.set_title(f'freq : {w}, voltage: {V}')
        ax.set_xlabel('time (ms)')
        ax.set_ylabel('current (ma)')
        plt.savefig('gallery/RLC_example.png')
        print(f'resonance was at {np.sqrt(1/(L*C))}')
    return max(abs(analysis['1']-analysis['2']))/R
Exemple #17
0
def half_wave_rectifier(v, r, c, f):
    circuit = Circuit('half-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')
    circuit.R('load', 'output', circuit.gnd, u_Ω(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')
    figure, (ax1, ax2) = plt.subplots(2, figsize=(20, 10))

    ax1.set_title('Half-Wave Rectification')
    ax1.set_xlabel('Time [s]')
    ax1.set_ylabel('Voltage [V]')
    ax1.grid()
    ax1.plot(analysis['in'])
    ax1.plot(analysis.output)
    ax1.legend(('input', 'output'), loc=(.05, .1))
    ax1.set_ylim(float(-source.amplitude * 1.1), float(source.amplitude * 1.1))

    circuit.C('1', 'output', circuit.gnd, 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)

    ax2.set_title('Half-Wave Rectification with filtering')
    ax2.set_xlabel('Time [s]')
    ax2.set_ylabel('Voltage [V]')
    ax2.grid()
    ax2.plot(analysis['in'])
    ax2.plot(analysis.output)
    ax2.legend(('input', 'output'), loc=(.05, .1))
    ax2.set_ylim(float(-source.amplitude * 1.1), float(source.amplitude * 1.1))
    plt.tight_layout()

    return circuit, analysis, plt
Exemple #18
0
    def test(self):

        self._test_spice_declaration(
            PieceWiseLinearVoltageSource(
                Circuit(''),
                'pwl1', '1', '0',
                values=[(0, 0), (10@u_ms, 0), (11@u_ms, 5@u_V), (20@u_ms, 5@u_V)],
            ),
            'Vpwl1 1 0 PWL(0s 0V 10ms 0V 11ms 5V 20ms 5V r=0s td=0.0s)',
        )
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.Sinusoidal('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
Exemple #20
0
    def test(self):

        self._test_spice_declaration(
            PieceWiseLinearVoltageSource(
                Circuit(''),
                'pwl1',
                '1',
                '0',
                values=[(0, 0), (10 @ u_ms, 0), (11 @ u_ms, 5 @ u_V),
                        (20 @ u_ms, 5 @ u_V)],
            ),
            'Vpwl1 1 0 PWL(0s 0V 10ms 0V 11ms 5V 20ms 5V)',
        )

        self._test_spice_declaration(
            PieceWiseLinearVoltageSource(
                Circuit(''),
                'pwl1',
                '1',
                '0',
                values=[(0, 0), (10 @ u_ms, 0), (11 @ u_ms, 5 @ u_V),
                        (20 @ u_ms, 5 @ u_V)],
                repeat_time=12 @ u_ms,
                delay_time=34 @ u_ms,
            ),
            'Vpwl1 1 0 PWL(0s 0V 10ms 0V 11ms 5V 20ms 5V r=12ms td=34ms)',
        )

        self._test_spice_declaration(
            PieceWiseLinearVoltageSource(
                Circuit(''),
                'pwl1',
                '1',
                '0',
                values=[(0, 0), (10 @ u_ms, 0), (11 @ u_ms, 5 @ u_V),
                        (20 @ u_ms, 5 @ u_V)],
                repeat_time=12 @ u_ms,
                delay_time=34 @ u_ms,
                dc=50 @ u_V,
            ),
            'Vpwl1 1 0 DC 50V PWL(0s 0V 10ms 0V 11ms 5V 20ms 5V r=12ms td=34ms)',
        )
Exemple #21
0
    def register_device(circuit: SpiceCircuit, d: pya.Device):
        """
        Create a SPICE instance of the device `d` and add it to the `circuit`.
        :param circuit: PySpice circuit to add the device.
        :param d: KLayout device.
        :return:
        """
        device_class = d.device_class()

        # Map terminal names to nets
        terminal_map = {
            tdef.name: d.net_for_terminal(tdef.id())
            for tdef in device_class.terminal_definitions()
        }

        # Get net names at terminals
        ds1, gate, ds2 = [
            get_net_name(terminal_map[terminal_name])
            for terminal_name in ['S', 'G', 'D']
        ]

        # parameter_defs = device_class.parameter_definitions()

        assert device_class.name(
        ) in device_class_name_to_model_mapping, "Unknown device class name: {}".format(
            device_class.name())

        model = device_class_name_to_model_mapping[device_class.name()]

        length = d.parameter('L')
        width = d.parameter('W')
        area_drain = d.parameter('AD')
        area_source = d.parameter('AS')

        # Get net of body if defined. Otherwise create a new floating net.
        bulk = terminal_map.get('B', None)

        if bulk is None:
            if default_bulk_net == 'floating':
                bulk = temp_net_name()
            elif isinstance(default_bulk_net, dict):
                bulk = default_bulk_net[device_class.name()]

        # TODO: parameters AS, AD
        circuit.M(
            "{}".format(d.id()),
            ds1,
            gate,
            ds2,
            bulk,
            model=model,
            width=width @ u_um,
            length=length @ u_um,
        )
Exemple #22
0
 def create_netlist(self):
     self.circuit = Circuit('ANC Filter')
     self.creat_Mic_input(self.ac_source)  # 输入
     self.creat_Mic_OP_gain(self.mic_op_gain_data)  # mic放大器
     self.circuit.R('load', 'output', self.circuit.gnd, '1000k')  # 负载电阻
     self.circuit.R('load2', 'op02_out', self.circuit.gnd, '1000k')  # 负载电阻
     self.create_module01(self.module01)
     self.create_module02(self.module02)
     self.create_module03(self.module03)  # op gain
     self.create_module04(self.module04)  # high shelf
     self.create_module05(self.module05)  # low shelf
     self.create_module06(self.module06)  # op low pass
     self.create_module07(self.module07)  # op peak
     if self.op_model == 'two_op':
         self.create_module11(self.module11)
         self.create_module12(self.module12)
         self.create_module13(self.module13)  # op gain
         self.create_module14(self.module14)  # high shelf
         self.create_module15(self.module15)  # low shelf
         self.create_module16(self.module16)  # op low pass
         self.create_module17(self.module17)  # op peak
Exemple #23
0
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
Exemple #24
0
def make_database_core(w, V, R, C):
    circuit = Circuit('RC low-pass filter')
    # Include non-passive elements:
    # D1N4148 is a (regular&cheap) Diode
    circuit.include(spice_library['D1N4148'])
    fc = 1 / 2 / 3.14 / (R * 1000) / (C * 1E-9)  # Cut Frequency!
    circuit.V('1', 1, circuit.gnd, f'DC 0 AC {V} SIN(0 {V} {w})')
    circuit.R('1', 1, 2, R @ u_kΩ)
    circuit.C('1', 2, circuit.gnd, C @ u_nF)
    circuit.X('diodus', 'D1N4148', 2, circuit.gnd)
    f = w
    treshold = 4
    simulator = circuit.simulator(temperature=25, nominal_temperature=25)
    analysis = simulator.transient(step_time=((1 / f) / 10) @ u_s,
                                   end_time=(4 / f) @ u_s)
    outputter = int(float(max(-analysis['2'])) > treshold)
    del (circuit)
    return [w, V, R, C, outputter]
Exemple #25
0
 def register_subcircuit_instance(circuit: SpiceCircuit, inst: pya.Circuit):
     """
     Create a SPICE instance of the KLayout subcircuit instance `inst`.
     :param circuit: PySpice circuit to add the subcircuit instance ('X').
     :param inst: KLayout circuit instance.
     :return:
     """
     ref = inst.circuit_ref()
     name = ref.name
     num_pins = ref.pin_count()
     pin_nets = [inst.net_for_pin(i) for i in range(num_pins)]
     pin_names = [get_net_name(pin_net) for pin_net in pin_nets]
     circuit.X('{}'.format(inst.id()), name, *pin_names)
 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)
Exemple #27
0
    def register_subcircuit(circuit: SpiceCircuit, sc: pya.SubCircuit):
        """
        Convert the KLayout subcircuit into a PySpice subcircuit and attach it to `circuit`.
        :param circuit: PySpice circuit to add the subcircuit.
        :param sc: KLayout subcircuit to be added to `circuit`.
        :return:
        """
        num_pins = sc.pin_count()
        pin_nets = [sc.net_for_pin(i) for i in range(num_pins)]
        pin_names = [get_net_name(pin_net) for pin_net in pin_nets]

        subcircuit = SpiceSubCircuit(sc.name, *pin_names)

        for d in sc.each_device():
            if isinstance(d, pya.Circuit):
                logger.warning('Skipping circuit: ', d.name)
            else:
                register_device(subcircuit, d)

        # Loop through sub circuits.
        for subc in c.each_subcircuit():
            register_subcircuit_instance(subcircuit, subc)

        circuit.subcircuit(subcircuit)
Exemple #28
0
    def thread_function(qin, qout, clk_freq, init_x):
        try:

            c = Circuit('pygears')
            ins = []
            outs = []
            f(c, ins, outs)

            c.V('__x', ins[0][0], ins[0][1], f'dc {init_x} external')

            ngspice_shared = PgNgSpice(qin,
                                       qout,
                                       x=init_x,
                                       outs=outs,
                                       send_data=True)

            simulator = c.simulator(temperature=25,
                                    nominal_temperature=25,
                                    simulator='ngspice-shared',
                                    ngspice_shared=ngspice_shared)

            simulator.transient(step_time=1 / (2 * clk_freq), end_time=1e3)
        except GearDone:
            pass
Exemple #29
0
 def test_subcircuit(self):
     circuit = Circuit('')
     circuit.include('.../mosdriver.lib')
     circuit.X('test', 'mosdriver', '0', '1', '2', '3', '4', '5')
     circuit.BehavioralSource('test',
                              '1',
                              '0',
                              voltage_expression='if(0, 0, 1)',
                              smoothbsrc=1)
     print(circuit)
Exemple #30
0
def mkschematic(ind, nnodes, nodelist, spice_library):
    circuit = Circuit('generated circuit')

    circuit.V('vcc', 'vcc', circuit.gnd, '5V')
    circuit.V('vdd', 'vdd', circuit.gnd, '-5V')
    circuit.Sinusoidal('input', 'vin', circuit.gnd, amplitude=5)

    nodes = 0
    for i in range(nnodes):
        if ind[5 * i] == 1:
            circuit.R(nodes,
                      nodelist[ind[5 * i + 2]] if ind[5 * i + 2] != 0 else circuit.gnd,
                      nodelist[ind[5 * i + 3]] if ind[5 * i + 3] != 0 else circuit.gnd,
                      values.E12R[ind[5 * i + 1]])
        elif ind[5 * i] == 2:
            circuit.C(nodes,
                      nodelist[ind[5 * i + 2]]  if ind[5 * i + 2] != 0 else circuit.gnd,
                      nodelist[ind[5 * i + 3]]  if ind[5 * i + 3] != 0 else circuit.gnd,
                      values.E12C[ind[5 * i + 1]])
        elif ind[5 * i] == 3:
            circuit.include(spice_library['2n2222a'])
            circuit.BJT(nodes,
                        nodelist[ind[5 * i + 2]]  if ind[5 * i + 2] != 0 else circuit.gnd,
                        nodelist[ind[5 * i + 3]]  if ind[5 * i + 3] != 0 else circuit.gnd,
                        nodelist[ind[5 * i + 4]]  if ind[5 * i + 4] != 0 else circuit.gnd,
                        '2n2222a')
        elif ind[5 * i] == 4:
            circuit.include(spice_library['2n2907'])
            circuit.BJT(nodes,
                        nodelist[ind[5 * i + 2]]  if ind[5 * i + 2] != 0 else circuit.gnd,
                        nodelist[ind[5 * i + 3]]  if ind[5 * i + 3] != 0 else circuit.gnd,
                        nodelist[ind[5 * i + 4]]  if ind[5 * i + 4] != 0 else circuit.gnd,
                        '2n2907')
        elif ind[5 * i] == 6:
            circuit.include(spice_library['1N4148'])
            circuit.X('D{}'.format(nodes),
                      '1N4148',
                      nodelist[ind[5 * i + 2]]  if ind[5 * i + 2] != 0 else circuit.gnd,
                      nodelist[ind[5 * i + 3]]  if ind[5 * i + 3] != 0 else circuit.gnd)
        elif ind[5 * i] == 5:
            circuit.L(nodes,
                      nodelist[ind[5 * i + 2]]  if ind[5 * i + 2] != 0 else circuit.gnd,
                      nodelist[ind[5 * i + 3]]  if ind[5 * i + 3] != 0 else circuit.gnd,
                      values.E12I[ind[5 * i + 1]])
        elif ind[5 * i] == 0:
            continue
        else:
            continue
        nodes += 1
    print(circuit)
Exemple #31
0
def voltage_divider(v, r1, r2):
    circuit = Circuit('Voltage Divider')
    circuit.V('input', 1, circuit.gnd, u_V(float(v)))
    circuit.R(1, 1, 2, u_kOhm(float(r1)))
    circuit.R(2, 2, circuit.gnd, u_kOhm(float(r2)))
    simulator = circuit.simulator(temperature=25, nominal_temperature=25)
    analysis = simulator.operating_point()
    output = {}
    for node in analysis.nodes.values():
        output[str(node)] = str(round(float(node), 2)) + "V"

    return circuit, analysis, output
Exemple #32
0
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
Exemple #33
0
from PySpice.Spice.Library import SpiceLibrary
from PySpice.Spice.Netlist import Circuit
from PySpice.Unit.Units import *

####################################################################################################

libraries_path = os.path.join(os.environ['PySpice_examples_path'], 'libraries')
spice_library = SpiceLibrary(libraries_path)

####################################################################################################

from RingModulator import RingModulator

####################################################################################################

circuit = Circuit('Ring Modulator')

modulator = circuit.Sinusoidal('modulator', 'in', circuit.gnd, amplitude=1, frequency=kilo(1))
carrier = circuit.Sinusoidal('carrier', 'carrier', circuit.gnd, amplitude=10, frequency=kilo(100))
circuit.R('in', 'in', 1, 50)
circuit.R('carrier', 'carrier', 2, 50)

circuit.include(spice_library['1N4148'])
circuit.subcircuit(RingModulator(outer_inductance=micro(1),
                                 inner_inductance=micro(1),
                                 coupling=.99,
                                 diode_model='1N4148',
                             ))
circuit.X('ring_modulator', 'RingModulator',
          1, circuit.gnd,
          2, circuit.gnd,
Exemple #34
0
    def get_vsrc_data(self, voltage, time, node, ngspice_id):
        self._logger.debug('ngspice_id-{} get_vsrc_data @{} node {}'.format(ngspice_id, time, node))
        voltage[0] = self._amplitude * math.sin(self._pulsation * time)
        return 0

    ##############################################

    def get_isrc_data(self, current, time, node, ngspice_id):
        self._logger.debug('ngspice_id-{} get_isrc_data @{} node {}'.format(ngspice_id, time, node))
        current[0] = 1.
        return 0

####################################################################################################

circuit = Circuit('Voltage Divider')

circuit.V('input', 'input', circuit.gnd, 'dc 0 external')
circuit.R(1, 'input', 'output', kilo(10))
circuit.R(2, 'output', circuit.gnd, kilo(1))

amplitude = 10
frequency = Frequency(50)
ngspice_shared = MyNgSpiceShared(amplitude=amplitude, frequency=frequency, send_data=False)
simulator = circuit.simulator(temperature=25, nominal_temperature=25,
                              simulator='shared', ngspice_shared=ngspice_shared)
period = float(frequency.period)
analysis = simulator.transient(step_time=period/200, end_time=period*2)

####################################################################################################
import numpy as np
import matplotlib.pyplot as plt

#import PySpice.Logging.Logging as Logging
#logger = Logging.setup_logging()

from PySpice.Spice.Netlist import Circuit
from PySpice.Unit.Units import *
from PySpice.Spice.BasicElement import *
from PySpice.Spice.HighLevelElement import *
from PySpice.Spice.Simulation import *
from PySpiceDvTools.Loads import *
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.Sinusoidal('1', 'A', circuit.gnd, amplitude=220, frequency=50)

subcir= BasicNonLinearLoad(r=27.5,l=0.5)
circuit.subcircuit(subcir)
####################################################################################################

from PySpice.Probe.Plot import plot
from PySpice.Spice.Netlist import Circuit
from PySpice.Unit.Units import *

####################################################################################################

# Warning: the capacitor/inductor return current in the generator
#  could use switches instead

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

for element_type in 'capacitor', 'inductor':

    circuit = Circuit(element_type.title())
    # Fixme: compute value
    source = circuit.Pulse('input', 'in', circuit.gnd,
                           initial_value=0, pulsed_value=10,
                           pulse_width=milli(10), period=milli(20))
    circuit.R(1, 'in', 'out', kilo(1))
    if element_type == 'capacitor':
        element = circuit.C
        value = micro(1) # F
        # tau = RC = 1 ms
    else:
        element = circuit.L
        value = 1 # H
        # tau = L/R = 1 ms
    element(1, 'out', circuit.gnd, value)
    # circuit.R(2, 'out', circuit.gnd, kilo(1)) # for debug
from PySpice.Spice.Netlist import Circuit
from PySpice.Unit.Units import *
from PySpice.Spice.BasicElement import *
from PySpice.Spice.HighLevelElement import *
from PySpice.Spice.Simulation import *
from PySpiceDvTools.Loads import *
from PySpiceDvTools.LTSpiceServer import enableLtSpice
from AppliancesDetector.Appliances import *
from AppliancesDetector.Sonda import *
from PySpiceDvTools.SkFilters import *
from PySpiceDvTools.Filters import CascadeFilter
from scipy.fftpack import fft,fftfreq
from scipy.signal import resample

circuit = Circuit('Sensor Sim')

model = 'BasicOpamp'

circuit.include('Models/BasicOpamp.cir')
circuit.include('Models/AD8619.cir')
circuit.include('Models/TL084.cir')

microwave= MicroOndas1200()
sonda = Sonda()
vRef = VoltageReference (opAmpModel=model)

filterL = SKLowPassFilter(opAmpModel=model,R1=470,R2=kilo(3), C1=micro(1),C2=nano(100),name='sklpfi_400')
filterH = SKHighPassFilter(opAmpModel=model, R1=kilo(1), R2=kilo(33), C1=micro(4.7),C2=nano(100),name='skhpfi_40')
filter2o = CascadeFilter(fa=filterL,fb=filterH,name='wide_40_400')
####################################################################################################

from PySpice.Doc.ExampleTools import find_libraries
from PySpice.Spice.Library import SpiceLibrary
from PySpice.Spice.Netlist import Circuit
from PySpice.Spice.Parser import SpiceParser
from PySpice.Unit import *

####################################################################################################

libraries_path = find_libraries()
spice_library = SpiceLibrary(libraries_path)

####################################################################################################

circuit = Circuit('STM AN1476: Low-Cost Power Supply For Home Appliances')

circuit.include(spice_library['1N4148'])
# 1N5919B: 5.6 V, 3.0 W Zener Diode Voltage Regulator
circuit.include(spice_library['d1n5919brl'])

ac_line = circuit.AcLine('input', 'out', 'in', rms_voltage=230, frequency=50)
circuit.R('load', 'out', circuit.gnd, kilo(1))
circuit.C('load', 'out', circuit.gnd, micro(220))
circuit.X('D1', '1N4148', circuit.gnd, 1)
circuit.D(1, circuit.gnd, 1, model='DIODE1', off=True)
circuit.X('Dz1', 'd1n5919brl', 1, 'out')
circuit.C('ac', 1, 2, nano(470))
circuit.R('ac', 2, 'in', 470) # Fixme: , m=1, temperature='{25}'

source = str(circuit)
Exemple #39
0
from PySpice.Spice.Netlist import Circuit
from PySpice.Unit import *

####################################################################################################

libraries_path = find_libraries()
spice_library = SpiceLibrary(libraries_path)

####################################################################################################

#?# #cm# relay.m4

period = 50@u_ms
pulse_width = period / 2

circuit = Circuit('Relay')

# circuit.V('digital', 'Vdigital', circuit.gnd, 5@u_V)
circuit.PulseVoltageSource('clock', 'clock', circuit.gnd, 0@u_V, 5@u_V, pulse_width, period, rise_time=5@u_ms, fall_time=5@u_ms)
circuit.R('base', 'clock', 'base', 100@u_Ω)
circuit.BJT(1, 'collector', 'base', circuit.gnd, model='bjt') # Q is mapped to BJT !
circuit.model('bjt', 'npn', bf=80, cjc=pico(5), rb=100)
circuit.V('analog', 'VccAnalog', circuit.gnd, 8@u_V)
circuit.R('relay', 'VccAnalog', 1, 50@u_Ω)
circuit.L('relay', 1, 'collector', 100@u_mH)
circuit.include(spice_library['1N5822']) # Schottky diode
diode = circuit.X('D', '1N5822', 'collector', 'VccAnalog')
# Fixme: subcircuit node
# diode.minus.add_current_probe(circuit)

####################################################################################################
Exemple #40
0
logger = Logging.setup_logging()

####################################################################################################

from PySpice.Probe.Plot import plot
from PySpice.Spice.Library import SpiceLibrary
from PySpice.Spice.Netlist import Circuit
from PySpice.Unit.Units import *

####################################################################################################

from Transformer import Transformer

####################################################################################################

circuit = Circuit('Transformer')

ac_line = circuit.AcLine('input', 'input', circuit.gnd, rms_voltage=230, frequency=50)
circuit.subcircuit(Transformer(turn_ratio=10))
circuit.X('transformer', 'Transformer', 'input', circuit.gnd, 'output', circuit.gnd)
circuit.R('load', 'output', circuit.gnd, kilo(1))

simulator = circuit.simulator(temperature=25, nominal_temperature=25)
analysis = simulator.transient(step_time=ac_line.period/200, end_time=ac_line.period*3)

figure = plt.figure(1, (20, 10))
plot(analysis.input)
plot(analysis.output)
plt.legend(('Vin [V]', 'Vout [V]'), loc=(.8,.8))
plt.grid()
plt.xlabel('t [s]')
####################################################################################################

from PySpice.Spice.Library import SpiceLibrary
from PySpice.Spice.Netlist import Circuit
from PySpice.Spice.Server import SpiceServer
from PySpice.Unit.Units import *

####################################################################################################

libraries_path = os.path.join(os.path.dirname(__file__), "libraries")
spice_library = SpiceLibrary(libraries_path)
spice_server = SpiceServer()

####################################################################################################

circuit = Circuit("STM AN1476: Low-Cost Power Supply For Home Appliances")

circuit.include(spice_library["1N4148"])
# 1N5919B: 5.6 V, 3.0 W Zener Diode Voltage Regulator
circuit.include(spice_library["d1n5919brl"])

ac_line = circuit.AcLine("input", "out", "in", rms_voltage=230, frequency=50)
circuit.R("load", "out", circuit.gnd, kilo(1))
circuit.C("load", "out", circuit.gnd, micro(220))
circuit.X("D1", "1N4148", circuit.gnd, 1)
circuit.X("Dz1", "d1n5919brl", 1, "out")
circuit.C("ac", 1, 2, nano(470))
circuit.R("ac", 2, "in", 470)

simulation = circuit.simulation(temperature=25, nominal_temperature=25)
# Fixme: circuit.nodes[2].v, circuit.branch.current
Exemple #42
0
    def generate_and_test(self, gui, ind):
        circuit = Circuit('generated circuit')
        sys.stdout.write('  {:.1%}%\b\r'.format(self.GENCOUNTER/ self.POPSIZE))
        sys.stdout.flush()

        circuit.V('vcc', 'vcc', circuit.gnd, '5V')
        circuit.V('vdd', 'vdd', circuit.gnd, '-5V')
        circuit.Sinusoidal('input', 'vin', circuit.gnd, amplitude=2)

        nodes = 0
        try:
            for i in range(self.N_NODES):
                if ind[5 * i] == 1:
                    circuit.R(nodes,
                              self.NODELIST[ind[5 * i + 2]] if ind[5 * i + 2] != 0 else circuit.gnd,
                              self.NODELIST[ind[5 * i + 3]] if ind[5 * i + 3] != 0 else circuit.gnd,
                              values.E12R[ind[5 * i + 1]])
                elif ind[5 * i] == 2:
                    circuit.C(nodes,
                              self.NODELIST[ind[5 * i + 2]]  if ind[5 * i + 2] != 0 else circuit.gnd,
                              self.NODELIST[ind[5 * i + 3]]  if ind[5 * i + 3] != 0 else circuit.gnd,
                              values.E12C[ind[5 * i + 1]])
                elif ind[5 * i] == 3:
                    circuit.include(self.spice_library['2n2222a'])
                    circuit.BJT(nodes,
                                self.NODELIST[ind[5 * i + 2]]  if ind[5 * i + 2] != 0 else circuit.gnd,
                                self.NODELIST[ind[5 * i + 3]]  if ind[5 * i + 3] != 0 else circuit.gnd,
                                self.NODELIST[ind[5 * i + 4]]  if ind[5 * i + 4] != 0 else circuit.gnd,
                                '2n2222a')
                elif ind[5 * i] == 4:
                    circuit.include(self.spice_library['2n2907'])
                    circuit.BJT(nodes,
                                self.NODELIST[ind[5 * i + 2]]  if ind[5 * i + 2] != 0 else circuit.gnd,
                                self.NODELIST[ind[5 * i + 3]]  if ind[5 * i + 3] != 0 else circuit.gnd,
                                self.NODELIST[ind[5 * i + 4]]  if ind[5 * i + 4] != 0 else circuit.gnd,
                                '2n2907')
                elif ind[5 * i] == 6:
                    circuit.include(self.spice_library['1N4148'])
                    circuit.X('D{}'.format(nodes),
                              '1N4148',
                              self.NODELIST[ind[5 * i + 2]]  if ind[5 * i + 2] != 0 else circuit.gnd,
                              self.NODELIST[ind[5 * i + 3]]  if ind[5 * i + 3] != 0 else circuit.gnd)
                elif ind[5 * i] == 5:
                    circuit.L(nodes,
                              self.NODELIST[ind[5 * i + 2]]  if ind[5 * i + 2] != 0 else circuit.gnd,
                              self.NODELIST[ind[5 * i + 3]]  if ind[5 * i + 3] != 0 else circuit.gnd,
                              values.E12I[ind[5 * i + 1]])
                elif ind[5 * i] == 0:
                    continue
                else:
                    continue
                nodes += 1
            simulator = circuit.simulator(temperature=25, nominal_temperature=25)
            analysis = simulator.transient(start_time="2ms", step_time='1ms', end_time='40ms', max_time='40ms ')
        except:
            self.DEAD += 1
            self.s['pop'][self.s['counter']] = [self.GEN, -1, self.GENCOUNTER]
            self.s['counter'] += 1
            self.GENCOUNTER += 1 
            return (-1.,)
        result = 0
        try:
            j = 0.
            for n, m in zip(analysis.nodes['vin'][1:-1], analysis.nodes['out'][1:-1]):
                j += self.toolbox.evaluator(n, m)
            result = (j / max([len (analysis.nodes['out'][1:-1]), len (analysis.nodes['out'][1:-1])])) * (1 + 0.01 * (self.N_NODES - nodes)) 
            if result > 0 and  gui != None:
                gui.dc.update_data(result, analysis.nodes['out'][1:-1], analysis.nodes['vin'][1:-1])
            self.s['pop'][self.s['counter']] = [self.GEN, result, self.GENCOUNTER]
            self.GENCOUNTER += 1
            self.s['counter'] += 1
            return (result if result > 0 else 0,)
        except:
            self.s['pop'][self.s['counter']] = [self.GEN, -0.5, self.GENCOUNTER]
            self.s['counter'] += 1
            self.GENCOUNTER += 1
            return (-0.5, )
Exemple #43
0
            voltage_expression='V(overfl)+V(prop)',
        )
        self.BehavioralSource(
            'VClip',
            'Out', self.gnd,
            voltage_expression='V(sum)< {0} ? {0} : V(sum) > {1} ? {1} : V(sum)'.format(MINV, MAXV),
        )

        # integrator part - fixme with int model from NGSpice ?
        self.VoltageControlledCurrentSource(
            'I_Int',
            'antiwind', self.gnd, self.gnd,
            'integ', multiplier=KI,
        )
        self.C('i', 'integ', self.gnd, 1)
        self.R('i', 'integ', self.gnd, 1000000)

####################################################################################################

circuit = Circuit('Issue 107')

KG1, KIG1, AWG1, MING1, MAXG1 = range(5)
circuit.subcircuit(PI('PI1', KG1, KIG1, AWG1, MING1, MAXG1))
circuit.X('PI_sensor', 'PI', 'CCDSetPoint', 'L3_CCD', 'HeaterCtrl')

KG2, KIG2, AWG2, MING2, MAXG2 = range(5)
circuit.subcircuit(PI('PI2', KG2, KIG2, AWG2, MING2, MAXG2))
circuit.X('PI2_sensor', 'PI', 'PlateSetPoint', 'CryoPlate', 'PlateCtrl')

print(circuit)
Exemple #44
0
####################################################################################################

import PySpice.Logging.Logging as Logging
logger = Logging.setup_logging()

####################################################################################################

from PySpice.Spice.Netlist import Circuit, SubCircuit
from PySpice.Unit.Units import *

####################################################################################################

circuit = Circuit('Regulator')

# Netlist.TwoPortElement
# .. warning:: As opposite to Spice, the input nodes are specified before the output nodes.
# circuit.VCVS(1, 1, 0, 2, 0, , milli(50))

gain = SubCircuit('GAIN', 1, 2, K=milli(20))
gain.VCVS(1, 1, 0, 2, 0, '{K}')

circuit.subcircuit(gain)
circuit.X(2, 'GAIN', 7, 6, K=milli(50))

print(str(circuit))

####################################################################################################
#
# End
#
####################################################################################################
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)

####################################################################################################

#f# circuit_macros('ac-coupled-amplifier.m4')

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Ω)

####################################################################################################
Exemple #46
0
import PySpice.Logging.Logging as Logging
logger = Logging.setup_logging()

####################################################################################################

from PySpice.Plot.BodeDiagram import bode_diagram
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
from PySpice.Unit import *

####################################################################################################

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,
                                 coupling=.99,
                                 diode_model='1N4148',
                             ))
circuit.X('ring_modulator', 'RingModulator',
          1, circuit.gnd,
          2, circuit.gnd,
# ?# impedances.

####################################################################################################

import PySpice.Logging.Logging as Logging

logger = Logging.setup_logging()

####################################################################################################

from PySpice.Spice.Netlist import Circuit
from PySpice.Unit.Units import *

####################################################################################################

thevenin_circuit = Circuit("Thévenin Representation")

thevenin_circuit.V("input", 1, thevenin_circuit.gnd, 10)
thevenin_circuit.R("generator", 1, "load", 10)
thevenin_circuit.R("load", "load", thevenin_circuit.gnd, kilo(1))

simulator = thevenin_circuit.simulator(temperature=25, nominal_temperature=25)
analysis = simulator.operating_point()

load_node = analysis.load
print("Node {}: {:5.2f} V".format(str(load_node), float(load_node)))
# o#

norton_circuit = Circuit("Norton Representation")

norton_circuit.I(
from PySpice.Spice.Netlist import Circuit, SubCircuitFactory
from PySpice.Unit import *

####################################################################################################

class SubCircuit1(SubCircuitFactory):
    __name__ = 'sub_circuit1'
    __nodes__ = ('n1', 'n2')
    def __init__(self):
        super().__init__()
        self.R(1, 'n1', 'n2', 1@u_Ω)
        self.R(2, 'n1', 'n2', 2@u_Ω)

#r# Let define a circuit.

circuit = Circuit('Test')

#r# When we add an element to a circuit, we can get a reference to it or ignore it:

C1 = circuit.C(1, 0, 1, 1@u_uF)

circuit.C(2, 1, 2, 2@u_uF)
circuit.subcircuit(SubCircuit1())
circuit.X('1', 'sub_circuit1', 2, 0)

#r# We can get back an element of a circuit using its name, either as a class attribute or using the
#r# dictionary interface:

C1 = circuit.C1
C1 = circuit['C1']
class Level2(SubCircuitFactory):
    __name__ = 'level2'
    __nodes__ = ('d4', 'g4', 'v4')
    def __init__(self):
        super().__init__()
        self.M(1, 'd4', 'g4', 'v4', 'v4', model='nmos', w=1e-5, l=3.5e-7)

class Level1(SubCircuitFactory):
    __name__ = 'level1'
    __nodes__ = ('d3', 'g3', 'v3')
    def __init__(self):
        super().__init__()
        self.X('mos2', 'level2', 'd3', 'g3', 'v3')
        self.subcircuit(Level2())

circuit = Circuit('Transistor output characteristics')
circuit.V('dd', 'd1', circuit.gnd, 2)
circuit.V('ss', 'vsss', circuit.gnd, 0)
circuit.V('sig', 'g1', 'vsss', 0)
circuit.X('mos1', 'level1', 'd1', 'g1', 'vsss')

if True:
    circuit.subcircuit(Level1())
else:
    subcircuit_level2 = SubCircuit('level2', 'd4', 'g4', 'v4')
    subcircuit_level2.M(1, 'd4', 'g4', 'v4', 'v4', model='nmos', w=1e-5, l=3.5e-7)

    subcircuit_level1 = SubCircuit('level1', 'd3', 'g3', 'v3')
    subcircuit_level1.X('mos2', 'level2', 'd3', 'g3', 'v3')
    subcircuit_level1.subcircuit(subcircuit_level2)
Exemple #51
0
def _gen_netlist_(self, **kwargs):
    """
    Return a PySpice Circuit generated from a SKiDL circuit.

    Args:
        title: String containing the title for the PySpice circuit.
        libs: String or list of strings containing the paths to directories
            containing SPICE models.
    """

    if USING_PYTHON2:
        return None

    # Create an empty PySpice circuit.
    title = kwargs.pop('title', '') # Get title and remove it from kwargs.
    circuit = PySpiceCircuit(title)

    # Initialize set of libraries to include in the PySpice circuit.
    includes = set()

    # Add any models used by the parts.
    models = set([getattr(part, 'model', None) for part in self.parts])
    models.discard(None)
    lib_dirs = set(flatten([kwargs.get('libs', None)]))
    lib_dirs.discard(None)
    spice_libs = [SpiceLibrary(dir) for dir in lib_dirs]
    for model in models:
        for spice_lib in spice_libs:
            try:
                includes.add(spice_lib[model])
            except KeyError:
                pass
            else:
                break
        else:
            logger.error('Unknown SPICE model: {}'.format(model))

    # Add any subckt libraries used by the parts.
    part_names = set([getattr(part, 'name', None) for part in self.parts if getattr(part, 'filename', None)])
    lib_files = set([getattr(part, 'filename', None) for part in self.parts])
    lib_files.discard(None)
    lib_dirs = [os.path.dirname(f) for f in lib_files]
    spice_libs = [SpiceLibrary(dir) for dir in lib_dirs]
    for part_name in part_names:
        for spice_lib in spice_libs:
            try:
                includes.add(spice_lib[part_name])
            except KeyError:
                pass
            else:
                break
        else:
            logger.error('Unknown SPICE subckt: {}'.format(part_name))

    # Add the models and subckt libraries to the PySpice circuit.
    for inc in includes:
        circuit.include(inc)

    # Add each part in the SKiDL circuit to the PySpice circuit.
    for part in sorted(self.parts, key=lambda p: str(p.ref)):
        # Add each part. All PySpice parts have an add_to_spice attribute
        # and can be added directly. Other parts are added as subcircuits.
        try:
            add_func = part.pyspice['add']
        except (AttributeError, KeyError):
            logger.error('Part has no SPICE model: {}'.format(part))
        else:
            add_func(part, circuit)
                    
    return circuit
Exemple #52
0
import PySpice.Logging.Logging as Logging
logger = Logging.setup_logging()

from PySpice.Doc.ExampleTools import find_libraries
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)

####################################################################################################

circuit = Circuit('test')

R1 = circuit.R(1, 'p1', 'p2', 4@u_kΩ)
R2 = circuit.R(2, 'p2', 'p6', 1@u_kΩ)
R3 = circuit.R(3, 'p1', 'p5', 1@u_kΩ)
R4 = circuit.R(4, 'p5', 'p6', 1@u_kΩ)
R5 = circuit.R(5, 'p6', 0, 1e-9@u_Ω)

I1 = circuit.I(1, 0, 'p1', 1@u_A)

V1 = circuit.V(1, 'p1', 'p4', -10@u_V)
V2 = circuit.V(2, 'p2', 'p3', -10@u_V)

print(str(circuit))

simulator = circuit.simulator(simulator='xyce-serial')
Exemple #53
0
####################################################################################################

import PySpice.Logging.Logging as Logging
logger = Logging.setup_logging()

####################################################################################################

from PySpice.Spice.Netlist import Circuit
from PySpice.Unit import *

####################################################################################################

thevenin_circuit = Circuit('Thevenin Representation')

thevenin_circuit.V('input', 1, thevenin_circuit.gnd, 10@u_V)
thevenin_circuit.R('generator', 1, 'load', 10@u_Ω)
thevenin_circuit.R('load', 'load', thevenin_circuit.gnd, 1@u_kΩ)

simulator = thevenin_circuit.simulator(simulator='xyce-serial', temperature=25, nominal_temperature=25)
# simulator._spice_server._xyce_command = "C:\\Program Files\\Xyce 6.10 OPENSOURCE\\bin\\Xyce.exe"
analysis = simulator.operating_point()

load_node = analysis.load
print('Node {}: {:5.2f} V'.format(str(load_node), float(load_node)))
#o#
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)

####################################################################################################

#?# circuit_macros('buck-converter.m4')

circuit = Circuit('Buck Converter')

circuit.include(spice_library['1N5822']) # Schottky diode
circuit.include(spice_library['irf150'])

# From Microchip WebSeminars - Buck Converter Design Example

Vin = 12@u_V
Vout = 5@u_V
ratio = Vout / Vin

Iload = 2@u_A
Rload = Vout / (.8 * Iload)

frequency = 400@u_kHz
period = frequency.period
Exemple #55
0
from PySpice.Unit import *

####################################################################################################

libraries_path = find_libraries()
spice_library = SpiceLibrary(libraries_path)

####################################################################################################

from HP54501A import HP54501A

#f# literal_include('HP54501A.py')

####################################################################################################

circuit = Circuit('HP54501A CEM')
circuit.include(spice_library['1N4148'])
diode_model = '1N4148'
ac_line = circuit.AcLine('input', 'input', circuit.gnd, rms_voltage=230@u_V, frequency=50@u_Hz)
# circuit.subcircuit(HP54501A(diode_model='1N4148'))
# circuit.X('hp54501a', 'HP54501A', 'input', circuit.gnd)
circuit.C(1, 'input', circuit.gnd, 1@u_uF)
circuit.X('D1', diode_model, 'line_plus', 'top')
circuit.X('D2', diode_model, 'scope_ground', 'input')
circuit.X('D3', diode_model, circuit.gnd, 'top')
circuit.X('D4', diode_model, 'scope_ground', circuit.gnd)
circuit.R(1, 'top', 'output', 10@u_Ω)
circuit.C(2, 'output', 'scope_ground', 50@u_uF)
circuit.R(2, 'output', 'scope_ground', 900@u_Ω)

simulator = circuit.simulator(temperature=25, nominal_temperature=25)
import PySpice.Logging.Logging as Logging
logger = Logging.setup_logging()

####################################################################################################

from PySpice.Plot.BodeDiagram import bode_diagram
from PySpice.Probe.Plot import plot
from PySpice.Spice.Netlist import Circuit
from PySpice.Unit.Units import *

from OperationalAmplifier import BasicOperationalAmplifier

####################################################################################################

circuit = Circuit('Operational Amplifier')

# AC 1 PWL(0US 0V  0.01US 1V)
circuit.Sinusoidal('input', 'in', circuit.gnd, amplitude=1)
circuit.subcircuit(BasicOperationalAmplifier())
circuit.X('op', 'BasicOperationalAmplifier', 'in', circuit.gnd, 'out')
circuit.R('load', 'out', circuit.gnd, 470)

simulator = circuit.simulator(temperature=25, nominal_temperature=25)
analysis = simulator.ac(start_frequency=1, stop_frequency=mega(100), number_of_points=5,  variation='dec')

figure = plt.figure(1, (20, 10))
plt.title("Bode Diagram of an Operational Amplifier")
bode_diagram(axes=(plt.subplot(211), plt.subplot(212)),
             frequency=analysis.frequency,
             gain=20*np.log10(np.absolute(analysis.out)),