Skip to content

Instantly share code, notes, and snippets.

@swo
Created April 4, 2025 15:35
Show Gist options
  • Save swo/ed3dfb79e3a3da0306ea3250f029bbd0 to your computer and use it in GitHub Desktop.
Save swo/ed3dfb79e3a3da0306ea3250f029bbd0 to your computer and use it in GitHub Desktop.
Two-part logistic
import altair as alt
import numpy as np
import polars as pl
import streamlit as st
def logistic(x, y0, scale, x0, k):
return y0 + scale / (1 + np.exp(-k * (x - x0)))
def app():
st.title("My curve")
k_left = st.slider("k_left", 0.0, 5.0, 1.0)
scale_left = st.slider("scale_left", 0.0, 1.0, 0.25)
scale_right = st.slider("scale_right", 0.0, 3.0, 0.75)
x0 = 0.0
a1 = 0.0
a2 = (scale_left - scale_right) / 2.0
k_right = k_left * scale_left / scale_right
x = np.linspace(-10, 10, 1001)
y_left = logistic(x, y0=a1, scale=scale_left, x0=x0, k=k_left)
y_right = logistic(x, y0=a2, scale=scale_right, x0=x0, k=k_right)
y = np.where(x < x0, y_left, y_right)
df = pl.DataFrame({"x": x, "y": y})
chart = (
alt.Chart(df)
.mark_line()
.encode(
x=alt.X("x", title="x"),
y=alt.Y("y", title="y", scale=alt.Scale(domain=(0.0, 1.0))),
)
)
st.altair_chart(chart, use_container_width=True)
st.header("Math")
st.markdown(
r"""
Each half $i \in \{1, 2\}$ of the curve follows this form:
$$
f_i(x; a_i, L_i, x_0, k_i) = a_i + \frac{L_i}{1 + e^{-k_i (x - x_0)}}
$$
with a combined curve:
$$
f(x) = \begin{cases}
f_1(x; a_1, L_1, x_0, k_1) & \text{if } x < x_0 \\
f_2(x; a_2, L_2, x_0, k_2) & \text{if } x \geq x_0
\end{cases}
$$
We immediately set $a_1 = 0$. To ensure continuity, we require:
$$
\begin{align*}
f_1(x_0) &= f_2(x_0) \\
a_1 + \frac{1}{2} L_1 &= a_2 + \frac{1}{2} L_2 \\
\frac{1}{2} (L_1 - L_2) &= a_2
\end{align*}
$$
And also:
$$
\begin{align*}
f_1'(x_0) &= f_2'(x_0) \\
\frac{1}{4} k_1 L_1 &= \frac{1}{4} k_2 L_2 \\
k_1 \frac{L_1}{L_2} &= k_2
\end{align*}
$$
This leaves free params: $x_0$, $L_1$, $L_2$, and $k_1$.
"""
)
if __name__ == "__main__":
app()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment