---
title: Get started with polarstate
jupyter: python3
---

This is a reproducible example that shows how to use polarstate, and compare the outputs to {lifelines} package.

First:
Import polars as a dependency:

```{python}
import polars as pl
```


# Competing Risks Example

::: {.panel-tabset}

## polarstate (Py 🐍)

```{python}

from polarstate import prepare_event_table

times_and_reals = pl.DataFrame({
    "times": [1, 2, 2, 3, 4, 5, 6],
    "reals": [1, 0, 2, 1, 0, 2, 1]
})

event_table = prepare_event_table(times_and_reals)

print(event_table)

```

### Prediction for Specific Time-Horizons


```{python}
from polarstate import predict_aj_estimates

predict_aj_estimates(event_table, pl.Series([1, 3, 5]))

```

## lifelines (Py 🐍)

```{python}

import pandas as pd
from lifelines import AalenJohansenFitter

df = pd.DataFrame({
    "duration": [1, 2, 2, 3, 4, 5, 6],
    "event":    [1, 0, 2, 1, 0, 2, 1]
})

ajf_priamry = AalenJohansenFitter()
ajf_priamry.fit(df["duration"], df["event"], event_of_interest=1)

print("Event Table for event type 1")
print(ajf_priamry.cumulative_density_)

ajf_competing = AalenJohansenFitter()
ajf_competing.fit(df["duration"], df["event"], event_of_interest=2)

print("Event Table for event type 2")
print(ajf_competing.cumulative_density_)



```

### Prediction for Specific Time-Horizons

```{python}
print("Cumulative incidence for event type 1 at times 1, 3, 5:")
print(ajf_priamry.predict([1, 3, 5]))

print("Cumulative incidence for event type 2 at times 1, 3, 5:")
print(ajf_competing.predict([1, 3, 5]))

```


## tidycmprsk (R 🔵)

```{r}
library(tidycmprsk)
cuminc(Surv(ttdeath, death_cr) ~ 1, trial)

times_and_reals <- data.frame(
  times = c(1, 2, 2, 3, 4, 5, 6),
  reals = factor(c(1, 0, 2, 1, 0, 2, 1),
                 levels = c(0, 1, 2),
                 labels = c("censored", "primary_event", "competing_event"))
)

(cuminc(Surv(times, reals) ~ 1, times_and_reals)) |>
    tidy() |>
    print()

```

:::

# No Compating Risks Example


::: {.panel-tabset}


## polarstate (Py 🐍)


```{python}

from lifelines import AalenJohansenFitter
from lifelines.datasets import load_waltons
from polarstate import prepare_event_table


T, E = load_waltons()['T'], load_waltons()['E']

times_and_reals = pl.DataFrame({
        "times": T,
        "reals": E
    })

result = prepare_event_table(times_and_reals)

print(result)
```




## lifelines (Py 🐍)


```{python}

from lifelines import AalenJohansenFitter
from lifelines.datasets import load_waltons
T, E = load_waltons()['T'], load_waltons()['E']
ajf = AalenJohansenFitter(calculate_variance=True)
ajf.fit(T, E, event_of_interest=1)
ajf.cumulative_density_


```



:::