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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Gradio App for Entropy-Conserving Transformations
|
| 3 |
+
|
| 4 |
+
This app demonstrates how divergence-free vector fields can transform
|
| 5 |
+
arbitrary distributions towards Gaussian form while conserving entropy.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import gradio as gr
|
| 9 |
+
import matplotlib
|
| 10 |
+
import matplotlib.pyplot as plt
|
| 11 |
+
import numpy as np
|
| 12 |
+
import pandas as pd
|
| 13 |
+
|
| 14 |
+
from entra import DataFrameTransformer
|
| 15 |
+
|
| 16 |
+
matplotlib.use("Agg")
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def generate_uniform_data(n_per_dim: int = 20, dimensions: int = 2) -> pd.DataFrame:
|
| 20 |
+
"""Generate uniform grid data."""
|
| 21 |
+
if dimensions == 2:
|
| 22 |
+
x = np.linspace(-10, 10, n_per_dim)
|
| 23 |
+
y = np.linspace(-10, 10, n_per_dim)
|
| 24 |
+
xx, yy = np.meshgrid(x, y)
|
| 25 |
+
df = pd.DataFrame({"x": xx.ravel(), "y": yy.ravel()})
|
| 26 |
+
else: # 3D
|
| 27 |
+
x = np.linspace(-10, 10, n_per_dim)
|
| 28 |
+
y = np.linspace(-10, 10, n_per_dim)
|
| 29 |
+
z = np.linspace(-10, 10, n_per_dim)
|
| 30 |
+
xx, yy, zz = np.meshgrid(x, y, z)
|
| 31 |
+
df = pd.DataFrame({"x": xx.ravel(), "y": yy.ravel(), "z": zz.ravel()})
|
| 32 |
+
return df
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def generate_sample_csv(n_per_dim: int, dimensions: int):
|
| 36 |
+
"""Generate sample CSV and return as downloadable file."""
|
| 37 |
+
df = generate_uniform_data(n_per_dim, dimensions)
|
| 38 |
+
|
| 39 |
+
# Save to temp file for download
|
| 40 |
+
temp_path = "/tmp/generated_uniform_data.csv"
|
| 41 |
+
df.to_csv(temp_path, index=False)
|
| 42 |
+
|
| 43 |
+
n_points = len(df)
|
| 44 |
+
cols = list(df.columns)
|
| 45 |
+
preview = df.head(10).to_string()
|
| 46 |
+
|
| 47 |
+
return (
|
| 48 |
+
temp_path,
|
| 49 |
+
f"Generated {n_points} points with columns: {cols}\n\nPreview:\n{preview}",
|
| 50 |
+
df,
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def load_csv_file(file):
|
| 55 |
+
"""Load uploaded CSV file."""
|
| 56 |
+
if file is None:
|
| 57 |
+
return None, "No file uploaded", None
|
| 58 |
+
|
| 59 |
+
df = pd.read_csv(file.name)
|
| 60 |
+
n_points = len(df)
|
| 61 |
+
cols = list(df.columns)
|
| 62 |
+
preview = df.head(10).to_string()
|
| 63 |
+
|
| 64 |
+
return (
|
| 65 |
+
file.name,
|
| 66 |
+
f"Loaded {n_points} points with columns: {cols}\n\nPreview:\n{preview}",
|
| 67 |
+
df,
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def run_transformation(
|
| 72 |
+
df_state,
|
| 73 |
+
columns_str: str,
|
| 74 |
+
sigma: float,
|
| 75 |
+
max_iterations: int,
|
| 76 |
+
):
|
| 77 |
+
"""Run the LM optimization and return results."""
|
| 78 |
+
if df_state is None:
|
| 79 |
+
return (
|
| 80 |
+
None,
|
| 81 |
+
None,
|
| 82 |
+
None,
|
| 83 |
+
"Error: No data loaded. Please upload or generate data first.",
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
df = df_state
|
| 87 |
+
|
| 88 |
+
# Parse columns
|
| 89 |
+
columns = [c.strip() for c in columns_str.split(",")]
|
| 90 |
+
|
| 91 |
+
# Validate columns exist
|
| 92 |
+
missing = [c for c in columns if c not in df.columns]
|
| 93 |
+
if missing:
|
| 94 |
+
return (
|
| 95 |
+
None,
|
| 96 |
+
None,
|
| 97 |
+
None,
|
| 98 |
+
f"Error: Columns not found: {missing}. Available: {list(df.columns)}",
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
# Create transformer
|
| 102 |
+
transformer = DataFrameTransformer(
|
| 103 |
+
sigma=sigma,
|
| 104 |
+
max_iterations=max_iterations,
|
| 105 |
+
verbose=False,
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
# Run transformation
|
| 109 |
+
df_transformed = transformer.fit_transform(df, columns=columns)
|
| 110 |
+
|
| 111 |
+
# Get entropy comparison
|
| 112 |
+
entropy = transformer.get_entropy_comparison(df, df_transformed)
|
| 113 |
+
|
| 114 |
+
# Create plots
|
| 115 |
+
fig_scatter = create_scatter_plot(df, df_transformed, columns)
|
| 116 |
+
fig_hist = create_histogram_plot(df, df_transformed, columns)
|
| 117 |
+
fig_history = create_history_plot(transformer.history_)
|
| 118 |
+
|
| 119 |
+
# Create results text
|
| 120 |
+
results_text = format_results(entropy, transformer.history_)
|
| 121 |
+
|
| 122 |
+
return fig_scatter, fig_hist, fig_history, results_text
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def create_scatter_plot(df_orig, df_trans, columns):
|
| 126 |
+
"""Create before/after scatter plot."""
|
| 127 |
+
fig, axes = plt.subplots(1, 2, figsize=(12, 5))
|
| 128 |
+
|
| 129 |
+
if len(columns) >= 2:
|
| 130 |
+
x_col, y_col = columns[0], columns[1]
|
| 131 |
+
|
| 132 |
+
axes[0].scatter(df_orig[x_col], df_orig[y_col], c="blue", alpha=0.5, s=10)
|
| 133 |
+
axes[0].set_xlabel(x_col)
|
| 134 |
+
axes[0].set_ylabel(y_col)
|
| 135 |
+
axes[0].set_title("Original Distribution")
|
| 136 |
+
axes[0].set_aspect("equal")
|
| 137 |
+
axes[0].grid(True, alpha=0.3)
|
| 138 |
+
|
| 139 |
+
axes[1].scatter(df_trans[x_col], df_trans[y_col], c="red", alpha=0.5, s=10)
|
| 140 |
+
axes[1].set_xlabel(x_col)
|
| 141 |
+
axes[1].set_ylabel(y_col)
|
| 142 |
+
axes[1].set_title("Transformed (Towards Gaussian)")
|
| 143 |
+
axes[1].set_aspect("equal")
|
| 144 |
+
axes[1].grid(True, alpha=0.3)
|
| 145 |
+
|
| 146 |
+
plt.tight_layout()
|
| 147 |
+
return fig
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def create_histogram_plot(df_orig, df_trans, columns):
|
| 151 |
+
"""Create marginal histogram plots."""
|
| 152 |
+
n_cols = min(len(columns), 3)
|
| 153 |
+
fig, axes = plt.subplots(n_cols, 2, figsize=(12, 4 * n_cols))
|
| 154 |
+
|
| 155 |
+
if n_cols == 1:
|
| 156 |
+
axes = axes.reshape(1, -1)
|
| 157 |
+
|
| 158 |
+
for i, col in enumerate(columns[:n_cols]):
|
| 159 |
+
# Original
|
| 160 |
+
axes[i, 0].hist(df_orig[col], bins=30, density=True, alpha=0.7, color="blue")
|
| 161 |
+
axes[i, 0].set_xlabel(col)
|
| 162 |
+
axes[i, 0].set_ylabel("Density")
|
| 163 |
+
axes[i, 0].set_title(f"Original {col} Marginal")
|
| 164 |
+
|
| 165 |
+
# Transformed with Gaussian overlay
|
| 166 |
+
axes[i, 1].hist(df_trans[col], bins=30, density=True, alpha=0.7, color="red")
|
| 167 |
+
x_range = np.linspace(df_trans[col].min(), df_trans[col].max(), 100)
|
| 168 |
+
mu = df_trans[col].mean()
|
| 169 |
+
std = df_trans[col].std()
|
| 170 |
+
gaussian = (1 / (std * np.sqrt(2 * np.pi))) * np.exp(
|
| 171 |
+
-0.5 * ((x_range - mu) / std) ** 2
|
| 172 |
+
)
|
| 173 |
+
axes[i, 1].plot(x_range, gaussian, "k--", linewidth=2, label="Gaussian fit")
|
| 174 |
+
axes[i, 1].set_xlabel(col)
|
| 175 |
+
axes[i, 1].set_ylabel("Density")
|
| 176 |
+
axes[i, 1].set_title(f"Transformed {col} Marginal")
|
| 177 |
+
axes[i, 1].legend()
|
| 178 |
+
|
| 179 |
+
plt.tight_layout()
|
| 180 |
+
return fig
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def create_history_plot(history):
|
| 184 |
+
"""Create optimization history plot."""
|
| 185 |
+
fig, axes = plt.subplots(1, 2, figsize=(12, 4))
|
| 186 |
+
|
| 187 |
+
# Determinant
|
| 188 |
+
axes[0].semilogy(history["iteration"], history["determinant"], "b-o", markersize=4)
|
| 189 |
+
axes[0].set_xlabel("Iteration")
|
| 190 |
+
axes[0].set_ylabel("Covariance Determinant")
|
| 191 |
+
axes[0].set_title("Determinant Minimization")
|
| 192 |
+
axes[0].grid(True, alpha=0.3)
|
| 193 |
+
|
| 194 |
+
# Gaussian entropy
|
| 195 |
+
axes[1].plot(history["iteration"], history["gaussian_entropy"], "r-o", markersize=4)
|
| 196 |
+
axes[1].set_xlabel("Iteration")
|
| 197 |
+
axes[1].set_ylabel("H(Gaussian)")
|
| 198 |
+
axes[1].set_title(
|
| 199 |
+
"Gaussian Entropy Bound\n(decreases because we start from uniform)"
|
| 200 |
+
)
|
| 201 |
+
axes[1].grid(True, alpha=0.3)
|
| 202 |
+
|
| 203 |
+
plt.tight_layout()
|
| 204 |
+
return fig
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def format_results(entropy, history):
|
| 208 |
+
"""Format results as text."""
|
| 209 |
+
det_reduction = (
|
| 210 |
+
entropy["original"]["determinant"] / entropy["transformed"]["determinant"]
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
text = f"""
|
| 214 |
+
TRANSFORMATION RESULTS
|
| 215 |
+
{'=' * 50}
|
| 216 |
+
|
| 217 |
+
Entropy Comparison (k-NN estimator):
|
| 218 |
+
Original: {entropy['original']['knn_entropy']:.6f} nats
|
| 219 |
+
Transformed: {entropy['transformed']['knn_entropy']:.6f} nats
|
| 220 |
+
Difference: {abs(entropy['original']['knn_entropy'] - entropy['transformed']['knn_entropy']):.6f} nats
|
| 221 |
+
|
| 222 |
+
(k-NN entropy should remain ~constant for volume-preserving transformation)
|
| 223 |
+
|
| 224 |
+
Gaussian Entropy of Transformed Data:
|
| 225 |
+
H(Gaussian): {entropy['transformed']['gaussian_entropy']:.6f} nats
|
| 226 |
+
|
| 227 |
+
(This is the entropy IF the transformed data were perfectly Gaussian)
|
| 228 |
+
|
| 229 |
+
Covariance Determinant:
|
| 230 |
+
Original: {entropy['original']['determinant']:.6e}
|
| 231 |
+
Transformed: {entropy['transformed']['determinant']:.6e}
|
| 232 |
+
Reduction: {det_reduction:.2f}x
|
| 233 |
+
|
| 234 |
+
Optimization:
|
| 235 |
+
Iterations with improvement: {len(history['iteration'])}
|
| 236 |
+
Final determinant: {history['determinant'][-1]:.6e}
|
| 237 |
+
Final H(Gaussian): {history['gaussian_entropy'][-1]:.6f}
|
| 238 |
+
"""
|
| 239 |
+
return text
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
# Markdown explanation of Levenberg-Marquardt
|
| 243 |
+
LM_EXPLANATION = """
|
| 244 |
+
## How the Levenberg-Marquardt Algorithm Works
|
| 245 |
+
|
| 246 |
+
The **Levenberg-Marquardt (LM) algorithm** is used to minimize the covariance determinant. Unlike gradient descent, **LM has no learning rate** - here's why:
|
| 247 |
+
|
| 248 |
+
### The Key Insight
|
| 249 |
+
|
| 250 |
+
LM is designed for **least-squares problems** where you minimize a sum of squared residuals. Instead of taking steps proportional to the gradient (like gradient descent), LM solves a **local linear approximation** of the problem at each step.
|
| 251 |
+
|
| 252 |
+
### How It Works
|
| 253 |
+
|
| 254 |
+
1. **Compute the Jacobian** `J` - the matrix of partial derivatives of residuals with respect to parameters
|
| 255 |
+
|
| 256 |
+
2. **Solve the normal equations**:
|
| 257 |
+
```
|
| 258 |
+
(J^T J + λI) δ = -J^T r
|
| 259 |
+
```
|
| 260 |
+
where `r` is the residual vector and `λ` is a damping parameter
|
| 261 |
+
|
| 262 |
+
3. **The damping parameter λ replaces the learning rate**:
|
| 263 |
+
- When `λ` is **large**: The step is small and in the gradient direction (like gradient descent with small learning rate)
|
| 264 |
+
- When `λ` is **small**: The step approaches the Gauss-Newton step (a direct jump to the local minimum of the quadratic approximation)
|
| 265 |
+
|
| 266 |
+
4. **Adaptive adjustment**:
|
| 267 |
+
- If a step **decreases** the objective: Accept it and **decrease λ** (take bigger steps)
|
| 268 |
+
- If a step **increases** the objective: Reject it and **increase λ** (take smaller, safer steps)
|
| 269 |
+
|
| 270 |
+
### Why No Learning Rate?
|
| 271 |
+
|
| 272 |
+
The LM algorithm **automatically adapts** its step size through the damping parameter λ:
|
| 273 |
+
- It starts cautious (large λ, small steps)
|
| 274 |
+
- As it finds a good direction, it becomes more aggressive (small λ, large steps)
|
| 275 |
+
- If it overshoots, it backs off automatically
|
| 276 |
+
|
| 277 |
+
This makes LM much more robust than gradient descent - you don't need to tune a learning rate!
|
| 278 |
+
|
| 279 |
+
### In This Application
|
| 280 |
+
|
| 281 |
+
We minimize `log(det(Cov))` where `Cov` is the covariance matrix of the transformed points. The transformation is parameterized by coefficients of divergence-free basis functions, ensuring the transformation is **volume-preserving** and thus **entropy-conserving**.
|
| 282 |
+
"""
|
| 283 |
+
|
| 284 |
+
THEORY_EXPLANATION = """
|
| 285 |
+
## Theoretical Background
|
| 286 |
+
|
| 287 |
+
### Maximum Entropy Principle
|
| 288 |
+
|
| 289 |
+
A fundamental theorem states: **Among all distributions with a given covariance matrix, the Gaussian has maximum entropy.**
|
| 290 |
+
|
| 291 |
+
This means for any distribution with entropy `H₀` and covariance `Σ`:
|
| 292 |
+
- The Gaussian with the same covariance has entropy `H_Gaussian(Σ) ≥ H₀`
|
| 293 |
+
- Equality holds only when the distribution is Gaussian
|
| 294 |
+
|
| 295 |
+
### The Key Insight
|
| 296 |
+
|
| 297 |
+
If we apply a **volume-preserving transformation**:
|
| 298 |
+
1. The entropy stays fixed at `H₀` (entropy is conserved)
|
| 299 |
+
2. But the covariance changes
|
| 300 |
+
|
| 301 |
+
By **minimizing the covariance determinant** while preserving entropy:
|
| 302 |
+
- We reduce `H_Gaussian(Σ)` (the Gaussian entropy bound)
|
| 303 |
+
- When `H_Gaussian(Σ) = H₀`, the distribution must be Gaussian!
|
| 304 |
+
|
| 305 |
+
### Why Divergence-Free?
|
| 306 |
+
|
| 307 |
+
Divergence-free vector fields define **volume-preserving** transformations:
|
| 308 |
+
- The Jacobian determinant equals 1 everywhere
|
| 309 |
+
- Total probability volume is conserved
|
| 310 |
+
- **Entropy is conserved** under the transformation
|
| 311 |
+
|
| 312 |
+
This is the incompressibility condition from fluid dynamics: `∇·v = 0`
|
| 313 |
+
|
| 314 |
+
### The Operator
|
| 315 |
+
|
| 316 |
+
We construct divergence-free basis functions using Lowitzsch's operator:
|
| 317 |
+
|
| 318 |
+
**Ô = -I∇² + ∇∇ᵀ**
|
| 319 |
+
|
| 320 |
+
Applied to Gaussian RBFs, this produces matrix-valued functions where each column is a divergence-free vector field.
|
| 321 |
+
"""
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
def create_app():
|
| 325 |
+
"""Create the Gradio interface."""
|
| 326 |
+
with gr.Blocks(
|
| 327 |
+
title="Entropy-Conserving Transformations", theme=gr.themes.Soft()
|
| 328 |
+
) as app:
|
| 329 |
+
gr.Markdown(
|
| 330 |
+
"""
|
| 331 |
+
# Entropy-Conserving Transformations Using Divergence-Free Vector Fields
|
| 332 |
+
|
| 333 |
+
Transform arbitrary distributions towards Gaussian form while **conserving entropy**.
|
| 334 |
+
|
| 335 |
+
This demo uses divergence-free basis functions to create volume-preserving transformations,
|
| 336 |
+
then minimizes the covariance determinant using the Levenberg-Marquardt algorithm.
|
| 337 |
+
"""
|
| 338 |
+
)
|
| 339 |
+
|
| 340 |
+
# State to hold the dataframe
|
| 341 |
+
df_state = gr.State(None)
|
| 342 |
+
|
| 343 |
+
with gr.Tabs():
|
| 344 |
+
with gr.Tab("Transform Data"):
|
| 345 |
+
with gr.Row():
|
| 346 |
+
with gr.Column(scale=1):
|
| 347 |
+
gr.Markdown("### Step 1: Load or Generate Data")
|
| 348 |
+
|
| 349 |
+
with gr.Accordion("Option A: Upload CSV", open=True):
|
| 350 |
+
file_upload = gr.File(
|
| 351 |
+
label="Upload CSV file", file_types=[".csv"]
|
| 352 |
+
)
|
| 353 |
+
upload_btn = gr.Button("Load CSV", variant="secondary")
|
| 354 |
+
|
| 355 |
+
with gr.Accordion("Option B: Generate Uniform Data", open=True):
|
| 356 |
+
n_per_dim = gr.Slider(
|
| 357 |
+
minimum=5,
|
| 358 |
+
maximum=50,
|
| 359 |
+
value=20,
|
| 360 |
+
step=1,
|
| 361 |
+
label="Points per dimension",
|
| 362 |
+
)
|
| 363 |
+
dimensions = gr.Radio(
|
| 364 |
+
choices=[2, 3], value=2, label="Dimensions"
|
| 365 |
+
)
|
| 366 |
+
generate_btn = gr.Button(
|
| 367 |
+
"Generate Uniform Distribution",
|
| 368 |
+
variant="secondary",
|
| 369 |
+
)
|
| 370 |
+
download_file = gr.File(label="Download generated CSV")
|
| 371 |
+
|
| 372 |
+
data_info = gr.Textbox(
|
| 373 |
+
label="Data Info", lines=8, interactive=False
|
| 374 |
+
)
|
| 375 |
+
|
| 376 |
+
gr.Markdown("### Step 2: Configure Transformation")
|
| 377 |
+
|
| 378 |
+
columns_input = gr.Textbox(
|
| 379 |
+
value="x, y",
|
| 380 |
+
label="Columns to transform (comma-separated)",
|
| 381 |
+
)
|
| 382 |
+
sigma = gr.Slider(
|
| 383 |
+
minimum=0.1,
|
| 384 |
+
maximum=20.0,
|
| 385 |
+
value=5.0,
|
| 386 |
+
step=0.1,
|
| 387 |
+
label="Sigma (RBF width)",
|
| 388 |
+
)
|
| 389 |
+
max_iterations = gr.Slider(
|
| 390 |
+
minimum=10,
|
| 391 |
+
maximum=500,
|
| 392 |
+
value=100,
|
| 393 |
+
step=10,
|
| 394 |
+
label="Max iterations",
|
| 395 |
+
)
|
| 396 |
+
|
| 397 |
+
transform_btn = gr.Button(
|
| 398 |
+
"Run Transformation", variant="primary", size="lg"
|
| 399 |
+
)
|
| 400 |
+
|
| 401 |
+
with gr.Column(scale=2):
|
| 402 |
+
gr.Markdown("### Results")
|
| 403 |
+
|
| 404 |
+
results_text = gr.Textbox(
|
| 405 |
+
label="Transformation Results",
|
| 406 |
+
lines=20,
|
| 407 |
+
interactive=False,
|
| 408 |
+
)
|
| 409 |
+
|
| 410 |
+
with gr.Row():
|
| 411 |
+
scatter_plot = gr.Plot(label="Before/After Scatter")
|
| 412 |
+
|
| 413 |
+
with gr.Row():
|
| 414 |
+
hist_plot = gr.Plot(label="Marginal Distributions")
|
| 415 |
+
|
| 416 |
+
with gr.Row():
|
| 417 |
+
history_plot = gr.Plot(label="Optimization History")
|
| 418 |
+
|
| 419 |
+
with gr.Tab("How LM Works"):
|
| 420 |
+
gr.Markdown(LM_EXPLANATION)
|
| 421 |
+
|
| 422 |
+
with gr.Tab("Theory"):
|
| 423 |
+
gr.Markdown(THEORY_EXPLANATION)
|
| 424 |
+
|
| 425 |
+
# Event handlers
|
| 426 |
+
def on_generate(n, dims):
|
| 427 |
+
path, info, df = generate_sample_csv(n, dims)
|
| 428 |
+
return path, info, df
|
| 429 |
+
|
| 430 |
+
def on_upload(file):
|
| 431 |
+
path, info, df = load_csv_file(file)
|
| 432 |
+
return info, df
|
| 433 |
+
|
| 434 |
+
generate_btn.click(
|
| 435 |
+
fn=on_generate,
|
| 436 |
+
inputs=[n_per_dim, dimensions],
|
| 437 |
+
outputs=[download_file, data_info, df_state],
|
| 438 |
+
)
|
| 439 |
+
|
| 440 |
+
upload_btn.click(
|
| 441 |
+
fn=on_upload, inputs=[file_upload], outputs=[data_info, df_state]
|
| 442 |
+
)
|
| 443 |
+
|
| 444 |
+
transform_btn.click(
|
| 445 |
+
fn=run_transformation,
|
| 446 |
+
inputs=[
|
| 447 |
+
df_state,
|
| 448 |
+
columns_input,
|
| 449 |
+
sigma,
|
| 450 |
+
max_iterations,
|
| 451 |
+
],
|
| 452 |
+
outputs=[scatter_plot, hist_plot, history_plot, results_text],
|
| 453 |
+
)
|
| 454 |
+
|
| 455 |
+
return app
|
| 456 |
+
|
| 457 |
+
|
| 458 |
+
if __name__ == "__main__":
|
| 459 |
+
app = create_app()
|
| 460 |
+
app.launch()
|