Skip to content

Schematic driven layout

A schematic is a graph representation of your circuit.

For complex circuits, a schematic allows you to create symbols and hierarchy levels to represent your circuit.

Having a schematic allows you to also ensure that your layout matches you schematic (design intent).

There are many schematic capturing tools out there:

  • Qucs-s: for RF.
  • Xschem: for analog circuits.
  • Lumerical interconnect: for photonic circuits.

These tools allow you to create schematics with either your mouse or by code.

gdsfactory also allows you to create complex Schematics directly from python with a very simple interface.

import gdsfactory as gf
import yaml
from functools import partial

gf.gpdk.PDK.activate()
@gf.schematic_cell
def my_schematic(x: float = 108.5, y: float = 53.1) -> gf.Schematic:
    """Returns a schematic with two rings connected by a waveguide."""
    s = gf.Schematic()
    r1 = s.create_inst(name="r1", component="ring_single")
    r1.place(x=0, y=0)

    r2 = s.create_inst(name="r2", component="ring_single", settings={"radius": 32.2})
    r2.place(x=x, y=y)

    s.add_route(
        name="r1-r2",
        nets=[[r1.ports["o2"], r2.ports["o1"]]],
        routing_strategy="route_bundle",
        settings={},
    )
    return s

c = my_schematic()
c.plot()

png

@gf.schematic_cell(
    factories=gf.get_factories.get_cells("gdsfactory"),
    routing_strategies=gf.get_active_pdk().routing_strategies
    or {
        "route_bundle": partial(
            gf.routing.route_bundle, layer=gf.get_layer((1, 0)), route_width=1
        )
    },
)
def my_schematic(x: float = 108.5, y: float = 53.1) -> gf.Schematic:
    """Returns a schematic with two rings connected by a waveguide."""
    s = gf.Schematic()
    r1 = s.create_inst(name="r1", component="ring_single")
    r1.place(x=0, y=0)

    r2 = s.create_inst(name="r2", component="ring_single", settings={"radius": 32.2})
    r2.place(x=x, y=y)

    s.add_route(
        name="r1-r2",
        nets=[[r1.ports["o2"], r2.ports["o1"]]],
        routing_strategy="route_bundle",
        settings={},
    )

    return s

c = my_schematic()
c.plot()

png

@gf.schematic_cell
def ring_array(n: int = 3, pitch_x: float = 100, pitch_y=50, radius: float = 10, radius_delta: float = 5) -> gf.Schematic:
    """Returns a schematic with n rings connected by a waveguide."""
    s = gf.Schematic()

    last_ring  = None

    for i in range(n):
        r = s.create_inst(name=f"r{i}", component="ring_single", settings={"radius": radius+i*radius_delta})
        r.place(x=i*pitch_x, y=i*pitch_y)
        if last_ring is not None:
            s.add_route(
                name=f"r{i-1}-r{i}",
                nets=[[last_ring.ports["o2"], r.ports["o1"]]],
                routing_strategy="route_bundle",
                settings={},
            )
        last_ring = r
    return s

c = ring_array()
c.plot()

png

c = gf.c.mzi()

# .plot_netlist_graphviz(): This method reads the component's netlist and uses Graphviz (a graph visualization tool) to create a block diagram.
# interactive=False: This parameter specifies that the output should be a static image rather than an interactive plot.
c.plot_netlist_graphviz(interactive=False)
Error: Layout type: "neato" not recognized. Use one of: dot
Error: Layout was not done.  Missing layout plugins?



---------------------------------------------------------------------------

CalledProcessError                        Traceback (most recent call last)

File ~/work/gdsfactory/gdsfactory/.venv/lib/python3.12/site-packages/graphviz/backend/execute.py:88, in run_check(cmd, input_lines, encoding, quiet, **kwargs)
     87 try:
---> 88     proc.check_returncode()
     89 except subprocess.CalledProcessError as e:


File /opt/hostedtoolcache/Python/3.12.16/x64/lib/python3.12/subprocess.py:502, in CompletedProcess.check_returncode(self)
    501 if self.returncode:
--> 502     raise CalledProcessError(self.returncode, self.args, self.stdout,
    503                              self.stderr)


CalledProcessError: Command '[PosixPath('dot'), '-Kdot', '-Tpng']' returned non-zero exit status 1.


During handling of the above exception, another exception occurred:


CalledProcessError                        Traceback (most recent call last)

Cell In[5], line 5
      1 c = gf.c.mzi()
      2 
      3 # .plot_netlist_graphviz(): This method reads the component's netlist and uses Graphviz (a graph visualization tool) to create a block diagram.
      4 # interactive=False: This parameter specifies that the output should be a static image rather than an interactive plot.
----> 5 c.plot_netlist_graphviz(interactive=False)


File ~/work/gdsfactory/gdsfactory/gdsfactory/component.py:1575, in Component.plot_netlist_graphviz(self, recursive, interactive, splines)
   1570 from gdsfactory.schematic import plot_graphviz
   1572 n = self.to_graphviz(
   1573     recursive=recursive,
   1574 )
-> 1575 plot_graphviz(n, splines=splines, interactive=interactive)


File ~/work/gdsfactory/gdsfactory/gdsfactory/schematic.py:461, in plot_graphviz(graph, interactive, splines)
    459     graph.view()
    460 else:
--> 461     png_data = graph.pipe(format="png")
    462     display(Image(data=png_data))


