Debugging chained operations
A long chain of methods reads well, but when it fails, which step was it? This recipe takes a lazy query on a table of Pokémon apart, step by step.
import nanuq
let lf = scanCsv("data/polars-cookbook/pokemon.csv")import polars as pl
lf = pl.scan_csv('data/polars-cookbook/pokemon.csv')The query ranks the Pokémon on three of their stats, keeps a few columns and shows the
five with the lowest total. rank with the Dense method gives tied values the same rank
and leaves no gaps.
nbShow lf
.withColumns(
col.Attack.rank(Dense).alias("Atk Rank"),
col.Defense.rank(Dense).alias("Def Rank"),
col.Speed.rank(Dense).alias("Spe Rank"))
.select(col("Name", "Total", "Attack", "Defense", "Speed"), col("^*Rank$"))
.sort("Total")
.head()
.collect
| Name | Total | Attack | Defense | Speed | Atk Rank | Def Rank | Spe Rank |
|---|---|---|---|---|---|---|---|
| str | i64 | i64 | i64 | i64 | u32 | u32 | u32 |
| "Caterpie" | 195 | 30 | 35 | 45 | 5 | 6 | 10 |
| "Weedle" | 195 | 35 | 30 | 50 | 6 | 5 | 12 |
| "Magikarp" | 200 | 10 | 55 | 80 | 2 | 16 | 27 |
| "Metapod" | 205 | 20 | 55 | 30 | 3 | 16 | 4 |
| "Kakuna" | 205 | 25 | 50 | 35 | 4 | 13 | 5 |
(
lf
.with_columns(
pl.col('Attack').rank(method='dense').alias('Atk Rank'),
pl.col('Defense').rank(method='dense').alias('Def Rank'),
pl.col('Speed').rank(method='dense').alias('Spe Rank'),
)
.select(
'Name',
'Total',
'Attack',
'Defense',
'Speed',
pl.col('^*Rank$')
)
.sort('Total')
.head()
.collect()
)| Name | Total | Attack | Defense | Speed | Atk Rank | Def Rank | Spe Rank |
|---|---|---|---|---|---|---|---|
| str | i64 | i64 | i64 | i64 | u32 | u32 | u32 |
| "Caterpie" | 195 | 30 | 35 | 45 | 5 | 6 | 10 |
| "Weedle" | 195 | 35 | 30 | 50 | 6 | 5 | 12 |
| "Magikarp" | 200 | 10 | 55 | 80 | 2 | 16 | 27 |
| "Metapod" | 205 | 20 | 55 | 30 | 3 | 16 | 4 |
| "Kakuna" | 205 | 25 | 50 | 35 | 4 | 13 | 5 |
Now with a typo, Deffense. In a lazy query, the error comes when the plan is resolved,
at collect, not at the line with the typo:
try:
discard lf
.withColumns(
col.Attack.rank(Dense).alias("Atk Rank"),
col.Defense.rank(Dense).alias("Def Rank"),
col.Speed.rank(Dense).alias("Spe Rank"))
.select(col("Name", "Total", "Attack", "Deffense", "Speed"), col("^*Rank$"))
.sort("Total")
.head()
.collect
except ColumnNotFoundError:
echo "ColumnNotFoundError"
ColumnNotFoundError
try:
(
lf
.with_columns(
pl.col('Attack').rank(method='dense').alias('Atk Rank'),
pl.col('Defense').rank(method='dense').alias('Def Rank'),
pl.col('Speed').rank(method='dense').alias('Spe Rank'),
)
.select(
'Name',
'Total',
'Attack',
'Deffense',
'Speed',
pl.col('^*Rank$')
)
.sort('Total')
.head()
.collect()
)
except pl.exceptions.ColumnNotFoundError as e:
print(type(e).__name__)ColumnNotFoundError
The recipe's way to find the culprit: comment out steps until the query runs. Without the
select, it does:
nbShow lf
.withColumns(
col.Attack.rank(Dense).alias("Atk Rank"),
col.Defense.rank(Dense).alias("Def Rank"),
col.Speed.rank(Dense).alias("Spe Rank"))
# .select(col("Name", "Total", "Attack", "Deffense", "Speed"), col("^*Rank$"))
.sort("Total")
.head()
.collect
| # | Name | Type 1 | Type 2 | Total | HP | Attack | Defense | Sp. Atk | Sp. Def | Speed | Generation | Legendary | Atk Rank | Def Rank | Spe Rank |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| i64 | str | str | str | i64 | i64 | i64 | i64 | i64 | i64 | i64 | i64 | bool | u32 | u32 | u32 |
| 10 | "Caterpie" | "Bug" | null | 195 | 45 | 30 | 35 | 20 | 20 | 45 | 1 | false | 5 | 6 | 10 |
| 13 | "Weedle" | "Bug" | "Poison" | 195 | 40 | 35 | 30 | 20 | 20 | 50 | 1 | false | 6 | 5 | 12 |
| 129 | "Magikarp" | "Water" | null | 200 | 20 | 10 | 55 | 15 | 20 | 80 | 1 | false | 2 | 16 | 27 |
| 11 | "Metapod" | "Bug" | null | 205 | 50 | 20 | 55 | 25 | 25 | 30 | 1 | false | 3 | 16 | 4 |
| 14 | "Kakuna" | "Bug" | "Poison" | 205 | 45 | 25 | 50 | 25 | 25 | 35 | 1 | false | 4 | 13 | 5 |
(
lf
.with_columns(
pl.col('Attack').rank(method='dense').alias('Atk Rank'),
pl.col('Defense').rank(method='dense').alias('Def Rank'),
pl.col('Speed').rank(method='dense').alias('Spe Rank'),
)
# .select(
# 'Name',
# 'Total',
# 'Attack',
# 'Deffense',
# 'Speed',
# pl.col('^*Rank$')
# )
.sort('Total')
.head()
.collect()
)| # | Name | Type 1 | Type 2 | Total | HP | Attack | Defense | Sp. Atk | Sp. Def | Speed | Generation | Legendary | Atk Rank | Def Rank | Spe Rank |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| i64 | str | str | str | i64 | i64 | i64 | i64 | i64 | i64 | i64 | i64 | bool | u32 | u32 | u32 |
| 10 | "Caterpie" | "Bug" | null | 195 | 45 | 30 | 35 | 20 | 20 | 45 | 1 | false | 5 | 6 | 10 |
| 13 | "Weedle" | "Bug" | "Poison" | 195 | 40 | 35 | 30 | 20 | 20 | 50 | 1 | false | 6 | 5 | 12 |
| 129 | "Magikarp" | "Water" | null | 200 | 20 | 10 | 55 | 15 | 20 | 80 | 1 | false | 2 | 16 | 27 |
| 11 | "Metapod" | "Bug" | null | 205 | 50 | 20 | 55 | 25 | 25 | 30 | 1 | false | 3 | 16 | 4 |
| 14 | "Kakuna" | "Bug" | "Poison" | 205 | 45 | 25 | 50 | 25 | 25 | 35 | 1 | false | 4 | 13 | 5 |
Another way to keep a chain readable: give the steps names. Python does it with functions
and pipe; in Nim a proc that takes a LazyFrame is called with the same dot syntax as a
method, so no pipe is needed.
proc addRanks(lf: LazyFrame): LazyFrame =
lf.withColumns(
col.Attack.rank(Dense).alias("Atk Rank"),
col.Defense.rank(Dense).alias("Def Rank"),
col.Speed.rank(Dense).alias("Spe Rank"))
proc keepCols(lf: LazyFrame): LazyFrame =
lf.select(col("Name", "Total", "Attack", "Defense", "Speed"), col("^*Rank$"))
nbShow lf.addRanks.keepCols.sort("Total").head().collect
| Name | Total | Attack | Defense | Speed | Atk Rank | Def Rank | Spe Rank |
|---|---|---|---|---|---|---|---|
| str | i64 | i64 | i64 | i64 | u32 | u32 | u32 |
| "Caterpie" | 195 | 30 | 35 | 45 | 5 | 6 | 10 |
| "Weedle" | 195 | 35 | 30 | 50 | 6 | 5 | 12 |
| "Magikarp" | 200 | 10 | 55 | 80 | 2 | 16 | 27 |
| "Metapod" | 205 | 20 | 55 | 30 | 3 | 16 | 4 |
| "Kakuna" | 205 | 25 | 50 | 35 | 4 | 13 | 5 |
def add_ranks(lf: pl.LazyFrame) -> pl.LazyFrame:
return (
lf
.with_columns(
pl.col('Attack').rank(method='dense').alias('Atk Rank'),
pl.col('Defense').rank(method='dense').alias('Def Rank'),
pl.col('Speed').rank(method='dense').alias('Spe Rank'),
)
)
def keep_cols(lf: pl.LazyFrame) -> pl.LazyFrame:
return (
lf
.select(
'Name',
'Total',
'Attack',
'Defense',
'Speed',
pl.col('^*Rank$')
)
)
(
lf
.pipe(add_ranks)
.pipe(keep_cols)
.sort('Total')
.head()
.collect()
)| Name | Total | Attack | Defense | Speed | Atk Rank | Def Rank | Spe Rank |
|---|---|---|---|---|---|---|---|
| str | i64 | i64 | i64 | i64 | u32 | u32 | u32 |
| "Caterpie" | 195 | 30 | 35 | 45 | 5 | 6 | 10 |
| "Weedle" | 195 | 35 | 30 | 50 | 6 | 5 | 12 |
| "Magikarp" | 200 | 10 | 55 | 80 | 2 | 16 | 27 |
| "Metapod" | 205 | 20 | 55 | 30 | 3 | 16 | 4 |
| "Kakuna" | 205 | 25 | 50 | 35 | 4 | 13 | 5 |
Inspecting and optimizing the query plan
One more step, a filter on the Pokémon's types:
proc keepGrassOrFire(lf: LazyFrame): LazyFrame =
let acceptedTypes = ["Grass", "Fire"]
lf.filter(col("Type 1").isIn(acceptedTypes) or col("Type 2").isIn(acceptedTypes))def keep_grass_or_fire(lf):
accepted_types = ['Grass', 'Fire']
return (
lf
.filter(
(pl.col('Type 1').is_in(accepted_types))
| (pl.col('Type 2').is_in(accepted_types))
)
)explain prints the plan Polars will run, after optimization. Read it from the bottom up:
the CSV scan reads only the columns the query needs, and the filter sits right above it.
echo lf.addRanks.keepGrassOrFire.keepCols.explain
simple π 8/8 ["Name", "Total", "Attack", ... 5 other columns]
FILTER (col("Type 1").is_in([["Grass", "Fire"].alias("")]) | col("Type 2").is_in([["Grass", "Fire"].alias("")]))
FROM
simple π 10/10 ["Name", "Total", "Attack", ... 7 other columns]
WITH_COLUMNS:
[col("Attack").rank().alias("Atk Rank"), col("Defense").rank().alias("Def Rank"), col("Speed").rank().alias("Spe Rank")]
Csv SCAN [data/polars-cookbook/pokemon.csv]
PROJECT 7/13 COLUMNS
ESTIMATED ROWS: 161
print(
lf
.pipe(add_ranks)
.pipe(keep_grass_or_fire)
.pipe(keep_cols)
.explain()
)simple π 8/8 ["Name", "Total", "Attack", ... 5 other columns]
FILTER (col("Type 1").is_in([["Grass", "Fire"]]) | col("Type 2").is_in([["Grass", "Fire"]]))
FROM
simple π 10/10 ["Name", "Total", "Attack", ... 7 other columns]
WITH_COLUMNS:
[col("Attack").rank().alias("Atk Rank"), col("Defense").rank().alias("Def Rank"), col("Speed").rank().alias("Spe Rank")]
Csv SCAN [data/polars-cookbook/pokemon.csv]
PROJECT 7/13 COLUMNS
ESTIMATED ROWS: 161The order of the steps matters. The ranks are computed before the filter here, on all the Pokémon. Filtering first, the ranks are computed among grass and fire types only: a different query, with a different plan.
echo lf.keepGrassOrFire.keepCols.addRanks.explain
WITH_COLUMNS:
[col("Attack").rank().alias("Atk Rank"), col("Defense").rank().alias("Def Rank"), col("Speed").rank().alias("Spe Rank")]
simple π 5/5 ["Name", "Total", "Attack", ... 2 other columns]
Csv SCAN [data/polars-cookbook/pokemon.csv]
PROJECT 7/13 COLUMNS
SELECTION: (col("Type 1").is_in([["Grass", "Fire"].alias("")]) | col("Type 2").is_in([["Grass", "Fire"].alias("")]))
ESTIMATED ROWS: 161
print(
lf
.pipe(keep_grass_or_fire)
.pipe(keep_cols)
.pipe(add_ranks)
.explain()
) WITH_COLUMNS:
[col("Attack").rank().alias("Atk Rank"), col("Defense").rank().alias("Def Rank"), col("Speed").rank().alias("Spe Rank")]
simple π 5/5 ["Name", "Total", "Attack", ... 2 other columns]
Csv SCAN [data/polars-cookbook/pokemon.csv]
PROJECT 7/13 COLUMNS
SELECTION: (col("Type 1").is_in([["Grass", "Fire"]]) | col("Type 2").is_in([["Grass", "Fire"]]))
ESTIMATED ROWS: 161import nanuqbook
bookInit()
nbText: "# Debugging chained operations"
attribution polarsCookbook(12, "Testing and Debugging in Polars",
"Two recipes of the chapter: debugging chained operations, and inspecting the query " &
"plan. Data is read from `data/polars-cookbook/`. Left out: `show_graph`, " &
"`explain(optimized=False)` and the testing recipes with pytest and cuallee.")
nbText: """
A long chain of methods reads well, but when it fails, which step was it? This recipe
takes a lazy query on a table of Pokémon apart, step by step.
"""
tabs """
import polars as pl
lf = pl.scan_csv('data/polars-cookbook/pokemon.csv')
""":
nbCode:
import nanuq
let lf = scanCsv("data/polars-cookbook/pokemon.csv")
nbText: """
The query ranks the Pokémon on three of their stats, keeps a few columns and shows the
five with the lowest total. `rank` with the `Dense` method gives tied values the same rank
and leaves no gaps.
"""
tabs """
(
lf
.with_columns(
pl.col('Attack').rank(method='dense').alias('Atk Rank'),
pl.col('Defense').rank(method='dense').alias('Def Rank'),
pl.col('Speed').rank(method='dense').alias('Spe Rank'),
)
.select(
'Name',
'Total',
'Attack',
'Defense',
'Speed',
pl.col('^*Rank$')
)
.sort('Total')
.head()
.collect()
)
""":
nbCode:
nbShow lf
.withColumns(
col.Attack.rank(Dense).alias("Atk Rank"),
col.Defense.rank(Dense).alias("Def Rank"),
col.Speed.rank(Dense).alias("Spe Rank"))
.select(col("Name", "Total", "Attack", "Defense", "Speed"), col("^*Rank$"))
.sort("Total")
.head()
.collect
nanuq """
`rank` is new in Nanuq 0.3. Its method is the enum `RankMethod` (`Average`, the default,
`Min`, `Max`, `Dense`, `Ordinal`, `Random`), passed by position since Python's argument
name, `method`, is a Nim keyword.
"""
nbText: """
Now with a typo, `Deffense`. In a lazy query, the error comes when the plan is resolved,
at `collect`, not at the line with the typo:
"""
tabs """
try:
(
lf
.with_columns(
pl.col('Attack').rank(method='dense').alias('Atk Rank'),
pl.col('Defense').rank(method='dense').alias('Def Rank'),
pl.col('Speed').rank(method='dense').alias('Spe Rank'),
)
.select(
'Name',
'Total',
'Attack',
'Deffense',
'Speed',
pl.col('^*Rank$')
)
.sort('Total')
.head()
.collect()
)
except pl.exceptions.ColumnNotFoundError as e:
print(type(e).__name__)
""":
nbCode:
try:
discard lf
.withColumns(
col.Attack.rank(Dense).alias("Atk Rank"),
col.Defense.rank(Dense).alias("Def Rank"),
col.Speed.rank(Dense).alias("Spe Rank"))
.select(col("Name", "Total", "Attack", "Deffense", "Speed"), col("^*Rank$"))
.sort("Total")
.head()
.collect
except ColumnNotFoundError:
echo "ColumnNotFoundError"
nbText: """
The recipe's way to find the culprit: comment out steps until the query runs. Without the
`select`, it does:
"""
tabs """
(
lf
.with_columns(
pl.col('Attack').rank(method='dense').alias('Atk Rank'),
pl.col('Defense').rank(method='dense').alias('Def Rank'),
pl.col('Speed').rank(method='dense').alias('Spe Rank'),
)
# .select(
# 'Name',
# 'Total',
# 'Attack',
# 'Deffense',
# 'Speed',
# pl.col('^*Rank$')
# )
.sort('Total')
.head()
.collect()
)
""":
nbCode:
nbShow lf
.withColumns(
col.Attack.rank(Dense).alias("Atk Rank"),
col.Defense.rank(Dense).alias("Def Rank"),
col.Speed.rank(Dense).alias("Spe Rank"))
# .select(col("Name", "Total", "Attack", "Deffense", "Speed"), col("^*Rank$"))
.sort("Total")
.head()
.collect
nanuq """
The recipe also collects first and runs the chain eagerly, so that the error points at its
step. Nanuq's eager methods run a lazy query each, so that gives the same error.
"""
nbText: """
Another way to keep a chain readable: give the steps names. Python does it with functions
and `pipe`; in Nim a proc that takes a LazyFrame is called with the same dot syntax as a
method, so no `pipe` is needed.
"""
tabs """
def add_ranks(lf: pl.LazyFrame) -> pl.LazyFrame:
return (
lf
.with_columns(
pl.col('Attack').rank(method='dense').alias('Atk Rank'),
pl.col('Defense').rank(method='dense').alias('Def Rank'),
pl.col('Speed').rank(method='dense').alias('Spe Rank'),
)
)
def keep_cols(lf: pl.LazyFrame) -> pl.LazyFrame:
return (
lf
.select(
'Name',
'Total',
'Attack',
'Defense',
'Speed',
pl.col('^*Rank$')
)
)
(
lf
.pipe(add_ranks)
.pipe(keep_cols)
.sort('Total')
.head()
.collect()
)
""":
nbCode:
proc addRanks(lf: LazyFrame): LazyFrame =
lf.withColumns(
col.Attack.rank(Dense).alias("Atk Rank"),
col.Defense.rank(Dense).alias("Def Rank"),
col.Speed.rank(Dense).alias("Spe Rank"))
proc keepCols(lf: LazyFrame): LazyFrame =
lf.select(col("Name", "Total", "Attack", "Defense", "Speed"), col("^*Rank$"))
nbShow lf.addRanks.keepCols.sort("Total").head().collect
nbText: """
## Inspecting and optimizing the query plan
One more step, a filter on the Pokémon's types:
"""
tabs """
def keep_grass_or_fire(lf):
accepted_types = ['Grass', 'Fire']
return (
lf
.filter(
(pl.col('Type 1').is_in(accepted_types))
| (pl.col('Type 2').is_in(accepted_types))
)
)
""":
nbCode:
proc keepGrassOrFire(lf: LazyFrame): LazyFrame =
let acceptedTypes = ["Grass", "Fire"]
lf.filter(col("Type 1").isIn(acceptedTypes) or col("Type 2").isIn(acceptedTypes))
nbText: """
`explain` prints the plan Polars will run, after optimization. Read it from the bottom up:
the CSV scan reads only the columns the query needs, and the filter sits right above it.
"""
tabs """
print(
lf
.pipe(add_ranks)
.pipe(keep_grass_or_fire)
.pipe(keep_cols)
.explain()
)
""":
nbCode:
echo lf.addRanks.keepGrassOrFire.keepCols.explain
nbText: """
The order of the steps matters. The ranks are computed before the filter here, on all the
Pokémon. Filtering first, the ranks are computed among grass and fire types only: a
different query, with a different plan.
"""
tabs """
print(
lf
.pipe(keep_grass_or_fire)
.pipe(keep_cols)
.pipe(add_ranks)
.explain()
)
""":
nbCode:
echo lf.keepGrassOrFire.keepCols.addRanks.explain
nanuq """
Wait: `keep_cols` before `add_ranks` selects the rank columns before they exist. The regex
`^*Rank$` matches no column at that point, so it selects nothing, and the query still runs.
Nanuq's `explain` has no `optimized = false` yet, and no `show_graph`.
"""
bookSave()
On GitHub: book/polars-cookbook/debugging_chains.nim