Spaces:
Sleeping
Sleeping
File size: 5,242 Bytes
de9ce02 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 | from pathlib import Path
from typing import Literal
import matplotlib.pyplot as plt
from sympy import sympify
from logic import (
DataGenerationOptions,
Dataset,
PlotData,
compute_plot_values,
generate_dataset,
load_dataset_from_csv,
)
class Manager:
def __init__(self) -> None:
self.dataset = Dataset(x=[], y=[])
self.plots_data: PlotData | None = None
def update_dataset(
self,
dataset_type: Literal["Generate", "CSV"],
function: str,
data_xmin: float,
data_xmax: float,
sigma: float,
nsample: int,
sample_method: Literal["Grid", "Random"],
csv_path: str | Path | None,
has_header: bool,
xcol: int,
ycol: int,
) -> None:
if dataset_type == "Generate":
try:
parsed_function = sympify(function)
except Exception as exc:
raise ValueError(f"Invalid function: {exc}") from exc
sampling = sample_method.lower()
if sampling not in ["grid", "random"]:
raise ValueError(f"Unknown sampling method: {sample_method}")
self.dataset = generate_dataset(
parsed_function,
(data_xmin, data_xmax),
DataGenerationOptions(
method=sampling,
num_samples=nsample,
noise=sigma,
),
)
return
normalized_path = self._normalize_csv_path(csv_path)
if normalized_path is None:
raise ValueError("Please upload a CSV file.")
self.dataset = load_dataset_from_csv(
normalized_path,
has_header,
xcol,
ycol,
)
def compute_plot_data(
self,
kernel: str,
distribution: Literal["Prior", "Posterior"],
plot_xmin: float,
plot_xmax: float,
) -> None:
self.plots_data = compute_plot_values(
self.dataset,
kernel,
distribution,
plot_xmin,
plot_xmax,
)
def handle_generate_plots(
self,
dataset_type: Literal["Generate", "CSV"],
function: str,
data_xmin: float,
data_xmax: float,
sigma: float,
nsample: int,
sample_method: Literal["Grid", "Random"],
csv_path: str | Path | None,
has_header: bool,
xcol: int,
ycol: int,
kernel: str,
distribution: Literal["Prior", "Posterior"],
plot_xmin: float,
plot_xmax: float,
):
self.update_dataset(
dataset_type,
function,
data_xmin,
data_xmax,
sigma,
nsample,
sample_method,
csv_path,
has_header,
xcol,
ycol,
)
true_dataset = self._build_true_dataset(
dataset_type,
function,
plot_xmin,
plot_xmax,
)
self.compute_plot_data(
kernel,
distribution,
plot_xmin,
plot_xmax,
)
return self.generate_plot(true_dataset)
def generate_plot(self, true_dataset: Dataset):
if self.plots_data is None:
raise ValueError("Plot data has not been computed.")
fig, ax = plt.subplots(figsize=(12, 9))
cmap = plt.get_cmap("tab20")
ax.scatter(self.dataset.x, self.dataset.y, color=cmap(0), label="Data Points")
if true_dataset.y is not None and len(true_dataset.y) > 0:
ax.plot(true_dataset.x, true_dataset.y, color=cmap(1), label="True Function")
ax.plot(self.plots_data.x, self.plots_data.pred_mean, color=cmap(2), label="Mean Prediction")
ax.fill_between(
self.plots_data.x,
self.plots_data.pred_mean - 1.96 * self.plots_data.pred_std,
self.plots_data.pred_mean + 1.96 * self.plots_data.pred_std,
color=cmap(3),
alpha=0.2,
label="95% Confidence Interval",
)
ax.legend()
return fig
def _build_true_dataset(
self,
dataset_type: Literal["Generate", "CSV"],
function: str,
xmin: float,
xmax: float,
) -> Dataset:
if dataset_type == "CSV":
return Dataset(x=[], y=[])
try:
parsed_function = sympify(function)
except Exception as exc:
raise ValueError(f"Invalid function: {exc}") from exc
return generate_dataset(
parsed_function,
(xmin, xmax),
DataGenerationOptions(
method="grid",
num_samples=1000,
noise=0.0,
),
)
def _normalize_csv_path(self, csv_path: str | Path | None) -> str | None:
if csv_path is None:
return None
if isinstance(csv_path, Path):
return str(csv_path)
if isinstance(csv_path, str):
return csv_path
name = getattr(csv_path, "name", None)
if name:
return str(name)
return None
|