From 4a796f55944b560b52d18107e23b175c5171df9f Mon Sep 17 00:00:00 2001 From: salmonik Date: Sun, 19 Apr 2026 00:47:42 +0200 Subject: error handling in plot.py Signed-off-by: salmonik --- cogs/plot.py | 29 ++++++++++++++++++----------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/cogs/plot.py b/cogs/plot.py index 4fcde44..ee19de9 100644 --- a/cogs/plot.py +++ b/cogs/plot.py @@ -20,10 +20,10 @@ _plot_available = False def _ensure_plot(): global _plt_module, _plot_available - + if _plt_module is not None: return _plot_available - + try: import matplotlib matplotlib.use("Agg") @@ -61,12 +61,12 @@ class Plot(commands.Cog): def _generate_plot(self, func_expr: str, output_path: str): global _plt_module - + if not _ensure_plot(): raise RuntimeError("matplotlib not available") plt = _plt_module - + if is_implicit(func_expr): self._generate_implicit_plot(func_expr, output_path) return @@ -100,6 +100,10 @@ class Plot(commands.Cog): except Exception: y.append(float("nan")) + valid_y = [yi for yi in y if not math.isnan(yi)] + if not valid_y: + raise ValueError("Brak danych do wykreślenia dla podanej funkcji") + fig, ax = plt.subplots(figsize=(10, 6)) ax.plot(x, y, linewidth=2, color="#00ff00") ax.set_title(f"y = {func_expr}", fontsize=14) @@ -117,15 +121,15 @@ class Plot(commands.Cog): def _generate_implicit_plot(self, func_expr: str, output_path: str): global _plt_module plt = _plt_module - + lhs, rhs = parse_implicit(func_expr) - + x_range = 20 y_range = 20 - + x_vals = [] y_vals = [] - + for xi in range(-x_range * 10, x_range * 10 + 1): x = xi / 10.0 for yi in range(-y_range * 10, y_range * 10 + 1): @@ -139,7 +143,10 @@ class Plot(commands.Cog): y_vals.append(y) except Exception: pass - + + if not x_vals or not y_vals: + raise ValueError("Brak danych do wykreślenia dla podanej funkcji") + fig, ax = plt.subplots(figsize=(10, 10)) ax.scatter(x_vals, y_vals, s=1, color="#00ff00", alpha=0.5) ax.set_title(f"{func_expr}", fontsize=14) @@ -153,7 +160,7 @@ class Plot(commands.Cog): ax.set_aspect("equal") ax.set_facecolor("#1a1a1a") fig.patch.set_facecolor("#1a1a1a") - + plt.savefig(output_path, dpi=100, bbox_inches="tight") plt.close() @@ -185,4 +192,4 @@ class Plot(commands.Cog): def setup(bot): - bot.add_cog(Plot(bot)) \ No newline at end of file + bot.add_cog(Plot(bot)) -- cgit v1.2.3