From 059b22df4df431489fd6c1bb158b92ed97935cf2 Mon Sep 17 00:00:00 2001 From: mioupa <79833278+mioupa@users.noreply.github.com> Date: Thu, 12 Nov 2026 15:03:49 +0900 Subject: [PATCH 01/10] Design Phase 5d (box, violin, heatmap, custom-function fits) and record the decisions Split the original 5d into 5d (G8, G10) and 5e (G9 subplots). Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 1 + docs/PHASE5_DESIGN.md | 154 ++++++++++++++++++++++++++++++++++++++++++ docs/REQUIREMENTS.md | 7 +- 3 files changed, 161 insertions(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index 25f4edf..bd04eeb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -405,3 +405,4 @@ uv run pytest tests/e2e # E2E(Chromium とローカルの静的サー - G6: 列は `[N]` か Excel の列記号(`A` = `[0]`)で参照する。式は許可した要素だけを自前で解釈し(`eval` を使わない)、生成コードは解釈した結果から決まった形で書く。 - 5b(2026-11-10): 系列の複製は全設定を写し、色だけパレットの未使用の色にして直後に入れる(近似曲線は写さない)。近似曲線の式は「温度の近似: y = 1.234x + 5.678(R² = 0.9981)」(係数は有効数字4桁、R² は小数4桁で固定。「図の中」は左上に並べる)。文字列の X・棒グラフの X では、注釈の X は「何番目のカテゴリか(0 始まり)」。画面の「透明度」は「不透明度」(0〜1、alpha と同じ向き)と表示する。 - 5c(2026-11-12): ヒストグラムの複数系列は区間ごとに横に並べる(区間は全系列で共通)。計算した列の式から、ほかの計算した列は参照できない(読み直しで列の数が変わると式の列番号を直せないため。複数の処理は1つの式に書く)。計算した列は「描画から除外する先頭行」を除いた行で計算し(集計もその行だけ)、データ確認タブには出さない。色分け散布図は、凡例の点を灰色にし、第2Y軸は使えず、色の範囲は全系列共通で自動(指定なし)。重さは普通の散布図と同じ見た目で作って計測し、1 秒を超えたら見直す。→ 計測で約 1.21 秒になったため、点の縁を描かず、縁の太さ(1.5 pt)の分だけ点の面積を大きくすることにした(約 0.94 秒。点の形が x / + のときは縁を描く。2026-11-12 にユーザーが決定)。 +- 5d・5e(2026-11-12): 5d を2本に分ける(5d: G8・G10、5e: G9。G9 は軸が1組という前提を全体で変え、G8 の種類もパネルに載せるため後にする。5e の詳しい設計は 5d のマージ後に相談)。ヒートマップは X・Y・値の3列から格子を作る(同じ組は平均、系列は1つ)。箱ひげ図・バイオリン図は系列ごとに左から並べ、塗りは系列の色、ひげは 1.5×IQR、外れ値は表示・平均は非表示が既定、縦向きだけ、凡例なし。任意関数のフィッティングは変数 `x` とパラメータ `a`〜`e`、初期値の既定 1、表示は「y = 式(a = …、R² = …)」。dev の依存に scipy を足す。 diff --git a/docs/PHASE5_DESIGN.md b/docs/PHASE5_DESIGN.md index 43713da..9971f21 100644 --- a/docs/PHASE5_DESIGN.md +++ b/docs/PHASE5_DESIGN.md @@ -565,3 +565,157 @@ ax.plot(x_fit, fit(x_fit), color="#FF4B00", linewidth=2.0, linestyle="dashed", l 2. **計算した列からほかの計算した列は参照できない**、でよいか(読み直しで列の数が変わったとき、式の中の列番号は直せないため。「正規化してから移動平均」は `rolling_mean([1] / max([1]), 5)` のように1つの式に書ける)。 3. **計算する行**: 「描画から除外する先頭行」を除いた行で計算する(`max` や `first` もその行だけ)。データ確認タブには計算した列を出さない。これでよいか。 4. **色分け散布図**: 凡例の点は灰色、第2Y軸は使えない、色の範囲は全系列共通で自動(範囲の指定は無し)。重さは §6.6 のとおり計測してから判断する。これでよいか。 + +--- + +## 7. 5d の詳細(G8 グラフの種類 第2弾、G9 サブプロット、G10 任意関数のフィッティング) + +作成: 2026-11-12。2026-11-12 にユーザーが承認(§7.8 はすべて提案どおり。5d と 5e に分け、ヒートマップは案 H2)。 + +### 7.0 準備 + +- PR #7(5b)は main にマージ済み。#8(5c)は CI の実行中で、まだマージしていない。5d は `phase5c-data` から `phase5d-more` を作って進め、PR は #8 のマージ後に main 向きで作る(#6 のように main 以外にマージされるのを防ぐため)。 +- スキーマは v4 のまま、項目を足す(§2.1)。新しい項目の既定値では、生成コードは Phase 4 と1文字も変わらない(ゴールデンテスト)。 +- scipy(G10、U5): Pyodide 314.0.3 の同梱パッケージに scipy 1.18.0 がある。依存は numpy だけで、numpy は読み込み済みなので、初めて使うときに取得するのは wheel 1つ(約 14.0 MB)。`pyodide_js.loadPackage(["scipy"])` と名前で読むと、取得先は Pyodide の版を含む jsDelivr の URL(`/pyodide/v314.0.3/full/`)で、ハッシュも確かめられる。リポジトリに URL を書かないので、`test_cdn_pinning.py` は変えなくてよい。 +- 開発環境には scipy が無い。単体テストで生成コードを実行するため、`pyproject.toml` の dev グループに `scipy==1.18.0`(ブラウザと同じ版)を足す(実行時には使わない。openpyxl と同じ扱い)。 +- CPython での実測(10,000 行 × 5 系列、8×6 inch、dpi 100、PNG まで、中央値): 箱ひげ図 22 ms、バイオリン図 43 ms、ヒートマップ(10,000 行を 100×100 の格子に集計 + `pcolormesh` + カラーバー)31 ms。参考: 今の line(5 本、凡例の位置 best)198 ms。`curve_fit`(`a*exp(-b*x)+c`、10,000 点 × 5 系列)6 ms。2×2 のサブプロット(線 8 本)154 ms(1つの軸に 8 本だと 299 ms。凡例の位置の探索が軸ごとに小さくなるため)。 + +### 7.1 PR の分け方(提案: 5d と 5e に分ける) + +| PR | 内容 | +|---|---| +| **5d** | G8(箱ひげ図・バイオリン図・ヒートマップ)、G10(任意関数のフィッティング) | +| **5e** | G9(サブプロット) | + +- G9 は、今のコード生成の「軸は `ax` と `ax2` の1組」という前提を、ほぼすべての出力(系列・注釈・近似曲線・軸・グリッドと凡例・カラーバー・ヒストグラムの共通の区間)で変える。G8 の新しい種類もパネルに載せる必要があるので、G8 の後にまとめて作るほうが作り直しが無い。 +- G8・G10 は、今の構造にグラフの種類と近似のモデルを足すだけで済む。 +- 5e の詳しい設計は、5d のマージ後に改めて相談する(§7.5 は方針だけ)。 + +### 7.2 追加する設定項目(v4 に足す) + +| キー | 既定値 | 受け付ける値・検証 | +|---|---|---| +| `plot.type` | `"line"` | `box` / `violin` / `heatmap` を足す | +| `plot.box` | `{fliers: true, means: false}` | 外れ値の点を描くか、平均の印を描くか(真偽)。`box` のときだけ使う | +| `plot.violin` | `{medians: true, means: false}` | 中央値の線・平均の線を描くか(真偽)。`violin` のときだけ使う | +| `plot.colormap` / `plot.colorbarLabel` | 今のまま | `heatmap` でも使う(色分け散布図と共有) | +| `series[].colorColumn` | 今のまま | `heatmap` でも使い、必須(ヒートマップの値。画面の欄名は「値の列」にする) | +| `fits[].model` | `"linear"` | `custom`(任意の式)を足す | +| `fits[].expr` | `""` | 任意の式。`custom` のときだけ使う。200 文字まで、空はエラー(「近似曲線Nの式を入力してください。」) | +| `fits[].initial` | `{a: 1, b: 1, c: 1, d: 1, e: 1}` | パラメータの初期値。式で使うパラメータの分だけ検証する(有限の数。誤りは「近似曲線Nの初期値(a)」) | + +### 7.3 G8 グラフの種類 第2弾 + +種類ごとに使う設定(§2.2。§6.2 の表に3列を足す): + +| 設定 | box | violin | heatmap | +|---|---|---|---| +| 系列の X 列 | – | – | ○ | +| X列(全系列共通。`#xColumn`) | – | – | – | +| Y 列 | ○(箱にする値) | ○(胴にする値) | ○ | +| 色分けの列(「値の列」) | – | – | ○(必須) | +| 点の形・点サイズ | – | – | – | +| 線幅 | ○(箱の縁・ひげ) | ○(胴の縁) | – | +| 線種 | – | – | – | +| 色 | ○(箱の塗り) | ○(胴の塗り) | –(カラーマップを使う) | +| 不透明度 | ○ | ○ | ○ | +| エラーバー・塗りつぶし帯・第2Y軸・近似曲線 | – | – | – | +| 注釈 | ○ | ○ | ○ | + +1. **箱ひげ図(`box`)**: 系列ごとに1つの箱を、左から系列の順に 0, 1, 2, … の位置に描く(`ax.boxplot(..., positions=[0, 1, …], tick_labels=[凡例名, …], patch_artist=True)`。`tick_labels` は matplotlib 3.9 からの名前)。 + - 箱の塗りは系列の色と不透明度、縁・ひげ・中央値の線は黒。ひげは matplotlib の既定(箱の端から 1.5×IQR まで)。外れ値の点と平均の印は `plot.box` で切り替える。 + - 値は `pd.to_numeric(...).dropna()` にしてから渡す(NaN が混ざると中央値が NaN になるため)。数値にできない値は、今の系列と同じ形で警告する。値が無い系列は、位置を空けたまま描かない(警告)。 +2. **バイオリン図(`violin`)**: 同じ並べ方で、系列ごとに `ax.violinplot(..., positions=[i])` を呼ぶ(系列ごとに色を付けやすい)。 + - 胴の塗りは系列の色と不透明度。中央値・端の線も系列の色。密度の推定は matplotlib の既定(Scott の方法、100 点)。 + - 値が 2 個未満の系列は、密度を推定できないので描かない(警告)。 + - 箱ひげ図・バイオリン図の軸: + - 横軸はカテゴリ(系列の凡例名)。目盛は「何個おき」、注釈の X は「何番目か(0 始まり)」で、棒グラフと同じ。 + - 縦軸は数値か対数。Y が日時の列はエラーにする。 + - 系列ごとにデータ元が違ってもよい(ヒストグラムと同じ)。 + - 自動の軸ラベルは、横軸が空。縦軸は、系列が1つならその Y 列の名前、2つ以上なら空。 + - 凡例は出さない(名前は目盛に出る)。向きは縦だけ(横向きは作らない)。 +3. **ヒートマップ(`heatmap`)**: データの形は §7.8 の 2 で決める。推奨は案 H2(X・Y・値の3列の縦長の表から格子を作る)。 + ```python + heat = pd.DataFrame({"x": x[ok], "y": y[ok], "z": c[ok]}).pivot_table(index="y", columns="x", values="z", aggfunc="mean") + mesh = ax.pcolormesh(heat.columns.to_numpy(), heat.index.to_numpy(), heat.to_numpy(), cmap="viridis", shading="nearest") + colorbar = fig.colorbar(mesh, ax=ax) + ``` + - 同じ X・Y の組が複数あれば、平均を描く(件数を警告)。値の無いマスは塗らない。 + - X・Y は数値の列か文字列の列(文字列は現れた順にカテゴリとして並べる)。日時の列は 5d では使えない(日本語のエラー)。 + - X・Y の異なる値は、それぞれ 500 種類まで。多すぎるとマスが細かくなりすぎるうえ、格子でないデータを選んだ取り違えのことが多い。超えたら日本語のエラーにする(上限は計測して見直す)。 + - 系列は1つだけ。2つ以上はエラー(「ヒートマップは系列1つで描きます。」)。ヒートマップを並べるのは G9(5e)のパネルで行う。 + - H2 を推奨する理由: 色分け散布図と同じ3列(X・Y・色分けの列)を使うので、種類を切り替えても設定がそのまま使える。測定の格子(走査したマップなど)の縦長の表をそのまま描ける。 + - 案 H1(行列の表): 表を行列として扱い、系列の Y 列を左から並べて列にし、行は X列(`#xColumn`)の値にする。「1列目が軸、残りの列が測定値」の表(分光の時間変化など)に向く。ただし列が多いと、系列を1つずつ足すことになる。 + +### 7.4 G10 任意関数のフィッティング + +- 近似曲線のモデルに「任意の式」(`custom`)を足す。 +- 式は G6 の解釈器(`expr.py`)に「モデルの式」の入口(`parse_model`)を足して解釈する。 + - 使えるもの: 変数 `x`、パラメータ `a`〜`e`(式で使ったものだけ。1つ以上)、数、`+ - * /`、`**`(`^`)、括弧、要素ごとの関数(`abs sqrt exp log log10 sin cos tan`)。 + - 集計・系列の処理・列の参照は、日本語のエラーにする。`x` を含まない式もエラー。 +- 生成コード(近似曲線を描く位置は今と同じく、系列本体の直後): + ```python + def fit_model_1(x, a, b, c): # 近似曲線1の式: a * exp(-b * x) + c + return a * np.exp(-b * x) + c + fit_params, _ = curve_fit(fit_model_1, x[ok], y[ok], p0=[1.0, 1.0, 1.0], maxfev=10000) + r2 = 1 - np.sum((y[ok] - fit_model_1(x[ok], *fit_params)) ** 2) / np.sum((y[ok] - y[ok].mean()) ** 2) + x_fit = np.linspace(x[ok].min(), x[ok].max(), 200) + ax.plot(x_fit, fit_model_1(x_fit, *fit_params), color=..., linewidth=..., linestyle=..., label=...) + ``` + - 関数の本体は、解釈した木から決まった形で書く(`to_code`)。利用者が書いた式の文字列は、`comment_text()` を通してコメントにだけ入る。 + - `from scipy.optimize import curve_fit` は、任意の式の近似曲線があるときだけ冒頭の import に足す。「使い方」に scipy が要ることを書く。 +- 表示: 「温度の近似: y = a*exp(-b*x) + c(a = 1.234, b = 0.5678, c = 9.012、R² = 0.9981)」。 + - 式は、解釈した木から整えた形で書く(利用者の文字列そのままではない)。 + - パラメータは有効数字4桁で、実行時に `fit_params` から作る。 + - 表示先(凡例・図の中・なし)は今と同じ。 +- エラー: + - 収束しない(`curve_fit` の RuntimeError)、初期値で計算できない値になる(ValueError)は、手順(`Step`)で「近似曲線N: 式を当てはめられませんでした。初期値を変えてみてください。」に置き換える。 + - 点の数がパラメータの数以下のときは、dataprep が先に日本語のエラーにする。 + - X が日時・文字列の系列などは、今の近似曲線と同じ。 +- scipy の読み込み(U5): openpyxl と同じく、初めて必要になったときだけ `ensureScipy()` で読み込む。 + - GUI 同期では、描画・保存・コピーの前に、任意の式の近似曲線が使われていれば読み込む。進捗には「scipy を読み込み中…(初回のみ)」と出す。 + - 編集モードでは、コードに `import scipy` / `from scipy` があれば、実行前に読み込む。 + - 読み込めなければ、日本語のエラーにする(「scipy を読み込めませんでした。インターネット接続を確かめてください。」)。 + - コードだけの更新(`script`)では読み込まない。runner の ImportError の案内に scipy を足す。 + +### 7.5 G9 サブプロット(5e。方針だけ) + +- 図の分け方は `plot.layout = {rows, cols}`(1〜4。既定は 1×1 で、今と同じ)。 +- 系列ごとにパネルを選ぶ(`series[].panel`)。注釈もパネルを選ぶ。近似曲線は系列のパネルに描く。 +- 生成コードは、`fig, axs = plt.subplots(行, 列, squeeze=False)` の後、パネルごとの節で `ax = axs[0, 1]` と置き直す。系列・注釈・軸・グリッドと凡例は、今の書き方をそのまま使う(第2Y軸もパネルごとに `ax2 = ax.twinx()`)。1×1 のときは、今のコードと1文字も変えない。 +- 軸の設定(スケール・範囲・目盛)は全パネル共通。タイトルと軸ラベルは、パネルごとに上書きできる。グラフの種類も全パネル共通。 +- (a)(b) のラベルは各パネルの左上に置く(`ax.set_title("(a)", loc="left")`。注釈の数え方を変えないため)。 +- 詳しい設計(系列の無いパネル、色分け散布図のカラーバー、ヒストグラムの区間をパネルで共有するか、など)は、5d のマージ後に相談する。 + +### 7.6 性能の見込み + +- 箱ひげ図・バイオリン図・ヒートマップは、今の line(5 系列)より軽い(§7.0 の実測)。 +- 任意の式の近似曲線の計算は数 ms。初回だけ scipy の取得(約 14 MB)と読み込みに数秒かかる。 +- 計測(`--only p5d`): + - 箱ひげ図・バイオリン図(10,000 行 × 5 系列)の設定変更 → 再描画。 + - ヒートマップ(10,000 行を 100×100 の格子に)の設定変更 → 再描画。 + - 任意の式の近似曲線(5 系列)の設定変更 → 再描画。 + - scipy の初回読み込み(近似曲線を「任意の式」にしてから、図が出るまで)。参考値で、ネットワークに左右される。 + +### 7.7 テスト + +- 単体: + - `test_expr.py`(モデルの式): `x` と `a`〜`e`、使えない要素のエラー、`e` と `exp` と `1e-3` の区別、使ったパラメータの順。 + - `test_chart_types.py`: box / violin / heatmap の artist、隠れる設定、NaN と値の無い系列、ヒートマップの集計・欠けたマス・上限・文字列の軸、自動のラベル、注釈の X。 + - `test_fits.py`(任意の式): scipy で直接当てはめた値との一致、表示の文字、収束しないときの手順のメッセージ、点の不足、注入。 + - どれも「全体を実行した図」と「自動描画用の図」が一致することを確かめる。既定の設定はゴールデンテストで確かめる。 +- `figure_summary` に、箱・バイオリンを数えるキーを足す(例 `boxes` / `violins`。ヒートマップは `colorbar` と `meshes`)。 +- E2E: + - 種類ごとの欄の出し分けと `data-summary`。 + - ヒートマップの値の列が未選択のときと、系列が2つのときのエラーと復帰。 + - 任意の式の近似曲線(scipy を実際に読み込む。インターネット接続が必要)。 + - 編集モードで scipy を import するコード。 + - 狭い画面。 + - 一致確認に box / violin / heatmap / 任意の式を足す。 + +### 7.8 確認したいこと + +1. **PR の分け方**: 5d(G8・G10)と 5e(G9)に分けてよいか(§7.1。推奨)。分けない場合は、G9 の詳細もこの設計に足す。 +2. **ヒートマップのデータの形**: 案 H2(X・Y・値の3列の縦長の表から格子を作る。推奨)か、案 H1(系列の Y 列を並べて行列にする)か(§7.3)。 +3. **箱ひげ図・バイオリン図の見た目**: 箱・胴の塗りは系列の色。ひげは 1.5×IQR。外れ値は表示・平均は非表示が既定。向きは縦だけで、凡例は出さない。これでよいか。 +4. **任意の式**: パラメータは `a`〜`e` の5つまで、初期値の既定は 1、表示は「y = 式(a = …, b = …、R² = …)」。開発用の依存に scipy を足す。これでよいか。 diff --git a/docs/REQUIREMENTS.md b/docs/REQUIREMENTS.md index f404442..36d43cf 100644 --- a/docs/REQUIREMENTS.md +++ b/docs/REQUIREMENTS.md @@ -63,7 +63,7 @@ ### 2.5 Phase 5 の決定事項(2026-11-10 にユーザーが決定) -- PR を4本に分ける。5a: G1・G2。5b: G3・G4・G5 と「注釈・解析」の区分。5c: G6・G7。5d: G8–G10。「注釈・解析」の区分は、中身が入る 5b で作る(空の区分を作らないため)。 +- PR を4本に分ける。5a: G1・G2。5b: G3・G4・G5 と「注釈・解析」の区分。5c: G6・G7。5d: G8–G10。「注釈・解析」の区分は、中身が入る 5b で作る(空の区分を作らないため)。→ 5d を2本に分けた(2026-11-12)。5d: G8・G10、5e: G9(下記)。 - 設定スキーマを version 4 にする(5a)。5b〜5d は v4 に項目を足す。新しい項目の既定値は、どれも v3 の出力を変えない値にする。v3 からの移行は version を上げるだけ。後の PR で既存の項目の意味を変えるときは、version 5 にする。 - 画面で隠した設定(グラフの種類や軸の種類で使えない設定)は図に使わない。値は消さないので、戻せば効く。表示している設定どうしが組み合わせとして使えないときは、日本語のエラーで案内する。 - エラーバー(G1): @@ -91,6 +91,11 @@ - 計算した列は「描画から除外する先頭行」を除いた行で計算する(`max` や `first` などの集計も、その行だけを使う)。データ確認タブには計算した列を出さない(読み込んだファイルの内容だけを出す)。 - 色分け散布図: 凡例の点は灰色にする(色はカラーバーで読む)。第2Y軸は使えない(カラーバーと第2Y軸の位置がずれるため)。色の範囲は全系列で共通にし、自動で決める(範囲の指定は無し)。描画の重さは、普通の散布図と同じ見た目で作ってブラウザで計測し、1 秒を超えたら見直す。 - 色分け散布図の点は、縁を描かない(2026-11-12 にユーザーが決定)。点ごとに色が違うと matplotlib が点の縁を1点ずつ描くため、10,000 行 × 5 系列の再描画がブラウザで約 1.21 秒かかり、1 秒を超えた。縁を描かず、縁の太さ(1.5 pt)の分だけ点の面積を大きくして、見た目の点の大きさを普通の散布図にそろえる(約 0.94 秒)。点の形が「x」「+」のときは、線だけでできた点なので、縁を描く(今までの描き方)。 +- 5d・5e(G8–G10、2026-11-12): + - PR を 5d(G8 グラフの種類 第2弾、G10 任意関数のフィッティング)と 5e(G9 サブプロット)に分ける。G9 は図の軸が1組という前提をコード生成のほぼすべてで変え、G8 の新しい種類もパネルに載せる必要があるため、G8 の後に作る。5e の詳しい設計は、5d のマージ後に相談する。 + - ヒートマップは、X・Y・値の3列(縦長の表)から格子を作る(色分け散布図と同じ3列)。同じ X・Y の組は平均を描き、値の無いマスは塗らない。系列は1つだけ。 + - 箱ひげ図・バイオリン図は、系列ごとに1つずつ左から並べる。箱・胴の塗りは系列の色、ひげは箱の端から 1.5×IQR まで、外れ値は表示・平均は非表示が既定。向きは縦だけで、凡例は出さない(名前は目盛に出す)。 + - 任意関数のフィッティングの式は、変数 `x` とパラメータ `a`〜`e`(5つまで)で書く。初期値の既定は 1。表示は「y = 式(a = …, b = …、R² = …)」。開発用の依存(単体テスト用)に scipy を足す(ブラウザと同じ版。実行時は U5 のとおり使うときだけ読み込む)。 --- From cd48a7157746176ac9050148fc660b3b7274fd42 Mon Sep 17 00:00:00 2001 From: mioupa <79833278+mioupa@users.noreply.github.com> Date: Thu, 12 Nov 2026 15:08:02 +0900 Subject: [PATCH 02/10] Add fit-model expressions (x and parameters a-e) to the expression parser (Phase 5d, G10) Co-Authored-By: Claude Opus 5.5 --- py/mplgui/expr.py | 156 +++++++++++++++++++++++++++++- tests/unit/test_expr.py | 204 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 357 insertions(+), 3 deletions(-) diff --git a/py/mplgui/expr.py b/py/mplgui/expr.py index eeabdff..5f74f9c 100644 --- a/py/mplgui/expr.py +++ b/py/mplgui/expr.py @@ -27,6 +27,11 @@ _NAME_HINT = "列は [N] か大文字の列記号(A, B, …)で、関数は max( のように書いてください" _CONST_MESSAGE = "計算できない定数があります(0 での割り算など)" +MODEL_VARIABLE = "x" +MODEL_PARAMS = ("a", "b", "c", "d", "e") +_MODEL_NAME_HINT = "使える名前は x と a〜e です" +_MODEL_COLUMN_MESSAGE = "近似の式では列は使えません(変数は x、パラメータは a〜e です)。" + _KIND_ORDER = {"const": 0, "scalar": 1, "series": 2} @@ -86,7 +91,16 @@ class Call: kind: str = field(default="const", compare=False, repr=False) -Node = Number | Column | Unary | Binary | Call +@dataclass(frozen=True) +class Var: + """近似の式(モデル)の変数 x とパラメータ a〜e。""" + + name: str + pos: int + kind: str = field(default="scalar", compare=False, repr=False) + + +Node = Number | Column | Unary | Binary | Call | Var # ---- 字句解析 --------------------------------------------------------------- @@ -128,7 +142,7 @@ def _excel_index(letters: str) -> int: return n - 1 -def _tokenize(s: str) -> list[_Tok]: +def _tokenize(s: str, model: bool = False) -> list[_Tok]: toks: list[_Tok] = [] n = len(s) i = 0 @@ -142,6 +156,8 @@ def _tokenize(s: str) -> list[_Tok]: toks.append(_Tok("num", m.group(), pos, float(m.group()))) i = m.end() elif c == "[": + if model: + raise ExprError(_MODEL_COLUMN_MESSAGE, pos) m = _COLUMN.match(s, i) if m is None: raise ExprError("列は [0] のように、角括弧の中に番号を書いてください", pos) @@ -154,6 +170,10 @@ def _tokenize(s: str) -> list[_Tok]: while j < n and s[j] in " \t": j += 1 paren = j < n and s[j] == "(" + if model: + _model_ident(toks, name, pos, paren) + i = m.end() + continue if name.isalpha() and name.isupper(): if paren: raise ExprError(f"関数名は小文字で書いてください({name.lower()})", pos) @@ -195,6 +215,29 @@ def _tokenize(s: str) -> list[_Tok]: return toks +def _model_ident(toks: list[_Tok], name: str, pos: int, paren: bool) -> None: + if name.isalpha() and name.isupper() and not paren and len(name) <= 3: + raise ExprError(_MODEL_COLUMN_MESSAGE, pos) + if name in ELEMENTWISE: + if not paren: + raise ExprError( + f"「{name}」は関数です。{name}( のように、括弧で値を指定してください", pos + ) + toks.append(_Tok("func", name, pos, name)) + elif name in AGGREGATES or name in SERIES_FUNCS: + raise ExprError( + f"「{name}」は近似の式では使えません。使える関数: {', '.join(ELEMENTWISE)}", pos + ) + elif paren: + raise ExprError( + f"「{name}」という関数はありません。使える関数: {', '.join(ELEMENTWISE)}", pos + ) + elif name == MODEL_VARIABLE or name in MODEL_PARAMS: + toks.append(_Tok("var", name, pos, name)) + else: + raise ExprError(f"「{name}」は使えません。{_MODEL_NAME_HINT}", pos) + + # ---- ノードの生成(種類の判定と定数の畳み込み) -------------------------------- @@ -293,7 +336,7 @@ def leave(self) -> None: self.depth -= 1 def _is_value_start(self, t: _Tok) -> bool: - return t.kind in ("num", "col", "func", "(") + return t.kind in ("num", "col", "func", "var", "(") def _unexpected(self, lparen: _Tok | None) -> ExprError: """式の途中で、演算子や閉じ括弧でないものが来たときの誤り。""" @@ -368,6 +411,9 @@ def atom(self) -> Node: if t.kind == "col": self.advance() return Column(t.value, t.pos) + if t.kind == "var": + self.advance() + return Var(t.value, t.pos, "series" if t.value == MODEL_VARIABLE else "scalar") if t.kind == "func": self.advance() lp = self.advance() # tokenizer guarantees "(" @@ -411,6 +457,26 @@ def parse(text: str) -> Node: return node +def parse_model(text: str) -> Node: + """近似の式(変数 x、パラメータ a〜e)を解釈する。""" + if len(text) > MAX_LENGTH: + raise ExprError(f"式は{MAX_LENGTH}文字までです") + s = _normalize(text) + if not s.strip(" \t"): + raise ExprError("式を入力してください") + toks = _tokenize(s, model=True) + try: + node = _Parser(toks).parse_top() + except RecursionError: + raise ExprError(_DEPTH_MESSAGE) from None + names = _var_names(node) + if MODEL_VARIABLE not in names: + raise ExprError("式に x を含めてください。") + if not any(p in names for p in MODEL_PARAMS): + raise ExprError("式にパラメータ(a〜e)を1つ以上含めてください。") + return node + + # ---- 木の調査 --------------------------------------------------------------- @@ -424,6 +490,23 @@ def _children(node: Node) -> tuple: return () +def _var_names(node: Node) -> set[str]: + names: set[str] = set() + stack = [node] + while stack: + n = stack.pop() + if isinstance(n, Var): + names.add(n.name) + stack.extend(_children(n)) + return names + + +def model_params(node: Node) -> tuple[str, ...]: + """式で使っているパラメータ(a〜e の順。1つにつき1回)。""" + names = _var_names(node) + return tuple(p for p in MODEL_PARAMS if p in names) + + def column_refs(node: Node) -> tuple[tuple[int, int], ...]: refs: list[tuple[int, int]] = [] stack = [node] @@ -540,6 +623,8 @@ def go(nd: Node) -> tuple[str, int]: if isinstance(nd, Number): s = number(float(nd.value)) return s, (_P_UNARY if s.startswith("-") else _P_ATOM) + if isinstance(nd, Var): + return nd.name, _P_ATOM if isinstance(nd, Column): return column_var(nd.index), _P_ATOM if isinstance(nd, Unary): @@ -577,3 +662,68 @@ def go(nd: Node) -> tuple[str, int]: return f"{base}.{name}()", _P_ATOM return go(node)[0] + + +def model_to_code(node: Node, number: Callable[[float], str]) -> str: + """近似の式の numpy コード(名前は x, a〜e のまま。入力文字列は写さない)。""" + return to_code(node, lambda i: "", number) + + +def _format_number(v: float) -> str: + return "%.15g" % v + + +def model_to_text(node: Node) -> str: + """図のラベル用の、木から整えた式(ASCII だけ。例: a*exp(-b*x) + c)。""" + + def go(nd: Node) -> tuple[str, int]: + if isinstance(nd, Number): + s = _format_number(float(nd.value)) + return s, (_P_UNARY if s.startswith("-") else _P_ATOM) + if isinstance(nd, Var): + return nd.name, _P_ATOM + if isinstance(nd, Unary): + s, p = go(nd.operand) + if p <= _P_UNARY: + s = f"({s})" + return f"-{s}", _P_UNARY + if isinstance(nd, Binary): + op = nd.op + prec = _OP_PREC[op] + ls, lp = go(nd.left) + rs, rp = go(nd.right) + if op == "**": + lparen, rparen = lp <= _P_POW, rp < _P_UNARY + else: + lparen, rparen = lp < prec, rp <= prec + if lparen: + ls = f"({ls})" + if rparen: + rs = f"({rs})" + if op in ("+", "-"): + return f"{ls} {op} {rs}", prec + return f"{ls}{'^' if op == '**' else op}{rs}", prec + s, _ = go(nd.args[0]) + return f"{nd.name}({s})", _P_ATOM + + return go(node)[0] + + +def evaluate_model(node: Node, x, params: Mapping[str, float]) -> np.ndarray: + """近似の式を numpy で評価する(model_to_code と同じ意味)。""" + xs = np.asarray(x, dtype=float) + ps = {k: np.float64(v) for k, v in params.items()} + + def go(nd: Node): + if isinstance(nd, Number): + return float(nd.value) + if isinstance(nd, Var): + return xs if nd.name == MODEL_VARIABLE else ps[nd.name] + if isinstance(nd, Unary): + return -go(nd.operand) + if isinstance(nd, Binary): + return _BINARY_OPS[nd.op](go(nd.left), go(nd.right)) + return getattr(np, nd.name)(go(nd.args[0])) + + with np.errstate(all="ignore"): + return np.broadcast_to(np.asarray(go(node), dtype=float), xs.shape).copy() diff --git a/tests/unit/test_expr.py b/tests/unit/test_expr.py index 6798c55..be8c12c 100644 --- a/tests/unit/test_expr.py +++ b/tests/unit/test_expr.py @@ -324,3 +324,207 @@ def test_invalid_count_aggregate(): assert count == 1 and r.isna().all() r, count = run("max([2]) + 1") assert count == 0 + + +# ---- 近似の式(モデル。G10) ------------------------------------------------- + +MODELS = [ + "a*exp(-b*x) + c", + "a*x^2 + b*x + c", + "a/(1 + exp(-b*(x - c)))", + "a*sin(b*x + c) + d", + "-a^2 * x", + "a^b^c + x", + "(a + b)*(x - e)/2", + "a*x**-b + 1e-3", + "a - (b - x)", + "a/(b*x)", + "log(abs(x) + 1)*a + sqrt(b**2)", +] + + +def merr(text): + with pytest.raises(ExprError) as e: + expr.parse_model(text) + return e.value + + +def mcode(text): + return expr.model_to_code(expr.parse_model(text), repr) + + +def mrun(text, x, **p): + ns = {"np": np, "x": x, **{k: np.float64(v) for k, v in p.items()}} + with np.errstate(all="ignore"): + return eval(mcode(text), ns) # テスト内だけで使う + + +@pytest.mark.parametrize("text", MODELS) +def test_model_accepted(text): + node = expr.parse_model(text) + assert expr.model_params(node) + + +def test_model_params_order_and_dedup(): + assert expr.model_params(expr.parse_model("c*x + a*x + c")) == ("a", "c") + assert expr.model_params(expr.parse_model("e*x + d + b")) == ("b", "d", "e") + + +def test_model_e_vs_number_vs_exp(): + n = expr.parse_model("1e-3*x + e") + assert expr.model_params(n) == ("e",) + assert expr.model_to_text(n) == "0.001*x + e" + n = expr.parse_model("2.5E3*x + a") + assert expr.model_to_text(n) == "2500*x + a" + n = expr.parse_model("exp(x) + e") + assert expr.model_params(n) == ("e",) + assert expr.model_to_code(n, repr) == "np.exp(x) + e" + + +def test_model_errors_with_positions(): + e = merr("a*[0]*x") + assert (e.message, e.position) == ( + "近似の式では列は使えません(変数は x、パラメータは a〜e です)。", + 3, + ) + e = merr("a*A + x") + assert e.position == 3 and "列は使えません" in e.message + assert merr("a*BC*x").position == 3 + for name in ("min", "max", "mean", "median", "std", "first", "last"): + e = merr(f"a*{name}(x)") + assert e.position == 3 and "近似の式では使えません" in e.message and "sqrt" in e.message + for name in ("rolling_mean", "diff", "cumsum"): + e = merr(f"{name}(x)*a") + assert e.position == 1 and "近似の式では使えません" in e.message + assert merr("a + 1").message == "式に x を含めてください。" + assert merr("a*2*3").message == "式に x を含めてください。" + assert merr("x + 1").message == "式にパラメータ(a〜e)を1つ以上含めてください。" + e = merr("a*y + x") + assert e.position == 3 and "使える名前は x と a〜e です" in e.message + assert merr("f*x").position == 1 + assert merr("a*x + k").position == 7 + e = merr("2e") + assert e.position == 2 and "演算子" in e.message + assert merr("a*x ab").position == 5 + assert merr("a(x)").position == 1 + assert merr("exp").position == 1 + assert merr("").message == "式を入力してください" + + +def test_model_normal_parse_unchanged(): + for text in ("x", "a", "x + [0]", "a*[0]"): + with pytest.raises(ExprError) as e: + parse(text) + assert "使えません" in e.value.message + assert parse("[0] + 1").kind == "series" + + +def test_model_fullwidth(): + n = expr.parse_model("a*exp(-b*x)+c") + assert expr.model_to_text(n) == "a*exp(-b*x) + c" + + +def test_model_precedence_and_assoc(): + x = np.array([0.5, 1.0, 2.0]) + assert np.allclose(mrun("-a^2 + 0*x", x, a=3), -9.0) # -(a^2) + assert np.allclose(mrun("a^b^c + 0*x", x, a=2, b=3, c=2), 2**9) + assert np.allclose(mrun("(-a)^2 + 0*x", x, a=3), 9.0) + assert np.allclose(mrun("a - (b - x)", x, a=1, b=5), 1 - (5 - x)) + assert expr.model_to_text(expr.parse_model("-a^2 + x")) == "-a^2 + x" + assert expr.model_to_text(expr.parse_model("(-a)^2 + x")) == "(-a)^2 + x" + assert expr.model_to_text(expr.parse_model("a^b^c + x")) == "a^b^c + x" + assert expr.model_to_text(expr.parse_model("(a^b)^c + x")) == "(a^b)^c + x" + assert expr.model_to_code(expr.parse_model("(a^b)^c + x"), repr) == "(a ** b) ** c + x" + + +@pytest.mark.parametrize("text", MODELS) +@pytest.mark.parametrize("kind", ["array", "series"]) +def test_model_code_matches_evaluate(text, kind): + xs = np.array([0.1, 0.5, 1.0, 2.0, 3.5]) + x = xs if kind == "array" else pd.Series(xs, index=range(5, 10)) + params = {"a": 1.3, "b": 0.7, "c": 2.0, "d": -0.4, "e": 1.1} + node = expr.parse_model(text) + got = np.asarray(mrun(text, x, **params), dtype=float) + want = expr.evaluate_model(node, xs, params) + assert np.allclose(got, want, equal_nan=True) + assert want.shape == xs.shape + + +def test_model_code_as_function_body(): + code = mcode("a*exp(-b*x) + c") + ns = {"np": np} + exec(f"def f(x, a, b, c):\n return {code}\n", ns) # テスト内だけで使う + x = np.linspace(0, 2, 5) + assert np.allclose(ns["f"](x, np.float64(2), np.float64(1), np.float64(0.5)), 2 * np.exp(-x) + 0.5) + assert expr.evaluate_model(expr.parse_model("a*x + 1"), [1, 2], {"a": 2}).tolist() == [3.0, 5.0] + + +@pytest.mark.parametrize( + "text, want", + [ + ("a*exp(-b*x)+c", "a*exp(-b*x) + c"), + ("a * x ** 2 + b * x + c", "a*x^2 + b*x + c"), + ("a/(1+exp(-b*(x-c)))", "a/(1 + exp(-b*(x - c)))"), + ("a*x^0.5", "a*x^0.5"), + ("a*x + 1e-5", "a*x + 1e-05"), + ("(a*x)^2", "(a*x)^2"), + ("a/(b*x)", "a/(b*x)"), + ("a*(b + x)", "a*(b + x)"), + ("2*3*a*x", "6*a*x"), + ], +) +def test_model_to_text(text, want): + assert expr.model_to_text(expr.parse_model(text)) == want + + +@pytest.mark.parametrize("text", MODELS) +def test_model_text_is_safe(text): + t = expr.model_to_text(expr.parse_model(text)) + assert t.isascii() and "$" not in t and "\n" not in t + assert set(t) <= set("abcdexlogsintqrpw0123456789.+-*/^() ") + + +@pytest.mark.parametrize( + "text", + [ + "a*x); import os #", + "a*x\nimport os", + "__import__('os')", + "a*x; b", + "a.real*x", + "x[0]*a", + "a*x$", + "lambda: a*x", + "a*x if b else c", + ], +) +def test_model_injection_rejected(text): + with pytest.raises(ExprError): + expr.parse_model(text) + + +def test_model_limits(): + with pytest.raises(ExprError): + expr.parse_model("a*x" + "+1" * 100) + e = merr("a*x+" + "1" * 200) + assert "200文字" in e.message + with pytest.raises(ExprError): + expr.parse_model("(" * 60 + "a*x" + ")" * 60) + with pytest.raises(ExprError): + expr.parse_model("-" * 150 + "a*x") + with pytest.raises(ExprError): + expr.parse_model("a^" * 90 + "x") + + +def test_model_nonfinite_constant(): + with pytest.raises(ExprError): + expr.parse_model("a*x + 1/0") + + +def test_no_dynamic_execution_in_module(): + import inspect + import re + + src = inspect.getsource(expr) + for word in ("eval", "exec", "compile", "ast"): + assert not re.search(rf"(? Date: Thu, 12 Nov 2026 15:21:09 +0900 Subject: [PATCH 03/10] Add box, violin and heatmap to settings, the plot plan and generated code (Phase 5d, G8) Regroup the per-type rule constants (XY_TYPES, BOX_TYPES, COLOR_COLUMN_TYPES, ...) and mirror them in js/chart-types.js with a parity test. Co-Authored-By: Claude Opus 5.5 --- docs/PHASE5_DESIGN.md | 3 +- js/chart-types.js | 27 +- js/defaults.js | 2 + py/mplgui/codegen.py | 145 ++++++++- py/mplgui/dataprep.py | 208 ++++++++++-- py/mplgui/runner.py | 13 +- py/mplgui/settings.py | 88 +++-- tests/unit/test_chart_types.py | 578 +++++++++++++++++++++++++++++++++ 8 files changed, 999 insertions(+), 65 deletions(-) diff --git a/docs/PHASE5_DESIGN.md b/docs/PHASE5_DESIGN.md index 9971f21..d1b7709 100644 --- a/docs/PHASE5_DESIGN.md +++ b/docs/PHASE5_DESIGN.md @@ -626,7 +626,8 @@ ax.plot(x_fit, fit(x_fit), color="#FF4B00", linewidth=2.0, linestyle="dashed", l - 箱の塗りは系列の色と不透明度、縁・ひげ・中央値の線は黒。ひげは matplotlib の既定(箱の端から 1.5×IQR まで)。外れ値の点と平均の印は `plot.box` で切り替える。 - 値は `pd.to_numeric(...).dropna()` にしてから渡す(NaN が混ざると中央値が NaN になるため)。数値にできない値は、今の系列と同じ形で警告する。値が無い系列は、位置を空けたまま描かない(警告)。 2. **バイオリン図(`violin`)**: 同じ並べ方で、系列ごとに `ax.violinplot(..., positions=[i])` を呼ぶ(系列ごとに色を付けやすい)。 - - 胴の塗りは系列の色と不透明度。中央値・端の線も系列の色。密度の推定は matplotlib の既定(Scott の方法、100 点)。 + - 胴の塗りは系列の色と不透明度。端の線も系列の色。密度の推定は matplotlib の既定(Scott の方法、100 点)。 + - 実装時の変更: 中央値・平均の線は黒にした(系列の色では、塗りつぶした胴(既定の不透明度 1)の上で見えないため。箱ひげ図の中央値の線と同じ)。 - 値が 2 個未満の系列は、密度を推定できないので描かない(警告)。 - 箱ひげ図・バイオリン図の軸: - 横軸はカテゴリ(系列の凡例名)。目盛は「何個おき」、注釈の X は「何番目か(0 始まり)」で、棒グラフと同じ。 diff --git a/js/chart-types.js b/js/chart-types.js index 596e981..402c8ee 100644 --- a/js/chart-types.js +++ b/js/chart-types.js @@ -1,19 +1,23 @@ // グラフの種類ごとに「どの設定を使うか」の規則(Python の settings / dataprep と同じ。要件 §2.2: 隠した設定は図に使わない)。 // 純粋な ES module(DOM にも state にも触れない)。画面の出し分けはすべてここを見る。 -// py/mplgui/settings.py の BAR_LIKE_TYPES / NO_Y2_TYPES / NO_Y_ERROR_TYPES と揃えること。 +// py/mplgui/settings.py の XY_TYPES / BOX_TYPES / CATEGORY_BAR_TYPES / SERIES_X_TYPES / NO_Y2_TYPES / NO_Y_ERROR_TYPES / +// COLOR_COLUMN_TYPES と揃えること(tests/unit/test_chart_types.py が node で比べる)。 -export const PLOT_TYPES = ["line", "step", "scatter", "scatterColor", "bar", "barStacked", "barh", "hist"]; +export const PLOT_TYPES = ["line", "step", "scatter", "scatterColor", "bar", "barStacked", "barh", "hist", "box", "violin", "heatmap"]; const LINE_LIKE = ["line", "step"]; const SCATTER_LIKE = ["scatter", "scatterColor"]; -const XY_TYPES = [...LINE_LIKE, ...SCATTER_LIKE]; // 系列ごとに X 列を持つ種類 +const XY_TYPES = [...LINE_LIKE, ...SCATTER_LIKE]; // 点の形・帯・X 方向のエラーバー・近似曲線を使う(系列ごとに X 列を持つ) +const BOX_TYPES = ["box", "violin"]; // 系列ごとに1つの箱・胴(横軸は系列の名前) +const SERIES_X_TYPES = [...XY_TYPES, "heatmap"]; // 系列ごとの X 列を使う種類 const CATEGORY_BAR_TYPES = ["bar", "barStacked", "barh"]; // 全系列共通の X列(#xColumn)を使う種類 -const NO_Y2_TYPES = ["barh", "barStacked", "hist", "scatterColor"]; -const NO_Y_ERROR_TYPES = ["barStacked", "hist"]; +const NO_Y2_TYPES = ["barh", "barStacked", "hist", "scatterColor", ...BOX_TYPES, "heatmap"]; +const NO_Y_ERROR_TYPES = ["barStacked", "hist", ...BOX_TYPES, "heatmap"]; +const COLOR_COLUMN_TYPES = ["scatterColor", "heatmap"]; export const isLineLike = (type) => LINE_LIKE.includes(type); // 点サイズの自動は 0(点なし) export const isScatterLike = (type) => SCATTER_LIKE.includes(type); // 点サイズの自動は 24 -export const usesSeriesX = (type) => XY_TYPES.includes(type); // 系列ごとの X 列 +export const usesSeriesX = (type) => SERIES_X_TYPES.includes(type); // 系列ごとの X 列 export const usesGlobalX = (type) => CATEGORY_BAR_TYPES.includes(type); // X列(#xColumn) export const usesMarker = (type) => XY_TYPES.includes(type); // 点の形・点サイズ export const usesFill = (type) => XY_TYPES.includes(type); // 塗りつぶし帯 @@ -21,6 +25,15 @@ export const usesFits = (type) => XY_TYPES.includes(type); // 近似曲線 export const usesXErrors = (type) => XY_TYPES.includes(type); // X 方向のエラーバー export const usesYErrors = (type) => !NO_Y_ERROR_TYPES.includes(type); // エラーバー(Y 方向)。使わなければ折りたたみごと隠す export const usesY2 = (type) => !NO_Y2_TYPES.includes(type); // 第2Y軸 -export const usesColorColumn = (type) => type === "scatterColor"; +export const usesColorColumn = (type) => COLOR_COLUMN_TYPES.includes(type); // 色分けの列(ヒートマップでは「値の列」) +export const usesColormap = (type) => COLOR_COLUMN_TYPES.includes(type); // カラーマップ・カラーバーのラベル export const usesStep = (type) => type === "step"; export const usesHist = (type) => type === "hist"; +export const usesBox = (type) => type === "box"; +export const usesViolin = (type) => type === "violin"; +export const isBoxLike = (type) => BOX_TYPES.includes(type); // 箱ひげ・バイオリン(横軸は系列の名前) +export const isHeatmap = (type) => type === "heatmap"; +// 色・線幅・線種を使うか(ヒートマップはカラーマップを使うので隠す。箱ひげ・バイオリンは線種を使わない) +export const usesColor = (type) => type !== "heatmap"; +export const usesLineWidth = (type) => type !== "heatmap"; +export const usesLineStyle = (type) => type !== "heatmap" && !BOX_TYPES.includes(type); diff --git a/js/defaults.js b/js/defaults.js index b1799df..15c2554 100644 --- a/js/defaults.js +++ b/js/defaults.js @@ -96,6 +96,8 @@ export const DEFAULT_SETTINGS = { hist: { bins: null, density: false }, colormap: "viridis", colorbarLabel: "", + box: { fliers: true, means: false }, + violin: { medians: true, means: false }, }, axes: { x: { label: "", scale: "linear", min: null, max: null, dateFormat: "", ...defaultTicks(), majorStepUnit: "day", dateMin: "", dateMax: "" }, diff --git a/py/mplgui/codegen.py b/py/mplgui/codegen.py index 3446e54..cc48289 100644 --- a/py/mplgui/codegen.py +++ b/py/mplgui/codegen.py @@ -24,6 +24,8 @@ LINE_ONLY_MARKERS = {"x", "+"} # 線だけでできた点の形(縁を描かないと見えない) XY_TYPES = {"line", "step", "scatter", "scatterColor"} # X と Y の組で描く種類(X が日時なら日時の軸、エラーバー・帯・近似曲線を使える) +BOX_TYPES = {"box", "violin"} # 系列ごとに1つの箱・胴を描く種類(横軸は系列の名前) +NO_SERIES_LEGEND_TYPES = {"box", "violin", "heatmap"} # 系列を凡例に出さない種類(名前は目盛に出る・カラーバーで読む) GENERIC_ERROR_MESSAGE = "グラフを描画できませんでした。X列・Y列に指定した列の値の形式(数値と文字列の混在など)や、設定の値を確認してください。" TIGHT_LAYOUT_ERROR = "レイアウトの自動調整に失敗しました。余白を手動で指定するか、図の大きさ・フォントサイズを小さくしてください。" @@ -219,13 +221,17 @@ def _emit_header( def _positions_form(plan: PlotPlan) -> bool: """棒を位置(0, 1, 2, …)に置き、カテゴリのラベルを付ける形(複数系列の棒・横棒、積み上げ棒)。""" - return plan.plot_type == "barStacked" or (plan.plot_type in {"bar", "barh"} and len(plan.series) > 1) + return plan.plot_type in {"barStacked"} | BOX_TYPES or (plan.plot_type in {"bar", "barh"} and len(plan.series) > 1) def _scale(settings: Settings, plan: PlotPlan, name: str) -> str: """軸のスケール。横棒の縦軸(カテゴリ)は Y のスケールを使わない。""" if plan.plot_type == "barh" and name == "y": return "linear" + if plan.plot_type in BOX_TYPES and name == "x": + return "linear" # 横軸はカテゴリ(系列の名前) + if plan.plot_type == "heatmap" and name in {"x", "y"} and getattr(plan.axes, name).kind == "category": + return "linear" # 文字列の列の軸はカテゴリ return getattr(settings.axes, name).scale @@ -856,6 +862,120 @@ def _emit_scatter_color_series(b: _Builder, settings: Settings, plan: PlotPlan) ) +def _emit_box_series(b: _Builder, settings: Settings, plan: PlotPlan) -> None: + """箱ひげ図(box)・バイオリン図(violin)。系列ごとに Y 列の値の分布を1つ、左から系列の順(0, 1, 2, …)に描く。 + + 系列の名前は目盛のラベル(x_labels)になる。値が無い系列(バイオリンは2個未満)は、位置を空けたまま描かない。""" + violin = plan.plot_type == "violin" + n = len(plan.series) + plot = settings.plot + if violin: + b.add("# バイオリン図: 系列ごとに1つの胴を、左から系列の順(0, 1, 2, …)に描く(値が2個未満の系列は描かない)") + else: + b.add("# 箱ひげ図: 系列ごとに1つの箱を、左から系列の順(0, 1, 2, …)に描く(箱の端はひげまで 1.5×IQR。外れ値は点)") + labels = ", ".join(literal(p.legend_label) for p in plan.series) + b.add( + f"positions = np.arange({n}) # {'胴' if violin else '箱'}の位置(系列の順に 0, 1, 2, …)", + f"x_labels = [{labels}] # 目盛のラベル(系列の凡例名)", + ) + for s, p in zip(settings.series, plan.series): + i = p.number - 1 + b.blank() + b.add(f"# 系列{p.number}{'' if p.data_var == 'df' else f'({p.data_var})'}: Y = {_column_comment(p, 'y')}") + if not p.has_points: + b.add(f"# 描ける値が無い({'2個未満' if violin else '数値の行が無い'})ため、この系列は描かない(位置は空けておく)") + continue + width, color = literal(s.line_width), literal(s.color) + alpha = f', "alpha": {literal(p.alpha)}' if p.alpha != 1.0 else "" + with b.step(GENERIC_ERROR_MESSAGE): + b.add( + f'values = pd.to_numeric({p.data_var}.iloc[:, {p.y_index}], errors="coerce").replace([np.inf, -np.inf], np.nan).dropna()' + " # 数値にできない値・欠けた値は使わない" + ) + if violin: + b.add( + f"vp = ax.violinplot([values], positions=[{i}], widths=0.8, showmedians={literal(plot.violin_medians)}, " + f"showmeans={literal(plot.violin_means)}, showextrema=True)", + 'for body in vp["bodies"]:', + f' body.set(facecolor={color}, edgecolor={color}, linewidth={width}, alpha={literal(p.alpha)}, label="_violin")' + " # 胴(凡例には出さない)", + 'for key in ("cbars", "cmins", "cmaxes"): # 端の線は系列の色。中央値・平均の線は、胴の上でも見えるように黒', + f" vp[key].set(color={color}, linewidth={width})", + 'for key in ("cmedians", "cmeans"):', + " if key in vp:", + f' vp[key].set(color="black", linewidth={width})', + ) + else: + line = f'{{"color": "black", "linewidth": {width}}}' + b.add( + f"bp = ax.boxplot([values], positions=[{i}], widths=0.6, patch_artist=True, manage_ticks=False, " + f"showfliers={literal(plot.box_fliers)}, showmeans={literal(plot.box_means)},", + f' boxprops={{"facecolor": {color}, "edgecolor": "black", "linewidth": {width}{alpha}}},', + f" whiskerprops={line}, capprops={line}, medianprops={line},", + ' flierprops={"marker": "o", "markersize": 4, "markerfacecolor": "none", "markeredgecolor": "black"},', + ' meanprops={"marker": "D", "markersize": 6, "markerfacecolor": "white", "markeredgecolor": "black"})', + 'for artists in bp.values():', + ' plt.setp(artists, label="_box") # 凡例には出さない(ラベルが _ で始まる)', + ) + b.blank() + b.add(f"ax.set_xlim(-0.5, {n} - 0.5) # 横軸は系列の数に合わせる") + + +def _emit_heatmap_series(b: _Builder, settings: Settings, plan: PlotPlan) -> None: + """ヒートマップ(heatmap)。X・Y・値の3列の縦長の表から格子を作り、pcolormesh で描く(系列は1つ)。""" + p, hm, colorbar = plan.series[0], plan.heatmap, plan.colorbar + assert hm is not None and colorbar is not None + cmap = literal(colorbar.colormap) + b.add(f"# 系列1: X = {_column_comment(p, 'x')}、Y = {_column_comment(p, 'y')}、値 = {comment_text(p.color_label)}") + with b.step("ヒートマップの格子を作れませんでした。X・Y・値の列を確認してください。", "系列1の値の列"): + _emit_x_data(b, p) + if hm.y_convert: + b.add(f'y = pd.to_numeric({p.data_var}.iloc[:, {p.y_index}], errors="coerce") # 数値にできない値は NaN にする') + else: + b.add(f"y = {p.data_var}.iloc[:, {p.y_index}]") + b.add( + f'c = pd.to_numeric({p.data_var}.iloc[:, {p.color_index}], errors="coerce") # 値の列(数値にできない値は NaN)', + "ok = x.notna() & y.notna() & c.notna() # X・Y・値のどれかが欠けている行は使わない", + 'heat = pd.DataFrame({"x": x[ok], "y": y[ok], "z": c[ok]})', + ) + if hm.x_text: + b.add('heat["x"], x_cats = pd.factorize(heat["x"]) # X が文字列: 現れた順にカテゴリの番号にする') + b.add("x_cats = [str(v) for v in x_cats] # 目盛のラベル") + if hm.y_text: + b.add('heat["y"], y_cats = pd.factorize(heat["y"]) # Y が文字列: 現れた順にカテゴリの番号にする') + b.add("y_cats = [str(v) for v in y_cats] # 目盛のラベル") + b.add('grid = heat.pivot_table(index="y", columns="x", values="z", aggfunc="mean") # 格子にする(同じ X・Y の組は平均。値の無いマスは NaN)') + alpha = f", alpha={literal(p.alpha)}" if p.alpha != 1.0 else "" + size = _label_size_expr(settings.plot.font_size) + with b.step("ヒートマップを描けませんでした。カラーマップと値の列を確認してください。", "カラーマップ"): + b.add( + f'mesh = ax.pcolormesh(grid.columns.to_numpy(), grid.index.to_numpy(), grid.to_numpy(), cmap={cmap}, shading="nearest"{alpha})' + " # 値の無いマスは塗らない", + "colorbar = fig.colorbar(mesh, ax=ax)", + f"colorbar.set_label({literal(colorbar.label)}, fontsize=FONT_SIZE)", + f'colorbar.ax.tick_params(which="both", direction="in", labelsize={size})', + ) + + +def _emit_heatmap_ticks(b: _Builder, plan: PlotPlan) -> None: + """ヒートマップで、X・Y が文字列の列のとき、目盛にカテゴリの名前を付ける(主目盛の間隔か、25個を超えるときの間引き)。""" + hm = plan.heatmap + assert hm is not None + for which, text, ap in (("x", hm.x_text, plan.axes.x), ("y", hm.y_text, plan.axes.y)): + if not text: + continue + name = which.upper() + if ap.major_step is not None: + b.add(f"# {name} の目盛にカテゴリの名前を付ける({name}軸の主目盛の間隔: {ap.major_step}個おき)", f"{which}_tick_step = {literal(ap.major_step)}") + else: + b.add(f"# {name} の目盛にカテゴリの名前を付ける(25個を超えるときは間引く)", f"{which}_tick_step = max(1, len({which}_cats) // 25)") + b.add(f"ax.set_{which}ticks(np.arange(len({which}_cats))[::{which}_tick_step])") + if which == "x": + b.add('ax.set_xticklabels(x_cats[::x_tick_step], rotation=45, ha="right")') + else: + b.add("ax.set_yticklabels(y_cats[::y_tick_step])") + + SERIES_EMITTERS: dict[str, Callable[[_Builder, Settings, PlotPlan], None]] = { "line": _emit_line_series, "scatter": _emit_scatter_series, @@ -865,6 +985,9 @@ def _emit_scatter_color_series(b: _Builder, settings: Settings, plan: PlotPlan) "barStacked": _emit_stacked_series, "hist": _emit_hist_series, "scatterColor": _emit_scatter_color_series, + "box": _emit_box_series, + "violin": _emit_box_series, + "heatmap": _emit_heatmap_series, } @@ -1004,8 +1127,8 @@ def _major_lines(blk: _AxisBlock, settings: Settings, plan: PlotPlan) -> list[st f"{axis_var}.set_major_formatter({formatter})", ] if ap.kind == "category": - if _positions_form(plan): - return [] # 棒の位置に目盛を付ける節(tick_step)で扱う + if _positions_form(plan) or plan.plot_type == "heatmap": + return [] # 棒(箱)の位置・ヒートマップのカテゴリに目盛を付ける節(tick_step)で扱う if ap.major_step is not None: return [f"{axis_var}.set_major_locator(ticker.MultipleLocator({literal(ap.major_step)})) # {label}軸の主目盛: {ap.major_step}個おきにラベルを出す"] if plan.plot_type in XY_TYPES and plan.thin_categorical_x: @@ -1075,6 +1198,10 @@ def _emit_spines(b: _Builder, settings: Settings, plan: PlotPlan) -> None: b.add('ax.spines["right"].set_visible(False) # 右の枠線を消す') +def _position_word(plan: PlotPlan) -> str: + return {"box": "箱", "violin": "胴"}.get(plan.plot_type, "棒") + + def _emit_axes(b: _Builder, settings: Settings, plan: PlotPlan) -> None: b.section("軸(ラベル・スケール・範囲・目盛)") plot, axes = settings.plot, settings.axes @@ -1096,19 +1223,21 @@ def _emit_axes(b: _Builder, settings: Settings, plan: PlotPlan) -> None: with b.step(tick_error_message(blk.label), f"{blk.label}軸の目盛"): b.add(*ticks) + if plan.plot_type == "heatmap": + _emit_heatmap_ticks(b, plan) if _positions_form(plan): horizontal = plan.plot_type == "barh" axis_name = "Y" if horizontal else "X" - what = "カテゴリの値" if horizontal else "X の値" + what = "カテゴリの値" if horizontal else ("系列の名前" if plan.plot_type in BOX_TYPES else "X の値") step = (plan.axes.y if horizontal else plan.axes.x).major_step if step is not None: b.add( - f"# 棒の位置に {what}を目盛として付ける({axis_name}軸の主目盛の間隔: {step}個おき)", + f"# {_position_word(plan)}の位置に {what}を目盛として付ける({axis_name}軸の主目盛の間隔: {step}個おき)", f"tick_step = {literal(step)}", ) else: b.add( - f"# 棒の位置に {what}を目盛として付ける(25個を超えるときは間引く)", + f"# {_position_word(plan)}の位置に {what}を目盛として付ける(25個を超えるときは間引く)", "tick_step = max(1, len(positions) // 25)", ) if horizontal: @@ -1153,7 +1282,9 @@ def _emit_grid_and_legend(b: _Builder, settings: Settings, plan: PlotPlan) -> No if plot.legend_location == "none": b.add("# 凡例は表示しない") return - labelled = any(p.has_points and p.legend_label and not p.legend_label.startswith("_") for p in plan.series) + labelled = plan.plot_type not in NO_SERIES_LEGEND_TYPES and any( + p.has_points and p.legend_label and not p.legend_label.startswith("_") for p in plan.series + ) labelled = labelled or any(a.label and not a.label.startswith("_") for a in plan.annotations) labelled = labelled or any(f.show == "legend" for f in plan.fits) if not labelled: diff --git a/py/mplgui/dataprep.py b/py/mplgui/dataprep.py index 21afb8c..bd6a5d0 100644 --- a/py/mplgui/dataprep.py +++ b/py/mplgui/dataprep.py @@ -17,7 +17,7 @@ from .errors import UserError from .loader import is_blank_cell as _is_blank_cell from .loader import looks_numeric as _looks_numeric -from .settings import BAR_LIKE_TYPES, MAX_HIST_BINS, AxisSettings, ErrorSpec, Settings, check_axis_range, validate_date_range +from .settings import MAX_HEATMAP_SIZE, MAX_HIST_BINS, XY_TYPES, AxisSettings, ErrorSpec, Settings, check_axis_range, validate_date_range from .settings import _DATE_EXAMPLE, _date_range_value, _to_float MAX_EXAMPLES = 3 @@ -230,8 +230,8 @@ class SeriesPlan: marker: str = "" # line は描く点の形("" = 点なし)、scatter は "" = 既定の丸(引数を足さない) alpha: float = 1.0 # 不透明度(1 のときはコードに書かない) fill: FillPlan | None = None # 塗りつぶし帯(line / step / scatter / scatterColor のみ) - color_index: int | None = None # scatterColor の色分けの列番号 - color_label: str = "" # scatterColor の色分けの列の表示(「名前 [番号]」) + color_index: int | None = None # scatterColor の色分けの列番号(heatmap では値の列番号) + color_label: str = "" # scatterColor の色分けの列(heatmap では値の列)の表示(「名前 [番号]」) @dataclass(frozen=True) @@ -244,9 +244,21 @@ class HistPlan: max_height: float # 度数(density なら確率密度)の最大 +@dataclass(frozen=True) +class HeatmapPlan: + """ヒートマップ(heatmap)。X・Y が文字列の列か(現れた順のカテゴリにする)、数値に変換する列か、格子の大きさ。""" + + x_text: bool + y_text: bool + y_convert: bool # Y を pd.to_numeric で変換する(X は SeriesPlan.convert_x) + x_count: int # X の異なる値の数 + y_count: int + duplicates: int # 同じ X・Y の組の重複の件数(平均を描く) + + @dataclass(frozen=True) class ColorbarPlan: - """色分け散布図(scatterColor)のカラーマップとカラーバーのラベル。""" + """色分け散布図(scatterColor)・ヒートマップ(heatmap)のカラーマップとカラーバーのラベル。""" colormap: str label: str # 実際に使うラベル(設定が空なら系列1の色分けの列の表示) @@ -313,7 +325,8 @@ class PlotPlan: annotations: tuple[AnnotationPlan, ...] = () fits: tuple[FitPlan, ...] = () # 近似曲線(line / step / scatter / scatterColor のみ) hist: HistPlan | None = None # hist のときだけ - colorbar: ColorbarPlan | None = None # scatterColor のときだけ + colorbar: ColorbarPlan | None = None # scatterColor / heatmap のときだけ + heatmap: HeatmapPlan | None = None # heatmap のときだけ computed: tuple["ComputedPlan", ...] = () # 計算した列(描画に使うデータ元のものだけ。カードの順) @property @@ -335,6 +348,8 @@ class ComputedPlan: refs: tuple[tuple[int, str], ...] = () # 式が使うファイルの列(番号、コメント用の「列 [i]: 名前」) +HEATMAP_SERIES_MESSAGE = "ヒートマップは系列1つで描きます。系列を1つにしてください。" +HEATMAP_DATETIME_MESSAGE = "系列{n}: {what}({name})は日時の列です。ヒートマップでは日時の列を使えません。" MAX_CATEGORY_TICKS = 25 # X が文字列の列のとき、目盛に出すカテゴリの最大数 Y_DATETIME_MESSAGE = "系列{n}: Y列({name})は日時の列です。Y列には数値の列を選んでください。" @@ -507,7 +522,7 @@ def _plan_fill(df: pd.DataFrame, series, n: int, ok: pd.Series, y_axis: str, ext def _plan_fits(settings: Settings) -> list[tuple[int, object]]: """(近似曲線の番号, FitSettings) を、系列の番号ごとに引けるように並べる。棒グラフでは使わない。""" - if settings.plot.type in BAR_LIKE_TYPES: + if settings.plot.type not in XY_TYPES: return [] return list(enumerate(settings.fits, start=1)) @@ -753,6 +768,8 @@ def plan_plot(data, settings: Settings) -> PlotPlan: default_id = files[0].id if files else next(iter(data)) multi = len(files) >= 2 + if plot.type == "heatmap" and len(settings.series) > 1: + raise UserError(HEATMAP_SERIES_MESSAGE, field="系列") ids: list[str] = [] # 系列ごとのデータ元 for n, s in enumerate(settings.series, start=1): sid = s.source or default_id @@ -787,6 +804,10 @@ def plan_plot(data, settings: Settings) -> PlotPlan: plan = _plan_xy(dfs, settings, y_requests) elif plot.type == "hist": plan = _plan_hist(dfs, settings, y_requests) + elif plot.type in {"box", "violin"}: + plan = _plan_box(dfs, settings, y_requests) + elif plot.type == "heatmap": + plan = _plan_heatmap(dfs[0], settings, y_requests[0]) else: plan = _plan_bar(dfs[0], settings, y_requests) series = tuple(replace(sp, data_id=sid, data_var=var_of[sid]) for sp, sid in zip(plan.series, ids)) @@ -931,9 +952,11 @@ def _plan_axis( def _plan_axes( - settings: Settings, x_kind: str, uses_secondary: bool, ext: _Extents, categories: int, y_kind: str | None = None + settings: Settings, x_kind: str, uses_secondary: bool, ext: _Extents, categories: int, y_kind: str | None = None, + y_categories: int | None = None, ) -> AxesPlan: - """y_kind は Y 軸の種類(横棒の縦軸は category / number。そのとき categories は Y 軸のカテゴリ数)。None なら Y のスケールから決める。""" + """y_kind は Y 軸の種類(横棒の縦軸は category / number。そのとき categories は Y 軸のカテゴリ数)。None なら Y のスケールから決める。 + y_categories があるとき(ヒートマップ)は、categories が X 軸、y_categories が Y 軸のカテゴリ数。""" axes = settings.axes plot_type = settings.plot.type bar = plot_type in {"bar", "barStacked", "hist"} # 縦向きの棒: Y 軸(値)の範囲に 0 を含める @@ -941,33 +964,39 @@ def _plan_axes( def num_kind(axis: AxisSettings) -> str: return "log" if axis.scale == "log" else "number" + if y_categories is not None: + x_cat, y_cat = categories, y_categories + else: + x_cat, y_cat = (0 if y_kind else categories), (categories if y_kind == "category" else 0) return AxesPlan( - x=_plan_axis(axes.x, x_kind, "X", ext, "x", categories=0 if y_kind else categories, include_zero=plot_type == "barh"), - y=_plan_axis(axes.y, y_kind or num_kind(axes.y), "Y", ext, "y", categories=categories if y_kind == "category" else 0, include_zero=bar), + x=_plan_axis(axes.x, x_kind, "X", ext, "x", categories=x_cat, include_zero=plot_type == "barh"), + y=_plan_axis(axes.y, y_kind or num_kind(axes.y), "Y", ext, "y", categories=y_cat, include_zero=bar), y2=_plan_axis(axes.y2, num_kind(axes.y2), "第2Y", ext, "y2", include_zero=plot_type == "bar") if uses_secondary else None, ) -def _color_column(df: pd.DataFrame, requested: str, n: int) -> int: - field_name = f"系列{n}の色分けの列" +def _color_column(df: pd.DataFrame, requested: str, n: int, what: str = "色分けの列") -> int: + field_name = f"系列{n}の{what}" idx = parse_column_index(requested) if idx is None: - raise UserError(f"系列{n}の色分けの列を選んでください。", field=field_name) + raise UserError(f"系列{n}の{what}を選んでください。", field=field_name) if idx >= len(df.columns): raise UserError(_column_out_of_range(idx, len(df.columns)), field=field_name) return idx -def _color_values(df: pd.DataFrame, idx: int, mask: pd.Series, n: int, load, warnings: list[dict]) -> pd.Series: - """色分けの列を数値にする(数値にできない値は NaN。空欄も NaN で、警告しない)。警告の件数と例は、描く行(mask)だけで数える。""" +def _color_values( + df: pd.DataFrame, idx: int, mask: pd.Series, n: int, load, warnings: list[dict], what: str = "色分けの列", skipped: str = "その点は描きません" +) -> pd.Series: + """色分けの列(heatmap では値の列)を数値にする(数値にできない値は NaN。空欄も NaN で、警告しない)。警告の件数と例は、描く行(mask)だけで数える。""" raw = df.iloc[:, idx] numeric, _, _ = coerce_numeric(raw) _, count, examples = coerce_numeric(raw[mask.reindex(df.index, fill_value=False)]) if count: ex = ", ".join(f'"{e}"' for e in examples) message = ( - f"系列{n}: 色分けの列「{df.columns[idx]}」[{idx}] に数値にできない値が{count}件あったため、" - f"その点は描きません(例: {ex})。{load_hint(examples, load)}" + f"系列{n}: {what}「{df.columns[idx]}」[{idx}] に数値にできない値が{count}件あったため、" + f"{skipped}(例: {ex})。{load_hint(examples, load)}" ) warnings.append({"series": n, "message": message}) return numeric @@ -1267,6 +1296,140 @@ def _plan_hist(dfs: list[pd.DataFrame], settings: Settings, y_requests: list[str ) +BOX_NO_VALUES = "系列{n}: 描ける値(数値の行)が無いため、{what}は描きません。" +VIOLIN_FEW_VALUES = "系列{n}: 値が1個だけなので密度を推定できず、バイオリンは描きません。" + + +def _plan_box(dfs: list[pd.DataFrame], settings: Settings, y_requests: list[str]) -> PlotPlan: + """箱ひげ図(box)・バイオリン図(violin)。系列ごとに Y 列の値の分布を1つ、左から系列の順(0, 1, 2, …)に描く。 + + 値が無い系列(バイオリンは2個未満)は、位置を空けたまま描かない(警告)。X 列は使わない。""" + violin = settings.plot.type == "violin" + what = "バイオリン" if violin else "箱" + plans: list[SeriesPlan] = [] + warnings: list[dict] = [] + ext = _Extents() + for n, (df, series, y_request) in enumerate(zip(dfs, settings.series, y_requests), start=1): + y_index = resolve_column_index(df, y_request) + y_name, data_label = _label_for(df, y_index) + if _is_datetime(df.iloc[:, y_index]): + raise UserError(Y_DATETIME_MESSAGE.format(n=n, name=y_name), field=f"系列{n}のY列") + numeric, dropped, examples = coerce_numeric(df.iloc[:, y_index]) + if dropped: + warnings.append(dropped_warning(n, f"系列{n}({y_name})", dropped, examples, settings.load)) + vals = numeric.dropna() + vals = vals[np.isfinite(vals.to_numpy(dtype=float))] + drawable = len(vals) >= (2 if violin else 1) + if not drawable: + warnings.append({"series": n, "message": (VIOLIN_FEW_VALUES if len(vals) == 1 and violin else BOX_NO_VALUES).format(n=n, what=what)}) + else: + ext.add_values("y", vals) + plans.append( + SeriesPlan( + number=n, + y_index=y_index, + y_name=y_name, + x_index=None, + x_label="", + data_label=data_label, + legend_label=series.label or data_label, + convert_x=False, + categorical_x=False, + marker_size=series.effective_marker_size("bar"), + has_points=drawable, + secondary=False, + alpha=series.alpha, + ) + ) + if not any(p.has_points for p in plans): + raise UserError(_no_data_message(warnings)) + return _finish(settings, plans, warnings, "", None, axes_args=("category", ext, len(plans))) + + +def _plan_heatmap(df: pd.DataFrame, settings: Settings, y_request: str) -> PlotPlan: + """ヒートマップ。X・Y・値(色分けの列)の3列の縦長の表から格子を作る(案 H2)。系列は1つだけ。 + + X・Y は数値の列か文字列の列(文字列は現れた順のカテゴリ)。日時の列は使えない。同じ X・Y の組は平均を描く。""" + series = settings.series[0] + n = 1 + warnings: list[dict] = [] + x_index = resolve_column_index(df, series.x) if series.x else None + x_label = str(df.columns[x_index]) if x_index is not None else "index" + y_index = resolve_column_index(df, y_request) + y_name, data_label = _label_for(df, y_index) + x_series = df.iloc[:, x_index] if x_index is not None else pd.Series(df.index) + y_series = df.iloc[:, y_index] + if _is_datetime(x_series): + raise UserError(HEATMAP_DATETIME_MESSAGE.format(n=n, what="X列", name=x_label), field=f"系列{n}のX列") + if _is_datetime(y_series): + raise UserError(HEATMAP_DATETIME_MESSAGE.format(n=n, what="Y列", name=y_name), field=f"系列{n}のY列") + convert_x = convert_y = False + if x_index is not None and not pd.api.types.is_numeric_dtype(x_series.dtype) and _looks_numeric(x_series): + convert_x = True + x_series, dropped, examples = coerce_numeric(x_series) + if dropped: + warnings.append(dropped_warning(n, f"系列{n}のX列({x_label})", dropped, examples, settings.load)) + if not pd.api.types.is_numeric_dtype(y_series.dtype) and _looks_numeric(y_series): + convert_y = True + y_series, dropped, examples = coerce_numeric(y_series) + if dropped: + warnings.append(dropped_warning(n, f"系列{n}のY列({y_name})", dropped, examples, settings.load)) + x_text = not pd.api.types.is_numeric_dtype(x_series.dtype) + y_text = not pd.api.types.is_numeric_dtype(y_series.dtype) + + value_index = _color_column(df, series.color_column, n, "値の列") + value_label = _label_for(df, value_index)[1] + if _is_datetime(df.iloc[:, value_index]): + raise UserError( + f"系列{n}の値の列({df.columns[value_index]})は日時の列です。値の列には数値の列を選んでください。", field=f"系列{n}の値の列" + ) + present = y_series.notna() & x_series.notna() + values = _color_values(df, value_index, present, n, settings.load, warnings, "値の列", "その行は使いません") + ok = present & values.notna() + if not bool(ok.any()): + raise UserError(_no_data_message(warnings)) + heat = pd.DataFrame({"x": x_series[ok], "y": y_series[ok]}) + x_count, y_count = int(heat["x"].nunique()), int(heat["y"].nunique()) + for count, which, field_name in ((x_count, "X", f"系列{n}のX列"), (y_count, "Y", f"系列{n}のY列")): + if count > MAX_HEATMAP_SIZE: + raise UserError( + f"ヒートマップの{which}の異なる値が{count}種類あります({MAX_HEATMAP_SIZE}種類まで)。" + f"{which}列に格子の軸になる列を選んでいるか確認してください。", + field=field_name, + ) + duplicates = int(heat.duplicated(["x", "y"]).sum()) + if duplicates: + warnings.append({"series": n, "message": f"系列{n}: 同じ X・Y の組が{duplicates}件重複していたため、その平均を描きます。"}) + ext = _Extents() + if not x_text: + ext.add_values("x", x_series[ok]) + if not y_text: + ext.add_values("y", y_series[ok]) + x_kind = "category" if x_text else ("log" if settings.axes.x.scale == "log" else "number") + y_kind = "category" if y_text else ("log" if settings.axes.y.scale == "log" else "number") + plan = SeriesPlan( + number=n, + y_index=y_index, + y_name=y_name, + x_index=x_index, + x_label=x_label, + data_label=data_label, + legend_label=series.label or data_label, + convert_x=convert_x, + categorical_x=x_text, + marker_size=series.effective_marker_size("bar"), + has_points=True, + secondary=False, + alpha=series.alpha, + color_index=value_index, + color_label=value_label, + ) + return _finish( + settings, [plan], warnings, x_label, None, axes_args=(x_kind, ext, x_count if x_text else 0, y_kind, y_count if y_text else 0), + heatmap=HeatmapPlan(x_text=x_text, y_text=y_text, y_convert=convert_y, x_count=x_count, y_count=y_count, duplicates=duplicates), + ) + + def _finish( settings: Settings, plans: list[SeriesPlan], @@ -1277,15 +1440,17 @@ def _finish( datetime_x: bool = False, thin_categorical_x: bool = False, bar_date_format: str | None = None, - axes_args: tuple | None = None, # (X の軸の種類, _Extents, カテゴリ数[, Y の軸の種類(横棒の縦軸)]) + axes_args: tuple | None = None, # (X の軸の種類, _Extents, カテゴリ数[, Y の軸の種類(横棒の縦軸・ヒートマップ)[, Y のカテゴリ数(ヒートマップ)]]) fits: tuple[FitPlan, ...] = (), hist: HistPlan | None = None, + heatmap: HeatmapPlan | None = None, ) -> PlotPlan: primary = [p.data_label for p in plans if not p.secondary] secondary = [p.data_label for p in plans if p.secondary] uses_secondary = any(p.secondary and p.has_points for p in plans) x_kind, ext, categories, *rest = axes_args or ("number", _Extents(), 0) y_kind = rest[0] if rest else None + y_categories = rest[1] if len(rest) > 1 else None annotations = _plan_annotations(settings, x_kind, uses_secondary, ext, y_kind) # 範囲を ext に足すので、軸の計画より前 plot_type = settings.plot.type y_label = primary[0] if len(primary) == 1 else "values" @@ -1294,8 +1459,10 @@ def _finish( x_label, y_label = plans[0].data_label, x_label elif plot_type == "hist": x_label, y_label = plans[0].data_label, "確率密度" if settings.plot.hist_density else "度数" - elif plot_type == "scatterColor": + elif plot_type in {"scatterColor", "heatmap"}: colorbar = ColorbarPlan(settings.plot.colormap, settings.plot.colorbar_label or plans[0].color_label) + elif plot_type in {"box", "violin"}: # 横軸は系列の名前(目盛)。縦軸は、系列が1つならその Y 列の名前 + x_label, y_label = "", plans[0].data_label if len(plans) == 1 else "" return PlotPlan( skip_rows=settings.plot.skip_rows, plot_type=settings.plot.type, @@ -1310,9 +1477,10 @@ def _finish( datetime_x=datetime_x, thin_categorical_x=thin_categorical_x, bar_date_format=bar_date_format, - axes=_plan_axes(settings, x_kind, uses_secondary, ext, categories, y_kind), + axes=_plan_axes(settings, x_kind, uses_secondary, ext, categories, y_kind, y_categories), annotations=annotations, fits=fits, hist=hist, colorbar=colorbar, + heatmap=heatmap, ) diff --git a/py/mplgui/runner.py b/py/mplgui/runner.py index 2ed71af..6cad8a6 100644 --- a/py/mplgui/runner.py +++ b/py/mplgui/runner.py @@ -93,7 +93,7 @@ def _offset_text(axis) -> str: return str(get_offset()) if get_offset is not None else "" -_AUX_LINE_LABELS = {"_errorbar", "_fit"} +_AUX_LINE_LABELS = {"_errorbar", "_fit", "_box"} # _box: 箱ひげ図のひげ・端・中央値・外れ値・平均の線 def _is_fit_label(label: str) -> bool: @@ -181,6 +181,9 @@ def _style_summary(ax) -> dict: }, "fitlines": sum(1 for ln in lines if _is_fit_label(ln.get_label())), "fittexts": fit_texts, + "boxes": sum(1 for p in ax.patches if p.get_label() == "_box"), + "violins": sum(1 for c in ax.collections if c.get_label() == "_violin"), + "meshes": sum(1 for c in ax.collections if type(c).__name__ == "QuadMesh"), } @@ -192,7 +195,13 @@ def figure_summary(fig) -> list[dict]: - bars: {vertical, horizontal, containers, stacked}。BarContainer の棒の本数(縦向き・横向き)、容器ごとの棒の数、 棒の下端(横棒は左端)が 0 でない容器の数(積み上げ棒の2系列目以降)。ヒストグラムも BarContainer - colorbar: カラーバーが無ければ null、あれば {label, cmap, vmin, vmax}。カラーバーの Axes は軸ごとの一覧に入れず、 - 元の Axes の項目として出す(色分け散布図は第2Y軸が無いので、最初の Axes に付く) + 元の Axes の項目として出す(色分け散布図・ヒートマップは第2Y軸が無いので、最初の Axes に付く) + + Phase 5d で足したキー(既存のキーの値は変えない): + - boxes: 箱ひげ図の箱の数(ラベルが `_box` の patch。生成コードが箱ひげ図の部品すべてにこのラベルを付ける)。 + 箱ひげ図の線(ひげ・端・中央値・外れ値・平均)も `_box` なので、markers / alphas / drawstyles には数えない(lines には数える) + - violins: バイオリン図の胴の数(ラベルが `_violin` の collection。中央値・端の線は LineCollection で collections に数える) + - meshes: ヒートマップ(pcolormesh)の QuadMesh の数 """ out = [] colorbar = _colorbar_summary(fig) diff --git a/py/mplgui/settings.py b/py/mplgui/settings.py index 6a80877..b9bbe52 100644 --- a/py/mplgui/settings.py +++ b/py/mplgui/settings.py @@ -19,14 +19,19 @@ SCHEMA_VERSION = 4 -PLOT_TYPES = ("line", "scatter", "bar", "step", "barh", "barStacked", "hist", "scatterColor") -# 種類ごとに画面で隠す設定は、検証せず使わない(要件 §2.2。docs/PHASE5_DESIGN.md §6.2) -BAR_LIKE_TYPES = ("bar", "barh", "barStacked", "hist") # 点の形・塗りつぶし帯・X 方向のエラーバー・近似曲線を使わない -NO_Y2_TYPES = ("barh", "barStacked", "hist", "scatterColor") # 第2Y軸を使わない -NO_Y_ERROR_TYPES = ("barStacked", "hist") # Y 方向のエラーバーを使わない +PLOT_TYPES = ("line", "scatter", "bar", "step", "barh", "barStacked", "hist", "scatterColor", "box", "violin", "heatmap") +# 種類ごとに画面で隠す設定は、検証せず使わない(要件 §2.2。docs/PHASE5_DESIGN.md §6.2・§7.3)。js/chart-types.js と揃えること +XY_TYPES = ("line", "step", "scatter", "scatterColor") # 点の形・塗りつぶし帯・X 方向のエラーバー・近似曲線を使う(系列ごとの X と Y の組で描く) +BOX_TYPES = ("box", "violin") # 系列ごとに1つの箱・胴を描く(横軸は系列の名前) +CATEGORY_BAR_TYPES = ("bar", "barStacked", "barh") # 全系列共通の X列(plot.xColumn)を使う +SERIES_X_TYPES = XY_TYPES + ("heatmap",) # 系列ごとの X 列を使う +NO_Y2_TYPES = ("barh", "barStacked", "hist", "scatterColor") + BOX_TYPES + ("heatmap",) # 第2Y軸を使わない +NO_Y_ERROR_TYPES = ("barStacked", "hist") + BOX_TYPES + ("heatmap",) # Y 方向のエラーバーを使わない +COLOR_COLUMN_TYPES = ("scatterColor", "heatmap") # 色分けの列(ヒートマップでは値の列)を使う STEP_WHERE_CHOICES = ("pre", "mid", "post") COLORMAPS = ("viridis", "cividis", "plasma", "inferno", "magma", "coolwarm", "RdBu_r", "gray") MAX_HIST_BINS = 1000 +MAX_HEATMAP_SIZE = 500 # ヒートマップの X・Y の異なる値の上限(それぞれ) LINE_STYLES = ("solid", "dashed", "dashdot", "dotted") SCALES = ("linear", "log") SAVE_FORMATS = ("png", "jpg", "svg", "pdf") @@ -175,6 +180,8 @@ def default_settings() -> dict: "hist": {"bins": None, "density": False}, "colormap": "viridis", "colorbarLabel": "", + "box": {"fliers": True, "means": False}, + "violin": {"medians": True, "means": False}, }, "axes": { "x": { @@ -277,8 +284,12 @@ class PlotSettings: step_where: str = "post" # step のときだけ使う: pre / mid / post hist_bins: int | None = None # hist のときだけ使う: None = 自動(numpy の "auto") hist_density: bool = False # hist のときだけ使う: 縦軸を確率密度にする - colormap: str = "viridis" # scatterColor のときだけ使う - colorbar_label: str = "" # scatterColor のときだけ使う("" = 系列1の色分けの列の名前) + colormap: str = "viridis" # scatterColor / heatmap のときだけ使う + colorbar_label: str = "" # scatterColor / heatmap のときだけ使う("" = 系列1の色分けの列(値の列)の名前) + box_fliers: bool = True # box のときだけ使う: 外れ値の点を描く + box_means: bool = False # box のときだけ使う: 平均の印を描く + violin_medians: bool = True # violin のときだけ使う: 中央値の線を描く + violin_means: bool = False # violin のときだけ使う: 平均の線を描く @dataclass(frozen=True) @@ -336,7 +347,7 @@ class SeriesSettings: marker: str = "auto" # auto / none / o / s / ^ / v / D / x / + / *(棒グラフでは使わない) alpha: float = 1.0 # 不透明度(1 = 透けない) fill: FillSettings = field(default_factory=FillSettings) # 棒グラフでは使わない - color_column: str = "" # "__idx__N"。scatterColor のときだけ使う(必須) + color_column: str = "" # "__idx__N"。scatterColor / heatmap(値の列)のときだけ使う(必須) def effective_marker_size(self, plot_type: str) -> float: """自動(None)は line / step=0 / それ以外=24。scatter / scatterColor で 0 以下なら 24 に補正する。""" @@ -769,12 +780,12 @@ def _parse_error_spec(raw: dict, axis: str, owner: str) -> ErrorSpec: def _parse_error_bars(raw: dict, plot_type: str, owner: str) -> ErrorBarSettings: - if plot_type in NO_Y_ERROR_TYPES: # 積み上げ棒・ヒストグラムはエラーバーを両方向とも隠すので、何も検証しない + if plot_type in NO_Y_ERROR_TYPES: # 積み上げ棒・ヒストグラム・箱ひげ・バイオリン・ヒートマップはエラーバーを両方向とも隠すので、何も検証しない return ErrorBarSettings() cap = _number(raw["capSize"], "エラーバーの端の長さ", default=3.0, minimum=0, maximum=MAX_CAP_SIZE, owner=owner) return ErrorBarSettings( y=ErrorSpec() if plot_type in NO_Y_ERROR_TYPES else _parse_error_spec(raw["y"], "Y", owner), # 積み上げ棒・ヒストグラムでは Y 方向を隠す - x=ErrorSpec() if plot_type in BAR_LIKE_TYPES else _parse_error_spec(raw["x"], "X", owner), # 棒グラフ・ヒストグラムでは X 方向を隠す + x=_parse_error_spec(raw["x"], "X", owner) if plot_type in XY_TYPES else ErrorSpec(), # X 方向は XY の種類だけ cap_size=cap, ) @@ -802,13 +813,13 @@ def _parse_fill(raw: dict, owner: str) -> FillSettings: return FillSettings(lower=lower, upper=upper, alpha=alpha) -def _parse_color_column(value: Any, owner: str) -> str: - """色分けの列(scatterColor のときだけ。必須)。""" - field_name = f"{owner}色分けの列" +def _parse_color_column(value: Any, owner: str, what: str = "色分けの列") -> str: + """色分けの列(scatterColor では「色分けの列」、heatmap では「値の列」。どちらも必須)。""" + field_name = f"{owner}{what}" if value is None or (isinstance(value, str) and not value.strip()): - raise UserError(f"{owner}色分けの列を選んでください。", field=field_name) + raise UserError(f"{owner}{what}を選んでください。", field=field_name) if not isinstance(value, str) or not _COLUMN_RE.fullmatch(value.strip()): - raise UserError(f"{owner}「色分けの列」の指定が正しくありません。列を選び直してください。", field=field_name) + raise UserError(f"{owner}「{what}」の指定が正しくありません。列を選び直してください。", field=field_name) return value.strip() @@ -825,21 +836,29 @@ def _parse_series(raw_series: Any, plot_type: str = "line") -> tuple[SeriesSetti while sid in used_ids: sid += "_" used_ids.add(sid) - color = _string(s["color"], "色", owner=owner).strip() or _DEFAULT_SERIES["color"] - if not is_color_like(color): - raise UserError(f"{owner}「色」が不正です。", field="色") - line_width = _number(s["lineWidth"], "線幅", default=2.0, exclusive_min=0, owner=owner) - marker = _number(s["markerSize"], "点サイズ", default=None, minimum=0, owner=owner) + heat = plot_type == "heatmap" # ヒートマップは色・線幅・線種・点サイズを隠す(カラーマップを使う)。検証せず使わない + box = plot_type in BOX_TYPES # 箱ひげ・バイオリンは点サイズ・線種を隠す + color = _DEFAULT_SERIES["color"] + line_width = 2.0 + if not heat: + color = _string(s["color"], "色", owner=owner).strip() or _DEFAULT_SERIES["color"] + if not is_color_like(color): + raise UserError(f"{owner}「色」が不正です。", field="色") + line_width = _number(s["lineWidth"], "線幅", default=2.0, exclusive_min=0, owner=owner) + marker = None if (heat or box) else _number(s["markerSize"], "点サイズ", default=None, minimum=0, owner=owner) + line_style = "solid" if (heat or box) else _choice(s["lineStyle"], "線種", LINE_STYLES, owner=owner) marker_shape = "auto" fill = FillSettings() - if plot_type not in BAR_LIKE_TYPES: # 棒グラフ・ヒストグラムでは点の形と塗りつぶし帯を隠すので、検証せず使わない + if plot_type in XY_TYPES: # 点の形と塗りつぶし帯は XY の種類だけ。ほかは隠すので、検証せず使わない marker_shape = _choice(s["marker"], "点の形", MARKERS, owner=owner, field_name=f"{owner}点の形") if plot_type in {"scatter", "scatterColor"} and marker_shape == "none": raise UserError( f"{owner}「点の形」を「なし」にすると、散布図の点が見えなくなります。点の形を選んでください。", field=f"{owner}点の形" ) fill = _parse_fill(s["fill"], owner) - color_column = _parse_color_column(s["colorColumn"], owner) if plot_type == "scatterColor" else "" + color_column = "" + if plot_type in COLOR_COLUMN_TYPES: + color_column = _parse_color_column(s["colorColumn"], owner, "値の列" if heat else "色分けの列") out.append( SeriesSettings( id=sid, @@ -847,7 +866,7 @@ def _parse_series(raw_series: Any, plot_type: str = "line") -> tuple[SeriesSetti y=_string(s["y"], "Y列", owner=owner).strip(), color=color, line_width=line_width, - line_style=_choice(s["lineStyle"], "線種", LINE_STYLES, owner=owner), + line_style=line_style, marker_size=marker, label=_string(s["label"], "凡例名", owner=owner).strip(), # 横棒・積み上げ棒・ヒストグラム・色分け散布図では第2Y軸を隠す(false として扱い、検証しない) @@ -1056,6 +1075,7 @@ def parse_settings(raw: dict | None) -> Settings: plot_type = _choice(p["type"], "プロット種別", PLOT_TYPES) step_where, hist_bins, hist_density, colormap, colorbar_label = "post", None, False, "viridis", "" + box_fliers, box_means, violin_medians, violin_means = True, False, True, False if plot_type == "step": step = p["step"] if isinstance(p["step"], dict) else {} step_where = _choice(step.get("where", "post"), "段の付き方", STEP_WHERE_CHOICES) @@ -1063,14 +1083,22 @@ def parse_settings(raw: dict | None) -> Settings: hist = p["hist"] if isinstance(p["hist"], dict) else {} hist_bins = _int_range(hist.get("bins"), "区間の数", 1, MAX_HIST_BINS, default=None) hist_density = _boolean(hist.get("density", False), "確率密度") - elif plot_type == "scatterColor": + elif plot_type in COLOR_COLUMN_TYPES: colormap = _choice(p["colormap"], "カラーマップ", COLORMAPS) colorbar_label = _string(p["colorbarLabel"], "カラーバーのラベル").strip() + elif plot_type == "box": + box = p["box"] if isinstance(p["box"], dict) else {} + box_fliers = _boolean(box.get("fliers", True), "外れ値の点") + box_means = _boolean(box.get("means", False), "平均の印") + elif plot_type == "violin": + violin = p["violin"] if isinstance(p["violin"], dict) else {} + violin_medians = _boolean(violin.get("medians", True), "中央値の線") + violin_means = _boolean(violin.get("means", False), "平均の線") plot = PlotSettings( type=plot_type, skip_rows=_integer(p["skipRows"], "除外する先頭行数", default=0, minimum=0), - x_column="" if plot_type == "hist" else _string(p["xColumn"], "X列").strip(), # ヒストグラムは X列を隠す + x_column="" if plot_type in {"hist", "box", "violin", "heatmap"} else _string(p["xColumn"], "X列").strip(), # ヒストグラム・箱ひげ・バイオリン・ヒートマップは X列を隠す title=_string(p["title"], "タイトル").strip(), font_size=_number(p["fontSize"], "フォントサイズ", default=15.0, exclusive_min=0), figure=figure, @@ -1087,6 +1115,10 @@ def parse_settings(raw: dict | None) -> Settings: hist_density=hist_density, colormap=colormap, colorbar_label=colorbar_label, + box_fliers=box_fliers, + box_means=box_means, + violin_medians=violin_medians, + violin_means=violin_means, ) ax = merged["axes"] @@ -1097,7 +1129,7 @@ def parse_settings(raw: dict | None) -> Settings: and any(isinstance(s, dict) and s.get("secondaryAxis") is True for s in raw_series) ) axes = AxesSettings( - x=_parse_axis(ax, "x", "X"), + x=_parse_axis(ax, "x", "X", linear=plot.type in BOX_TYPES), # 箱ひげ・バイオリンの横軸はカテゴリなので、X のスケールは使わない y=_parse_axis(ax, "y", "Y", linear=plot.type == "barh"), # 横棒の縦軸はカテゴリなので、Y のスケールは使わない y2=_parse_axis(ax, "y2", "第2Y", ticks=y2_used), ) @@ -1112,8 +1144,8 @@ def parse_settings(raw: dict | None) -> Settings: check_axis_range(axes.y2, "第2Y") annotations = _parse_annotations(raw.get("annotations"), any(s.secondary_axis for s in series)) - # 棒グラフ・ヒストグラムでは近似曲線を使わない(隠れているので検証しない) - fits = () if plot.type in BAR_LIKE_TYPES else _parse_fits(raw.get("fits"), {s.id for s in series}) + # XY の種類以外では近似曲線を使わない(隠れているので検証しない) + fits = _parse_fits(raw.get("fits"), {s.id for s in series}) if plot.type in XY_TYPES else () # 計算した列は常に表示されるので、グラフの種類によらず検証する computed = _parse_computed(raw.get("computed"), file_ids) diff --git a/tests/unit/test_chart_types.py b/tests/unit/test_chart_types.py index f46be5b..2ac81cc 100644 --- a/tests/unit/test_chart_types.py +++ b/tests/unit/test_chart_types.py @@ -750,3 +750,581 @@ def fn(fig): assert proxies[0].get_sizes()[0] == pytest.approx((24 ** 0.5 + 1.5) ** 2) and list(proxies[0].get_linewidths()) == [0.0] bt.check(fn) + + +# ================================================================ Phase 5d: 箱ひげ図・バイオリン図・ヒートマップ(G8) + +import json # noqa: E402 +import shutil # noqa: E402 +import subprocess # noqa: E402 +from pathlib import Path # noqa: E402 + +from mplgui import settings as settings_module # noqa: E402 +from mplgui.settings import MAX_HEATMAP_SIZE # noqa: E402 + +REPO = Path(__file__).resolve().parents[2] +NEW_TYPES = ("box", "violin", "heatmap") + + +def dist_frame(n=40, seed=1): + """値の列 3 つ(a: 外れ値あり、b: 文字列を含む、c: 欠けた値だけ)と 1 行だけの列。""" + rng = np.random.default_rng(seed) + a = list(rng.normal(0, 1, n)) + a[0] = 15.0 # 外れ値 + b = [str(v) for v in rng.normal(3, 1, n)] + b[1] = "bad" + return pd.DataFrame({"a": a, "b": b, "c": [np.nan] * n, "one": [2.0] + [np.nan] * (n - 1)}) + + +def grid_frame(): + """縦長の表: x(数値)・y(数値)・z(値)・tx(文字列)・ty(文字列)。3×2 の格子で (1, 0) の組が 1 つ欠け、(0, 0) は 2 回現れる。""" + rows = [(0, 0, 1.0), (0, 0, 3.0), (0, 1, 4.0), (1, 1, 5.0), (2, 0, 6.0), (2, 1, 7.0)] + df = pd.DataFrame(rows, columns=["x", "y", "z"]) + df["tx"] = df["x"].map({0: "low", 1: "mid", 2: "high"}) + df["ty"] = df["y"].map({0: "off", 1: "on"}) + return df + + +def hm(x=0, y=1, z=2, **kw): + return series(y=y, x=x, colorColumn=f"__idx__{z}", **kw) + + +def build_new(tmp_path, plot_type, series_list, df, **plot): + return Built(tmp_path, df=df, series_list=series_list, plot_type=plot_type, mutate=mutate_plot(**plot)) + + +# ---------------------------------------------------------------- 設定(settings) + + +def test_new_types_accepted_and_plot_defaults(): + for t in NEW_TYPES: + sl = [hm()] if t == "heatmap" else [series()] + assert parse_settings(raw_settings(sl, plot_type=t)).plot.type == t + d = parse_settings(raw_settings(plot_type="line")).plot + assert (d.box_fliers, d.box_means, d.violin_medians, d.violin_means) == (True, False, True, False) + raw = settings_module.default_settings() + assert raw["plot"]["box"] == {"fliers": True, "means": False} and raw["plot"]["violin"] == {"medians": True, "means": False} + assert settings_module.SCHEMA_VERSION == 4 + + +def test_box_violin_options_validated_only_for_own_type(): + bad = {"box": {"fliers": "x", "means": 3}, "violin": {"medians": "x", "means": 3}} + for t in ("line", "bar", "hist", "heatmap", "box", "violin"): + sl = [hm()] if t == "heatmap" else [series()] + if t == "box": + bad2 = {"violin": bad["violin"]} + elif t == "violin": + bad2 = {"box": bad["box"]} + else: + bad2 = bad + parse_settings(raw_settings(sl, plot_type=t, mutate=mutate_plot(**bad2))) # 隠れているので、エラーにならない + with pytest.raises(UserError) as e: + parse_settings(raw_settings(plot_type="box", mutate=mutate_plot(box={"fliers": "x"}))) + assert e.value.field == "外れ値の点" + with pytest.raises(UserError) as e: + parse_settings(raw_settings(plot_type="violin", mutate=mutate_plot(violin={"medians": 3}))) + assert e.value.field == "中央値の線" + s = parse_settings(raw_settings(plot_type="box", mutate=mutate_plot(box={"fliers": False, "means": True}))).plot + assert (s.box_fliers, s.box_means) == (False, True) + s = parse_settings(raw_settings(plot_type="violin", mutate=mutate_plot(violin={"medians": False, "means": True}))).plot + assert (s.violin_medians, s.violin_means) == (False, True) + + +def test_heatmap_value_column_required_with_value_wording(): + with pytest.raises(UserError) as e: + parse_settings(raw_settings([series()], plot_type="heatmap")) + assert str(e.value) == "系列1の値の列を選んでください。" and e.value.field == "系列1の値の列" + with pytest.raises(UserError) as e: + parse_settings(raw_settings([hm(), series(colorColumn="abc")], plot_type="heatmap")) + assert e.value.field == "系列2の値の列" and "値の列" in str(e.value) + # scatterColor の文言は変えない + with pytest.raises(UserError) as e: + parse_settings(raw_settings([series()], plot_type="scatterColor")) + assert e.value.field == "系列1の色分けの列" + for t in ("box", "violin"): # 使わない種類では要らない・検証しない + assert parse_settings(raw_settings([series(colorColumn=5)], plot_type=t)).series[0].color_column == "" + + +def test_heatmap_colormap_used_and_validated_for_heatmap_only(): + with pytest.raises(UserError) as e: + parse_settings(raw_settings([hm()], plot_type="heatmap", mutate=mutate_plot(colormap="nope"))) + assert e.value.field == "カラーマップ" + s = parse_settings(raw_settings([hm()], plot_type="heatmap", mutate=mutate_plot(colormap="plasma", colorbarLabel=" 値 "))) + assert (s.plot.colormap, s.plot.colorbar_label) == ("plasma", "値") + for t in ("box", "violin"): + parse_settings(raw_settings(plot_type=t, mutate=mutate_plot(colormap="nope"))) + + +def test_new_types_hide_settings_and_keep_existing_rules(): + bad = {"marker": "zzz", "fill": {"lower": "x", "upper": ""}, "secondaryAxis": "yes", "errorBars": {"x": {"mode": "zzz"}, "y": {"mode": "zzz"}}} + fit = [{"series": "s1", "model": "zzz"}] + for t in NEW_TYPES: + extra = {"colorColumn": "__idx__2"} if t == "heatmap" else {} + s = parse_settings(raw_settings([series(**bad, **extra)], plot_type=t, fits=fit)) + sr = s.series[0] + assert s.fits == () and sr.marker == "auto" and not sr.fill.enabled and sr.secondary_axis is False + assert not sr.error_bars.y.enabled if hasattr(sr.error_bars.y, "enabled") else sr.error_bars.y.mode == "none" + assert sr.error_bars.x.mode == "none" + # 使う設定は従来どおり検証する(不透明度は3種類とも使う) + for t in NEW_TYPES: + extra = {"colorColumn": "__idx__2"} if t == "heatmap" else {} + with pytest.raises(UserError): + parse_settings(raw_settings([series(alpha=5, **extra)], plot_type=t)) + # box / violin は色・線幅を使う。線種・点サイズは使わない + with pytest.raises(UserError): + parse_settings(raw_settings([series(color="zzz")], plot_type="box")) + with pytest.raises(UserError): + parse_settings(raw_settings([series(lineWidth=0)], plot_type="violin")) + parse_settings(raw_settings([series(lineStyle="zzz", markerSize="x")], plot_type="box")) + parse_settings(raw_settings([series(lineStyle="zzz", markerSize="x")], plot_type="violin")) + # heatmap は色・線幅・線種・点サイズを使わない(検証せず、既定の値) + s = parse_settings(raw_settings([hm(color="zzz", lineWidth=-1, lineStyle="zzz", markerSize="x")], plot_type="heatmap")).series[0] + assert (s.line_width, s.line_style, s.marker_size) == (2.0, "solid", None) + # 既存の種類は従来どおり(色・線種は検証する) + for t in ("line", "bar", "hist"): + with pytest.raises(UserError): + parse_settings(raw_settings([series(color="zzz")], plot_type=t)) + with pytest.raises(UserError): + parse_settings(raw_settings([series(lineStyle="zzz")], plot_type=t)) + # X列(plot.xColumn)は新しい種類で使わない + for t in NEW_TYPES: + sl = [hm()] if t == "heatmap" else [series()] + assert parse_settings(raw_settings(sl, plot_type=t, mutate=mutate_plot(xColumn="__idx__3"))).plot.x_column == "" + assert parse_settings(raw_settings(plot_type="bar", mutate=mutate_plot(xColumn="__idx__3"))).plot.x_column == "__idx__3" + + +def test_python_rule_constants_are_consistent(): + S = settings_module + assert set(S.XY_TYPES) == {"line", "step", "scatter", "scatterColor"} + assert set(S.BOX_TYPES) == {"box", "violin"} + assert set(S.NO_Y2_TYPES) == {"barh", "barStacked", "hist", "scatterColor", "box", "violin", "heatmap"} + assert set(S.NO_Y_ERROR_TYPES) == {"barStacked", "hist", "box", "violin", "heatmap"} + assert set(S.SERIES_X_TYPES) == set(S.XY_TYPES) | {"heatmap"} + assert set(S.COLOR_COLUMN_TYPES) == {"scatterColor", "heatmap"} + assert set(S.CATEGORY_BAR_TYPES) == {"bar", "barStacked", "barh"} + + +@pytest.mark.skipif(shutil.which("node") is None, reason="node が無い") +def test_js_chart_types_match_python_rules(tmp_path): + """js/chart-types.js の述語が、settings.py の規則の定数と、全種類で一致する。""" + (tmp_path / "package.json").write_text('{"type": "module"}', encoding="utf-8") + (tmp_path / "chart-types.js").write_text((REPO / "js/chart-types.js").read_text(encoding="utf-8"), encoding="utf-8") + (tmp_path / "run.mjs").write_text( + """ + import * as m from "./chart-types.js"; + const out = {types: m.PLOT_TYPES}; + for (const t of m.PLOT_TYPES) { + out[t] = { + seriesX: m.usesSeriesX(t), globalX: m.usesGlobalX(t), marker: m.usesMarker(t), fill: m.usesFill(t), fits: m.usesFits(t), + xErr: m.usesXErrors(t), yErr: m.usesYErrors(t), y2: m.usesY2(t), color: m.usesColorColumn(t), colormap: m.usesColormap(t), + box: m.usesBox(t), violin: m.usesViolin(t), boxLike: m.isBoxLike(t), heatmap: m.isHeatmap(t), + }; + } + console.log(JSON.stringify(out)); + """, + encoding="utf-8", + ) + js = json.loads(subprocess.run(["node", "run.mjs"], cwd=tmp_path, capture_output=True, text=True, check=True, timeout=30).stdout) + S = settings_module + assert set(js["types"]) == set(S.PLOT_TYPES) + for t in S.PLOT_TYPES: + r = js[t] + assert r["seriesX"] == (t in S.SERIES_X_TYPES), t + assert r["globalX"] == (t in S.CATEGORY_BAR_TYPES), t + assert r["marker"] == r["fill"] == r["fits"] == r["xErr"] == (t in S.XY_TYPES), t + assert r["yErr"] == (t not in S.NO_Y_ERROR_TYPES), t + assert r["y2"] == (t not in S.NO_Y2_TYPES), t + assert r["color"] == r["colormap"] == (t in S.COLOR_COLUMN_TYPES), t + assert r["boxLike"] == (t in S.BOX_TYPES) and r["box"] == (t == "box") and r["violin"] == (t == "violin"), t + assert r["heatmap"] == (t == "heatmap") + + +# ---------------------------------------------------------------- 箱ひげ図 + + +def test_box_one_box_per_series_with_labels_and_positions(tmp_path): + bt = build_new(tmp_path, "box", [series(y=0), series(y=1, label="B系列"), series(y=3)], dist_frame()) + + def fn(fig): + ax = fig.axes[0] + assert [t.get_text() for t in ax.get_xticklabels()] == ["a [0]", "B系列", "one [3]"] + assert ax.get_legend() is None and ax.get_xlim() == (-0.5, 2.5) + + s = bt.check(fn) + assert s[0]["boxes"] == 3 and s[0]["violins"] == 0 and s[0]["meshes"] == 0 + assert s[0]["xlabel"] == "" and s[0]["ylabel"] == "" # 系列が複数なら縦軸の自動ラベルは空 + assert s[0]["markers"] == [] and s[0]["alphas"] == [] and s[0]["drawstyles"] == [] # 箱ひげの線は系列の線に数えない + assert s[0]["xscale"] == "linear" and s[0]["legend"] == [] + assert "tick_labels" not in bt.script.text and "vert=" not in bt.script.text + + +def test_box_values_style_fliers_means_and_numeric_cleaning(tmp_path): + df = dist_frame() + sl = [series(y=0, color="#00AA00", lineWidth=3.0, alpha=0.5), series(y=1)] + bt = build_new(tmp_path, "box", sl, df) + with bt.full() as run: + ax = run.fig.axes[0] + patches = [p for p in ax.patches if p.get_label() == "_box"] + assert len(patches) == 2 + assert patches[0].get_alpha() == 0.5 and patches[0].get_linewidth() == 3.0 + assert matplotlib_color(patches[0].get_facecolor()[:3]) == "#00aa00" and matplotlib_color(patches[0].get_edgecolor()[:3]) == "#000000" + meds = [ln for ln in ax.lines if ln.get_label() == "_box" and len(ln.get_xdata()) == 2 and ln.get_ydata()[0] == ln.get_ydata()[1] and abs(ln.get_xdata()[1] - ln.get_xdata()[0]) < 0.6 and ln.get_linewidth() == 3.0] + assert meds and all(ln.get_color() == "black" for ln in meds) + # 外れ値(15.0)が点として描かれる。NaN が混ざっても中央値は NaN にならない + fliers = [ln for ln in ax.lines if ln.get_marker() == "o" and ln.get_label() == "_box"] + assert any(15.0 in list(ln.get_ydata()) for ln in fliers) + assert not any(np.isnan(np.asarray(ln.get_ydata(), dtype=float)).any() for ln in ax.lines) + # 数値にできない値は警告(既存の形式) + assert any(w["series"] == 2 and "数値に変換できない値が1件" in w["message"] and '"bad"' in w["message"] for w in bt.plan.warnings) + assert bt.plan.warnings[0]["message"].startswith("系列2(b):") + # alpha 1 はコードに書かない + assert '"alpha"' in bt.script.text and bt.script.text.count('"alpha"') == 1 + + +def matplotlib_color(rgb): + from matplotlib.colors import to_hex + + return to_hex(rgb) + + +def test_box_fliers_and_means_toggle(tmp_path): + on = build_new(tmp_path, "box", [series(y=0)], dist_frame(), box={"fliers": True, "means": False}) + off = build_new(tmp_path, "box", [series(y=0)], dist_frame(), box={"fliers": False, "means": True}) + + def counts(bt): + with bt.full() as run: + ax = run.fig.axes[0] + fl = [ln for ln in ax.lines if ln.get_marker() == "o"] + means = [ln for ln in ax.lines if ln.get_marker() == "D"] + return sum(len(ln.get_xdata()) for ln in fl), len(means) + + assert counts(on)[0] >= 1 and counts(on)[1] == 0 and counts(off) == (0, 1) + assert "showfliers=True" in on.script.text and "showmeans=True" in off.script.text + on.check(lambda f: None) + off.check(lambda f: None) + + +def test_box_empty_series_keeps_its_position_and_warns(tmp_path): + bt = build_new(tmp_path, "box", [series(y=0), series(y=2), series(y=1)], dist_frame()) + assert any(w["series"] == 2 and "箱は描きません" in w["message"] for w in bt.plan.warnings) + assert [p.has_points for p in bt.plan.series] == [True, False, True] + assert "描ける値が無い" in bt.script.text + + def fn(fig): + ax = fig.axes[0] + assert ax.get_xlim() == (-0.5, 2.5) + assert [t.get_text() for t in ax.get_xticklabels()] == ["a [0]", "c [2]", "b [1]"] + centers = sorted(round(float((p.get_path().vertices[:, 0].min() + p.get_path().vertices[:, 0].max()) / 2), 3) for p in ax.patches if p.get_label() == "_box") + assert centers == [0.0, 2.0] # 2 つ目の位置は空いたまま + + assert bt.check(fn)[0]["boxes"] == 2 + + +def test_box_no_values_at_all_is_error(): + with pytest.raises(UserError) as e: + plan_of(df=dist_frame(), plot_type="box", series_list=[series(y=2)]) + assert "描画可能な数値データがありません" in str(e.value) + + +def test_box_datetime_y_is_error(): + df = pd.DataFrame({"d": pd.to_datetime(["2024-01-01", "2024-01-02"]), "v": [1.0, 2.0]}) + for t in ("box", "violin"): + with pytest.raises(UserError) as e: + plan_of(df=df, plot_type=t, series_list=[series(y=0)]) + assert e.value.field == "系列1のY列" and "日時の列" in str(e.value) + + +def test_box_single_series_label_and_multiple_sources(tmp_path): + bt = build_new(tmp_path, "box", [series(y=0)], dist_frame()) + s = bt.check(lambda f: None) + assert s[0]["ylabel"] == "a [0]" and s[0]["xlabel"] == "" + # データ元が違ってもよい(複数ファイル) + from mplgui.dataprep import plan_plot + + sets = raw_settings([series(y=0), series(y=0, source="d2")], plot_type="box") + sets["load"]["files"] = [{"id": "d1", "name": "a.csv", "sheet": ""}, {"id": "d2", "name": "b.csv", "sheet": ""}] + st = parse_settings(sets) + frames = {"d1": dist_frame(), "d2": dist_frame(seed=5)} + plan = plan_plot(frames, st) + assert [p.data_var for p in plan.series] == ["df1", "df2"] + from mplgui.codegen import generate_script + from mplgui.loader import load_file + from mplgui.runner import figure_summary, run_script + + infos = {} + for i, fid in enumerate(("d1", "d2")): + (tmp_path / f"f{i}.csv").write_text(frames[fid].to_csv(index=False), encoding="utf-8") + infos[fid] = load_file((tmp_path / f"f{i}.csv").read_bytes(), f"f{i}.csv", "", True).source + script = generate_script(st, infos, plan) + with run_script(script.auto_render_text(), injected={"df1": frames["d1"], "df2": frames["d2"]}) as run: + assert figure_summary(run.fig)[0]["boxes"] == 2 + + +def test_box_log_y_and_tick_step_and_annotation_index(tmp_path): + df = pd.DataFrame({f"s{i}": [1.0 + i, 5, 20, 80 + i] for i in range(5)}) + sl = [series(y=i) for i in range(5)] + + def mutate(raw): + raw["axes"]["y"]["scale"] = "log" + raw["axes"]["x"]["majorStep"] = 2 + raw["axes"]["x"]["scale"] = "log" # 横軸はカテゴリなので使わない + raw["annotations"] = [ + {"kind": "vline", "x": "1.5", "label": "境目"}, + {"kind": "text", "text": "メモ", "x": "3", "y": "30"}, + ] + + bt = Built(tmp_path, df=df, series_list=sl, plot_type="box", mutate=mutate) + s = bt.check(lambda f: None) + assert s[0]["yscale"] == "log" and s[0]["xscale"] == "linear" + assert [t for t in s[0]["xticklabels"] if t] == ["s0 [0]", "s2 [2]", "s4 [4]"] # 2 個おき + assert "tick_step = 2" in bt.script.text + assert s[0]["annotations"]["vlines"] == 1 and s[0]["annotations"]["texts"] == 1 + assert s[0]["legend"] == ["境目"] # 注釈の凡例名だけ。箱は凡例に出さない + # 注釈の X は 0 始まりの番号。文字列は解釈できない + with pytest.raises(UserError) as e: + Built(tmp_path, df=df, series_list=sl, plot_type="box", mutate=lambda r: r.update(annotations=[{"kind": "vline", "x": "abc"}])) + assert "注釈1" in str(e.value) + + +def test_box_axis_labels_override_and_title(tmp_path): + def mutate(raw): + raw["axes"]["x"]["label"] = "群" + raw["axes"]["y"]["label"] = "値" + + bt = Built(tmp_path, df=dist_frame(), series_list=[series(y=0), series(y=1)], plot_type="box", mutate=mutate) + s = bt.check(lambda f: None) + assert (s[0]["xlabel"], s[0]["ylabel"]) == ("群", "値") + + +def test_box_tick_step_too_many_is_error(): + df = pd.DataFrame({"a": [1.0, 2, 3]}) + with pytest.raises(UserError): + plan_of(df=df, plot_type="box", series_list=[series(y=0)], mutate=lambda r: r["axes"]["x"].update(majorStep=0.5)) + + +# ---------------------------------------------------------------- バイオリン図 + + +def test_violin_bodies_medians_means_and_colors(tmp_path): + sl = [series(y=0, color="#0000FF", lineWidth=2.5, alpha=0.4), series(y=1)] + bt = build_new(tmp_path, "violin", sl, dist_frame(), violin={"medians": True, "means": True}) + + def fn(fig): + ax = fig.axes[0] + bodies = [c for c in ax.collections if c.get_label() == "_violin"] + assert len(bodies) == 2 + assert bodies[0].get_alpha() == 0.4 and matplotlib_color(bodies[0].get_facecolor()[0][:3]) == "#0000ff" + assert bodies[0].get_linewidth()[0] == 2.5 + assert [t.get_text() for t in ax.get_xticklabels()] == ["a [0]", "b [1]"] + + s = bt.check(fn) + assert s[0]["violins"] == 2 and s[0]["boxes"] == 0 and s[0]["lines"] == 0 and s[0]["legend"] == [] + assert s[0]["collections"] == 2 + 2 * 5 # 胴 2 つ + (端 3 + 中央値 + 平均) × 2 + assert "vert=" not in bt.script.text + + +def test_violin_medians_off_and_means_off(tmp_path): + bt = build_new(tmp_path, "violin", [series(y=0)], dist_frame(), violin={"medians": False, "means": False}) + s = bt.check(lambda f: None) + assert s[0]["collections"] == 1 + 3 # 胴 + 端の線 3 つ + assert "showmedians=False" in bt.script.text + + +def test_violin_needs_two_values(tmp_path): + bt = build_new(tmp_path, "violin", [series(y=0), series(y=3), series(y=2)], dist_frame()) + msgs = [w["message"] for w in bt.plan.warnings] + assert any("系列2" in m and "値が1個だけ" in m for m in msgs) and any("系列3" in m and "描きません" in m for m in msgs) + s = bt.check(lambda f: None) + assert s[0]["violins"] == 1 and s[0]["xlim"] == [-0.5, 2.5] + with pytest.raises(UserError): + plan_of(df=dist_frame(), plot_type="violin", series_list=[series(y=3)]) # 描ける系列が無い + + +# ---------------------------------------------------------------- ヒートマップ + + +def test_heatmap_numeric_grid_missing_cell_duplicates_and_colorbar(tmp_path): + bt = build_new(tmp_path, "heatmap", [hm()], grid_frame(), colormap="plasma", colorbarLabel="温度 (℃)") + assert any("1件重複" in w["message"] and w["series"] == 1 for w in bt.plan.warnings) + + def fn(fig): + ax = fig.axes[0] + mesh = [c for c in ax.collections if type(c).__name__ == "QuadMesh"][0] + z = np.ma.filled(mesh.get_array().astype(float), np.nan).reshape(2, 3) + assert np.allclose(z, [[2.0, np.nan, 6.0], [4.0, 5.0, 7.0]], equal_nan=True) # (0,0) は 1 と 3 の平均。欠けたマスは NaN + assert mesh.get_cmap().name == "plasma" and ax.get_legend() is None + + s = bt.check(fn) + assert s[0]["meshes"] == 1 and s[0]["boxes"] == 0 and s[0]["violins"] == 0 + assert s[0]["colorbar"] == {"label": "温度 (℃)", "cmap": "plasma", "vmin": 2.0, "vmax": 7.0} + assert (s[0]["xlabel"], s[0]["ylabel"]) == ("x", "y [1]") and len(s) == 1 + assert s[0]["xlim"] == [-0.5, 2.5] and s[0]["ylim"] == [-0.5, 1.5] + assert 'shading="nearest"' in bt.script.text and "pivot_table" in bt.script.text and "alpha=" not in bt.script.text + + +def test_heatmap_default_colorbar_label_and_alpha(tmp_path): + bt = build_new(tmp_path, "heatmap", [hm(alpha=0.5)], grid_frame()) + s = bt.check(lambda f: None) + assert s[0]["colorbar"]["label"] == "z [2]" and s[0]["colorbar"]["cmap"] == "viridis" + assert "alpha=0.5" in bt.script.text + with bt.full() as run: + mesh = [c for c in run.fig.axes[0].collections if type(c).__name__ == "QuadMesh"][0] + assert mesh.get_alpha() == 0.5 + + +def test_heatmap_text_axes_in_order_of_appearance_and_tick_step(tmp_path): + df = grid_frame() + bt = build_new(tmp_path, "heatmap", [hm(x=3, y=4)], df) + + def fn(fig): + ax = fig.axes[0] + assert [t.get_text() for t in ax.get_xticklabels()] == ["low", "mid", "high"] # 現れた順(アルファベット順ではない) + assert [t.get_text() for t in ax.get_yticklabels()] == ["off", "on"] + + s = bt.check(fn) + assert s[0]["xlim"] == [-0.5, 2.5] and (s[0]["xlabel"], s[0]["ylabel"]) == ("tx", "ty [4]") + + wide = pd.DataFrame({"x": [f"c{i}" for i in range(10)] * 2, "y": ["r1"] * 10 + ["r2"] * 10, "z": np.arange(20.0)}) + bt = Built(tmp_path, df=wide, series_list=[hm()], plot_type="heatmap", mutate=lambda r: r["axes"]["x"].update(majorStep=3)) + s = bt.check(lambda f: None) + assert [t for t in s[0]["xticklabels"] if t] == ["c0", "c3", "c6", "c9"] and "x_tick_step = 3" in bt.script.text + + +def test_heatmap_numeric_looking_text_axis_is_converted_with_warning(tmp_path): + df = pd.DataFrame({"x": ["1", "2", "bad", "1", "2"], "y": [1.0, 1, 1, 2, 2], "z": [1.0, 2, 3, 4, 5]}) + bt = build_new(tmp_path, "heatmap", [hm()], df) + assert any("X列" in w["message"] and "数値に変換できない値が1件" in w["message"] for w in bt.plan.warnings) + s = bt.check(lambda f: None) + assert s[0]["xlim"] == [0.5, 2.5] # X は数値の軸(bad の行は除外) + + +def test_heatmap_value_column_warnings_and_errors(): + df = grid_frame() + df["zs"] = ["1", "x", "3", "4", "5", "6"] + plan = plan_of(df=df, plot_type="heatmap", series_list=[hm(z=5)]) + assert any("値の列" in w["message"] and "数値にできない値が1件" in w["message"] and "その行は使いません" in w["message"] for w in plan.warnings) + df2 = grid_frame() + df2["d"] = pd.to_datetime(["2024-01-01"] * 6) + for kw, field_name in (({"z": 5}, "系列1の値の列"), ({"x": 5}, "系列1のX列"), ({"y": 5}, "系列1のY列")): + with pytest.raises(UserError) as e: + plan_of(df=df2, plot_type="heatmap", series_list=[hm(**kw)]) + assert e.value.field == field_name and "日時の列" in str(e.value) + with pytest.raises(UserError) as e: + plan_of(df=df, plot_type="heatmap", series_list=[hm(z=9)]) + assert e.value.field == "系列1の値の列" and "列" in str(e.value) + with pytest.raises(UserError) as e: + plan_of(df=df, plot_type="heatmap", series_list=[hm(), hm()]) + assert str(e.value).startswith("ヒートマップは系列1つで描きます。") and e.value.field == "系列" + nan_z = pd.DataFrame({"x": [0, 1], "y": [0, 1], "z": ["a", "b"]}) + with pytest.raises(UserError) as e: + plan_of(df=nan_z, plot_type="heatmap", series_list=[hm()]) + assert "描画可能な数値データがありません" in str(e.value) + + +def test_heatmap_size_limit(): + n = MAX_HEATMAP_SIZE + ok = pd.DataFrame({"x": np.arange(n, dtype=float), "y": np.zeros(n), "z": np.ones(n)}) + assert plan_of(df=ok, plot_type="heatmap", series_list=[hm()]).heatmap.x_count == n + big = pd.DataFrame({"x": np.arange(n + 1, dtype=float), "y": np.zeros(n + 1), "z": np.ones(n + 1)}) + with pytest.raises(UserError) as e: + plan_of(df=big, plot_type="heatmap", series_list=[hm()]) + assert e.value.field == "系列1のX列" and f"{n + 1}種類" in str(e.value) and "X" in str(e.value) + with pytest.raises(UserError) as e: + plan_of(df=big[["y", "x", "z"]], plot_type="heatmap", series_list=[hm()]) + assert e.value.field == "系列1のY列" and "Y" in str(e.value) + + +def test_heatmap_single_row_column_log_axes_and_annotation(tmp_path): + df = pd.DataFrame({"x": [1.0, 10, 100], "y": [1.0, 1, 1], "z": [1.0, 2, 3]}) # 1 行だけの格子 + + def mutate(raw): + raw["axes"]["x"]["scale"] = "log" + raw["annotations"] = [{"kind": "vline", "x": "10"}] + + bt = Built(tmp_path, df=df, series_list=[hm()], plot_type="heatmap", mutate=mutate) + s = bt.check(lambda f: None) + assert s[0]["meshes"] == 1 and s[0]["xscale"] == "log" and s[0]["annotations"]["vlines"] == 1 + one = pd.DataFrame({"x": [3.0], "y": [4.0], "z": [5.0]}) # 1 マスだけ + assert Built(tmp_path, df=one, series_list=[hm()], plot_type="heatmap").check(lambda f: None)[0]["meshes"] == 1 + + +def test_heatmap_annotation_on_text_axis_is_index(tmp_path): + def mutate(raw): + raw["annotations"] = [{"kind": "vline", "x": "1"}, {"kind": "hline", "y": "0.5"}] + + bt = Built(tmp_path, df=grid_frame(), series_list=[hm(x=3, y=4)], plot_type="heatmap", mutate=mutate) + s = bt.check(lambda f: None) + assert s[0]["annotations"]["vlines"] == 1 and s[0]["annotations"]["hlines"] == 1 + # 日時の注釈は文字列の軸では使えない + with pytest.raises(UserError): + Built(tmp_path, df=grid_frame(), series_list=[hm(x=3, y=4)], plot_type="heatmap", mutate=lambda r: r.update(annotations=[{"kind": "vline", "x": "2024-01-01"}])) + + +def test_heatmap_legend_not_emitted_without_labelled_artists(tmp_path): + bt = Built(tmp_path, df=grid_frame(), series_list=[hm(label="系列名")], plot_type="heatmap") + assert "凡例に出せるラベルが無い" in bt.script.text + assert bt.check(lambda f: None)[0]["legend"] == [] + + +# ---------------------------------------------------------------- 共通 + +@pytest.mark.parametrize("plot_type", NEW_TYPES) +def test_new_types_full_and_auto_summaries_match(tmp_path, plot_type): + if plot_type == "heatmap": + bt = build_new(tmp_path, plot_type, [hm(x=3, y=1)], grid_frame()) + else: + bt = build_new(tmp_path, plot_type, [series(y=0), series(y=1, label="B")], dist_frame()) + bt.check(lambda f: None) + + +@pytest.mark.parametrize("plot_type", NEW_TYPES) +def test_new_types_steps_and_axis_ranges(tmp_path, plot_type): + bt = build_new(tmp_path, plot_type, [hm()] if plot_type == "heatmap" else [series(y=0)], grid_frame() if plot_type == "heatmap" else dist_frame()) + steps = bt.script.steps + assert steps and all(s.message for s in steps) + if plot_type == "heatmap": + assert {"系列1の値の列", "カラーマップ"} <= {s.field for s in steps} + assert any("ヒートマップ" in s.message for s in steps) + else: + assert any(s.message.startswith("グラフを描画できませんでした") for s in steps) + + +def test_existing_types_summaries_have_zero_new_keys(tmp_path): + for t in ("line", "bar", "hist", "scatterColor"): + sl = [colored()] if t == "scatterColor" else [series(y=1, x=4)] + s = build(tmp_path, t, sl).check(lambda f: None) + assert (s[0]["boxes"], s[0]["violins"], s[0]["meshes"]) == (0, 0, 0) + + +def test_injection_new_types(tmp_path): + import ast + + evil = '"); import os; os.system("echo hi") #' + label = "'''\n" + evil + df = pd.DataFrame( + { + 'c"\'\n' + evil: ["a", "b", "a", "b", "c"], + "v" + evil: [1.0, 2, 3, 4, 5], + "z" + evil: [1.0, 2, 3, 4, 6], + "t" + evil: ["p", "q", "p", "q", "p"], + } + ) + cases = [ + ("box", [series(y=1, label=label), series(y=2, label=label)], {}), + ("violin", [series(y=1, label=label), series(y=2, label=label)], {}), + ("heatmap", [series(y=3, x=0, label=label, colorColumn="__idx__2")], {"colorbarLabel": label}), + ] + for plot_type, sl, plot in cases: + bt = build_new(tmp_path, plot_type, sl, df, **plot) + tree = ast.parse(bt.script.text) + assert not [n for n in ast.walk(tree) if isinstance(n, ast.Call) and getattr(n.func, "attr", "") == "system"] + for line in bt.script.text.splitlines(): + if line.lstrip().startswith("#"): + continue + assert "echo hi" not in line.split(" #")[0] or line.count('"') >= 2 # コードの中では文字列の内側にだけ現れる + with bt.full() as run: + assert run.fig is not None and "echo hi" not in run.output + bt.check(lambda f: None) + # 凡例名は目盛のラベルとしてリテラルに入る(柔軟な文字列でもそのまま読み戻せる) + bt = build_new(tmp_path, "box", [series(y=1, label=label)], df) + assert bt.check(lambda f: None)[0]["xticklabels"][0] == label From cd849b3e4a18630580b8b3a9140c193eee7ba4fb Mon Sep 17 00:00:00 2001 From: mioupa <79833278+mioupa@users.noreply.github.com> Date: Thu, 12 Nov 2026 15:27:45 +0900 Subject: [PATCH 04/10] Add custom-function fits (scipy curve_fit) to settings, the plot plan and generated code (Phase 5d, G10) scipy is imported by the generated code only when a custom fit is used, and is loaded in the browser on demand (ensureScipy). Pin scipy 1.18.0 (the Pyodide 314.0.3 version) as a dev dependency for the unit tests. Co-Authored-By: Claude Opus 5.5 --- js/defaults.js | 2 +- py/main.py | 40 +++++++ py/mplgui/api.py | 12 ++ py/mplgui/codegen.py | 53 ++++++++- py/mplgui/dataprep.py | 24 +++- py/mplgui/runner.py | 4 +- py/mplgui/settings.py | 34 +++++- pyproject.toml | 1 + tests/unit/test_fits.py | 247 ++++++++++++++++++++++++++++++++++++++++ uv.lock | 33 ++++++ 10 files changed, 440 insertions(+), 10 deletions(-) diff --git a/js/defaults.js b/js/defaults.js index 15c2554..c2c7f49 100644 --- a/js/defaults.js +++ b/js/defaults.js @@ -62,7 +62,7 @@ export const DEFAULT_ANNOTATION = { }; // 近似曲線(fits[])1つの既定値。id は f1, f2, ...。series は追加するときに系列1の id にする -export const DEFAULT_FIT = { id: "f1", series: "s1", model: "linear", degree: 2, show: "legend", color: "", lineStyle: "dashed" }; +export const DEFAULT_FIT = { id: "f1", series: "s1", model: "linear", degree: 2, show: "legend", color: "", lineStyle: "dashed", expr: "", initial: { a: 1, b: 1, c: 1, d: 1, e: 1 } }; // 計算した列(computed[])1つの既定値。id は追加するときに c1, c2, ... を振る(削除しても再利用しない) export const DEFAULT_COMPUTED = { id: "", source: "", name: "", expr: "" }; diff --git a/py/main.py b/py/main.py index 1eaf3a0..d48eb33 100644 --- a/py/main.py +++ b/py/main.py @@ -72,6 +72,45 @@ async def _ensure_excel(): return json.dumps({"ok": False, "error": err.to_dict()}, ensure_ascii=False) +_SCIPY_STATE = {"ready": False, "task": None} + + +def _scipy_available(): + import importlib.util + + return importlib.util.find_spec("scipy") is not None + + +async def _install_scipy(): + import pyodide_js + + # scipy は Pyodide 同梱のパッケージなので、名前だけで読み込める(初回は約 14 MB を取得する) + await pyodide_js.loadPackage(to_js(["scipy"])) + + +async def _ensure_scipy(): + """任意の式の近似曲線を使う前に JS から呼ぶ。2回目以降は何もしない。戻り値は JSON 文字列。""" + if _SCIPY_STATE["ready"] or _scipy_available(): + _SCIPY_STATE["ready"] = True + return json.dumps({"ok": True}) + try: + if _SCIPY_STATE["task"] is None: + _SCIPY_STATE["task"] = asyncio.ensure_future(_install_scipy()) + await _SCIPY_STATE["task"] + if not _scipy_available(): + raise RuntimeError("scipy を導入後も import できません") + _SCIPY_STATE["ready"] = True + return json.dumps({"ok": True}) + except Exception as exc: + _SCIPY_STATE["task"] = None # 次回は再試行する + err = UserError( + "scipy を読み込めませんでした。インターネット接続を確かめてから、もう一度試してください。", + field="近似曲線", + detail=f"{type(exc).__name__}: {exc}", + ) + return json.dumps({"ok": False, "error": err.to_dict()}, ensure_ascii=False) + + def _load_file(name, data, load_settings_json, source_id=None, pasted=None): # source_id / pasted は JS が渡さない(null / undefined)ときは既定値 return api.load_file_json( @@ -121,6 +160,7 @@ def _script_filename(save_filename): # create_proxy の参照を保持しておく(GC されると JS から呼べなくなる) _PROXIES = { "ensureExcel": create_proxy(_ensure_excel), + "ensureScipy": create_proxy(_ensure_scipy), "loadFile": create_proxy(_load_file), "removeSource": create_proxy(_remove_source), "clearSources": create_proxy(_clear_sources), diff --git a/py/mplgui/api.py b/py/mplgui/api.py index 1a573ff..0808d57 100644 --- a/py/mplgui/api.py +++ b/py/mplgui/api.py @@ -8,6 +8,7 @@ import base64 import dataclasses import hashlib +import importlib.util import json import struct import traceback @@ -247,11 +248,22 @@ def _generate(settings: Settings): return plan, generate_script(settings, infos, plan) +def _require_scipy(plan) -> None: + """任意の式の近似曲線があるのに scipy が無いときは、日本語のエラーにする(ブラウザでは JS が先に ensureScipy を呼ぶ)。""" + custom = [f.number for f in plan.fits if f.model == "custom"] + if custom and importlib.util.find_spec("scipy") is None: + raise UserError( + "scipy を読み込めていません。任意の式の近似曲線には scipy が必要です。ページを再読み込みして、もう一度試してください。", + field=f"近似曲線{custom[0]}", + ) + + def _run(settings: Settings | None, code: str | None, *, file_format: str, transparent: bool, dpi: int, svg_text: str = "path"): """GUI 同期(code が None): 設定から生成したスクリプトを、読込済みの df で実行する(読込・保存の行は空にする)。 編集モード(code が文字列): そのスクリプトを、アップロードしたファイルのある作業フォルダで実行する。設定は使わない。""" if code is None: plan, script = _generate(settings) + _require_scipy(plan) # 計算した列は生成コードが df.insert で足すので、そのデータ元はコピーを渡す(描画のたびに列が増えるのを防ぐ) with_computed = {c.data_id for c in plan.computed} injected = { diff --git a/py/mplgui/codegen.py b/py/mplgui/codegen.py index cc48289..e0bd0b7 100644 --- a/py/mplgui/codegen.py +++ b/py/mplgui/codegen.py @@ -181,10 +181,11 @@ def _emit_header( f"「{comment_text(src.filename)}」" + ("(貼り付けたデータを保存したもの)" if src.pasted else "") for src in sources ) usage = f"# 使い方: データファイル {names} を、このスクリプトと同じフォルダに置いて、python {SCRIPT_NAME} で実行します。" + custom_fit = plan is not None and _uses_custom_fit(plan) b.add( "# matplotlib GUI が生成したスクリプト", usage, - "# 必要なライブラリ: pandas, matplotlib, numpy", + "# 必要なライブラリ: pandas, matplotlib, numpy" + (", scipy(任意の式の近似曲線。pip install scipy)" if custom_fit else ""), ) if plan is not None and _uses_date_axis(plan): b.add("import matplotlib.dates as mdates") @@ -196,6 +197,10 @@ def _emit_header( b.add( "import numpy as np", "import pandas as pd", + ) + if custom_fit: + b.add("from scipy.optimize import curve_fit") + b.add( "", "# 日本語フォント: 一覧の先頭から、見つかったものを使う。", "# どれも無い環境では DejaVu Sans になる(日本語は豆腐になるが、実行はできる)", @@ -464,7 +469,48 @@ def _emit_band(b: _Builder, s: SeriesSettings, p: SeriesPlan, step: str = "") -> def _uses_poly_text(plan: PlotPlan) -> bool: - return plan.plot_type in XY_TYPES and any(f.show in {"legend", "text"} for f in plan.fits) + return plan.plot_type in XY_TYPES and any(f.show in {"legend", "text"} and f.model != "custom" for f in plan.fits) + + +def _uses_custom_fit(plan: PlotPlan) -> bool: + return plan.plot_type in XY_TYPES and any(f.model == "custom" for f in plan.fits) + + +def _custom_label_expr(fit: FitPlan) -> str: + """任意の式の近似曲線の凡例・図の中の文字を作る式(パラメータは実行時に fit_params から作る)。""" + names = "[" + ", ".join(literal(name) for name in fit.params) + "]" + head = literal(f"{fit.label_prefix}: y = {expr_module.model_to_text(fit.node)}(") + return f'{head} + ", ".join(f"{{name}} = {{value:.4g}}" for name, value in zip({names}, fit_params)) + f"、$R^2$ = {{r2:.4f}})"' + + +def _emit_custom_fit(b: _Builder, p: SeriesPlan, fit: FitPlan) -> None: + params = ", ".join(fit.params) + func = f"fit_model_{fit.number}" + body = expr_module.model_to_code(fit.node, lambda v: literal(float(v))) + p0 = "[" + ", ".join(literal(float(v)) for v in fit.p0) + "]" + b.add( + f"# 近似曲線{fit.number}: 系列{p.number}({comment_text(fit.series_label)})に任意の式を当てはめる(最小二乗。scipy の curve_fit)", + f"def {func}(x, {params}): # 近似曲線{fit.number}の式: {comment_text(fit.expr)}", + f" return {body}", + ) + with b.step(f"近似曲線{fit.number}: 式を当てはめられませんでした。初期値を変えてみてください。", f"近似曲線{fit.number}の初期値"): + b.add( + f"fit_params, _ = curve_fit({func}, x[ok], y[ok], p0={p0}, maxfev=10000) # 初期値 p0 から当てはめる(パラメータは {params} の順)", + f"fit_y = {func}(x[ok], *fit_params) # 当てはめた曲線の、データの X での値", + "if not np.all(np.isfinite(fit_y)): # 初期値のところで計算できない値になると、curve_fit は黙って初期値を返すことがある", + ' raise ValueError("当てはめた式の値が有限ではありません")', + "r2 = 1 - np.sum((y[ok] - fit_y) ** 2) / np.sum((y[ok] - y[ok].mean()) ** 2) # 決定係数 R²", + "x_fit = np.linspace(x[ok].min(), x[ok].max(), 200) # 近似曲線を描く X(データの範囲を 200 点)", + ) + style = f"color={literal(fit.color)}, linewidth={literal(fit.line_width)}, linestyle={literal(fit.line_style)}" + label = _custom_label_expr(fit) if fit.show == "legend" else '"_fit"' + b.add(f"{fit.target}.plot(x_fit, {func}(x_fit, *fit_params), {style}, label={label})") + if fit.show == "text": + y_pos = literal(round(0.97 - 0.07 * fit.text_index, 2)) + b.add( + f"{fit.target}.text(0.03, {y_pos}, {_custom_label_expr(fit)}, transform={fit.target}.transAxes, va=\"top\", " + f"color={literal(fit.color)}, fontsize=FONT_SIZE) # 近似曲線の式を図の中(左上)に書く" + ) def _fit_label_expr(fit: FitPlan) -> str: @@ -476,6 +522,9 @@ def _emit_fits(b: _Builder, plan: PlotPlan, p: SeriesPlan) -> None: for fit in plan.fits: if fit.series_number != p.number: continue + if fit.model == "custom": + _emit_custom_fit(b, p, fit) + continue with b.step(f"近似曲線{fit.number}を描けませんでした。近似曲線の設定とデータを確認してください。", f"近似曲線{fit.number}"): kind = "1 次式" if fit.degree == 1 else f"{fit.degree} 次式" b.add( diff --git a/py/mplgui/dataprep.py b/py/mplgui/dataprep.py index bd6a5d0..ecf473b 100644 --- a/py/mplgui/dataprep.py +++ b/py/mplgui/dataprep.py @@ -205,6 +205,12 @@ class FitPlan: label_prefix: str # 凡例・図の中の文字の先頭(「温度の近似」) text_index: int # show が text の近似曲線のうちの順番(0 始まり。それ以外は -1) target: str # ax / ax2 + # 任意の式(model が custom)のとき: 解釈済みの式の木・使うパラメータ(a〜e の順)・初期値 + model: str = "poly" # linear / poly / custom + expr: str = "" + node: object = field(default=None, compare=False, repr=False) + params: tuple[str, ...] = () + p0: tuple[float, ...] = () @dataclass(frozen=True) @@ -538,9 +544,16 @@ def _check_fit_data(n: int, fit, p: "SeriesPlan", x: pd.Series, y: pd.Series) -> if p.categorical_x: raise _fit_error(n, "X が文字列の列の系列は近似できません。") distinct = int(pd.Series(x).nunique()) - need = fit.degree + 1 - if distinct < need: - raise _fit_error(n, f"{fit.degree}次式で近似するには、X の異なる値が{need}個以上必要です(今は{distinct}個)。") + if fit.model == "custom": + need = len(fit.params) + 1 + if distinct < need: + raise _fit_error( + n, f"パラメータが{len(fit.params)}個の式で近似するには、X の異なる値が{need}個以上必要です(今は{distinct}個)。" + ) + else: + need = fit.degree + 1 + if distinct < need: + raise _fit_error(n, f"{fit.degree}次式で近似するには、X の異なる値が{need}個以上必要です(今は{distinct}個)。") if int(pd.Series(y).nunique()) < 2: raise _fit_error(n, "Y の値がすべて同じなので、近似できません(決定係数 R² を計算できません)。") @@ -568,6 +581,11 @@ def _build_fit_plans(settings: Settings, plans: list["SeriesPlan"]) -> tuple[Fit label_prefix=f"{base}の近似", text_index=text_index if fit.show == "text" else -1, target="ax2" if sp.secondary else "ax", + model=fit.model, + expr=fit.expr, + node=fit.expr_node, + params=fit.params, + p0=fit.initial, ) ) if fit.show == "text": diff --git a/py/mplgui/runner.py b/py/mplgui/runner.py index 6cad8a6..7d440fa 100644 --- a/py/mplgui/runner.py +++ b/py/mplgui/runner.py @@ -252,8 +252,8 @@ def figure_summary(fig) -> list[dict]: (SyntaxError, "書き方(文法)が正しくありません"), (NameError, "定義されていない名前を使っています"), (FileNotFoundError, "ファイルが見つかりません"), - (ModuleNotFoundError, "読み込めないライブラリがあります(使えるのは pandas, matplotlib, numpy です)"), - (ImportError, "読み込めないライブラリや名前があります(使えるのは pandas, matplotlib, numpy です)"), + (ModuleNotFoundError, "読み込めないライブラリがあります(使えるのは pandas, matplotlib, numpy です。scipy は任意の式の近似曲線でも使えます)"), + (ImportError, "読み込めないライブラリや名前があります(使えるのは pandas, matplotlib, numpy です。scipy は任意の式の近似曲線でも使えます)"), (KeyError, "存在しないキー(列名など)を指定しています"), (IndexError, "範囲の外の位置を指定しています"), (TypeError, "型が合わない操作をしています"), diff --git a/py/mplgui/settings.py b/py/mplgui/settings.py index b9bbe52..e7f3f40 100644 --- a/py/mplgui/settings.py +++ b/py/mplgui/settings.py @@ -74,7 +74,7 @@ ANNOTATION_KINDS = ("text", "hline", "vline", "hspan", "vspan") ANNOTATION_COORDS = ("data", "axes") ANNOTATION_AXES = ("y", "y2") -FIT_MODELS = ("linear", "poly") +FIT_MODELS = ("linear", "poly", "custom") FIT_SHOWS = ("legend", "text", "none") MAX_ANNOTATIONS = 50 MAX_FITS = 20 @@ -113,7 +113,10 @@ "label": "", } _DEFAULT_COMPUTED = {"id": "", "source": "", "name": "", "expr": ""} -_DEFAULT_FIT = {"id": "f1", "series": "s1", "model": "linear", "degree": 2, "show": "legend", "color": "", "lineStyle": "dashed"} +_DEFAULT_FIT = { + "id": "f1", "series": "s1", "model": "linear", "degree": 2, "show": "legend", "color": "", "lineStyle": "dashed", + "expr": "", "initial": {"a": 1, "b": 1, "c": 1, "d": 1, "e": 1}, +} _DEFAULT_SERIES = { "id": "s1", @@ -389,6 +392,11 @@ class FitSettings: show: str = "legend" # legend / text / none color: str = "" # "" = 系列の色 line_style: str = "dashed" + # custom(任意の式)のときだけ使う。expr_node は解釈済みの式、params は使うパラメータ(a〜e の順)、initial はその初期値 + expr: str = "" + expr_node: Any = field(default=None, compare=False, repr=False) + params: tuple[str, ...] = () + initial: tuple[float, ...] = () @dataclass(frozen=True) @@ -982,6 +990,24 @@ def _parse_fits(raw: Any, series_ids: set[str]) -> tuple[FitSettings, ...]: degree = 1 if model == "poly": degree = _int_range(f["degree"], f"{owner}次数", 2, 6, default=2) + expr_text, node, params, initial = "", None, (), () + if model == "custom": + expr_text = _string(f["expr"], "式", owner=owner) + if not expr_text.strip(): + raise UserError(f"近似曲線{n}の式を入力してください。", field=f"近似曲線{n}の式") + try: + node = expr_module.parse_model(expr_text) + except expr_module.ExprError as e: + raise UserError(f"近似曲線{n}の式: {e}", field=f"近似曲線{n}の式") from None + params = expr_module.model_params(node) + given_initial = f["initial"] if isinstance(f["initial"], dict) else {} + initial = tuple( + _number( + given_initial.get(name, 1), f"初期値({name})", default=1.0, owner=owner, + field_name=f"{owner}初期値({name})", + ) + for name in params + ) color = _string(f["color"], "色", owner=owner).strip() if color and not is_color_like(color): raise UserError(f"{owner}「色」が不正です。", field=f"{owner}色") @@ -994,6 +1020,10 @@ def _parse_fits(raw: Any, series_ids: set[str]) -> tuple[FitSettings, ...]: show=_choice(f["show"], "式の表示先", FIT_SHOWS, owner=owner, field_name=f"{owner}式の表示先"), color=color, line_style=_choice(f["lineStyle"], "線種", LINE_STYLES, owner=owner, field_name=f"{owner}線種"), + expr=expr_text, + expr_node=node, + params=params, + initial=initial, ) ) return tuple(out) diff --git a/pyproject.toml b/pyproject.toml index 62fb3d2..c8c296c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -24,6 +24,7 @@ dev = [ "matplotlib==3.10.8", "numpy==2.4.3", "openpyxl==3.1.5", + "scipy==1.18.0", "pytest>=9.1.1", "pytest-playwright>=0.9.0", "pyyaml>=6.0.3", diff --git a/tests/unit/test_fits.py b/tests/unit/test_fits.py index 0ec64f3..b559b3b 100644 --- a/tests/unit/test_fits.py +++ b/tests/unit/test_fits.py @@ -309,3 +309,250 @@ def test_column_name_comment_cannot_inject(tmp_path): def test_uses_only_numpy_in_generated_code(tmp_path): b = Built(tmp_path, df=quad_frame(), fits=[fit()]) assert "polyfit" not in b.script.text and "scipy" not in b.script.text + + +# ---------------------------------------------------------------- 任意の式(G10) + +from scipy.optimize import curve_fit # noqa: E402 + +from mplgui.api import _step_error # noqa: E402 +from mplgui.runner import ScriptError, run_script # noqa: E402 + + +def custom(expr="a * exp(-b * x) + c", **kw): + d = {"series": "s1", "model": "custom", "expr": expr} + d.update(kw) + return d + + +def decay_frame(): + t = np.linspace(0, 5, 30) + return pd.DataFrame({"t": t, "y": 3.0 * np.exp(-0.8 * t) + 0.5 + 0.01 * np.cos(7 * t)}) + + +def logistic_frame(): + t = np.linspace(-5, 5, 40) + return pd.DataFrame({"t": t, "y": 4.0 / (1 + np.exp(-1.5 * (t - 0.5))) + 0.02 * np.sin(5 * t)}) + + +def test_custom_defaults_and_settings(): + d = default_fit() + assert d["expr"] == "" and d["initial"] == {"a": 1, "b": 1, "c": 1, "d": 1, "e": 1} + f = parse_settings(raw_settings(fits=[custom(initial={"a": "2.5", "b": 3, "c": 7})])).fits[0] + assert f.model == "custom" and f.params == ("a", "b", "c") and f.initial == (2.5, 3.0, 7.0) + # 使うパラメータだけ。式の中の順に関わらず a〜e の順 + f = parse_settings(raw_settings(fits=[custom("c * x + a", initial={"a": 4, "c": 9})])).fits[0] + assert f.params == ("a", "c") and f.initial == (4.0, 9.0) + # 空欄・欠けは 1 + f = parse_settings(raw_settings(fits=[custom("a * x", initial={"a": ""})])).fits[0] + assert f.initial == (1.0,) + + +@pytest.mark.parametrize( + "item, field_name, text", + [ + (custom(""), "近似曲線1の式", "近似曲線1の式を入力してください。"), + (custom(" "), "近似曲線1の式", "近似曲線1の式を入力してください。"), + (custom("a * (x"), "近似曲線1の式", "近似曲線1の式: "), + (custom("a * " + "x" * 300), "近似曲線1の式", "近似曲線1の式: "), + (custom("a * b"), "近似曲線1の式", "x を含めて"), + (custom("x + 1"), "近似曲線1の式", "パラメータ"), + (custom("max(x) * a"), "近似曲線1の式", "近似曲線1の式: "), + (custom("a * x", initial={"a": "abc"}), "近似曲線1の初期値(a)", "初期値(a)"), + (custom("a * x", initial={"a": float("inf")}), "近似曲線1の初期値(a)", "初期値(a)"), + (custom("a * x + b", initial={"a": 1, "b": None if False else "zz"}), "近似曲線1の初期値(b)", "初期値(b)"), + ], +) +def test_custom_validation_errors(item, field_name, text): + with pytest.raises(UserError) as e: + parse_settings(raw_settings(fits=[item])) + assert e.value.field == field_name and text in str(e.value) + + +def test_custom_fields_hidden_for_other_models(): + # expr / initial は custom 以外では検証せず使わない。custom の degree も使わない + for model in ("linear", "poly"): + f = parse_settings(raw_settings(fits=[fit(model=model, expr="((", initial={"a": "zz"})])).fits[0] + assert f.expr == "" and f.expr_node is None and f.params == () + parse_settings(raw_settings(fits=[custom(degree="abc")])) + # 使っていないパラメータの初期値は検証しない + parse_settings(raw_settings(fits=[custom("a * x", initial={"a": 1, "b": "zz"})])) + + +def test_custom_exponential_matches_scipy(tmp_path): + df = decay_frame() + b = Built(tmp_path, df=df, series_list=[series(1, label="減衰")], fits=[custom(initial={"a": 1, "b": 1, "c": 1})]) + assert "from scipy.optimize import curve_fit" in b.script.text + assert "scipy" in b.script.text.split("\n")[2] + + def model(x, a, b, c): + return a * np.exp(-b * x) + c + + x, y = df["t"].to_numpy(), df["y"].to_numpy() + expect, _ = curve_fit(model, x, y, p0=[1.0, 1.0, 1.0], maxfev=10000) + r2 = 1 - np.sum((y - model(x, *expect)) ** 2) / np.sum((y - y.mean()) ** 2) + + def check(fig): + ax = fig.axes[0] + line = fit_line(ax) + assert line.get_label().startswith("減衰の近似: y = a*exp(-b*x) + c(a = ") + assert line.get_label().endswith(f"、$R^2$ = {r2:.4f})") + xs, ys = line.get_data() + assert len(xs) == 200 and xs[0] == x.min() and xs[-1] == x.max() + np.testing.assert_allclose(ys, model(xs, *expect), rtol=1e-6) + for name, value in zip("abc", expect): + assert f"{name} = {value:.4g}" in line.get_label() + + summary = b.check(check) + assert summary[0]["fitlines"] == 1 + + +def test_custom_logistic_matches_scipy(tmp_path): + df = logistic_frame() + b = Built(tmp_path, df=df, fits=[custom("a / (1 + exp(-b * (x - c)))", initial={"a": 3, "b": 1, "c": 0})]) + + def model(x, a, b, c): + return a / (1 + np.exp(-b * (x - c))) + + x, y = df["t"].to_numpy(), df["y"].to_numpy() + expect, _ = curve_fit(model, x, y, p0=[3.0, 1.0, 0.0], maxfev=10000) + + def check(fig): + xs, ys = fit_line(fig.axes[0]).get_data() + np.testing.assert_allclose(ys, model(xs, *expect), rtol=1e-6) + + b.check(check) + assert "p0=[3.0, 1.0, 0.0]" in b.script.text and "def fit_model_1(x, a, b, c):" in b.script.text + + +def test_custom_generated_snippet(tmp_path): + b = Built(tmp_path, df=decay_frame(), fits=[custom()]) + text = b.script.text + assert "def fit_model_1(x, a, b, c): # 近似曲線1の式: a * exp(-b * x) + c" in text + assert " return a * np.exp(-b * x) + c" in text or "np.exp(" in text + assert "fit_params, _ = curve_fit(fit_model_1, x[ok], y[ok], p0=[1.0, 1.0, 1.0], maxfev=10000)" in text + assert "fit_model_1(x[ok], *fit_params)" in text and "np.isfinite(fit_y)" in text + + +def test_custom_show_variants(tmp_path): + df = decay_frame() + b = Built( + tmp_path, df=df, series_list=[series(1, label="A")], + fits=[custom(show="text"), custom("a * x + b", show="none"), custom("a * x + b")], + ) + + def check(fig): + ax = fig.axes[0] + assert len(ax.texts) == 1 and ax.texts[0].get_position() == (0.03, 0.97) + assert ax.texts[0].get_text().startswith("Aの近似: y = a*exp(-b*x) + c(") + legend = [t.get_text() for t in ax.get_legend().get_texts()] + assert len(legend) == 2 and legend[0] == "A" and legend[1].startswith("Aの近似: y = a*x + b(a = ") + assert sum(ln.get_label() == "_fit" for ln in ax.lines) == 2 # show=text と none + + summary = b.check(check) + assert summary[0]["fitlines"] == 3 and summary[0]["fittexts"] == 1 + assert "poly_text" not in b.script.text # 任意の式だけなら poly_text は要らない + + +def test_custom_mixed_with_poly(tmp_path): + b = Built(tmp_path, df=decay_frame(), fits=[custom(), fit(model="poly", degree=2)]) + assert "def poly_text(coef):" in b.script.text and "curve_fit" in b.script.text + assert b.check(lambda fig: None)[0]["fitlines"] == 2 + + +def test_custom_secondary_axis(tmp_path): + df = decay_frame().assign(w=lambda d: 2 * d["y"] + 1) + b = Built(tmp_path, df=df, series_list=[series(1), series(2, secondaryAxis=True)], fits=[{**custom(show="text"), "series": "s2"}]) + assert "ax2.plot(x_fit, fit_model_1(x_fit, *fit_params)" in b.script.text and "ax2.text(0.03, 0.97" in b.script.text + + def check(fig): + ax, ax2 = fig.axes + assert len(ax2.texts) == 1 and not ax.texts + + b.check(check) + + +def test_custom_fit_number_names_function(tmp_path): + b = Built(tmp_path, df=decay_frame(), fits=[fit(), custom("a * x + b")]) + assert "def fit_model_2(x, a, b):" in b.script.text and "fit_model_1" not in b.script.text + assert b.check(lambda fig: None)[0]["fitlines"] == 2 + + +def test_scipy_not_imported_without_custom(tmp_path): + for fits in ([], [fit()], [fit(model="poly", degree=2, show="text")]): + b = Built(tmp_path, df=decay_frame(), fits=fits) + assert "scipy" not in b.script.text and "curve_fit" not in b.script.text + b = Built(tmp_path, df=decay_frame(), fits=[custom()], plot_type="bar") # 棒グラフでは使わない + assert "scipy" not in b.script.text + + +@pytest.mark.filterwarnings("ignore:invalid value encountered in log:RuntimeWarning") +@pytest.mark.filterwarnings("ignore:Covariance of the parameters could not be estimated") +def test_custom_non_finite_initial_maps_to_step_message(tmp_path): + t = np.arange(10.0) + df = pd.DataFrame({"t": t, "y": 2 * t + 1}) + b = Built(tmp_path, df=df, fits=[custom("log(a) * x + b", initial={"a": -1, "b": 1})]) + with pytest.raises(ScriptError) as e: + with run_script(b.script.text, cwd=tmp_path): + pass + mapped = _step_error(b.script, e.value) + assert mapped.args[0] == "近似曲線1: 式を当てはめられませんでした。初期値を変えてみてください。" + assert mapped.field == "近似曲線1の初期値" + + +def test_custom_no_convergence_maps_to_step_message(tmp_path): + b = Built(tmp_path, df=decay_frame(), fits=[custom()]) + + def fail(*args, **kwargs): # 収束しないときの curve_fit と同じ例外(plot.py の外で起こす) + raise RuntimeError("Optimal parameters not found: The maximum number of function evaluations is exceeded.") + + text = b.script.text.replace("from scipy.optimize import curve_fit", "curve_fit = fail") + assert text.count("\n") == b.script.text.count("\n") + with pytest.raises(ScriptError) as e: + with run_script(text, injected={"fail": fail}, cwd=tmp_path): + pass + mapped = _step_error(b.script, e.value) + assert mapped.args[0] == "近似曲線1: 式を当てはめられませんでした。初期値を変えてみてください。" + assert mapped.field == "近似曲線1の初期値" + + +def test_custom_not_enough_distinct_x(): + df = pd.DataFrame({"t": [1.0, 1.0, 2.0, 2.0, 3.0, 3.0], "v": [1.0, 2.0, 3.0, 4.0, 5.0, 7.0]}) + plan_of(df=df, fits=[custom("a * x + b")]) # 3 個 > 2 個 + with pytest.raises(UserError) as e: + plan_of(df=df, fits=[custom("a * x**2 + b * x + c")]) # 3 個 <= 3 個 + assert e.value.field == "近似曲線1の系列" and "近似曲線1: " in str(e.value) and "4個以上" in str(e.value) + + +def test_custom_data_errors(): + df = decay_frame().assign(d=pd.date_range("2026-01-01", periods=30).strftime("%Y-%m-%d"), c=[f"k{i}" for i in range(30)]) + for x, word in ((2, "日時"), (3, "文字列")): + with pytest.raises(UserError) as e: + plan_of(df=df, series_list=[series(1, x=x)], fits=[custom()]) + assert e.value.field == "近似曲線1の系列" and word in str(e.value) + flat = pd.DataFrame({"t": np.arange(5.0), "v": np.full(5, 3.0)}) + with pytest.raises(UserError) as e: + plan_of(df=flat, fits=[custom("a * x + b")]) + assert "すべて同じ" in str(e.value) + + +def test_custom_injection(tmp_path): + evil = 'x"\n__import__("os").system("x") # \'\'\'' + b = Built(tmp_path, df=decay_frame(), series_list=[series(1, label=evil)], fits=[custom(), custom("a * x + b", show="text")]) + compile(b.script.text, "plot.py", "exec") + assert "\n__import__" not in b.script.text + with b.full() as run: + assert any(ln.get_label().startswith(evil + "の近似: ") for ln in run.fig.axes[0].lines) + # 式の文字列に命令を入れても、パーサが拒否する + for bad in ('a * __import__("os")', "a * x; import os", "a * x\nimport os", "a.__class__ * x", "a * x # \n"): + with pytest.raises(UserError): + parse_settings(raw_settings(fits=[custom(bad)])) + + +def test_custom_expression_only_in_comment(tmp_path): + b = Built(tmp_path, df=decay_frame(), fits=[custom("a * exp( -b*x )+c")]) + lines = [ln for ln in b.script.text.split("\n") if "a * exp( -b*x )+c" in ln] + assert len(lines) == 1 and lines[0].startswith("def fit_model_1(") and "# 近似曲線1の式: " in lines[0] + assert "\n" not in lines[0] + # 木から整えた式だけがコードとラベルに入る + assert "a*exp(-b*x) + c" in b.script.text diff --git a/uv.lock b/uv.lock index 7ac725f..1c812be 100644 --- a/uv.lock +++ b/uv.lock @@ -297,6 +297,7 @@ dev = [ { name = "pytest" }, { name = "pytest-playwright" }, { name = "pyyaml" }, + { name = "scipy" }, ] [package.metadata] @@ -310,6 +311,7 @@ dev = [ { name = "pytest", specifier = ">=9.1.1" }, { name = "pytest-playwright", specifier = ">=0.9.0" }, { name = "pyyaml", specifier = ">=6.0.3" }, + { name = "scipy", specifier = "==1.18.0" }, ] [[package]] @@ -587,6 +589,37 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/a0/f4/c67b0b3f1b9245e8d266f0f112c500d50e5b4e83cb6f3b71b6528104182a/requests-2.34.2-py3-none-any.whl", hash = "sha256:2a0d60c172f83ac6ab31e4554906c0f3b3588d37b5cb939b1c061f4907e278e0", size = 73075, upload-time = "2026-05-14T19:25:26.443Z" }, ] +[[package]] +name = "scipy" +version = "1.18.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/a7/25/c2700dfaf6442b4effaa91af24ebce5dc9d31bb4a69706313aae70d72cd0/scipy-1.18.0.tar.gz", hash = "sha256:67b2ad2ad54c72ca6d04975a9b2df8c3638c34ddd5b28738e94fc2b57929d378", size = 30774447, upload-time = "2026-06-19T15:01:43.456Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/78/b5/915a19b3de2f7430062b509653563db1633ddbb6f021b06731521115d4e2/scipy-1.18.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:4c256ee70c0d1a8a2ace807e199ccd4e3f57037433842abb3fb36bc17eaa9578", size = 31036253, upload-time = "2026-06-19T15:00:43.216Z" }, + { url = "https://files.pythonhosted.org/packages/d7/88/b72def7262e150d16be13fca37a96481138d624e700340bc3362a7588929/scipy-1.18.0-cp314-cp314-macosx_12_0_arm64.whl", hash = "sha256:2ef3abc54a4ffc53765374b0d5728532dfdd2585ed23f6b11c206a1f0b1b9af8", size = 28673758, upload-time = "2026-06-19T15:00:46.663Z" }, + { url = "https://files.pythonhosted.org/packages/91/02/2e636a61a525632c373cf6a9c24442a3ffb79e364d38e98b32042964ac32/scipy-1.18.0-cp314-cp314-macosx_14_0_arm64.whl", hash = "sha256:f2a6af57bd9e4a75d70e4117e78a1bbee84f79ae3fbb6d0111005d6ebcc4cb8d", size = 20415514, upload-time = "2026-06-19T15:00:49.399Z" }, + { url = "https://files.pythonhosted.org/packages/c9/b6/2135974442f6aba159d9d39d774a1c8cb19947016725d69fecc685df45bf/scipy-1.18.0-cp314-cp314-macosx_14_0_x86_64.whl", hash = "sha256:3f1ac564d3bf6c03d861d2cd87a1bea0da2887136f7fb1bf519c05a8971452d6", size = 23034398, upload-time = "2026-06-19T15:00:51.941Z" }, + { url = "https://files.pythonhosted.org/packages/f6/e6/ba89ec5abf6ee9257c0d1ec985573f3ae32742c24bc03e016388a40b1b15/scipy-1.18.0-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:40395a5fcd1abee49a5c7aaa98c29db393eedc835138560a588c47ec16156690", size = 33998032, upload-time = "2026-06-19T15:00:54.838Z" }, + { url = "https://files.pythonhosted.org/packages/7f/c4/bc41eb19b0fd0db868f4132920879019318d80cc522ad8f2bca4611af808/scipy-1.18.0-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8ca01e8ae69f1b18e9a58d91afead31be3cef0dd905a10249dac559ee15460a0", size = 35283333, upload-time = "2026-06-19T15:00:58.152Z" }, + { url = "https://files.pythonhosted.org/packages/53/a4/cbdeef6eb3830a8462a9d4ada814de5fc984345cc9ecf17cbec51a036f1e/scipy-1.18.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:7a7f3b01647384dbc3a711e8c6778e0aabbe93959249fef5c7393396bcac0867", size = 35610216, upload-time = "2026-06-19T15:01:01.155Z" }, + { url = "https://files.pythonhosted.org/packages/80/4d/b2b82502b65f661d1b789c1665dcdf315d5f12194e06fc0b37946294ebae/scipy-1.18.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:6aa94e78ec192a30063a5e72e561c28af769dc311190b24fe91774eff1969709", size = 37418960, upload-time = "2026-06-19T15:01:04.155Z" }, + { url = "https://files.pythonhosted.org/packages/93/3e/902d836831474b0ab5a37d16404f7bc5fafd9efba632890e271ba952635f/scipy-1.18.0-cp314-cp314-win_amd64.whl", hash = "sha256:2d8bbdc6c817f5b4006a54d799d4f5bab6f910193cbb9a1ff310833d4d270f61", size = 37288845, upload-time = "2026-06-19T15:01:07.822Z" }, + { url = "https://files.pythonhosted.org/packages/b6/43/8d73b337a3bdb14daa0314f0434210747c02d79d729ce1777574a817dcf6/scipy-1.18.0-cp314-cp314-win_arm64.whl", hash = "sha256:18e9575f1569b2c54174e6159d32942e03731177f63dce7975f0a0c88d102f5b", size = 24988971, upload-time = "2026-06-19T15:01:11.076Z" }, + { url = "https://files.pythonhosted.org/packages/b4/b4/f11918b0508a2787031a0499a03fbe3546f3bb5ca05d01038c45b278c09a/scipy-1.18.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:f351e0dd702687d12a402b867a1b4146a256923e1c38317cbc472f6372b94707", size = 31399325, upload-time = "2026-06-19T15:01:13.723Z" }, + { url = "https://files.pythonhosted.org/packages/7b/d1/1f287b57c0ff0ee5185dff3946d92c8017d39b0e431f0ae79a3ff1859512/scipy-1.18.0-cp314-cp314t-macosx_12_0_arm64.whl", hash = "sha256:7c7a51b33ce387193c97f228320cf8e87361daa1bba750638677729598b3e677", size = 29092110, upload-time = "2026-06-19T15:01:16.908Z" }, + { url = "https://files.pythonhosted.org/packages/ff/1a/7b74eb6c392fdcb27d414c0e7558a6d0231eb3b6d73571f479bb81ea8794/scipy-1.18.0-cp314-cp314t-macosx_14_0_arm64.whl", hash = "sha256:84031d7b052a54fae2f8632e0ec802073d385476eb9a63079bce6e23ef9283d4", size = 20833811, upload-time = "2026-06-19T15:01:20.488Z" }, + { url = "https://files.pythonhosted.org/packages/7c/ad/f3941716320a7b9cb4d68734a903b45fe16eff5fb7da7e16f2e619304979/scipy-1.18.0-cp314-cp314t-macosx_14_0_x86_64.whl", hash = "sha256:56abf29a7c067dde59be8b9a22d606a4ea1b2f2a4b756d9d903c62818f5dacce", size = 23396644, upload-time = "2026-06-19T15:01:23.364Z" }, + { url = "https://files.pythonhosted.org/packages/22/22/1446b62ffe07f9719b7d9b1b6a4e05a772833ae8f441fe4c22c34c9b250f/scipy-1.18.0-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1ad44305cfa24b1ba5803cbbebf033590ccbac1aa5d612d727b785325ab408b0", size = 34079318, upload-time = "2026-06-19T15:01:26.002Z" }, + { url = "https://files.pythonhosted.org/packages/56/3b/b87da667098bb470fa30c7011b0ba351ee976dd395c78798c66e941665a3/scipy-1.18.0-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:945c1761b93f38d7f99ae81ae80c63e621471608c7eeead563f6df025585cd58", size = 35324320, upload-time = "2026-06-19T15:01:28.881Z" }, + { url = "https://files.pythonhosted.org/packages/f8/a1/c7932f91909759b0267f75fdea34e91309f96b895757534b76a90b6b4344/scipy-1.18.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:1a4441f15d620578772a49e5ab48c0ee1f7a0220e387110283062729136b2553", size = 35699541, upload-time = "2026-06-19T15:01:31.968Z" }, + { url = "https://files.pythonhosted.org/packages/f7/86/5185061a1fcc41d18c5dc2463969b3a3964b31d9ac67b2fb05d4c7ff7670/scipy-1.18.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:9aac6192fac56bf2ca534389d24623f07b39ff83317d58287285e7fbd622ff76", size = 37472480, upload-time = "2026-06-19T15:01:35.136Z" }, + { url = "https://files.pythonhosted.org/packages/31/8e/f04c68e39919a010d34f2ee1367fd705b0a25a02f609d755f0bfbc0a15fc/scipy-1.18.0-cp314-cp314t-win_amd64.whl", hash = "sha256:e40baea28ae7f5475c779741e2d90b1247c78531207b49c7030e698ff81cee3f", size = 37365390, upload-time = "2026-06-19T15:01:38.091Z" }, + { url = "https://files.pythonhosted.org/packages/d5/19/969dc072906c84dd0a3b05dcf57ea750936087d7873549e408b35cfc3f97/scipy-1.18.0-cp314-cp314t-win_arm64.whl", hash = "sha256:368e0a705903c466aa5f08eefb39e6b1b6b2d659e7352a31fd9e2438365be0f8", size = 25279661, upload-time = "2026-06-19T15:01:40.817Z" }, +] + [[package]] name = "six" version = "1.17.0" From 180314d34e72824beebcffcee102a2ad46631fa3 Mon Sep 17 00:00:00 2001 From: mioupa <79833278+mioupa@users.noreply.github.com> Date: Thu, 12 Nov 2026 15:33:46 +0900 Subject: [PATCH 05/10] Add box, violin and heatmap to the UI (Phase 5d, G8) Co-Authored-By: Claude Opus 5.5 --- index.html | 29 ++++- js/ui/forms.js | 4 + js/ui/series.js | 41 +++++-- tests/e2e/test_chart_types.py | 159 +++++++++++++++++++++++++- tests/e2e/test_codegen_consistency.py | 29 +++++ tests/e2e/test_fits.py | 2 +- tests/fixtures/README.md | 1 + tests/fixtures/grid.csv | 13 +++ tests/fixtures/make_fixtures.py | 10 ++ 9 files changed, 271 insertions(+), 17 deletions(-) create mode 100644 tests/fixtures/grid.csv diff --git a/index.html b/index.html index dfeedaf..a9bd4f9 100644 --- a/index.html +++ b/index.html @@ -140,6 +140,9 @@

Matplotlib GUI

+ + + @@ -164,6 +167,28 @@

Matplotlib GUI

+ + + +