#!/usr/bin/env python # coding: utf-8 # How to Use SubCircuit # ===================== # # This example shows how to use subcircuits. # # In[ ]: import PySpice.Logging.Logging as Logging logger = Logging.setup_logging() from PySpice import Circuit, SubCircuit, SubCircuitFactory from PySpice.Unit import * # There is two ways to define subcircuit with PySpice, either using # `PySpice.Spice.Netlist.SubCircuit`{.interpreted-text role="class"} or a # simpler alternative # `PySpice.Spice.Netlist.SubCircuitFactory`{.interpreted-text # role="class"}. # # Let define a parallel resistor subcircuit using the # `PySpice.Spice.Netlist.SubCircuitFactory`{.interpreted-text # role="class"} # # In[ ]: class ParallelResistor(SubCircuitFactory): NAME = 'parallel_resistor' NODES = ('n1', 'n2') def __init__(self, R1=1@u_Ω, R2=2@u_Ω): super().__init__() self.R(1, 'n1', 'n2', R1) self.R(2, 'n1', 'n2', R2) # Let define a circuit # # In[ ]: circuit = Circuit('Test') # then we can use this subcircuit like this # # In[ ]: circuit.subcircuit(ParallelResistor(R2=3@u_Ω)) circuit.X('1', 'parallel_resistor', 1, circuit.gnd) print(circuit) # If the above way is not suited for your purpose we can use this second # approach # # In[ ]: class ParallelResistor2(SubCircuit): NODES = ('n1', 'n2') def __init__(self, name, R1=1@u_Ω, R2=2@u_Ω): SubCircuit.__init__(self, name, *self.NODES) self.R(1, 'n1', 'n2', R1) self.R(2, 'n1', 'n2', R2) circuit = Circuit('Test') circuit.subcircuit(ParallelResistor2('pr1', R2=2@u_Ω)) circuit.X('1', 'pr1', 1, circuit.gnd) circuit.subcircuit(ParallelResistor2('pr2', R2=3@u_Ω)) circuit.X('2', 'pr2', 1, circuit.gnd) print(circuit)