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
12 |
+
# ]
|
13 |
+
# ///
|
14 |
+
|
15 |
+
import marimo
|
16 |
+
|
17 |
+
__generated_with = "0.11.17"
|
18 |
+
app = marimo.App(width="medium")
|
19 |
+
|
20 |
+
|
21 |
+
@app.cell(hide_code=True)
|
22 |
+
def _(mo):
|
23 |
+
mo.md(
|
24 |
+
r"""
|
25 |
+
# User-Defined Functions
|
26 |
+
|
27 |
+
_By [Péter Ferenc Gyarmati](http://github.com/peter-gy)_.
|
28 |
+
|
29 |
+
Throughout the previous chapters, you've seen how Polars provides a comprehensive set of built-in expressions for flexible data transformation. But what happens when you need something *more*? Perhaps your project has unique requirements, or you need to integrate functionality from an external Python library. This is where User-Defined Functions (UDFs) come into play, allowing you to extend Polars with your own custom logic.
|
30 |
+
|
31 |
+
In this chapter, we'll weigh the performance trade-offs of UDFs, pinpoint situations where they're truly beneficial, and explore different ways to effectively incorporate them into your Polars workflows. We'll walk through a complete, practical example.
|
32 |
+
"""
|
33 |
+
)
|
34 |
+
return
|
35 |
+
|
36 |
+
|
37 |
+
@app.cell(hide_code=True)
|
38 |
+
def _(mo):
|
39 |
+
mo.md(
|
40 |
+
r"""
|
41 |
+
## ⚖️ The Cost of UDFs
|
42 |
+
|
43 |
+
> Performance vs. Flexibility
|
44 |
+
|
45 |
+
Polars' built-in expressions are highly optimized for speed and parallel processing. User-defined functions (UDFs), however, introduce a significant performance overhead because they rely on standard Python code, which often runs in a single thread and bypasses Polars' logical optimizations. Therefore, always prioritize native Polars operations *whenever possible*.
|
46 |
+
|
47 |
+
However, UDFs become inevitable when you need to:
|
48 |
+
|
49 |
+
- **Integrate external libraries:** Use functionality not directly available in Polars.
|
50 |
+
- **Implement custom logic:** Handle complex transformations that can't be easily expressed with Polars' built-in functions.
|
51 |
+
|
52 |
+
Let's dive into a real-world project where UDFs were the only way to get the job done, demonstrating a scenario where native Polars expressions simply weren't sufficient.
|
53 |
+
"""
|
54 |
+
)
|
55 |
+
return
|
56 |
+
|
57 |
+
|
58 |
+
@app.cell(hide_code=True)
|
59 |
+
def _(mo):
|
60 |
+
mo.md(
|
61 |
+
r"""
|
62 |
+
## 📊 Project Overview
|
63 |
+
|
64 |
+
> Scraping and Analyzing Observable Notebook Statistics
|
65 |
+
|
66 |
+
If you're into data visualization, you've probably seen [D3.js](https://d3js.org/) and [Observable Plot](https://observablehq.com/plot/). Both have extensive galleries showcasing amazing visualizations. Each gallery item is a standalone [Observable notebook](https://observablehq.com/documentation/notebooks/), with metrics like stars, comments, and forks – indicators of popularity. But getting and analyzing these statistics directly isn't straightforward. We'll need to scrape the web.
|
67 |
+
"""
|
68 |
+
)
|
69 |
+
return
|
70 |
+
|
71 |
+
|
72 |
+
@app.cell(hide_code=True)
|
73 |
+
def _(mo):
|
74 |
+
mo.hstack(
|
75 |
+
[
|
76 |
+
mo.image(
|
77 |
+
"https://minio.peter.gy/static/assets/marimo/learn/polars/14_d3-gallery.png?0",
|
78 |
+
width=600,
|
79 |
+
caption="Screenshot of https://observablehq.com/@d3/gallery",
|
80 |
+
),
|
81 |
+
mo.image(
|
82 |
+
"https://minio.peter.gy/static/assets/marimo/learn/polars/14_plot-gallery.png?0",
|
83 |
+
width=600,
|
84 |
+
caption="Screenshot of https://observablehq.com/@observablehq/plot-gallery",
|
85 |
+
),
|
86 |
+
]
|
87 |
+
)
|
88 |
+
return
|
89 |
+
|
90 |
+
|
91 |
+
@app.cell(hide_code=True)
|
92 |
+
def _(mo):
|
93 |
+
mo.md(r"""Our goal is to use Polars UDFs to fetch the HTML content of these gallery pages. Then, we'll use the `BeautifulSoup` Python library to parse the HTML and extract the relevant metadata. After some data wrangling with native Polars expressions, we'll have a DataFrame listing each visualization notebook. Then, we'll use another UDF to retrieve the number of likes, forks, and comments for each notebook. Finally, we will create our own high-performance UDF to implement a custom notebook ranking scheme. This will involve multiple steps, showcasing different UDF approaches.""")
|
94 |
+
return
|
95 |
+
|
96 |
+
|
97 |
+
@app.cell(hide_code=True)
|
98 |
+
def _(mo):
|
99 |
+
mo.mermaid('''
|
100 |
+
graph LR;
|
101 |
+
url_df --> |"UDF: Fetch HTML"| html_df
|
102 |
+
html_df --> |"UDF: Parse with BeautifulSoup"| parsed_html_df
|
103 |
+
parsed_html_df --> |"Native Polars: Extract Data"| notebooks_df
|
104 |
+
notebooks_df --> |"UDF: Get Notebook Stats"| notebook_stats_df
|
105 |
+
notebook_stats_df --> |"Numba UDF: Compute Popularity"| notebook_popularity_df
|
106 |
+
''')
|
107 |
+
return
|
108 |
+
|
109 |
+
|
110 |
+
@app.cell(hide_code=True)
|
111 |
+
def _(mo):
|
112 |
+
mo.md(r"""Our starting point, `url_df`, is a simple DataFrame with a single `url` column containing the URLs of the D3 and Observable Plot gallery notebooks.""")
|
113 |
+
return
|
114 |
+
|
115 |
+
|
116 |
+
@app.cell(hide_code=True)
|
117 |
+
def _(pl):
|
118 |
+
url_df = pl.from_dict(
|
119 |
+
{
|
120 |
+
"url": [
|
121 |
+
"https://observablehq.com/@d3/gallery",
|
122 |
+
"https://observablehq.com/@observablehq/plot-gallery",
|
123 |
+
]
|
124 |
+
}
|
125 |
+
)
|
126 |
+
url_df
|
127 |
+
return (url_df,)
|
128 |
+
|
129 |
+
|
130 |
+
@app.cell(hide_code=True)
|
131 |
+
def _(mo):
|
132 |
+
mo.md(
|
133 |
+
r"""
|
134 |
+
## 🔂 Element-Wise UDFs
|
135 |
+
|
136 |
+
> Processing Value by Value
|
137 |
+
|
138 |
+
The most common way to use UDFs is to apply them element-wise. This means our custom function will execute for *each individual row* in a specified column. Our first task is to fetch the HTML content for each URL in `url_df`.
|
139 |
+
|
140 |
+
We'll define a Python function that takes a `url` (a string) as input, uses the `httpx` library (an HTTP client) to fetch the content, and returns the HTML as a string. We then integrate this function into Polars using the [`map_elements`](https://docs.pola.rs/api/python/stable/reference/expressions/api/polars.Expr.map_elements.html) expression.
|
141 |
+
|
142 |
+
You'll notice we have to explicitly specify the `return_dtype`. This is *crucial*. Polars doesn't automatically know what our custom function will return. We're responsible for defining the function's logic and, therefore, its output type. By providing the `return_dtype`, we help Polars maintain its internal representation of the DataFrame's schema, enabling query optimization. Think of it as giving Polars a "heads-up" about the data type it should expect.
|
143 |
+
"""
|
144 |
+
)
|
145 |
+
return
|
146 |
+
|
147 |
+
|
148 |
+
@app.cell(hide_code=True)
|
149 |
+
def _(httpx, pl, url_df):
|
150 |
+
html_df = url_df.with_columns(
|
151 |
+
html=pl.col("url").map_elements(
|
152 |
+
lambda url: httpx.get(url).text,
|
153 |
+
return_dtype=pl.String,
|
154 |
+
)
|
155 |
+
)
|
156 |
+
html_df
|
157 |
+
return (html_df,)
|
158 |
+
|
159 |
+
|
160 |
+
@app.cell(hide_code=True)
|
161 |
+
def _(mo):
|
162 |
+
mo.md(
|
163 |
+
r"""
|
164 |
+
Now, `html_df` holds the HTML for each URL. We need to parse it. Again, a UDF is the way to go. Parsing HTML with native Polars expressions would be a nightmare! Instead, we'll use the [`beautifulsoup4`](https://pypi.org/project/beautifulsoup4/) library, a standard tool for this.
|
165 |
+
|
166 |
+
These Observable pages are built with [Next.js](https://nextjs.org/), which helpfully serializes page properties as JSON within the HTML. This simplifies our UDF: we'll extract the raw JSON from the `<script id="__NEXT_DATA__" type="application/json">` tag. We'll use [`map_elements`](https://docs.pola.rs/api/python/stable/reference/expressions/api/polars.Expr.map_elements.html) again. For clarity, we'll define this UDF as a named function, `extract_nextjs_data`, since it's a bit more complex than a simple HTTP request.
|
167 |
+
"""
|
168 |
+
)
|
169 |
+
return
|
170 |
+
|
171 |
+
|
172 |
+
@app.cell(hide_code=True)
|
173 |
+
def _(BeautifulSoup):
|
174 |
+
def extract_nextjs_data(html: str) -> str:
|
175 |
+
soup = BeautifulSoup(html, "html.parser")
|
176 |
+
script_tag = soup.find("script", id="__NEXT_DATA__")
|
177 |
+
return script_tag.text
|
178 |
+
return (extract_nextjs_data,)
|
179 |
+
|
180 |
+
|
181 |
+
@app.cell(hide_code=True)
|
182 |
+
def _(extract_nextjs_data, html_df, pl):
|
183 |
+
parsed_html_df = html_df.select(
|
184 |
+
"url",
|
185 |
+
next_data=pl.col("html").map_elements(
|
186 |
+
extract_nextjs_data,
|
187 |
+
return_dtype=pl.String,
|
188 |
+
),
|
189 |
+
)
|
190 |
+
parsed_html_df
|
191 |
+
return (parsed_html_df,)
|
192 |
+
|
193 |
+
|
194 |
+
@app.cell(hide_code=True)
|
195 |
+
def _(mo):
|
196 |
+
mo.md(r"""With some data wrangling of the raw JSON (using *native* Polars expressions!), we get `notebooks_df`, containing the metadata for each notebook.""")
|
197 |
+
return
|
198 |
+
|
199 |
+
|
200 |
+
@app.cell(hide_code=True)
|
201 |
+
def _(parsed_html_df, pl):
|
202 |
+
notebooks_df = (
|
203 |
+
parsed_html_df.select(
|
204 |
+
"url",
|
205 |
+
# We extract the content of every cell present in the gallery notebooks
|
206 |
+
cell=pl.col("next_data")
|
207 |
+
.str.json_path_match("$.props.pageProps.initialNotebook.nodes")
|
208 |
+
.str.json_decode()
|
209 |
+
.list.eval(pl.element().struct.field("value")),
|
210 |
+
)
|
211 |
+
# We want one row per cell
|
212 |
+
.explode("cell")
|
213 |
+
# Only keep categorized notebook listing cells starting with H3
|
214 |
+
.filter(pl.col("cell").str.starts_with("### "))
|
215 |
+
# Split up the cells into [heading, description, config] sections
|
216 |
+
.with_columns(pl.col("cell").str.split("\n\n"))
|
217 |
+
.select(
|
218 |
+
gallery_url="url",
|
219 |
+
# Text after the '### ' heading, ignore '<!--' comments'
|
220 |
+
category=pl.col("cell").list.get(0).str.extract(r"###\s+(.*?)(?:\s+<!--.*?-->|$)"),
|
221 |
+
# Paragraph after heading
|
222 |
+
description=pl.col("cell")
|
223 |
+
.list.get(1)
|
224 |
+
.str.strip_chars(" ")
|
225 |
+
.str.replace_all("](/", "](https://observablehq.com/", literal=True),
|
226 |
+
# Parsed notebook config from ${preview([{...}])}
|
227 |
+
notebooks=pl.col("cell")
|
228 |
+
.list.get(2)
|
229 |
+
.str.strip_prefix("${previews([")
|
230 |
+
.str.strip_suffix("]})}")
|
231 |
+
.str.strip_chars(" \n")
|
232 |
+
.str.split("},")
|
233 |
+
# Simple regex-based attribute extraction from JS/JSON objects like
|
234 |
+
# ```js
|
235 |
+
# {
|
236 |
+
# path: "@d3/spilhaus-shoreline-map",
|
237 |
+
# "thumbnail": "66a87355e205d820...",
|
238 |
+
# title: "Spilhaus shoreline map",
|
239 |
+
# "author": "D3"
|
240 |
+
# }
|
241 |
+
# ```
|
242 |
+
.list.eval(
|
243 |
+
pl.struct(
|
244 |
+
*(
|
245 |
+
pl.element()
|
246 |
+
.str.extract(f'(?:"{key}"|{key})\s*:\s*"([^"]*)"')
|
247 |
+
.alias(key)
|
248 |
+
for key in ["path", "thumbnail", "title"]
|
249 |
+
)
|
250 |
+
)
|
251 |
+
),
|
252 |
+
)
|
253 |
+
.explode("notebooks")
|
254 |
+
.unnest("notebooks")
|
255 |
+
.filter(pl.col("path").is_not_null())
|
256 |
+
# Final projection to end up with directly usable values
|
257 |
+
.select(
|
258 |
+
pl.concat_str(
|
259 |
+
[
|
260 |
+
pl.lit("https://static.observableusercontent.com/thumbnail/"),
|
261 |
+
"thumbnail",
|
262 |
+
pl.lit(".jpg"),
|
263 |
+
],
|
264 |
+
).alias("notebook_thumbnail_src"),
|
265 |
+
"category",
|
266 |
+
"title",
|
267 |
+
"description",
|
268 |
+
pl.concat_str(
|
269 |
+
[pl.lit("https://observablehq.com"), "path"], separator="/"
|
270 |
+
).alias("notebook_url"),
|
271 |
+
)
|
272 |
+
)
|
273 |
+
notebooks_df
|
274 |
+
return (notebooks_df,)
|
275 |
+
|
276 |
+
|
277 |
+
@app.cell(hide_code=True)
|
278 |
+
def _(mo):
|
279 |
+
mo.md(
|
280 |
+
r"""
|
281 |
+
## 📦 Batch-Wise UDFs
|
282 |
+
|
283 |
+
> Processing Entire Series
|
284 |
+
|
285 |
+
`map_elements` calls the UDF for *each row*. Fine for our tiny, two-rows-tall `url_df`. But `notebooks_df` has almost 400 rows! Individual HTTP requests for each would be painfully slow.
|
286 |
+
|
287 |
+
We want stats for each notebook in `notebooks_df`. To avoid sequential requests, we'll use Polars' [`map_batches`](https://docs.pola.rs/api/python/stable/reference/expressions/api/polars.Expr.map_batches.html). This lets us process an *entire Series* (a column) at once.
|
288 |
+
|
289 |
+
Our UDF, `fetch_html_batch`, will take a *Series* of URLs and use `asyncio` to make concurrent requests – a huge performance boost.
|
290 |
+
"""
|
291 |
+
)
|
292 |
+
return
|
293 |
+
|
294 |
+
|
295 |
+
@app.cell(hide_code=True)
|
296 |
+
def _(Iterable, asyncio, httpx, mo):
|
297 |
+
async def _fetch_html_batch(urls: Iterable[str]) -> tuple[str, ...]:
|
298 |
+
async with httpx.AsyncClient(timeout=15) as client:
|
299 |
+
res = await asyncio.gather(*(client.get(url) for url in urls))
|
300 |
+
return tuple((r.text for r in res))
|
301 |
+
|
302 |
+
|
303 |
+
@mo.cache
|
304 |
+
def fetch_html_batch(urls: Iterable[str]) -> tuple[str, ...]:
|
305 |
+
return asyncio.run(_fetch_html_batch(urls))
|
306 |
+
return (fetch_html_batch,)
|
307 |
+
|
308 |
+
|
309 |
+
@app.cell(hide_code=True)
|
310 |
+
def _(mo):
|
311 |
+
mo.callout(
|
312 |
+
mo.md("""
|
313 |
+
Since `fetch_html_batch` is a pure Python function and performs multiple network requests, it's a good candidate for caching. We use [`mo.cache`](https://docs.marimo.io/api/caching/#marimo.cache) to avoid redundant requests to the same URL. This is a simple way to improve performance without modifying the core logic.
|
314 |
+
"""
|
315 |
+
),
|
316 |
+
kind="info",
|
317 |
+
)
|
318 |
+
return
|
319 |
+
|
320 |
+
|
321 |
+
@app.cell(hide_code=True)
|
322 |
+
def _(mo, notebooks_df):
|
323 |
+
category = mo.ui.dropdown(
|
324 |
+
notebooks_df.sort("category").get_column("category"),
|
325 |
+
value="Maps",
|
326 |
+
)
|
327 |
+
return (category,)
|
328 |
+
|
329 |
+
|
330 |
+
@app.cell(hide_code=True)
|
331 |
+
def _(category, extract_nextjs_data, fetch_html_batch, notebooks_df, pl):
|
332 |
+
notebook_stats_df = (
|
333 |
+
# Setting filter upstream to limit number of concurrent HTTP requests
|
334 |
+
notebooks_df.filter(category=category.value)
|
335 |
+
.with_columns(
|
336 |
+
notebook_html=pl.col("notebook_url")
|
337 |
+
.map_batches(fetch_html_batch, return_dtype=pl.List(pl.String))
|
338 |
+
.explode()
|
339 |
+
)
|
340 |
+
.with_columns(
|
341 |
+
notebook_data=pl.col("notebook_html")
|
342 |
+
.map_elements(
|
343 |
+
extract_nextjs_data,
|
344 |
+
return_dtype=pl.String,
|
345 |
+
)
|
346 |
+
.str.json_path_match("$.props.pageProps.initialNotebook")
|
347 |
+
.str.json_decode()
|
348 |
+
)
|
349 |
+
.drop("notebook_html")
|
350 |
+
.with_columns(
|
351 |
+
*[
|
352 |
+
pl.col("notebook_data").struct.field(key).alias(key)
|
353 |
+
for key in ["likes", "forks", "comments", "license"]
|
354 |
+
]
|
355 |
+
)
|
356 |
+
.drop("notebook_data")
|
357 |
+
.with_columns(pl.col("comments").list.len())
|
358 |
+
.select(
|
359 |
+
pl.exclude("description", "notebook_url"),
|
360 |
+
"description",
|
361 |
+
"notebook_url",
|
362 |
+
)
|
363 |
+
.sort("likes", descending=True)
|
364 |
+
)
|
365 |
+
return (notebook_stats_df,)
|
366 |
+
|
367 |
+
|
368 |
+
@app.cell(hide_code=True)
|
369 |
+
def _(mo, notebook_stats_df):
|
370 |
+
notebooks = mo.ui.table(notebook_stats_df, selection='single', initial_selection=[2], page_size=5)
|
371 |
+
notebook_height = mo.ui.slider(start=400, stop=2000, value=825, step=25, show_value=True, label='Notebook Height')
|
372 |
+
return notebook_height, notebooks
|
373 |
+
|
374 |
+
|
375 |
+
@app.cell(hide_code=True)
|
376 |
+
def _():
|
377 |
+
def nb_iframe(notebook_url: str, height=825) -> str:
|
378 |
+
embed_url = notebook_url.replace(
|
379 |
+
"https://observablehq.com", "https://observablehq.com/embed"
|
380 |
+
)
|
381 |
+
return f'<iframe width="100%" height="{height}" frameborder="0" src="{embed_url}?cell=*"></iframe>'
|
382 |
+
return (nb_iframe,)
|
383 |
+
|
384 |
+
|
385 |
+
@app.cell(hide_code=True)
|
386 |
+
def _(mo):
|
387 |
+
mo.md(r"""Now that we have access to notebook-level statistics, we can rank the visualizations by the number of likes they received & display them interactively.""")
|
388 |
+
return
|
389 |
+
|
390 |
+
|
391 |
+
@app.cell(hide_code=True)
|
392 |
+
def _(mo):
|
393 |
+
mo.callout("💡 Explore the visualizations by paging through the table below and selecting any of its rows.")
|
394 |
+
return
|
395 |
+
|
396 |
+
|
397 |
+
@app.cell(hide_code=True)
|
398 |
+
def _(category, mo, nb_iframe, notebook_height, notebooks):
|
399 |
+
notebook = notebooks.value.to_dicts()[0]
|
400 |
+
mo.vstack(
|
401 |
+
[
|
402 |
+
mo.hstack([category, notebook_height]),
|
403 |
+
notebooks,
|
404 |
+
mo.md(f"{notebook['description']}"),
|
405 |
+
mo.md('---'),
|
406 |
+
mo.md(nb_iframe(notebook["notebook_url"], notebook_height.value)),
|
407 |
+
]
|
408 |
+
)
|
409 |
+
return (notebook,)
|
410 |
+
|
411 |
+
|
412 |
+
@app.cell(hide_code=True)
|
413 |
+
def _(mo):
|
414 |
+
mo.md(
|
415 |
+
r"""
|
416 |
+
## ⚙️ Row-Wise UDFs
|
417 |
+
|
418 |
+
> Accessing All Columns at Once
|
419 |
+
|
420 |
+
Sometimes, you need to work with *all* columns of a row at once. This is where [`map_rows`](https://docs.pola.rs/api/python/stable/reference/dataframe/api/polars.DataFrame.map_rows.html) comes in. It operates directly on the DataFrame, passing each row to your UDF *as a tuple*.
|
421 |
+
|
422 |
+
Below, `create_notebook_summary` takes a row from `notebook_stats_df` (as a tuple) and returns a formatted Markdown string summarizing the notebook's key stats. We're essentially reducing the DataFrame to a single column. While this *could* be done with native Polars expressions, it would be much more cumbersome. This example demonstrates a case where a row-wise UDF simplifies the code, even if the underlying operation isn't inherently complex.
|
423 |
+
"""
|
424 |
+
)
|
425 |
+
return
|
426 |
+
|
427 |
+
|
428 |
+
@app.cell(hide_code=True)
|
429 |
+
def _():
|
430 |
+
def create_notebook_summary(row: tuple) -> str:
|
431 |
+
(
|
432 |
+
thumbnail_src,
|
433 |
+
category,
|
434 |
+
title,
|
435 |
+
likes,
|
436 |
+
forks,
|
437 |
+
comments,
|
438 |
+
license,
|
439 |
+
description,
|
440 |
+
notebook_url,
|
441 |
+
) = row
|
442 |
+
return (
|
443 |
+
f"""
|
444 |
+
### [{title}]({notebook_url})
|
445 |
+
|
446 |
+
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin: 12px 0;">
|
447 |
+
<div>⭐ <strong>Likes:</strong> {likes}</div>
|
448 |
+
<div>↗️ <strong>Forks:</strong> {forks}</div>
|
449 |
+
<div>💬 <strong>Comments:</strong> {comments}</div>
|
450 |
+
<div>⚖️ <strong>License:</strong> {license}</div>
|
451 |
+
</div>
|
452 |
+
|
453 |
+
<a href="{notebook_url}" target="_blank">
|
454 |
+
<img src="{thumbnail_src}" style="height: 300px;" />
|
455 |
+
<a/>
|
456 |
+
""".strip('\n')
|
457 |
+
)
|
458 |
+
return (create_notebook_summary,)
|
459 |
+
|
460 |
+
|
461 |
+
@app.cell(hide_code=True)
|
462 |
+
def _(create_notebook_summary, notebook_stats_df, pl):
|
463 |
+
notebook_summary_df = notebook_stats_df.map_rows(
|
464 |
+
create_notebook_summary,
|
465 |
+
return_dtype=pl.String,
|
466 |
+
).rename({"map": "summary"})
|
467 |
+
notebook_summary_df.head(1)
|
468 |
+
return (notebook_summary_df,)
|
469 |
+
|
470 |
+
|
471 |
+
@app.cell(hide_code=True)
|
472 |
+
def _(mo):
|
473 |
+
mo.callout("💡 You can explore individual notebook statistics through the carousel. Discover the visualization's source code by clicking the notebook title or the thumbnail.")
|
474 |
+
return
|
475 |
+
|
476 |
+
|
477 |
+
@app.cell(hide_code=True)
|
478 |
+
def _(mo, notebook_summary_df):
|
479 |
+
mo.carousel(
|
480 |
+
[
|
481 |
+
mo.lazy(mo.md(summary))
|
482 |
+
for summary in notebook_summary_df.get_column("summary")
|
483 |
+
]
|
484 |
+
)
|
485 |
+
return
|
486 |
+
|
487 |
+
|
488 |
+
@app.cell(hide_code=True)
|
489 |
+
def _(mo):
|
490 |
+
mo.md(
|
491 |
+
r"""
|
492 |
+
## 🚀 Higher-performance UDFs
|
493 |
+
|
494 |
+
> Leveraging Numba to Make Python Fast
|
495 |
+
|
496 |
+
Python code doesn't *always* mean slow code. While UDFs *often* introduce performance overhead, there are exceptions. NumPy's universal functions ([`ufuncs`](https://numpy.org/doc/stable/reference/ufuncs.html)) and generalized universal functions ([`gufuncs`](https://numpy.org/neps/nep-0005-generalized-ufuncs.html)) provide high-performance operations on NumPy arrays, thanks to low-level implementations.
|
497 |
+
|
498 |
+
But NumPy's built-in functions are predefined. We can't easily use them for *custom* logic. Enter [`numba`](https://numba.pydata.org/). Numba is a just-in-time (JIT) compiler that translates Python functions into optimized machine code *at runtime*. It provides decorators like [`numba.guvectorize`](https://numba.readthedocs.io/en/stable/user/vectorize.html#the-guvectorize-decorator) that let us create our *own* high-performance `gufuncs` – *without* writing low-level code!
|
499 |
+
"""
|
500 |
+
)
|
501 |
+
return
|
502 |
+
|
503 |
+
|
504 |
+
@app.cell(hide_code=True)
|
505 |
+
def _(mo):
|
506 |
+
mo.md(
|
507 |
+
r"""
|
508 |
+
Let's create a custom popularity metric to rank notebooks, considering likes, forks, *and* comments (not just likes). We'll define `weighted_popularity_numba`, decorated with `@numba.guvectorize`. The decorator arguments specify that we're taking three integer vectors of length `n` and returning a float vector of length `n`.
|
509 |
+
|
510 |
+
The weighted popularity score for each notebook is calculated using the following formula:
|
511 |
+
|
512 |
+
$$
|
513 |
+
\begin{equation}
|
514 |
+
\text{score}_i = w_l \cdot l_i^{f} + w_f \cdot f_i^{f} + w_c \cdot c_i^{f}
|
515 |
+
\end{equation}
|
516 |
+
$$
|
517 |
+
|
518 |
+
with:
|
519 |
+
"""
|
520 |
+
)
|
521 |
+
return
|
522 |
+
|
523 |
+
|
524 |
+
@app.cell(hide_code=True)
|
525 |
+
def _(mo, non_linear_factor, weight_comments, weight_forks, weight_likes):
|
526 |
+
mo.md(rf"""
|
527 |
+
| Symbol | Description |
|
528 |
+
|--------|-------------|
|
529 |
+
| $\text{{score}}_i$ | Popularity score for the *i*-th notebook |
|
530 |
+
| $w_l = {weight_likes.value}$ | Weight for likes |
|
531 |
+
| $l_i$ | Number of likes for the *i*-th notebook |
|
532 |
+
| $w_f = {weight_forks.value}$ | Weight for forks |
|
533 |
+
| $f_i$ | Number of forks for the *i*-th notebook |
|
534 |
+
| $w_c = {weight_comments.value}$ | Weight for comments |
|
535 |
+
| $c_i$ | Number of comments for the *i*-th notebook |
|
536 |
+
| $f = {non_linear_factor.value}$ | Non-linear factor (exponent) |
|
537 |
+
""")
|
538 |
+
return
|
539 |
+
|
540 |
+
|
541 |
+
@app.cell(hide_code=True)
|
542 |
+
def _(mo):
|
543 |
+
weight_likes = mo.ui.slider(
|
544 |
+
start=0.1,
|
545 |
+
stop=1,
|
546 |
+
value=0.5,
|
547 |
+
step=0.1,
|
548 |
+
show_value=True,
|
549 |
+
label="⭐ Weight for Likes",
|
550 |
+
)
|
551 |
+
weight_forks = mo.ui.slider(
|
552 |
+
start=0.1,
|
553 |
+
stop=1,
|
554 |
+
value=0.3,
|
555 |
+
step=0.1,
|
556 |
+
show_value=True,
|
557 |
+
label="↗️ Weight for Forks",
|
558 |
+
)
|
559 |
+
weight_comments = mo.ui.slider(
|
560 |
+
start=0.1,
|
561 |
+
stop=1,
|
562 |
+
value=0.5,
|
563 |
+
step=0.1,
|
564 |
+
show_value=True,
|
565 |
+
label="💬 Weight for Comments",
|
566 |
+
)
|
567 |
+
non_linear_factor = mo.ui.slider(
|
568 |
+
start=1,
|
569 |
+
stop=2,
|
570 |
+
value=1.2,
|
571 |
+
step=0.1,
|
572 |
+
show_value=True,
|
573 |
+
label="🎢 Non-Linear Factor",
|
574 |
+
)
|
575 |
+
return non_linear_factor, weight_comments, weight_forks, weight_likes
|
576 |
+
|
577 |
+
|
578 |
+
@app.cell(hide_code=True)
|
579 |
+
def _(
|
580 |
+
non_linear_factor,
|
581 |
+
np,
|
582 |
+
numba,
|
583 |
+
weight_comments,
|
584 |
+
weight_forks,
|
585 |
+
weight_likes,
|
586 |
+
):
|
587 |
+
w_l = weight_likes.value
|
588 |
+
w_f = weight_forks.value
|
589 |
+
w_c = weight_comments.value
|
590 |
+
nlf = non_linear_factor.value
|
591 |
+
|
592 |
+
|
593 |
+
@numba.guvectorize(
|
594 |
+
[(numba.int64[:], numba.int64[:], numba.int64[:], numba.float64[:])],
|
595 |
+
"(n), (n), (n) -> (n)",
|
596 |
+
)
|
597 |
+
def weighted_popularity_numba(
|
598 |
+
likes: np.ndarray,
|
599 |
+
forks: np.ndarray,
|
600 |
+
comments: np.ndarray,
|
601 |
+
out: np.ndarray,
|
602 |
+
):
|
603 |
+
for i in range(likes.shape[0]):
|
604 |
+
out[i] = (
|
605 |
+
w_l * (likes[i] ** nlf)
|
606 |
+
+ w_f * (forks[i] ** nlf)
|
607 |
+
+ w_c * (comments[i] ** nlf)
|
608 |
+
)
|
609 |
+
return nlf, w_c, w_f, w_l, weighted_popularity_numba
|
610 |
+
|
611 |
+
|
612 |
+
@app.cell(hide_code=True)
|
613 |
+
def _(mo):
|
614 |
+
mo.md(r"""We apply our JIT-compiled UDF using `map_batches`, as before. The key is that we're passing entire columns directly to `weighted_popularity_numba`. Polars and Numba handle the conversion to NumPy arrays behind the scenes. This direct integration is a major benefit of using `guvectorize`.""")
|
615 |
+
return
|
616 |
+
|
617 |
+
|
618 |
+
@app.cell(hide_code=True)
|
619 |
+
def _(notebook_stats_df, pl, weighted_popularity_numba):
|
620 |
+
notebook_popularity_df = (
|
621 |
+
notebook_stats_df.select(
|
622 |
+
pl.col("notebook_thumbnail_src").alias("thumbnail"),
|
623 |
+
"title",
|
624 |
+
"likes",
|
625 |
+
"forks",
|
626 |
+
"comments",
|
627 |
+
popularity=pl.struct(["likes", "forks", "comments"]).map_batches(
|
628 |
+
lambda obj: weighted_popularity_numba(
|
629 |
+
obj.struct.field("likes"),
|
630 |
+
obj.struct.field("forks"),
|
631 |
+
obj.struct.field("comments"),
|
632 |
+
),
|
633 |
+
return_dtype=pl.Float64,
|
634 |
+
),
|
635 |
+
url="notebook_url",
|
636 |
+
)
|
637 |
+
)
|
638 |
+
return (notebook_popularity_df,)
|
639 |
+
|
640 |
+
|
641 |
+
@app.cell(hide_code=True)
|
642 |
+
def _(mo):
|
643 |
+
mo.callout("💡 Adjust the hyperparameters of the popularity ranking UDF. How do the weights and non-linear factor affect the notebook rankings?")
|
644 |
+
return
|
645 |
+
|
646 |
+
|
647 |
+
@app.cell(hide_code=True)
|
648 |
+
def _(
|
649 |
+
mo,
|
650 |
+
non_linear_factor,
|
651 |
+
notebook_popularity_df,
|
652 |
+
weight_comments,
|
653 |
+
weight_forks,
|
654 |
+
weight_likes,
|
655 |
+
):
|
656 |
+
mo.vstack(
|
657 |
+
[
|
658 |
+
mo.hstack([weight_likes, weight_forks]),
|
659 |
+
mo.hstack([weight_comments, non_linear_factor]),
|
660 |
+
notebook_popularity_df,
|
661 |
+
]
|
662 |
+
)
|
663 |
+
return
|
664 |
+
|
665 |
+
|
666 |
+
@app.cell(hide_code=True)
|
667 |
+
def _(mo):
|
668 |
+
mo.md(r"""As the slope chart below demonstrates, this new ranking strategy significantly changes the notebook order, as it considers forks and comments, not just likes.""")
|
669 |
+
return
|
670 |
+
|
671 |
+
|
672 |
+
@app.cell(hide_code=True)
|
673 |
+
def _(alt, notebook_popularity_df, pl):
|
674 |
+
notebook_ranks_df = (
|
675 |
+
notebook_popularity_df.sort("likes", descending=True)
|
676 |
+
.with_row_index("rank_by_likes")
|
677 |
+
.with_columns(pl.col("rank_by_likes") + 1)
|
678 |
+
.sort("popularity", descending=True)
|
679 |
+
.with_row_index("rank_by_popularity")
|
680 |
+
.with_columns(pl.col("rank_by_popularity") + 1)
|
681 |
+
.select("thumbnail", "title", "rank_by_popularity", "rank_by_likes")
|
682 |
+
.unpivot(
|
683 |
+
["rank_by_popularity", "rank_by_likes"],
|
684 |
+
index="title",
|
685 |
+
variable_name="strategy",
|
686 |
+
value_name="rank",
|
687 |
+
)
|
688 |
+
)
|
689 |
+
|
690 |
+
# Slope chart to visualize rank differences by strategy
|
691 |
+
lines = notebook_ranks_df.plot.line(
|
692 |
+
x="strategy:O",
|
693 |
+
y="rank:Q",
|
694 |
+
color="title:N",
|
695 |
+
)
|
696 |
+
points = notebook_ranks_df.plot.point(
|
697 |
+
x="strategy:O",
|
698 |
+
y="rank:Q",
|
699 |
+
color=alt.Color("title:N", legend=None),
|
700 |
+
fill="title:N",
|
701 |
+
)
|
702 |
+
(points + lines).properties(width=400)
|
703 |
+
return lines, notebook_ranks_df, points
|
704 |
+
|
705 |
+
|
706 |
+
@app.cell(hide_code=True)
|
707 |
+
def _(mo):
|
708 |
+
mo.md(
|
709 |
+
r"""
|
710 |
+
## ⏱️ Quantifying the Overhead
|
711 |
+
|
712 |
+
> UDF Performance Comparison
|
713 |
+
|
714 |
+
To truly understand the performance implications of using UDFs, let's conduct a benchmark. We'll create a DataFrame with random numbers and perform the same numerical operation using four different methods:
|
715 |
+
|
716 |
+
1. **Native Polars:** Using Polars' built-in expressions.
|
717 |
+
2. **`map_elements`:** Applying a Python function element-wise.
|
718 |
+
3. **`map_batches`:** **Applying** a Python function to the entire Series.
|
719 |
+
4. **`map_batches` with Numba:** Applying a JIT-compiled function to batches, similar to a generalized universal function.
|
720 |
+
|
721 |
+
We'll use a simple, but non-trivial, calculation: `result = (x * 2.5 + 5) / (x + 1)`. This involves multiplication, addition, and division, giving us a realistic representation of a common numerical operation. We'll use the `timeit` module, to accurately measure execution times over multiple trials.
|
722 |
+
"""
|
723 |
+
)
|
724 |
+
return
|
725 |
+
|
726 |
+
|
727 |
+
@app.cell(hide_code=True)
|
728 |
+
def _(mo):
|
729 |
+
mo.callout("💡 Tweak the benchmark parameters to explore how execution times change with different sample sizes and trial counts. Do you notice anything surprising as you decrease the number of samples?")
|
730 |
+
return
|
731 |
+
|
732 |
+
|
733 |
+
@app.cell(hide_code=True)
|
734 |
+
def _(benchmark_plot, mo, num_samples, num_trials):
|
735 |
+
mo.vstack(
|
736 |
+
[
|
737 |
+
mo.hstack([num_samples, num_trials]),
|
738 |
+
mo.md(
|
739 |
+
f"""---
|
740 |
+
Performance comparison over **{num_trials.value:,} trials** with **{num_samples.value:,} samples**.
|
741 |
+
|
742 |
+
> Lower execution times are better.
|
743 |
+
"""
|
744 |
+
),
|
745 |
+
benchmark_plot,
|
746 |
+
]
|
747 |
+
)
|
748 |
+
return
|
749 |
+
|
750 |
+
|
751 |
+
@app.cell(hide_code=True)
|
752 |
+
def _(mo):
|
753 |
+
mo.md(
|
754 |
+
r"""
|
755 |
+
As anticipated, the `Batch-Wise UDF (Python)` and `Element-Wise UDF` exhibit significantly worse performance, essentially acting as pure-Python for-each loops.
|
756 |
+
|
757 |
+
However, when Python serves as an interface to lower-level, high-performance libraries, we observe substantial improvements. The `Batch-Wise UDF (NumPy)` lags behind both `Batch-Wise UDF (Numba)` and `Native Polars`, but it still represents a considerable improvement over pure-Python UDFs due to its vectorized computations.
|
758 |
+
|
759 |
+
Numba's Just-In-Time (JIT) compilation delivers a dramatic performance boost, achieving speeds comparable to native Polars expressions. This demonstrates that UDFs, particularly when combined with tools like Numba, don't inevitably lead to bottlenecks in numerical computations.
|
760 |
+
"""
|
761 |
+
)
|
762 |
+
return
|
763 |
+
|
764 |
+
|
765 |
+
@app.cell(hide_code=True)
|
766 |
+
def _(mo):
|
767 |
+
num_samples = mo.ui.slider(
|
768 |
+
start=1_000,
|
769 |
+
stop=1_000_000,
|
770 |
+
value=250_000,
|
771 |
+
step=1000,
|
772 |
+
show_value=True,
|
773 |
+
debounce=True,
|
774 |
+
label="Number of Samples",
|
775 |
+
)
|
776 |
+
num_trials = mo.ui.slider(
|
777 |
+
start=50,
|
778 |
+
stop=1_000,
|
779 |
+
value=100,
|
780 |
+
step=50,
|
781 |
+
show_value=True,
|
782 |
+
debounce=True,
|
783 |
+
label="Number of Trials",
|
784 |
+
)
|
785 |
+
return num_samples, num_trials
|
786 |
+
|
787 |
+
|
788 |
+
@app.cell(hide_code=True)
|
789 |
+
def _(np, num_samples, pl):
|
790 |
+
rng = np.random.default_rng(42)
|
791 |
+
sample_df = pl.from_dict({"x": rng.random(num_samples.value)})
|
792 |
+
return rng, sample_df
|
793 |
+
|
794 |
+
|
795 |
+
@app.cell(hide_code=True)
|
796 |
+
def _(np, num_trials, numba, pl, sample_df, timeit):
|
797 |
+
def run_native():
|
798 |
+
sample_df.with_columns(
|
799 |
+
result_native=(pl.col("x") * 2.5 + 5) / (pl.col("x") + 1)
|
800 |
+
)
|
801 |
+
|
802 |
+
|
803 |
+
def _calculate_elementwise(x: float) -> float:
|
804 |
+
return (x * 2.5 + 5) / (x + 1)
|
805 |
+
|
806 |
+
|
807 |
+
def run_map_elements():
|
808 |
+
sample_df.with_columns(
|
809 |
+
result_map_elements=pl.col("x").map_elements(
|
810 |
+
_calculate_elementwise,
|
811 |
+
return_dtype=pl.Float64,
|
812 |
+
)
|
813 |
+
)
|
814 |
+
|
815 |
+
|
816 |
+
def _calculate_batchwise_numpy(x_series: pl.Series) -> pl.Series:
|
817 |
+
x_array = x_series.to_numpy()
|
818 |
+
result_array = (x_array * 2.5 + 5) / (x_array + 1)
|
819 |
+
return pl.Series(result_array)
|
820 |
+
|
821 |
+
|
822 |
+
def run_map_batches_numpy():
|
823 |
+
sample_df.with_columns(
|
824 |
+
result_map_batches_numpy=pl.col("x").map_batches(
|
825 |
+
_calculate_batchwise_numpy,
|
826 |
+
return_dtype=pl.Float64,
|
827 |
+
)
|
828 |
+
)
|
829 |
+
|
830 |
+
|
831 |
+
def _calculate_batchwise_python(x_series: pl.Series) -> pl.Series:
|
832 |
+
x_array = x_series.to_list()
|
833 |
+
result_array = [_calculate_elementwise(x) for x in x_array]
|
834 |
+
return pl.Series(result_array)
|
835 |
+
|
836 |
+
|
837 |
+
def run_map_batches_python():
|
838 |
+
sample_df.with_columns(
|
839 |
+
result_map_batches_python=pl.col("x").map_batches(
|
840 |
+
_calculate_batchwise_python,
|
841 |
+
return_dtype=pl.Float64,
|
842 |
+
)
|
843 |
+
)
|
844 |
+
|
845 |
+
|
846 |
+
@numba.guvectorize([(numba.float64[:], numba.float64[:])], "(n) -> (n)")
|
847 |
+
def _calculate_batchwise_numba(x: np.ndarray, out: np.ndarray):
|
848 |
+
for i in range(x.shape[0]):
|
849 |
+
out[i] = (x[i] * 2.5 + 5) / (x[i] + 1)
|
850 |
+
|
851 |
+
|
852 |
+
def run_map_batches_numba():
|
853 |
+
sample_df.with_columns(
|
854 |
+
result_map_batches_numba=pl.col("x").map_batches(
|
855 |
+
_calculate_batchwise_numba,
|
856 |
+
return_dtype=pl.Float64,
|
857 |
+
)
|
858 |
+
)
|
859 |
+
|
860 |
+
|
861 |
+
def time_method(callable_name: str, number=num_trials.value) -> float:
|
862 |
+
fn = globals()[callable_name]
|
863 |
+
return timeit.timeit(fn, number=number)
|
864 |
+
return (
|
865 |
+
run_map_batches_numba,
|
866 |
+
run_map_batches_numpy,
|
867 |
+
run_map_batches_python,
|
868 |
+
run_map_elements,
|
869 |
+
run_native,
|
870 |
+
time_method,
|
871 |
+
)
|
872 |
+
|
873 |
+
|
874 |
+
@app.cell(hide_code=True)
|
875 |
+
def _(alt, pl, time_method):
|
876 |
+
benchmark_df = pl.from_dicts(
|
877 |
+
[
|
878 |
+
{
|
879 |
+
"title": "Native Polars",
|
880 |
+
"callable_name": "run_native",
|
881 |
+
},
|
882 |
+
{
|
883 |
+
"title": "Element-Wise UDF",
|
884 |
+
"callable_name": "run_map_elements",
|
885 |
+
},
|
886 |
+
{
|
887 |
+
"title": "Batch-Wise UDF (NumPy)",
|
888 |
+
"callable_name": "run_map_batches_numpy",
|
889 |
+
},
|
890 |
+
{
|
891 |
+
"title": "Batch-Wise UDF (Python)",
|
892 |
+
"callable_name": "run_map_batches_python",
|
893 |
+
},
|
894 |
+
{
|
895 |
+
"title": "Batch-Wise UDF (Numba)",
|
896 |
+
"callable_name": "run_map_batches_numba",
|
897 |
+
},
|
898 |
+
]
|
899 |
+
).with_columns(
|
900 |
+
time=pl.col("callable_name").map_elements(
|
901 |
+
time_method, return_dtype=pl.Float64
|
902 |
+
)
|
903 |
+
)
|
904 |
+
|
905 |
+
benchmark_plot = benchmark_df.plot.bar(
|
906 |
+
x=alt.X("title:N", title="Method", sort="-y"),
|
907 |
+
y=alt.Y("time:Q", title="Execution Time (s)", axis=alt.Axis(format=".3f")),
|
908 |
+
).properties(width=400)
|
909 |
+
return benchmark_df, benchmark_plot
|
910 |
+
|
911 |
+
|
912 |
+
@app.cell(hide_code=True)
|
913 |
+
def _():
|
914 |
+
import asyncio
|
915 |
+
import timeit
|
916 |
+
from typing import Iterable
|
917 |
+
|
918 |
+
import altair as alt
|
919 |
+
import httpx
|
920 |
+
import marimo as mo
|
921 |
+
import nest_asyncio
|
922 |
+
import numba
|
923 |
+
import numpy as np
|
924 |
+
from bs4 import BeautifulSoup
|
925 |
+
|
926 |
+
import polars as pl
|
927 |
+
|
928 |
+
# Fixes RuntimeError: asyncio.run() cannot be called from a running event loop
|
929 |
+
nest_asyncio.apply()
|
930 |
+
return (
|
931 |
+
BeautifulSoup,
|
932 |
+
Iterable,
|
933 |
+
alt,
|
934 |
+
asyncio,
|
935 |
+
httpx,
|
936 |
+
mo,
|
937 |
+
nest_asyncio,
|
938 |
+
np,
|
939 |
+
numba,
|
940 |
+
pl,
|
941 |
+
timeit,
|
942 |
+
)
|
943 |
+
|
944 |
+
|
945 |
+
if __name__ == "__main__":
|
946 |
+
app.run()
|