# Where the plan stops: `scipy.stats` inside a `LazyFrame`

`scipy.stats` already handles per-row distributions. Pass arrays as the parameters and a frozen distribution broadcasts them against the evaluation points, so scoring each sensor reading against its own sensor's baseline is one call:

```python
import numpy as np
from scipy import stats

reading = np.array([9.8, 10.4, 135.0])
mu = np.array([10.0, 10.0, 100.0])
sigma = np.array([0.5, 0.5, 2.0])

print(stats.norm(loc=mu, scale=sigma).sf(reading))
```

```python
[6.55421742e-01 2.11855399e-01 7.16345877e-69]
```

For the arithmetic, a Polars user needs nothing more. The trouble starts with where the result lands, which is a NumPy array, outside both the query plan and the expression API.

## The scipy route ends at `collect()`

Say the readings and the per-sensor baselines are both lazy, and you want the upper-tail probability of every reading from the north site. Sensor `c` is new and has no baseline yet.

```python
import polars as pl

readings = pl.LazyFrame(
    {
        "sensor": ["a", "a", "b", "b", "c"],
        "site": ["north", "north", "south", "north", "north"],
        "reading": [9.8, 10.4, 100.0, 135.0, 7.0],
        "battery": [0.9, 0.8, 0.7, 0.6, 0.5],
        "firmware": ["1.2", "1.2", "2.0", "2.0", "2.0"],
    }
)
baselines = pl.LazyFrame({"sensor": ["a", "b"], "mu": [10.0, 100.0], "sigma": [0.5, 2.0]})

joined = readings.join(baselines, on="sensor", how="left")
print(joined.explain())
```

```python
LEFT JOIN:
LEFT PLAN ON: [col("sensor")]
  DF ["sensor", "site", "reading", "battery", ...]; PROJECT */5 COLUMNS
RIGHT PLAN ON: [col("sensor")]
  DF ["sensor", "mu", "sigma"]; PROJECT */3 COLUMNS
END LEFT JOIN
```

scipy takes arrays, so you collect the query before you can score it. The optimiser plans what comes before `collect()` and nothing after it. It does not know the scoring needs three of the five reading columns, or that only the north site matters, so the plan reads all five columns of every row (`PROJECT */5 COLUMNS`). Against a Parquet scan, that is every column of every row group. You can write the `select` and the `filter` before `collect()` by hand, and keep them in step with whatever the query does next. The optimiser does that work only for the part of the query it can see.

```python
frame = joined.collect()
upper_tail = stats.norm(loc=frame["mu"].to_numpy(), scale=frame["sigma"].to_numpy()).sf(frame["reading"].to_numpy())

scored = frame.with_columns(upper_tail=upper_tail).filter(pl.col("site") == "north")
print(scored.select("sensor", "reading", "upper_tail"))
```

```python
shape: (4, 3)
┌────────┬─────────┬────────────┐
│ sensor ┆ reading ┆ upper_tail │
│ ---    ┆ ---     ┆ ---        │
│ str    ┆ f64     ┆ f64        │
╞════════╪═════════╪════════════╡
│ a      ┆ 9.8     ┆ 0.655422   │
│ a      ┆ 10.4    ┆ 0.211855   │
│ b      ┆ 135.0   ┆ 7.1635e-69 │
│ c      ┆ 7.0     ┆ NaN        │
└────────┴─────────┴────────────┘
```

The array lines up with `frame` because nothing came between `to_numpy()` and `with_columns`. Put a filter, a sort or a join in that gap and the alignment is yours to restore. Sensor `c` scores `NaN`: a float NumPy array has no null, so the missing baseline arrives as `NaN` and `NaN` is what comes back.

## `map_batches` keeps it in the plan

Wrapping the scipy call in `map_batches` puts it back inside the query:

```python
def scipy_norm_sf(batch: pl.Series) -> pl.Series:
    fields = batch.struct.unnest()
    dist = stats.norm(loc=fields["mu"].to_numpy(), scale=fields["sigma"].to_numpy())
    return pl.Series(dist.sf(fields["reading"].to_numpy()))


udf_query = (
    readings.join(baselines, on="sensor", how="left")
    .with_columns(upper_tail=pl.struct("reading", "mu", "sigma").map_batches(scipy_norm_sf, return_dtype=pl.Float64))
    .filter(pl.col("site") == "north")
    .select("sensor", "reading", "upper_tail")
)
print(udf_query.explain())
```

```python
simple π 3/3 ["sensor", "reading", ... 1 other column]
  FILTER col("site") == "north"
  FROM
    simple π 4/4 ["sensor", "reading", ... 2 other columns]
       WITH_COLUMNS:
       [col("reading").as_struct([col("mu"), col("sigma")]).python_udf().alias("upper_tail")] 
        LEFT JOIN:
        LEFT PLAN ON: [col("sensor")]
          DF ["sensor", "site", "reading", "battery", ...]; PROJECT["sensor", "site", "reading"] 3/5 COLUMNS
        RIGHT PLAN ON: [col("sensor")]
          DF ["sensor", "mu", "sigma"]; PROJECT */3 COLUMNS
        END LEFT JOIN
```