File ~/work/gdsfactory/gdsfactory/.venv/lib/python3.12/site-packages/graphviz/piping.py:104, in Pipe.pipe(self, format, renderer, formatter, neato_no_op, quiet, engine, encoding)
     55 def pipe(self,
     56          format: typing.Optional[str] = None,
     57          renderer: typing.Optional[str] = None,
   (...)     61          engine: typing.Optional[str] = None,
     62          encoding: typing.Optional[str] = None) -> typing.Union[bytes, str]:
     63     """Return the source piped through the Graphviz layout command.
     64 
     65     Args:
   (...)    102         '<?xml version='
    103     """
--> 104     return self._pipe_legacy(format,
    105                              renderer=renderer,
    106                              formatter=formatter,
    107                              neato_no_op=neato_no_op,
    108                              quiet=quiet,
    109                              engine=engine,
    110                              encoding=encoding)


File ~/work/gdsfactory/gdsfactory/.venv/lib/python3.12/site-packages/graphviz/_tools.py:185, in deprecate_positional_args.<locals>.decorator.<locals>.wrapper(*args, **kwargs)
    177     wanted = ', '.join(f'{name}={value!r}'
    178                        for name, value in deprecated.items())
    179     warnings.warn(f'The signature of {func_name} will be reduced'
    180                   f' to {supported_number} positional arg{s_}{qualification}'
    181                   f' {list(supported)}: pass {wanted} as keyword arg{s_}',
    182                   stacklevel=stacklevel,
    183                   category=category)
--> 185 return func(*args, **kwargs)


File ~/work/gdsfactory/gdsfactory/.venv/lib/python3.12/site-packages/graphviz/piping.py:121, in Pipe._pipe_legacy(self, format, renderer, formatter, neato_no_op, quiet, engine, encoding)
    112 @_tools.deprecate_positional_args(supported_number=1, ignore_arg='self')
    113 def _pipe_legacy(self,
    114                  format: typing.Optional[str] = None,
   (...)    119                  engine: typing.Optional[str] = None,
    120                  encoding: typing.Optional[str] = None) -> typing.Union[bytes, str]:
--> 121     return self._pipe_future(format,
    122                              renderer=renderer,
    123                              formatter=formatter,
    124                              neato_no_op=neato_no_op,
    125                              quiet=quiet,
    126                              engine=engine,
    127                              encoding=encoding)


File ~/work/gdsfactory/gdsfactory/.venv/lib/python3.12/site-packages/graphviz/piping.py:161, in Pipe._pipe_future(self, format, renderer, formatter, neato_no_op, quiet, engine, encoding)
    159     else:
    160         return raw.decode(encoding)
--> 161 return self._pipe_lines(*args, input_encoding=self.encoding, **kwargs)


File ~/work/gdsfactory/gdsfactory/.venv/lib/python3.12/site-packages/graphviz/backend/piping.py:161, in pipe_lines(engine, format, input_lines, input_encoding, renderer, formatter, neato_no_op, quiet)
    155 cmd = dot_command.command(engine, format,
    156                           renderer=renderer,
    157                           formatter=formatter,
    158                           neato_no_op=neato_no_op)
    159 kwargs = {'input_lines': (line.encode(input_encoding) for line in input_lines)}
--> 161 proc = execute.run_check(cmd, capture_output=True, quiet=quiet, **kwargs)
    162 return proc.stdout


File ~/work/gdsfactory/gdsfactory/.venv/lib/python3.12/site-packages/graphviz/backend/execute.py:90, in run_check(cmd, input_lines, encoding, quiet, **kwargs)
     88     proc.check_returncode()
     89 except subprocess.CalledProcessError as e:
---> 90     raise CalledProcessError(*e.args)
     92 return proc


CalledProcessError: Command '[PosixPath('dot'), '-Kdot', '-Tpng']' returned non-zero exit status 1. [stderr: b'Error: Layout type: "neato" not recognized. Use one of: dot\nError: Layout was not done.  Missing layout plugins? \n']
c.plot_netlist()
<networkx.classes.graph.Graph at 0x7c132c137e30>

png

Lets create a MZI lattice of 3 elements.

from kfactory.schematic import RegularArray
import gdsfactory as gf

@gf.cell
def splitter_tree_with_new_ports(**kwargs) -> gf.Component:
    """Returns a splitter tree with new ports."""
    c = gf.c.splitter_tree(**kwargs).copy()
    c.auto_rename_ports()
    return c


pdk = gf.get_active_pdk()
pdk.register_cells(splitter_tree_new_ports=splitter_tree_with_new_ports)


@gf.schematic_cell(overwrite_existing=True) # for development
def lidar(n: int = 2**3, dbr_pitch: float = 3) -> gf.Schematic:
    """Returns a schematic with lidar array by a waveguide."""
    s = gf.Schematic()
    spt = s.create_inst(name="splitter", component='splitter_tree_new_ports', settings={'noutputs': n, 'spacing': (50, 50)})
    dbr = s.create_inst(name="dbr", component='dbr', array=RegularArray(rows=n, column_pitch=0, row_pitch=dbr_pitch))
    spt.place(x=0, y=0)
    dbr.place(x=250+n*dbr_pitch, y=-n*dbr_pitch/2+dbr_pitch/2)

    start_ports = [spt.ports[f"o{i+2}"] for i in range(n)]
    end_ports = [dbr.ports["o1", 0, i] for i in range(n)]

    s.add_route(
            name="splitter_to_dbr",
            nets=[[start_ports[i], end_ports[i]] for i in range(n)],
            routing_strategy="route_bundle",
            settings={"radius": 5, "separation": 3, "sort_ports": True},
        )
    return s

c = lidar(n=2**4)
c.plot()

png