Python intro#
gdsfactory is written in python and requires some basic knowledge of python.
If you are new to python you can find many resources online
This notebook is for you to experiment with some common python patterns in gdsfactory
Classes#
Gdsfactory has already some pre-defined classes for you.
All the other classes (Component, ComponentReference, Port …) are already available in gf.typings
Classes are good for keeping state, which means that they store some information inside them (polygons, ports, references …).
In gdsfactory you will write functions instead of classes. Functions are easier to write and combine, and have clearly defined inputs and outputs.
import gdsfactory as gf
c = gf.Component()
c.add_polygon([(-8, -6), (6, 8), (7, 17), (9, 5)], layer=(1, 0))
c.plot()

Functions#
Functions have clear inputs and outputs, they usually accept some parameters (strings, floats, ints …) and return other parameters
def double(x):
return 2 * x
x = 1.5
y = double(x)
print(y)
3.0
It’s also nice to add type annotations
to your functions to clearly define what are the input/output types (string, int, float …)
def double(x: float) -> float:
return 2 * x
Factories#
A factory is a function that returns an object. In gdsfactory many functions return a Component
object
def bend(radius: float = 5) -> gf.Component:
return gf.components.bend_euler(radius=radius)
component = bend(radius=10)
print(component)
component.plot()
Component(name=bend_euler_gdsfactorypc_e95a7a4d, ports=['o1', 'o2'], instances=[], locked=True, kcl=DEFAULT)

Decorators#
A decorator is a special function in Python that lets you add extra functionality to other functions, without modifying their code.
In gdsfactory, decorators are used for managing functions that return a Component
. For example, the @cell
decorator:
Gives each
Component
a unique name based on its input parameters.Caches the returned
Component
for speed and to avoid duplicating cells.
For that you will see a @cell
decorator on many component functions.
An example of a decorator is validate_call
in the pydantic library.
from pydantic import validate_call
@validate_call
def double(x: float) -> float:
return 2 * x
x = 1.5
y = double(x)
print(y)
3.0
The validator decorator is equivalent to running
def double(x: float) -> float:
return 2 * x
double_with_validator = validate_call(double)
x = 1.5
y = double_with_validator(x)
print(y)
3.0
Lets try to create an error x
and you will get a clear message the the function double
does not work with strings
y = double("not_valid_number")
will raise a ValidationError
ValidationError: 1 validation error for double
0
Input should be a valid number, unable to parse string as a number ...
validate_call
will also cast
the input type based on the type annotation. So if you pass a another type it will convert it to float
x = "12"
print(f"{double(x)=}")
print(f"{double_with_validator(x)=}")
double(x)='1212'
double_with_validator(x)=24.0
List comprehensions#
You will also see some list comprehensions, which are common in python.
For example, you can write many loops in one line
y = []
for x in range(3):
y.append(double(x))
print(y)
[0, 2, 4]
y = [double(x) for x in range(3)] # much shorter and easier to read
print(y)
[0, 2, 4]
Functional programming#
Functional programming follows linux philosophy:
Write functions that do one thing and do it well.
Write functions to work together.
Write functions with clear inputs and outputs
partial#
Partial is an easy way to modify the default arguments of a function. This is useful in gdsfactory because we define Parametric Cells (PCells) using functions. from functools import partial
You can use partial to create a new function with some default arguments.
The following two functions are equivalent in functionality. Notice how the second one is shorter, more readable and easier to maintain thanks to partial
Example without partial#
def ring_sc1(gap=0.3, **kwargs) -> gf.Component:
return gf.components.ring_single(gap=gap, **kwargs)
# Usage
c1 = ring_sc1(radius=10)
Example with partial#
from functools import partial
ring_sc2 = partial(gf.components.ring_single, gap=0.3)
# Usage
c2 = ring_sc2(radius=10)
partial
becomes more useful as you customize more parameters and more widely reuse functions.
compose#
gf.compose
combines two functions into one. This is useful in gdsfactory because we
define PCells using functions and functions are easier to combine than classes.
(This is the compose function in the toolz package from toolz import compose
)
ring_sc5 = partial(gf.components.ring_single, radius=10)
add_gratings = gf.routing.add_fiber_array
ring_sc_gc = gf.compose(add_gratings, ring_sc5)
ring_sc_gc5 = ring_sc_gc(radius=5)
ring_sc_gc5

This is equivalent to calling the functions one after the other
ring_sc_gc5 = add_gratings(ring_sc1(radius=5))
ring_sc_gc5

Ipython#
This Jupyter Notebook uses an Interactive Python Terminal (Ipython). So you can interact with the code.
For more details on Jupyter Notebooks, you can visit the Jupyter website.
The most common trick that you will see is that we use ?
to see the documentation of a function or help(function)
gf.components.coupler?
help(gf.components.coupler)
Help on function coupler in module gdsfactory.components.couplers.coupler:
coupler(gap: 'float' = 0.236, length: 'float' = 20.0, dy: 'Delta' = 4.0, dx: 'Delta' = 10.0, cross_section: 'CrossSectionSpec' = 'strip', allow_min_radius_violation: 'bool' = False, bend: 'ComponentSpec' = 'bend_s') -> 'Component'
Symmetric coupler.
Args:
gap: between straights in um.
length: of coupling region in um.
dy: port to port vertical spacing in um.
dx: length of bend in x direction in um.
cross_section: spec (CrossSection, string or dict).
allow_min_radius_violation: if True does not check for min bend radius.
bend: input and output sbend components.
.. code::
dx dx
|------| |------|
o2 ________ ______o3
\ / |
\ length / |
======================= gap | dy
/ \ |
________/ \_______ |
o1 o4
coupler_straight coupler_symmetric
To see the source code of a function you can use ??
gf.components.coupler??
To time the execution time of a cell, you can add a %time
on top of the cell
%time
def hi() -> None:
print("hi")
hi()
CPU times: user 2 μs, sys: 0 ns, total: 2 μs
Wall time: 5.25 μs
hi
For more Ipython tricks you can find many resources available online
gdsfactory downloads#
You can also use python plot the downloads for gdsfactory over the last year.
import datetime
import plotly.graph_objects as go
import requests
downloads0 = 0
def get_total_downloads(package_name):
statistics = []
end_date = datetime.date.today()
while True:
url = f"https://pypistats.org/api/packages/{package_name}/overall"
response = requests.get(url, params={"last_day": end_date})
data = response.json()
if response.status_code != 200:
return None
statistics.extend(
[(entry["date"], entry["downloads"]) for entry in data["data"]]
)
if "next_day" in data:
end_date = data["next_day"]
else:
break
statistics.sort(key=lambda x: x[0]) # Sort by date
dates, downloads = zip(*statistics)
cumulative_downloads = [
sum(downloads[: i + 1]) + downloads0 for i in range(len(downloads))
]
return dates, cumulative_downloads
# Replace 'gdsfactory' with the package you want to check
package_name = "gdsfactory"
dates, cumulative_downloads = get_total_downloads(package_name)
if dates and cumulative_downloads:
fig = go.Figure(data=go.Scatter(x=dates, y=cumulative_downloads))
fig.update_layout(
xaxis=dict(title="Date", tickformat="%Y-%m-%d", tickangle=45, showgrid=True),
yaxis=dict(title="Total Downloads", showgrid=True),
title=f"Total Downloads - {package_name}",
)
fig.update_layout(autosize=False, width=800, height=600)
fig.show()
else:
print(f"Failed to retrieve download statistics for package '{package_name}'.")