Projection pushdown is back (`3/5 COLUMNS`), but the site filter stays above the `python_udf()` node. Polars cannot see inside the callback, so it cannot assume a row's result depends on that row alone, and filtering first could change the answer. Pass `is_elementwise=True` and the filter moves below the join; that flag is a promise about the body of the function, and keeping it is up to you. Sensor `c` still scores `NaN`, for the same reason as before.

## The same score as an expression

With `polars-stats`, the upper tail is a Polars expression:

```python
import polars_stats as ps

baseline = ps.Normal(mu="mu", sigma="sigma")
query = (
    readings.join(baselines, on="sensor", how="left")
    .with_columns(upper_tail=baseline.sf("reading"))
    .filter(pl.col("site") == "north")
    .select("sensor", "reading", "upper_tail")
)

print(query.explain())
```

```python
simple π 3/3 ["sensor", "reading", ... 1 other column]
   WITH_COLUMNS:
   [col("reading").libpolars_stats/_internal.abi3.so:normal_sf([col("mu"), col("sigma")]).alias("upper_tail")] 
    LEFT JOIN:
    LEFT PLAN ON: [col("sensor")]
      simple π 2/2 ["sensor", "reading"]
        FILTER col("site") == "north"
        FROM
          DF ["sensor", "site", "reading", "battery", ...]; PROJECT["sensor", "reading", "site"] 3/5 COLUMNS
    RIGHT PLAN ON: [col("sensor")]
      DF ["sensor", "mu", "sigma"]; PROJECT */3 COLUMNS
    END LEFT JOIN
```

The call is a named node in the plan (`normal_sf`). The library registers it as elementwise, so with no flag from you the optimiser moves the site filter under the join, next to the scan, and reads three of the five columns. The result:

```python
print(query.collect())
```

```python
shape: (4, 3)
┌────────┬─────────┬────────────┐
│ sensor ┆ reading ┆ upper_tail │
│ ---    ┆ ---     ┆ ---        │
│ str    ┆ f64     ┆ f64        │
╞════════╪═════════╪════════════╡
│ a      ┆ 9.8     ┆ 0.655422   │
│ a      ┆ 10.4    ┆ 0.211855   │
│ b      ┆ 135.0   ┆ 7.1635e-69 │
│ c      ┆ 7.0     ┆ null       │
└────────┴─────────┴────────────┘
```

Sensor `c` scores `null`. The library follows Polars' rules rather than NumPy's: a null input gives a null result, and an invalid parameter such as `sigma <= 0` raises instead of returning `NaN`. [Handle nulls and errors](<https://fbruzzesi.github.io/polars-stats/how-to/nulls-and-errors/index.md>) covers both cases.

## One distribution, any frame

A scipy frozen distribution holds arrays, so it belongs to the frame they came from. Each new question about the data means another `collect()` and another round of `to_numpy()`. `baseline` holds column names. It describes one distribution per row of any frame with `mu` and `sigma` columns, and each method returns an expression that goes wherever Polars takes one: a filter, an aggregation, a window.

None of that needs a `LazyFrame`. `frame` is the eager `DataFrame` collected for scipy earlier, and the same `baseline` counts each sensor's readings in the upper 1% tail and sums their log-likelihood:

```python
per_sensor = (
    frame.drop_nulls("mu")
    .group_by("sensor", maintain_order=True)
    .agg(
        tail_readings=(baseline.sf("reading") < 0.01).sum(),
        log_likelihood=baseline.log_pdf("reading").sum(),
    )
)
print(per_sensor)
```

```python
shape: (2, 3)
┌────────┬───────────────┬────────────────┐
│ sensor ┆ tail_readings ┆ log_likelihood │
│ ---    ┆ ---           ┆ ---            │
│ str    ┆ u32           ┆ f64            │
╞════════╪═══════════════╪════════════════╡
│ a      ┆ 0             ┆ -0.851583      │
│ b      ┆ 1             ┆ -156.349171    │
└────────┴───────────────┴────────────────┘
```

`drop_nulls` leaves out sensor `c`, which has no baseline to score against.

## Where the result lands

The scores agree wherever both libraries return one. scipy returns an array outside the plan, so the work around it (projection, filtering, alignment, missing values) moves into your code. An expression stays inside the plan, and the optimiser does that work. On an eager `DataFrame` there is no plan to optimise, and the expression still saves the round trips through `to_numpy()`.

The [README](<https://github.com/FBruzzesi/polars-stats#why>) has the short version of this argument, and [Compose in lazy pipelines](<https://fbruzzesi.github.io/polars-stats/how-to/lazy-pipelines/index.md>) shows the patterns that follow from it: scoring inside a join, aggregating a density over a window, collecting per group.
