{ "cells": [ { "cell_type": "markdown", "id": "0", "metadata": {}, "source": [ "# Python intro\n", "\n", "gdsfactory is written in python and requires some basic knowledge of python.\n", "\n", "If you are new to python you can find many resources online\n", "\n", "- [books](https://jakevdp.github.io/PythonDataScienceHandbook/index.html)\n", "- [youTube videos](https://www.youtube.com/c/anthonywritescode)\n", "- [courses](https://github.com/joamatab/practical-python)\n", "\n", "This notebook is for you to experiment with some common python patterns in `gdsfactory`\n", "\n", "## Classes\n", "\n", "Gdsfactory has already some pre-defined classes for you.\n", "\n", "All the other classes (Component, ComponentReference, Port ...) are already available in `gf.typings`\n", "\n", "Classes are good for keeping state, which means that they store some information inside them (polygons, ports, references ...).\n", "\n", "In gdsfactory you will write functions instead of classes. Functions are easier to write and combine, and have clearly defined inputs and outputs." ] }, { "cell_type": "code", "execution_count": null, "id": "1", "metadata": {}, "outputs": [], "source": [ "from functools import partial\n", "from pydantic import validate_call\n", "import gdsfactory as gf" ] }, { "cell_type": "code", "execution_count": null, "id": "2", "metadata": { "lines_to_next_cell": 2 }, "outputs": [], "source": [ "c = gf.Component()\n", "c.add_polygon([(-8, -6), (6, 8), (7, 17), (9, 5)], layer=(1, 0))\n", "c.plot()" ] }, { "cell_type": "markdown", "id": "3", "metadata": { "lines_to_next_cell": 2 }, "source": [ "## Functions\n", "\n", "Functions have clear inputs and outputs, they usually accept some parameters (strings, floats, ints ...) and return other parameters\n" ] }, { "cell_type": "code", "execution_count": null, "id": "4", "metadata": {}, "outputs": [], "source": [ "def double(x):\n", " return 2 * x\n", "\n", "\n", "x = 1.5\n", "y = double(x)\n", "print(y)" ] }, { "cell_type": "markdown", "id": "5", "metadata": { "lines_to_next_cell": 2 }, "source": [ "It's also nice to add `type annotations` to your functions to clearly define what are the input/output types (string, int, float ...)\n" ] }, { "cell_type": "code", "execution_count": null, "id": "6", "metadata": { "lines_to_next_cell": 2 }, "outputs": [], "source": [ "def double(x: float) -> float:\n", " return 2 * x" ] }, { "cell_type": "markdown", "id": "7", "metadata": { "lines_to_next_cell": 2 }, "source": [ "## Factories\n", "\n", "A factory is a function that returns an object. In gdsfactory many functions return a `Component` object\n" ] }, { "cell_type": "code", "execution_count": null, "id": "8", "metadata": { "lines_to_next_cell": 2 }, "outputs": [], "source": [ "def bend(radius: float = 5) -> gf.typings.Component:\n", " return gf.components.bend_euler(radius=radius)\n", "\n", "\n", "component = bend(radius=10)\n", "\n", "print(component)\n", "component.plot()" ] }, { "cell_type": "markdown", "id": "9", "metadata": { "lines_to_next_cell": 2 }, "source": [ "## Decorators\n", "\n", "gdsfactory has many functions, and we want to do some common operations for the ones that return a Component:\n", "\n", "- give a unique name (dependent on the input parameters) to a Component\n", "- validate input arguments based on type annotations\n", "- cache the Component that the function returns for speed and reuse cells.\n", "\n", "For that you will see a `@cell` decorator on many component functions.\n", "\n", "The validation functionality comes from the [pydantic](https://pydantic-docs.helpmanual.io/) package\n", "and is available to you automatically when using the `@cell` decorator\n" ] }, { "cell_type": "code", "execution_count": null, "id": "10", "metadata": {}, "outputs": [], "source": [ "@validate_call\n", "def double(x: float) -> float:\n", " return 2 * x\n", "\n", "\n", "x = 1.5\n", "y = double(x)\n", "print(y)" ] }, { "cell_type": "markdown", "id": "11", "metadata": { "lines_to_next_cell": 2 }, "source": [ "The validator decorator is equivalent to running\n" ] }, { "cell_type": "code", "execution_count": null, "id": "12", "metadata": {}, "outputs": [], "source": [ "def double(x: float) -> float:\n", " return 2 * x\n", "\n", "\n", "double_with_validator = validate_call(double)\n", "x = 1.5\n", "y = double_with_validator(x)\n", "print(y)" ] }, { "cell_type": "markdown", "id": "13", "metadata": {}, "source": [ "The `cell` decorator also leverages that validate arguments.\n", "So you should add type annotations to your component factories.\n", "\n", "Lets try to create an error `x` and you will get a clear message the the function `double` does not work with strings" ] }, { "cell_type": "markdown", "id": "14", "metadata": {}, "source": [ "```python\n", "y = double(\"not_valid_number\")\n", "```\n", "\n", "will raise a `ValidationError`\n", "\n", "```\n", "ValidationError: 0 validation error for Double\n", "x\n", " value is not a valid float (type=type_error.float)\n", "\n", "```\n", "\n", "It will also `cast` the input type based on the type annotation. So if you pass an `int` it will convert it to `float`" ] }, { "cell_type": "code", "execution_count": null, "id": "15", "metadata": {}, "outputs": [], "source": [ "x = 1\n", "y = double_with_validator(x)\n", "print(y, type(x), type(y))" ] }, { "cell_type": "markdown", "id": "16", "metadata": {}, "source": [ "## List comprehensions\n", "\n", "You will also see some list comprehensions, which are common in python.\n", "\n", "For example, you can write many loops in one line" ] }, { "cell_type": "code", "execution_count": null, "id": "17", "metadata": {}, "outputs": [], "source": [ "y = []\n", "for x in range(3):\n", " y.append(double(x))\n", "\n", "print(y)" ] }, { "cell_type": "code", "execution_count": null, "id": "18", "metadata": { "lines_to_next_cell": 2 }, "outputs": [], "source": [ "y = [double(x) for x in range(3)] # much shorter and easier to read\n", "print(y)" ] }, { "cell_type": "markdown", "id": "19", "metadata": { "lines_to_next_cell": 2 }, "source": [ "## Functional programming\n", "\n", "Functional programming follows linux philosophy:\n", "\n", "- Write functions that do one thing and do it well.\n", "- Write functions to work together.\n", "- Write functions with clear **inputs** and **outputs**\n", "\n", "### partial\n", "\n", "Partial is an easy way to modify the default arguments of a function. This is useful in gdsfactory because we define PCells using functions. `from functools import partial`\n", "\n", "You can use partial to create a new function with some default arguments.\n", "\n", "The following two functions are equivalent in functionality. Notice how the second one is shorter, more readable and easier to maintain thanks to `partial`:\n" ] }, { "cell_type": "code", "execution_count": null, "id": "20", "metadata": {}, "outputs": [], "source": [ "def ring_sc(gap=0.3, **kwargs) -> gf.Component:\n", " return gf.components.ring_single(gap=gap, **kwargs)\n", "\n", "\n", "ring_sc = partial(gf.components.ring_single, gap=0.3) # shorter and easier to read" ] }, { "cell_type": "markdown", "id": "21", "metadata": { "lines_to_next_cell": 2 }, "source": [ "As you customize more parameters, it's more obvious that the second one is easier to maintain\n" ] }, { "cell_type": "code", "execution_count": null, "id": "22", "metadata": {}, "outputs": [], "source": [ "def ring_sc(gap=0.3, radius=10, **kwargs):\n", " return gf.components.ring_single(gap=gap, radius=radius, **kwargs)\n", "\n", "\n", "ring_sc = partial(gf.components.ring_single, gap=0.3, radius=10)" ] }, { "cell_type": "markdown", "id": "23", "metadata": {}, "source": [ "### compose\n", "\n", "`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. You can also import compose from the toolz package `from toolz import compose`" ] }, { "cell_type": "code", "execution_count": null, "id": "24", "metadata": {}, "outputs": [], "source": [ "ring_sc = partial(gf.components.ring_single, radius=10)\n", "add_gratings = gf.routing.add_fiber_array\n", "\n", "ring_sc_gc = gf.compose(add_gratings, ring_sc)\n", "ring_sc_gc5 = ring_sc_gc(radius=5)\n", "ring_sc_gc5" ] }, { "cell_type": "code", "execution_count": null, "id": "25", "metadata": {}, "outputs": [], "source": [ "ring_sc_gc20 = ring_sc_gc(radius=20)\n", "ring_sc_gc20" ] }, { "cell_type": "markdown", "id": "26", "metadata": {}, "source": [ "This is equivalent and more readable than writing" ] }, { "cell_type": "code", "execution_count": null, "id": "27", "metadata": {}, "outputs": [], "source": [ "ring_sc_gc5 = add_gratings(ring_sc(radius=5))\n", "ring_sc_gc5" ] }, { "cell_type": "code", "execution_count": null, "id": "28", "metadata": {}, "outputs": [], "source": [ "ring_sc_gc20 = add_gratings(ring_sc(radius=20))\n", "ring_sc_gc20" ] }, { "cell_type": "code", "execution_count": null, "id": "29", "metadata": {}, "outputs": [], "source": [ "print(ring_sc_gc5)" ] }, { "cell_type": "markdown", "id": "30", "metadata": {}, "source": [ "## Ipython\n", "\n", "This Jupyter Notebook uses an Interactive Python Terminal (Ipython). So you can interact with the code.\n", "\n", "For more details on Jupyter Notebooks, you can visit the [Jupyter website](https://jupyter.org/).\n", "\n", "The most common trick that you will see is that we use `?` to see the documentation of a function or `help(function)`" ] }, { "cell_type": "code", "execution_count": null, "id": "31", "metadata": {}, "outputs": [], "source": [ "gf.components.coupler?" ] }, { "cell_type": "code", "execution_count": null, "id": "32", "metadata": {}, "outputs": [], "source": [ "help(gf.components.coupler)" ] }, { "cell_type": "markdown", "id": "33", "metadata": {}, "source": [ "To see the source code of a function you can use `??`" ] }, { "cell_type": "code", "execution_count": null, "id": "34", "metadata": {}, "outputs": [], "source": [ "gf.components.coupler??" ] }, { "cell_type": "markdown", "id": "35", "metadata": {}, "source": [ "To time the execution time of a cell, you can add a `%time` on top of the cell" ] }, { "cell_type": "code", "execution_count": null, "id": "36", "metadata": {}, "outputs": [], "source": [ "%time\n", "\n", "\n", "def hi() -> None:\n", " print(\"hi\")\n", "\n", "\n", "hi()" ] }, { "cell_type": "markdown", "id": "37", "metadata": {}, "source": [ "For more Ipython tricks you can find many resources available online\n", "\n", "## gdsfactory downloads\n", "\n", "You can also use python plot the downloads for gdsfactory over the last year." ] }, { "cell_type": "code", "execution_count": null, "id": "38", "metadata": {}, "outputs": [], "source": [ "import datetime\n", "\n", "import plotly.graph_objects as go\n", "import requests\n", "\n", "downloads0 = 0\n", "\n", "\n", "def get_total_downloads(package_name):\n", " statistics = []\n", " end_date = datetime.date.today()\n", "\n", " while True:\n", " url = f\"https://pypistats.org/api/packages/{package_name}/overall\"\n", " response = requests.get(url, params={\"last_day\": end_date})\n", " data = response.json()\n", "\n", " if response.status_code != 200:\n", " return None\n", "\n", " statistics.extend(\n", " [(entry[\"date\"], entry[\"downloads\"]) for entry in data[\"data\"]]\n", " )\n", " if \"next_day\" in data:\n", " end_date = data[\"next_day\"]\n", " else:\n", " break\n", " statistics.sort(key=lambda x: x[0]) # Sort by date\n", " dates, downloads = zip(*statistics)\n", " cumulative_downloads = [\n", " sum(downloads[: i + 1]) + downloads0 for i in range(len(downloads))\n", " ]\n", "\n", " return dates, cumulative_downloads\n", "\n", "\n", "# Replace 'gdsfactory' with the package you want to check\n", "package_name = \"gdsfactory\"\n", "dates, cumulative_downloads = get_total_downloads(package_name)\n", "\n", "if dates and cumulative_downloads:\n", " fig = go.Figure(data=go.Scatter(x=dates, y=cumulative_downloads))\n", " fig.update_layout(\n", " xaxis=dict(title=\"Date\", tickformat=\"%Y-%m-%d\", tickangle=45, showgrid=True),\n", " yaxis=dict(title=\"Total Downloads\", showgrid=True),\n", " title=f\"Total Downloads - {package_name}\",\n", " )\n", " fig.update_layout(autosize=False, width=800, height=600)\n", " fig.show()\n", "else:\n", " print(f\"Failed to retrieve download statistics for package '{package_name}'.\")" ] } ], "metadata": { "jupytext": { "cell_metadata_filter": "-all", "custom_cell_magics": "kql", "main_language": "python" }, "kernelspec": { "display_name": "base", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.5" } }, "nbformat": 4, "nbformat_minor": 5 }