.. include:: /project-links.txt .. include:: /abbreviation.txt .. getthecode:: subcircuit.py :language: python3 :hidden: ======================= How to Use SubCircuit ======================= This example shows how to use subcircuits. .. code-block:: py3 import PySpice.Logging.Logging as Logging logger = Logging.setup_logging() from PySpice.Spice.Netlist import Circuit, SubCircuit, SubCircuitFactory from PySpice.Unit import * There is two ways to define subcircuit with PySpice, either using :class:`PySpice.Spice.Netlist.SubCircuit` or a simpler alternative :class:`PySpice.Spice.Netlist.SubCircuitFactory`. Let define a parallel resistor subcircuit using the :class:`PySpice.Spice.Netlist.SubCircuitFactory` .. code-block:: py3 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 .. code-block:: py3 circuit = Circuit('Test') then we can use this subcircuit like this .. code-block:: py3 circuit.subcircuit(ParallelResistor(R2=3@u_Ω)) circuit.X('1', 'parallel_resistor', 1, circuit.gnd) print(circuit) .. code-block:: none .title Test .subckt parallel_resistor n1 n2 R1 n1 n2 1Ohm R2 n1 n2 3Ohm .ends parallel_resistor X1 1 0 parallel_resistor If the above way is not suited for your purpose we can use this second approach .. code-block:: py3 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) .. code-block:: none .title Test .subckt pr1 n1 n2 R1 n1 n2 1Ohm R2 n1 n2 2Ohm .ends pr1 .subckt pr2 n1 n2 R1 n1 n2 1Ohm R2 n1 n2 3Ohm .ends pr2 X1 1 0 pr1 X2 1 0 pr2