From 046712fb229fef03bbd1ff8bfa51032201c65646 Mon Sep 17 00:00:00 2001 From: mioupa <79833278+mioupa@users.noreply.github.com> Date: Thu, 12 Nov 2026 08:38:45 +0900 Subject: [PATCH 01/10] Design Phase 5c (computed columns, five chart types) and record the decisions Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 1 + docs/PHASE5_DESIGN.md | 127 ++++++++++++++++++++++++++++++++++++++++++ docs/REQUIREMENTS.md | 5 ++ 3 files changed, 133 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index b4770c5..927e8ef 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -368,3 +368,4 @@ uv run pytest tests/e2e # E2E(Chromium とローカルの静的サー - U4: G7 → G8 の順(G7 の中は ステップ → 横棒 → 積み上げ棒 → ヒストグラム → 色分け散布図)。U5: G10 を使うときだけ scipy を読み込み、生成コードもそのときだけ scipy を使う(4.2 の例外。openpyxl と同じ扱い)。 - 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 秒を超えたら見直す。 diff --git a/docs/PHASE5_DESIGN.md b/docs/PHASE5_DESIGN.md index ea62062..4a2937d 100644 --- a/docs/PHASE5_DESIGN.md +++ b/docs/PHASE5_DESIGN.md @@ -437,3 +437,130 @@ ax.plot(x_fit, fit(x_fit), color="#FF4B00", linewidth=2.0, linestyle="dashed", l 2. **近似曲線の式の表示**: 「温度の近似: y = 1.234x + 5.678(R² = 0.9981)」の形(係数は有効数字4桁、R² は小数4桁で固定)。「図の中」は左上に並べる(位置は固定)。これでよいか。 3. **文字列の X・棒グラフでの注釈の X の位置**は、「何番目のカテゴリか(0 始まり)」の数で指定する。これでよいか。 4. **欄の名前**: 要件の「透明度」は、matplotlib の alpha(1 で透けない)に合わせて「不透明度」と表示する。これでよいか。 + +--- + +## 6. 5c の詳細(G6 式で新しい列、G7 グラフの種類 第1弾) + +作成: 2026-11-11。2026-11-12 にユーザーが承認(§6.8 はすべて提案どおり。1 は「横に並べる」)。 + +### 6.0 準備 + +- PR #5(5a)と #6(5b)はまだマージされていない。5c は `phase5b-annotations` から `phase5c-data` を作り、その上に積む(PR の向き先は `phase5b-annotations`)。 +- スキーマは v4 のまま、項目を足す(§2.1)。新しい項目の既定値では、生成コードは Phase 4 と1文字も変わらない(ゴールデンテスト)。 + +### 6.1 追加する設定項目(v4 に足す) + +| キー | 既定値 | 受け付ける値・検証 | +|---|---|---| +| `plot.type` | `"line"` | 今の `line` / `scatter` / `bar` に、`step` / `barh` / `barStacked` / `hist` / `scatterColor` を足す | +| `plot.step` | `{where: "post"}` | `pre` / `mid` / `post`(段の付き方)。`step` のときだけ使う | +| `plot.hist` | `{bins: null, density: false}` | `bins` は null(自動。numpy の `"auto"`)か 1〜1000 の整数。`density` は真偽(縦軸を確率密度にする)。`hist` のときだけ使う | +| `plot.colormap` | `"viridis"` | `viridis` / `cividis` / `plasma` / `inferno` / `magma` / `coolwarm` / `RdBu_r` / `gray`。`scatterColor` のときだけ使う | +| `plot.colorbarLabel` | `""` | カラーバーのラベル(`""` は系列1の色分けの列の名前)。`scatterColor` のときだけ使う | +| `series[].colorColumn` | `""` | `""` か `__idx__N`(系列のデータ元の列)。`scatterColor` では必須(「系列Nの色分けの列」) | +| `computed` | `[]` | 計算した列。要素は `{id, source, name, expr}`(下記)。20 個まで | + +計算した列(`computed[]`)の要素: + +| キー | 既定値 | 内容 | +|---|---|---| +| `id` | `c1`, `c2`, … | 削除しても再利用しない | +| `source` | `""` | データ元のファイル id(`""` は先頭のファイル。系列と同じ規則) | +| `name` | `""` | 列の名前(50 文字まで。`""` は「計算N」) | +| `expr` | `""` | 式(200 文字まで。空はエラー「計算した列Nの式を入力してください」) | + +### 6.2 グラフの種類ごとに使う設定(隠した設定は使わない。§2.2) + +| 設定 | line | step | scatter | scatterColor | bar | barStacked | barh | hist | +|---|---|---|---|---|---|---|---|---| +| 系列の X 列 | ○ | ○ | ○ | ○ | – | – | – | – | +| X列(全系列共通。`#xColumn`) | – | – | – | – | ○ | ○ | ○(縦軸のカテゴリ) | – | +| 点の形・点サイズ | ○ | ○ | ○ | ○ | – | – | – | – | +| 線幅・線種 | ○ | ○ | – | – | ○(棒の縁) | ○ | ○ | ○ | +| 色 | ○ | ○ | ○ | ○(エラーバー・帯・近似曲線の色) | ○ | ○ | ○ | ○ | +| 不透明度 | ○ | ○ | ○ | ○ | ○ | ○ | ○ | ○ | +| エラーバー Y(値の方向) | ○ | ○ | ○ | ○ | ○ | – | ○(横向きに描く) | – | +| エラーバー X | ○ | ○ | ○ | ○ | – | – | – | – | +| 塗りつぶし帯 | ○ | ○(段に合わせる) | ○ | ○ | – | – | – | – | +| 第2Y軸 | ○ | ○ | ○ | – | ○ | – | – | – | +| 色分けの列 | – | – | – | ○ | – | – | – | – | +| 近似曲線 | ○ | ○ | ○ | ○ | – | – | – | – | +| 注釈 | ○ | ○ | ○ | ○ | ○ | ○ | ○ | ○ | + +- 軸の種類: `step` / `scatterColor` は line / scatter と同じ(X は列の種類で決まる)。`bar` / `barStacked` の X はカテゴリ。`barh` は、物理的な軸の設定をそのまま使う(X軸の設定=横軸=値、Y軸の設定=縦軸=カテゴリ。§2.6)。軸ラベルの自動の値だけ入れ替える(横軸は系列1の Y 列の名前、縦軸は X列の名前)。`barh` では Y軸のスケール(対数)を隠す。`hist` の横軸は値(数値)、縦軸は度数(`density` なら確率密度)。軸ラベルの自動の値は、横軸が系列1の Y 列の名前、縦軸が「度数」か「確率密度」。 +- 目盛(5a)・注釈(5b)は、この軸の種類に従う。`barh` の縦軸は「何個おき」、注釈の Y は「何番目のカテゴリか」。 + +### 6.3 G7 グラフの種類(U4 の順) + +1. **ステップ(`step`)**: line と同じ書き方に `drawstyle="steps-post"`(`pre` / `mid` / `post`)を足す。塗りつぶし帯は `fill_between(..., step="post")` で段に合わせる。line でできること(点の形・エラーバー・第2Y軸・近似曲線)はすべて使える。 +2. **横棒(`barh`)**: 今の棒グラフ(1系列・複数系列を並べる)と同じ並べ方を横向きにする(`ax.barh`。複数系列は縦方向にずらす)。エラーバーは Y 方向の設定を値の誤差として横向き(`xerr=`)に描く。カテゴリは matplotlib の既定どおり下から並ぶ(上から並べたいときは、Y軸の反転(5a)を使う。欄の補足に書く)。 +3. **積み上げ棒(`barStacked`)**: 複数系列を縦に積む。負の値は、正の値と別に下へ積む(正と負の段が重ならない)。欠けた値は 0 として積む。1系列なら普通の棒と同じ。エラーバーと第2Y軸は使わない(隠す)。 + ```python + stack_pos = np.zeros(len(positions)) # 正の値を積んだ高さ + stack_neg = np.zeros(len(positions)) # 負の値を積んだ深さ + # 系列1: … + v = bar_data["y1"].fillna(0.0).to_numpy() + ax.bar(positions, v, bottom=np.where(v >= 0, stack_pos, stack_neg), width=0.8, color=…, label=…) + stack_pos += np.where(v >= 0, v, 0.0) + stack_neg += np.where(v < 0, v, 0.0) + ``` +4. **ヒストグラム(`hist`)**: 各系列の Y 列の値の分布。X 列は使わない(隠す)。区間は全系列で共通(`np.histogram_bin_edges(全系列の値, bins=区間の数 か "auto")`)。複数系列の並べ方は確認事項 1。データ元が違う系列も使える(行の対応は要らないため)。 +5. **色分け散布図(`scatterColor`)**: scatter の点を、色分けの列の値で塗る(`ax.scatter(..., c=色の値, cmap=…, norm=color_norm)`)。色の範囲は全系列で共通(色分けの列の最小〜最大)で、カラーバーを1本付ける(`fig.colorbar(…, ax=ax, label=…)`)。凡例は系列を点の形で見分けるもので、凡例の点は灰色にする(色はカラーバーで読む)。色分けの列の数値にできない値は、その点を描かず警告する。第2Y軸は使えない(カラーバーと第2Y軸の位置がずれるため。隠す)。 + +- 「グラフの種類」の選択肢の表示は、今の `line` / `scatter` / `bar` を変えず、`step`、`barh(横棒)`、`bar(積み上げ)`、`hist(ヒストグラム)`、`scatter(色分け)` を足す。 +- 種類ごとの設定(段の付き方、区間の数と確率密度、カラーマップとカラーバーのラベル)は、「系列」の区分の「グラフの種類」の下に、その種類のときだけ出す(`#stepGroup` / `#stepWhere`、`#histGroup` / `#histBins` / `#histDensity`、`#colorMapGroup` / `#colorMap` / `#colorbarLabel`)。色分けの列は系列カードの `series--color-column`。 + +### 6.4 G6 式で新しい列 + +- **場所**: 「注釈・解析」の区分の「計算した列」(`#computedList`、「+ 列を追加」`#addComputedBtn`。§2.5)。カード `computed-` に、データ元 `-source`(2ファイル以上のときだけ)、名前 `-name`、式 `-expr`、雛形のボタン(正規化 `-tpl-normalize`、オフセット `-tpl-offset`、移動平均 `-tpl-rolling`)、削除 `-remove`。カードに「列 [N] として使えます」と、作った列の番号を出す。 +- **文法**(新しいモジュール `py/mplgui/expr.py`。`pyscript.toml` の `[files]` に足す。`eval` も Python の `ast` も使わず、字句解析と再帰下降の構文解析を自前で書く): + - 数(`1`、`2.5`、`1e3`)、列(`[N]` か Excel の列記号の大文字 `A`=`[0]`、`B`=`[1]`、…、`AA`=`[26]`)、`+ - * /`、`**` と `^`(どちらもべき乗)、括弧、単項マイナス。優先順位と結合は Python と同じ(`-2**2` は `-(2**2)`)。 + - 要素ごとの関数(小文字): `abs` `sqrt` `exp` `log`(自然対数)`log10` `sin` `cos` `tan`。 + - 集計(列 → 1つの値): `min` `max` `mean` `median` `std`(標本標準偏差。pandas の既定)`first` `last`(欠けていない最初・最後の値)。 + - 系列の処理: `rolling_mean(式, 窓の幅)`(中心の移動平均。窓の幅は 1〜1000 の整数の定数)、`diff(式)`、`cumsum(式)`。 + - 上限: 200 文字、入れ子の深さ 30。式には列を1つ以上含める(列の無い式はエラー)。 + - 誤りは日本語のエラー(`field` は「計算した列Nの式」)。何文字目かを添える(例「5文字目: 閉じ括弧が足りません」)。知らない関数は、使える関数の一覧を添える。 +- **参照できる列**: その計算した列のデータ元の、ファイルの列だけ(ほかの計算した列は参照できない。確認事項 2)。日時の列はエラー。数値にできない値は NaN として計算し、警告する(A7 と同じ形。桁区切り・小数点のヒント付き)。 +- **計算する行**: 「描画から除外する先頭行」を除いた行(`max` や `first` もその行だけで計算する。確認事項 3)。 +- **結果**: 0 での割り算・負の数の平方根などの ±inf / 計算できない値は NaN にする(生成コードは `with np.errstate(divide="ignore", invalid="ignore"):` の中で計算し、`replace([np.inf, -np.inf], np.nan)` する)。入力は数なのに計算できなかった値が出たときは、件数を警告する。 +- **列の番号**: 計算した列は、そのデータ元の列の後ろに、カードの順に足す(ファイルの列が 5 個なら、最初の計算した列は `[5]`)。系列の X・Y、エラーバー・帯・色分けの列の選択肢に「名前 [5](計算)」として出る。設定では `__idx__5`(今までどおり列番号)。 + - 計算した列を削除・データ元を変更したら、JS がその列を使う系列の列を空に戻し(警告する)、後ろの計算した列を使う系列の列番号を詰める。 + - ファイルの読み直しで列の数が変わったら、JS が計算した列を使う系列の列番号をずらす(計算した列を指したまま)。 +- **生成コード**: 「描画に使う行」の後に「計算した列」の節を、計算した列があるときだけ入れる。利用者が書いた式は、`comment_text()` を通してコメントにだけ入れる。名前は `literal()`。 + ```python + # ==== 3. 計算した列 ==== + with np.errstate(divide="ignore", invalid="ignore"): # 0 での割り算などは警告を出さず、下で NaN にする + # 計算した列1: 比(式: [1] / max([1]))→ 列 [5] + calc = pd.to_numeric(df.iloc[:, 1], errors="coerce") / pd.to_numeric(df.iloc[:, 1], errors="coerce").max() + df.insert(df.shape[1], "比", calc.replace([np.inf, -np.inf], np.nan), allow_duplicates=True) + ``` + 関数は決まった形で書く: `np.sqrt(…)`、`(…).max()`、`(…).dropna().iloc[0]`(first)、`(…).rolling(5, center=True).mean()`、`(…).diff()`、`(…).cumsum()`。数は `literal()`。 +- **雛形のボタン**: 式の欄を `[N] / max([N])`(正規化)、`[N] - first([N])`(オフセット)、`rolling_mean([N], 5)`(移動平均)にする。N は、系列1の Y 列(同じデータ元のとき)か、なければ `[1]`。 +- データ確認タブには、計算した列は出さない(読み込んだファイルの内容だけ)。 + +### 6.5 dataprep・codegen・runner の広げ方 + +- dataprep: 計算した列を `expr.py` で解釈し、データ元ごとに(`skipRows` を除いた)DataFrame の末尾に足してから、系列の計画を作る(列の範囲・数値の確認・警告は今と同じ道を通る)。グラフの種類ごとの計画(`PlotPlan` に種類別の小さな dataclass。`hist` の区間、`barStacked` の積んだ高さの範囲、`scatterColor` の色の範囲)を足し、軸の種類(`barh` の縦軸カテゴリ、`hist` の横軸)と `_Extents` を種類に合わせる。 +- 自動描画(GUI 同期)では、生成コードが `df.insert` で列を足すので、読込済みの DataFrame をそのまま渡さず、コピーを渡す(計算した列があるときだけ。描画のたびに列が増えるのを防ぐ)。 +- codegen: `SERIES_EMITTERS` に `step` / `barh` / `barStacked` / `hist` / `scatterColor` を足す(`step` は line の関数に `drawstyle` を渡す、`barh` は bar の関数を向きつきにする)。「計算した列」の節(`_emit_computed`)。 +- runner `figure_summary`: 線の `drawstyle`、棒の向き(縦・横)と積んだ棒の数、カラーバー(ラベル・カラーマップ・範囲。カラーバーの Axes は要約の一覧に入れず、元の Axes の項目として出す)を足す。 + +### 6.6 性能の見込み(CPython で実測。ブラウザは 1.2〜2 倍程度) + +- ステップ・横棒・積み上げ棒は、今の line・bar と同程度。ヒストグラム(10,000 行 × 5 系列)は描画 約 25 ms。 +- **色分け散布図は重い**: 10,000 点 × 5 系列で、普通の散布図(凡例なし 27 ms)に対して約 290 ms、凡例の位置「best」(既定)を足すと約 460 ms(普通の散布図は約 200 ms)。点ごとに色が違うと、点の縁を1つずつ描くため。縁を描かない(`linewidths=0`)と約 120 ms になるが、点が縁の分だけ小さく見える。まず普通の散布図と同じ見た目で作り、ブラウザで計測して 1 秒(デバウンス込み)を超えたら相談する。 +- 計算した列は 10,000 行で数 ms。 +- 計測(`--only p5c`): 色分け散布図(10,000 行 × 5 系列、凡例あり)、ヒストグラム(10,000 行 × 5 系列)、計算した列(正規化)を Y にした line(5 系列)の設定変更 → 再描画。 + +### 6.7 テスト + +- 単体: `test_expr.py`(字句・構文解析、優先順位、列記号、各関数の値を pandas で直接計算した値と比べる、エラーと何文字目か、上限、注入(式の文字列がコードに入らないこと、コメントの改行))、`test_computed.py`(列の番号、データ元、`skipRows` の後で計算すること、警告、生成コードと dataprep の結果の一致)、`test_chart_types.py`(種類ごとの artist、隠れる設定、軸の種類と自動のラベル、積み上げの正負、ヒストグラムの区間、カラーバー、凡例の灰色の点)。どれも「全体を実行した図」と「自動描画用の図」の一致。既定の設定のゴールデンテスト。 +- E2E: `test_chart_types.py`(種類の切り替えで欄が出し分けられる、各種類の `data-summary`、`barh` の軸ラベル、色分けの列が未選択のエラーと復帰)、`test_computed.py`(追加・式・雛形・系列の選択肢に出る・削除で系列の列が戻る・読み直しで列番号がずれない・式の誤りのエラーと「最新でない」印)。一致確認に、種類ごと(step・barh・積み上げ・hist・色分け)と計算した列(1ファイル・2ファイル)を足す。 + +### 6.8 確認したいこと + +1. **ヒストグラムの複数系列**: 区間ごとに横に並べる(`ax.hist([系列1, 系列2, …])`。matplotlib の既定。推奨)か、重ねて描く(各系列の不透明度を使う。既定の不透明度 1 だと後ろの系列が隠れる)か。 +2. **計算した列からほかの計算した列は参照できない**、でよいか(読み直しで列の数が変わったとき、式の中の列番号は直せないため。「正規化してから移動平均」は `rolling_mean([1] / max([1]), 5)` のように1つの式に書ける)。 +3. **計算する行**: 「描画から除外する先頭行」を除いた行で計算する(`max` や `first` もその行だけ)。データ確認タブには計算した列を出さない。これでよいか。 +4. **色分け散布図**: 凡例の点は灰色、第2Y軸は使えない、色の範囲は全系列共通で自動(範囲の指定は無し)。重さは §6.6 のとおり計測してから判断する。これでよいか。 diff --git a/docs/REQUIREMENTS.md b/docs/REQUIREMENTS.md index 61a5d4f..dc23db2 100644 --- a/docs/REQUIREMENTS.md +++ b/docs/REQUIREMENTS.md @@ -85,6 +85,11 @@ - 近似曲線の式は「温度の近似: y = 1.234x + 5.678(R² = 0.9981)」の形で表示する(係数は有効数字4桁、R² は小数4桁で固定)。「図の中」に表示するときは左上に並べる(位置は固定)。計算は numpy の最小二乗(`np.polynomial.Polynomial.fit`)。 - X が文字列の列と棒グラフの X では、注釈の X の位置を「何番目のカテゴリか(0 始まり)」の数で指定する。X が日時の列では日時で指定する。 - G3 の「透明度」は、matplotlib の alpha(1 で透けない)に合わせて、画面では「不透明度」(0〜1)と表示する。 +- 5c(G6・G7、2026-11-12): + - ヒストグラムで複数の系列を描くときは、区間ごとに系列を横に並べる(matplotlib の既定)。区間は全系列で共通にする。 + - 計算した列の式からは、ほかの計算した列を参照できない(ファイルを読み直して列の数が変わったとき、式の中の列番号を直せないため)。複数の処理は1つの式に書く(例 `rolling_mean([1] / max([1]), 5)`)。 + - 計算した列は「描画から除外する先頭行」を除いた行で計算する(`max` や `first` などの集計も、その行だけを使う)。データ確認タブには計算した列を出さない(読み込んだファイルの内容だけを出す)。 + - 色分け散布図: 凡例の点は灰色にする(色はカラーバーで読む)。第2Y軸は使えない(カラーバーと第2Y軸の位置がずれるため)。色の範囲は全系列で共通にし、自動で決める(範囲の指定は無し)。描画の重さは、普通の散布図と同じ見た目で作ってブラウザで計測し、1 秒を超えたら見直す。 --- From 6fab3eaf036ad1b03cc3bb1f7ebc76e9fbc9c4af Mon Sep 17 00:00:00 2001 From: mioupa <79833278+mioupa@users.noreply.github.com> Date: Thu, 12 Nov 2026 09:02:54 +0900 Subject: [PATCH 02/10] Add the expression parser for computed columns (Phase 5c, G6) A hand-written tokenizer and recursive-descent parser (no eval, exec or ast). evaluate() and to_code() share one semantics; constant subtrees are folded so the generated code never does Python-float-only arithmetic. Co-Authored-By: Claude Opus 5.5 --- py/mplgui/expr.py | 579 ++++++++++++++++++++++++++++++++++++++++ pyscript.toml | 1 + tests/unit/test_expr.py | 326 ++++++++++++++++++++++ 3 files changed, 906 insertions(+) create mode 100644 py/mplgui/expr.py create mode 100644 tests/unit/test_expr.py diff --git a/py/mplgui/expr.py b/py/mplgui/expr.py new file mode 100644 index 0000000..eeabdff --- /dev/null +++ b/py/mplgui/expr.py @@ -0,0 +1,579 @@ +"""式で新しい列を作るための、式の解釈・評価・コード生成(G6)。 + +標準ライブラリ・numpy・pandas だけに依存する純粋なモジュール。 +`eval` / `exec` / `compile` / `ast` は使わない。字句解析と構文解析は自前で行い、 +生成するコードには利用者の入力文字列を写さない(列の変数名・数値の文字列は呼び出し側が決める)。 +""" + +from __future__ import annotations + +import operator +import re +from collections.abc import Callable, Mapping +from dataclasses import dataclass, field + +import numpy as np +import pandas as pd + +MAX_LENGTH = 200 +MAX_DEPTH = 30 +MAX_WINDOW = 1000 +ELEMENTWISE = ("abs", "sqrt", "exp", "log", "log10", "sin", "cos", "tan") +AGGREGATES = ("min", "max", "mean", "median", "std", "first", "last") +SERIES_FUNCS = ("rolling_mean", "diff", "cumsum") +_ALL_FUNCS = ELEMENTWISE + AGGREGATES + SERIES_FUNCS + +_DEPTH_MESSAGE = f"入れ子が深すぎます({MAX_DEPTH} 段まで)" +_NAME_HINT = "列は [N] か大文字の列記号(A, B, …)で、関数は max( のように書いてください" +_CONST_MESSAGE = "計算できない定数があります(0 での割り算など)" + +_KIND_ORDER = {"const": 0, "scalar": 1, "series": 2} + + +class ExprError(Exception): + """式の誤り。`position` は元の文字列の 1 始まりの文字位置(無ければ None)。""" + + def __init__(self, message: str, position: int | None = None): + super().__init__(message) + self.message = message + self.position = position + + def __str__(self) -> str: + if self.position is None: + return self.message + return f"{self.position}文字目: {self.message}" + + +# ---- ノード ----------------------------------------------------------------- + + +@dataclass(frozen=True) +class Number: + value: float + pos: int + kind: str = field(default="const", compare=False, repr=False) + + +@dataclass(frozen=True) +class Column: + index: int + pos: int + kind: str = field(default="series", compare=False, repr=False) + + +@dataclass(frozen=True) +class Unary: + op: str + operand: "Node" + pos: int + kind: str = field(default="const", compare=False, repr=False) + + +@dataclass(frozen=True) +class Binary: + op: str + left: "Node" + right: "Node" + pos: int + kind: str = field(default="const", compare=False, repr=False) + + +@dataclass(frozen=True) +class Call: + name: str + args: tuple + pos: int + kind: str = field(default="const", compare=False, repr=False) + + +Node = Number | Column | Unary | Binary | Call + + +# ---- 字句解析 --------------------------------------------------------------- + +_NUMBER = re.compile(r"(?:[0-9]+\.?[0-9]*|\.[0-9]+)(?:[eE][+-]?[0-9]+)?") +_COLUMN = re.compile(r"\[[ \t]*([0-9]+)[ \t]*\]") +_IDENT = re.compile(r"[A-Za-z_][A-Za-z0-9_]*") + + +@dataclass(frozen=True) +class _Tok: + kind: str # num / col / func / op / ( / ) / , / eof + text: str + pos: int + value: object = None + + +def _normalize(text: str) -> str: + out = [] + for ch in text: + code = ord(ch) + if 0xFF01 <= code <= 0xFF5E: + out.append(chr(code - 0xFEE0)) + elif ch == " ": + out.append(" ") + else: + out.append(ch) + return "".join(out) + + +def _show(ch: str) -> str: + return ch if ch.isprintable() else repr(ch)[1:-1] + + +def _excel_index(letters: str) -> int: + n = 0 + for ch in letters: + n = n * 26 + (ord(ch) - 64) + return n - 1 + + +def _tokenize(s: str) -> list[_Tok]: + toks: list[_Tok] = [] + n = len(s) + i = 0 + while i < n: + c = s[i] + pos = i + 1 + if c in " \t": + i += 1 + elif c in "0123456789" or (c == "." and i + 1 < n and s[i + 1] in "0123456789"): + m = _NUMBER.match(s, i) + toks.append(_Tok("num", m.group(), pos, float(m.group()))) + i = m.end() + elif c == "[": + m = _COLUMN.match(s, i) + if m is None: + raise ExprError("列は [0] のように、角括弧の中に番号を書いてください", pos) + toks.append(_Tok("col", m.group(), pos, int(m.group(1)))) + i = m.end() + elif c.isascii() and (c.isalpha() or c == "_"): + m = _IDENT.match(s, i) + name = m.group() + j = m.end() + while j < n and s[j] in " \t": + j += 1 + paren = j < n and s[j] == "(" + if name.isalpha() and name.isupper(): + if paren: + raise ExprError(f"関数名は小文字で書いてください({name.lower()})", pos) + if len(name) > 3: + raise ExprError(f"「{name}」は使えません。{_NAME_HINT}", pos) + toks.append(_Tok("col", name, pos, _excel_index(name))) + elif name in _ALL_FUNCS: + if not paren: + raise ExprError( + f"「{name}」は関数です。{name}( のように、括弧で値を指定してください", pos + ) + toks.append(_Tok("func", name, pos, name)) + elif paren: + raise ExprError( + f"「{name}」という関数はありません。使える関数: {', '.join(_ALL_FUNCS)}", pos + ) + else: + raise ExprError(f"「{name}」は使えません。{_NAME_HINT}", pos) + i = m.end() + elif c == "*": + if i + 1 < n and s[i + 1] == "*": + toks.append(_Tok("op", "**", pos)) + i += 2 + else: + toks.append(_Tok("op", "*", pos)) + i += 1 + elif c == "^": + toks.append(_Tok("op", "^", pos, "**")) + i += 1 + elif c in "+-/": + toks.append(_Tok("op", c, pos)) + i += 1 + elif c in "(),": + toks.append(_Tok(c, c, pos)) + i += 1 + else: + raise ExprError(f"「{_show(c)}」は使えません", pos) + toks.append(_Tok("eof", "", n + 1)) + return toks + + +# ---- ノードの生成(種類の判定と定数の畳み込み) -------------------------------- + + +def _max_kind(*kinds: str) -> str: + return max(kinds, key=_KIND_ORDER.__getitem__) + + +def _fold(compute: Callable[[], object], pos: int) -> Number: + with np.errstate(all="ignore"): + v = float(compute()) + if not np.isfinite(v): + raise ExprError(_CONST_MESSAGE, pos) + return Number(v, pos) + + +_BINARY_OPS = { + "+": operator.add, + "-": operator.sub, + "*": operator.mul, + "/": operator.truediv, + "**": operator.pow, +} + + +def _make_number(value: float, pos: int) -> Number: + if not np.isfinite(value): + raise ExprError(_CONST_MESSAGE, pos) + return Number(value, pos) + + +def _make_unary(operand: Node, pos: int) -> Node: + if isinstance(operand, Number): + return _fold(lambda: -np.float64(operand.value), pos) + return Unary("-", operand, pos, operand.kind) + + +def _make_binary(op: str, left: Node, right: Node, pos: int) -> Node: + if isinstance(left, Number) and isinstance(right, Number): + fn = _BINARY_OPS[op] + return _fold(lambda: fn(np.float64(left.value), np.float64(right.value)), pos) + return Binary(op, left, right, pos, _max_kind(left.kind, right.kind)) + + +def _make_call(name: str, args: list[Node], pos: int) -> Node: + if name == "rolling_mean": + if len(args) != 2: + raise ExprError("rolling_mean には「式, 窓の幅」の2つを指定してください", pos) + elif len(args) != 1: + raise ExprError(f"{name} には値を1つ指定してください", pos) + first = args[0] + if name in ELEMENTWISE: + if isinstance(first, Number): + fn = getattr(np, name) + return _fold(lambda: fn(np.float64(first.value)), pos) + return Call(name, (first,), pos, first.kind) + if first.kind != "series": + raise ExprError(f"{name} の中には列を含めてください", pos) + if name == "rolling_mean": + w = args[1] + if not ( + isinstance(w, Number) + and w.value == int(w.value) + and 1 <= w.value <= MAX_WINDOW + ): + raise ExprError( + f"rolling_mean の窓の幅は 1〜{MAX_WINDOW} の整数で指定してください", w.pos + ) + kind = "scalar" if name in AGGREGATES else "series" + return Call(name, tuple(args), pos, kind) + + +# ---- 構文解析 --------------------------------------------------------------- + + +class _Parser: + def __init__(self, toks: list[_Tok]): + self.toks = toks + self.i = 0 + self.depth = 0 + + @property + def cur(self) -> _Tok: + return self.toks[self.i] + + def advance(self) -> _Tok: + t = self.toks[self.i] + self.i += 1 + return t + + def enter(self, pos: int) -> None: + self.depth += 1 + if self.depth > MAX_DEPTH: + raise ExprError(_DEPTH_MESSAGE, pos) + + def leave(self) -> None: + self.depth -= 1 + + def _is_value_start(self, t: _Tok) -> bool: + return t.kind in ("num", "col", "func", "(") + + def _unexpected(self, lparen: _Tok | None) -> ExprError: + """式の途中で、演算子や閉じ括弧でないものが来たときの誤り。""" + t = self.cur + if t.kind == "eof" and lparen is not None: + return ExprError("閉じ括弧「)」が足りません", lparen.pos) + if self._is_value_start(t): + return ExprError("値と値の間に演算子(+ - * / など)がありません", t.pos) + if t.kind == ")": + return ExprError("「)」に対応する「(」がありません", t.pos) + if t.kind == ",": + return ExprError("「,」は関数の引数の区切りにだけ使えます", t.pos) + return ExprError("式を解釈できません", t.pos) + + def parse_top(self) -> Node: + node = self.expr() + if self.cur.kind != "eof": + raise self._unexpected(None) + return node + + def expr(self) -> Node: + left = self.term() + while self.cur.kind == "op" and self.cur.text in "+-": + op = self.advance().text + right = self.term() + left = _make_binary(op, left, right, left.pos) + return left + + def term(self) -> Node: + left = self.unary() + while self.cur.kind == "op" and self.cur.text in ("*", "/"): + op = self.advance().text + right = self.unary() + left = _make_binary(op, left, right, left.pos) + return left + + def unary(self) -> Node: + t = self.cur + if t.kind == "op" and t.text in "+-": + self.enter(t.pos) + self.advance() + operand = self.unary() + self.leave() + return operand if t.text == "+" else _make_unary(operand, t.pos) + return self.power() + + def power(self) -> Node: + base = self.atom() + t = self.cur + if t.kind == "op" and t.text in ("**", "^"): + self.enter(t.pos) + self.advance() + exponent = self.unary() + self.leave() + return _make_binary("**", base, exponent, base.pos) + return base + + def _missing_operand(self) -> ExprError: + t = self.cur + if self.i == 0: + if t.kind == ")": + return ExprError("「)」に対応する「(」がありません", t.pos) + return ExprError(f"「{t.text}」の前に値がありません", t.pos) + prev = self.toks[self.i - 1] + return ExprError(f"「{prev.text}」の後に値がありません", prev.pos) + + def atom(self) -> Node: + t = self.cur + if t.kind == "num": + self.advance() + return _make_number(t.value, t.pos) + if t.kind == "col": + self.advance() + return Column(t.value, t.pos) + if t.kind == "func": + self.advance() + lp = self.advance() # tokenizer guarantees "(" + self.enter(t.pos) + args: list[Node] = [] + if self.cur.kind != ")": + args.append(self.expr()) + while self.cur.kind == ",": + self.advance() + args.append(self.expr()) + if self.cur.kind != ")": + raise self._unexpected(lp) + self.advance() + self.leave() + return _make_call(t.value, args, t.pos) + if t.kind == "(": + self.enter(t.pos) + self.advance() + inner = self.expr() + if self.cur.kind != ")": + raise self._unexpected(t) + self.advance() + self.leave() + return inner + raise self._missing_operand() + + +def parse(text: str) -> Node: + if len(text) > MAX_LENGTH: + raise ExprError(f"式は{MAX_LENGTH}文字までです") + s = _normalize(text) + if not s.strip(" \t"): + raise ExprError("式を入力してください") + toks = _tokenize(s) + try: + node = _Parser(toks).parse_top() + except RecursionError: + raise ExprError(_DEPTH_MESSAGE) from None + if node.kind == "const": + raise ExprError("式に列([N] か A, B, …)を1つ以上含めてください") + return node + + +# ---- 木の調査 --------------------------------------------------------------- + + +def _children(node: Node) -> tuple: + if isinstance(node, Unary): + return (node.operand,) + if isinstance(node, Binary): + return (node.left, node.right) + if isinstance(node, Call): + return node.args + return () + + +def column_refs(node: Node) -> tuple[tuple[int, int], ...]: + refs: list[tuple[int, int]] = [] + stack = [node] + while stack: + n = stack.pop() + if isinstance(n, Column): + refs.append((n.index, n.pos)) + stack.extend(reversed(_children(n))) + return tuple(refs) + + +def column_indices(node: Node) -> tuple[int, ...]: + return tuple(sorted({i for i, _ in column_refs(node)})) + + +def is_series(node: Node) -> bool: + return node.kind == "series" + + +# ---- 評価 ------------------------------------------------------------------- + +# pandas の集計は、全部欠損のとき Python の float を返すものがある(mean など)。 +# Python の float だと 0 での割り算が ZeroDivisionError になるため、必ず np.float64 にそろえる。 +_AGG_METHODS = { + "min": lambda x: np.float64(x.min()), + "max": lambda x: np.float64(x.max()), + "mean": lambda x: np.float64(x.mean()), + "median": lambda x: np.float64(x.median()), + "std": lambda x: np.float64(x.std()), + "first": lambda x: np.float64(x.bfill().iloc[0]), + "last": lambda x: np.float64(x.ffill().iloc[-1]), +} + + +def evaluate( + node: Node, columns: Mapping[int, pd.Series], index: pd.Index +) -> tuple[pd.Series, int]: + """式を評価する。戻り値は (float の Series, 計算できなかった行数)。""" + n = len(index) + bad = np.zeros(n, dtype=bool) + + def mark(result, operands) -> None: + r = np.asarray(result, dtype=float) + ok = np.ones((), dtype=bool) + for o in operands: + ok = ok & np.isfinite(np.asarray(o, dtype=float)) + b = ~np.isfinite(r) & ok + if b.ndim == 0: + if b: + bad[:] = True + else: + bad[...] |= b + + def go(nd: Node): + if isinstance(nd, Number): + return float(nd.value) + if isinstance(nd, Column): + return columns[nd.index] + if isinstance(nd, Unary): + x = go(nd.operand) + res = -x + mark(res, [x]) + return res + if isinstance(nd, Binary): + a = go(nd.left) + b = go(nd.right) + res = _BINARY_OPS[nd.op](a, b) + mark(res, [a, b]) + return res + name = nd.name + x = go(nd.args[0]) + if name in ELEMENTWISE: + res = getattr(np, name)(x) + mark(res, [x]) + return res + if name in AGGREGATES: + res = _AGG_METHODS[name](x) + if np.isfinite(np.asarray(x, dtype=float)).any() and not np.isfinite(res): + bad[:] = True + return res + if name == "rolling_mean": + return x.rolling(int(nd.args[1].value), center=True).mean() + if name == "diff": + return x.diff() + return x.cumsum() + + with np.errstate(divide="ignore", invalid="ignore", over="ignore"): + val = go(node) + if isinstance(val, pd.Series): + arr = val.to_numpy(dtype=float) + else: + arr = np.full(n, float(val)) + arr = np.where(np.isinf(arr), np.nan, arr) + count = int((bad & np.isnan(arr)).sum()) + return pd.Series(arr, index=index, dtype=float), count + + +# ---- コード生成 ------------------------------------------------------------- + +_P_ADD, _P_MUL, _P_UNARY, _P_POW, _P_ATOM = 1, 2, 3, 4, 5 +_OP_PREC = {"+": _P_ADD, "-": _P_ADD, "*": _P_MUL, "/": _P_MUL, "**": _P_POW} + + +def to_code( + node: Node, column_var: Callable[[int], str], number: Callable[[float], str] +) -> str: + """評価と同じ意味の pandas / numpy の式を文字列にする(入力文字列は写さない)。""" + + def method_base(arg: Node) -> str: + s, _ = go(arg) + return s if isinstance(arg, Column) else f"({s})" + + 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, Column): + return column_var(nd.index), _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})" + return f"{ls} {op} {rs}", prec + name = nd.name + if name in ELEMENTWISE: + s, _ = go(nd.args[0]) + return f"np.{name}({s})", _P_ATOM + base = method_base(nd.args[0]) + if name in AGGREGATES: + tail = { + "first": ".bfill().iloc[0]", + "last": ".ffill().iloc[-1]", + }.get(name, f".{name}()") + return f"np.float64({base}{tail})", _P_ATOM + if name == "rolling_mean": + return f"{base}.rolling({int(nd.args[1].value)}, center=True).mean()", _P_ATOM + return f"{base}.{name}()", _P_ATOM + + return go(node)[0] diff --git a/pyscript.toml b/pyscript.toml index 08787ef..06fb858 100644 --- a/pyscript.toml +++ b/pyscript.toml @@ -13,6 +13,7 @@ packages_cache = "passthrough" "./py/mplgui/settings.py" = "./mplgui/settings.py" "./py/mplgui/loader.py" = "./mplgui/loader.py" "./py/mplgui/dataprep.py" = "./mplgui/dataprep.py" +"./py/mplgui/expr.py" = "./mplgui/expr.py" "./py/mplgui/codegen.py" = "./mplgui/codegen.py" "./py/mplgui/formats.py" = "./mplgui/formats.py" "./py/mplgui/runner.py" = "./mplgui/runner.py" diff --git a/tests/unit/test_expr.py b/tests/unit/test_expr.py new file mode 100644 index 0000000..6798c55 --- /dev/null +++ b/tests/unit/test_expr.py @@ -0,0 +1,326 @@ +"""expr.py(式で新しい列)の単体テスト。""" + +import numpy as np +import pandas as pd +import pytest +from pandas.testing import assert_series_equal + +from mplgui import expr +from mplgui.expr import ExprError, evaluate, parse, to_code + +INDEX = pd.Index(range(10, 18)) +C0 = pd.Series([1.0, 2, 3, 4, 5, 6, 7, 8], index=INDEX) +C1 = pd.Series([2.0, 0, -1, 4, np.nan, 6, -7, 8], index=INDEX) +C2 = pd.Series([0.5, 1.5, np.nan, 2.5, 3.5, 4.5, 5.5, 6.5], index=INDEX) +COLS = {0: C0, 1: C0, 2: C1, 3: C2} # [1] = C0, [2] = C1, [3] = C2(A は [0]) + + +def run(text, columns=COLS, index=INDEX): + return evaluate(parse(text), columns, index) + + +def values(text): + return run(text)[0] + + +def code_of(text): + return to_code(parse(text), lambda i: f"col{i}", repr) + + +def via_code(text): + ns = {"np": np, "pd": pd, **{f"col{i}": s for i, s in COLS.items()}} + with np.errstate(all="ignore"): + r = eval(code_of(text), ns) # テスト内だけで使う + arr = np.full(len(INDEX), float(r)) if np.isscalar(r) or np.ndim(r) == 0 else r.to_numpy(float) + arr = np.where(np.isinf(arr), np.nan, arr) + return pd.Series(arr, index=INDEX, dtype=float) + + +def err(text): + with pytest.raises(ExprError) as e: + parse(text) + return e.value + + +# ---- 構文 ---- + + +def test_precedence_and_associativity(): + assert values("-2**2 + [1]*0").iloc[0] == -4 + assert values("2**3**2 + [1]*0").iloc[0] == 512 + assert values("2^-1 + [1]*0").iloc[0] == 0.5 + assert_series_equal(values("[1]-[2]-[3]"), C0 - C1 - C2, check_names=False) + assert_series_equal(values("[1]/[2]/[3]").fillna(-9), (C0 / C1 / C2).replace([np.inf, -np.inf], np.nan).fillna(-9), check_names=False) + assert_series_equal(values("2 + [1] * 3"), 2 + C0 * 3, check_names=False) + assert_series_equal(values("([0] + 1) * 2"), (C0 + 1) * 2, check_names=False) + assert_series_equal(values("+[1]"), C0, check_names=False) + + +@pytest.mark.parametrize( + "letters, index", [("A", 0), ("Z", 25), ("AA", 26), ("AZ", 51), ("BA", 52), ("ZZZ", 18277)] +) +def test_excel_letters(letters, index): + node = parse(f"{letters} + 1") + assert expr.column_indices(node) == (index,) + + +def test_fullwidth_input(): + node = parse("(A + 2) * max([2])") + assert expr.column_refs(node) == ((0, 2), (2, 15)) + assert_series_equal(values("[1] + 1"), C0 + 1, check_names=False) + + +def test_whitespace_and_bracket_spaces(): + assert parse("[ 3 ]").index == 3 + assert expr.column_indices(parse(" [ 3 ]\t+ B ")) == (1, 3) + + +def test_column_refs_positions_in_text_order(): + node = parse("[5] + max(A) * [2]") + assert expr.column_refs(node) == ((5, 1), (0, 11), (2, 16)) + assert expr.column_indices(node) == (0, 2, 5) + + +def test_is_series(): + assert expr.is_series(parse("[1] + 1")) + assert expr.is_series(parse("[1] - max([1])")) + assert not expr.is_series(parse("max([1])")) + assert not expr.is_series(parse("max([1]) / 2")) + assert expr.is_series(parse("diff([1])")) + + +# ---- 関数 ---- + + +@pytest.mark.parametrize("name", expr.ELEMENTWISE) +def test_elementwise(name): + with np.errstate(all="ignore"): + expected = getattr(np, name)(C1) + expected = expected.replace([np.inf, -np.inf], np.nan) + assert_series_equal(values(f"{name}([2])"), expected, check_names=False) + + +def test_aggregates_against_pandas(): + for name, ref in [ + ("min", C1.min()), ("max", C1.max()), ("mean", C1.mean()), + ("median", C1.median()), ("std", C1.std()), + ("first", C1.iloc[0]), ("last", C1.iloc[-1]), + ]: + r = values(f"{name}([2])") + assert (r == ref).all(), name + nan_head = pd.Series([np.nan, np.nan, 3.0, np.nan], index=pd.RangeIndex(4)) + cols = {0: nan_head} + assert run("first(A)", cols, nan_head.index)[0].eq(3.0).all() + assert run("last(A)", cols, nan_head.index)[0].eq(3.0).all() + all_nan = {0: pd.Series([np.nan] * 3)} + r, count = run("max(A)", all_nan, all_nan[0].index) + assert r.isna().all() and count == 0 + + +def test_aggregates_return_numpy_floats(): + s = pd.Series([1.0, 2.0, np.nan]) + nan = pd.Series([np.nan, np.nan]) + for name, fn in expr._AGG_METHODS.items(): + assert isinstance(fn(s), np.float64), name + assert isinstance(fn(nan), np.float64), name + # 生成コードでも 0 での割り算で例外にならない(全部欠損の mean は pandas では Python の float) + with np.errstate(all="ignore"): + assert np.isnan(eval(code_of("mean([1]) / 0"), {"np": np, "col1": nan})) + + +def test_series_funcs(): + assert_series_equal(values("rolling_mean([3], 3)"), C2.rolling(3, center=True).mean(), check_names=False) + assert_series_equal(values("diff([2])"), C1.diff(), check_names=False) + assert_series_equal(values("cumsum([3])"), C2.cumsum(), check_names=False) + assert_series_equal(values("[1] - rolling_mean([1], 1)"), C0 - C0.rolling(1, center=True).mean(), check_names=False) + + +CORPUS = [ + "[1]", "-[1]", "[1] + [2]", "[1] - [2]", "[1] * [2]", "[1] / [2]", "[1] ** 2", "[1] ^ 0.5", + "([1] + [2]) * [3]", "[1] + [2] * [3]", "[1] - ([2] - [3])", "[1] / ([2] / [3])", + "([1] * [2]) ** [3]", "[1] ** [2] ** [3]", "([1] ** [2]) ** [3]", "-[1] ** 2", "(-[1]) ** 2", + "2 ** -[1]", "-([1] + 1)", "-(-[1])", "(-2) ** [1]", "-2 * [1]", "[1] / -2", + "abs([2])", "sqrt([2])", "log([2]) + 1", "log10([1]) * 2", "exp([1] / 10)", "sin([1]) ** 2 + cos([1]) ** 2", + "tan([3])", "abs([2] - 3) / sqrt([1])", "max([1])", "max([1]) / 0", "[1] - mean([1])", + "([1] - min([1])) / (max([1]) - min([1]))", "std([2]) * [1]", "median([3]) - [3]", "first([1]) / last([1])", + "-max([2])", "max([2]) ** 2", "(max([1]) - 1) ** [1]", "rolling_mean([1], 3) * 2", "diff([1]) / [2]", + "cumsum([1]) - cumsum([3])", "1 / ([2] - [2])", "log([2]) / [1]", "[1] * (1 + 2) / 4", "A + B * C", "1e3 * [1] + .5", + "sqrt(max([1]) - 100)", +] + + +@pytest.mark.parametrize("text", CORPUS) +def test_evaluate_matches_generated_code(text): + assert_series_equal(values(text), via_code(text), check_names=False) + + +def test_code_is_minimal_and_precedence_aware(): + assert code_of("[1] + [2] * [3]") == "col1 + col2 * col3" + assert code_of("([1] + [2]) * [3]") == "(col1 + col2) * col3" + assert code_of("[1] - ([2] - [3])") == "col1 - (col2 - col3)" + assert code_of("[1] ** [2] ** [3]") == "col1 ** col2 ** col3" + assert code_of("([1] ** [2]) ** [3]") == "(col1 ** col2) ** col3" + assert code_of("-[1] ** 2") == "-col1 ** 2.0" + assert code_of("(-[1]) ** 2") == "(-col1) ** 2.0" + assert code_of("max([1]) - [1]") == "np.float64(col1.max()) - col1" + assert code_of("rolling_mean([1] + 1, 5)") == "(col1 + 1.0).rolling(5, center=True).mean()" + + +def test_injection_free_code(): + node = parse("[3] * 1.5 + abs( [4] ) - max(B)") + code = to_code(node, lambda i: f"COL{i}", lambda v: "NUM") + assert code == "COL3 * NUM + np.abs(COL4) - np.float64(COL1.max())" + + +@pytest.mark.parametrize( + "text", + ["__import__('os')", "[1]; import os", "[1]\n+1", "'a'", '"a"', "[1] \\ 2", "[1].real", "[1] if 1 else 2", "x = 1", "[1] % 2", "[1] // 2", "lambda"], +) +def test_injection_inputs_rejected(text): + with pytest.raises(ExprError): + parse(text) + + +# ---- 定数の畳み込み ---- + + +def test_constant_folding(): + node = parse("[1] * (1 + 2)") + assert isinstance(node.right, expr.Number) and node.right.value == 3.0 + assert code_of("[1] * (1 + 2)") == "col1 * 3.0" + assert code_of("sqrt(16) * [1]") == "4.0 * col1" + assert code_of("2 ** 3 ** 2 + [1]") == "512.0 + col1" + + +@pytest.mark.parametrize("text", ["[1] + 1/0", "[1] + sqrt(-1)", "[1] * (-8) ** 0.5", "[1] + log(0)", "1e999 + [1]", "[1] + exp(1000)"]) +def test_non_finite_constants_rejected(text): + e = err(text) + assert "計算できない定数" in e.message and e.position is not None + + +# ---- エラー ---- + + +@pytest.mark.parametrize( + "text, pos, msg", + [ + ("[1] # 2", 5, "「#」は使えません"), + ("([1] + 2", 1, "閉じ括弧「)」が足りません"), + ("max([1]", 4, "閉じ括弧「)」が足りません"), + ("[1] + 2)", 8, "「)」に対応する「(」がありません"), + (")[1]", 1, "「)」に対応する「(」がありません"), + ("[1] *", 5, "「*」の後に値がありません"), + ("[1] + * 2", 5, "「+」の後に値がありません"), + ("* [1]", 1, "「*」の前に値がありません"), + ("[1] [2]", 5, "値と値の間に演算子(+ - * / など)がありません"), + ("2[1]", 2, "値と値の間に演算子"), + ("[1] 2", 5, "値と値の間に演算子"), + ("[a]", 1, "列は [0] のように、角括弧の中に番号を書いてください"), + ("[]", 1, "列は [0] のように"), + ("[1", 1, "列は [0] のように"), + ("foo + [1]", 1, "「foo」は使えません"), + ("foo([1])", 1, "使える関数: abs, sqrt"), + ("max + [1]", 1, "「max」は関数です"), + ("MAX([1])", 1, "関数名は小文字で書いてください(max)"), + ("ABCD", 1, "「ABCD」は使えません"), + ("sqrt([1], 2)", 1, "sqrt には値を1つ指定してください"), + ("sqrt()", 1, "sqrt には値を1つ指定してください"), + ("rolling_mean([1])", 1, "rolling_mean には「式, 窓の幅」の2つを指定してください"), + ("max([1], [2])", 1, "max には値を1つ指定してください"), + ("max(1)", 1, "max の中には列を含めてください"), + ("max(max([1]))", 1, "max の中には列を含めてください"), + ("diff(2 + 3)", 1, "diff の中には列を含めてください"), + ("rolling_mean([1], 0)", 19, "rolling_mean の窓の幅は 1〜1000 の整数で指定してください"), + ("rolling_mean([1], 1001)", 19, "窓の幅は 1〜1000"), + ("rolling_mean([1], 2.5)", 19, "窓の幅は 1〜1000"), + ("rolling_mean([1], -1)", 19, "窓の幅は 1〜1000"), + ("rolling_mean([1], [2])", 19, "窓の幅は 1〜1000"), + ("1 + 2", None, "式に列"), + ("2 * 3", None, "式に列"), + ("", None, "式を入力してください"), + (" ", None, "式を入力してください"), + ("[1] + (2, 3)", 9, "「,」は関数の引数の区切りにだけ使えます"), + ], +) +def test_error_messages(text, pos, msg): + e = err(text) + assert msg in e.message + assert e.position == pos + + +def test_error_str_includes_position(): + e = err("[1] # 2") + assert str(e) == "5文字目: 「#」は使えません" + assert str(err("")) == "式を入力してください" + + +def test_limits(): + e = err("1" * 201) + assert e.message == "式は200文字までです" and e.position is None + parse("1+" * 98 + "[1]") # 200 文字ちょうど以下 + assert err("(" * 31 + "[1]" + ")" * 31).message.startswith("入れ子が深すぎます") + parse("(" * 30 + "[1]" + ")" * 30) + assert err("-" * 31 + "[1]").message.startswith("入れ子が深すぎます") + assert err("[1]" + "^2" * 40).message.startswith("入れ子が深すぎます") + assert err("abs(" * 31 + "[1]" + ")" * 31).message == "入れ子が深すぎます(30 段まで)" + parse("rolling_mean([1], 1)") + parse("rolling_mean([1], 1000)") + + +def test_no_recursion_error_on_long_inputs(): + for text in ["-" * 200, "(" * 200, "[1]" + "**2" * 66, "abs(" * 50, "[1]" + "+[1]" * 49]: + try: + parse(text) + except ExprError: + pass + + +# ---- スカラーだけの式 ---- + + +def test_scalar_only_expressions(): + r, count = run("max([1])") + assert r.eq(8.0).all() and len(r) == len(INDEX) and count == 0 + r, count = run("max([1]) / 0") + assert r.isna().all() and count == len(INDEX) + r, count = run("max([1]) / 2 + min([1])") + assert r.eq(5.0).all() + assert r.index.equals(INDEX) + + +# ---- invalid_count ---- + + +def test_invalid_count_division(): + r, count = run("[1] / [2]") + assert count == 1 and r.isna().sum() == 2 # 0 での割り算 1 行と、NaN 入力 1 行 + assert np.isnan(r.iloc[1]) and np.isnan(r.iloc[4]) + + +def test_invalid_count_sqrt_and_log(): + assert run("sqrt([2])")[1] == 2 # -1 と -7 + assert run("log([2])")[1] == 3 # 0, -1, -7(0 は -inf) + + +def test_invalid_count_edges_and_nan_not_counted(): + assert run("rolling_mean([1], 3)")[1] == 0 + assert run("diff([1])")[1] == 0 + assert run("cumsum([2])")[1] == 0 + c = {0: pd.Series([np.nan, 1.0, 4.0], index=pd.RangeIndex(3))} + r, count = run("sqrt(A)", c, c[0].index) + assert count == 0 and r.isna().sum() == 1 + + +def test_invalid_count_counts_only_final_nan(): + # 途中の inf は最終的に NaN になる行だけ数える + r, count = run("1 / ([2] - [2]) * 0") + assert count == len(INDEX) - 1 or count == 7 + assert r.isna().all() + + +def test_invalid_count_aggregate(): + c = {0: pd.Series([5.0], index=pd.RangeIndex(1))} + r, count = run("std(A)", c, c[0].index) # 1 行だと標準偏差は NaN + assert count == 1 and r.isna().all() + r, count = run("max([2]) + 1") + assert count == 0 From 192d6f0540a3d4cfdbdb1f3efe5100545fe70d66 Mon Sep 17 00:00:00 2001 From: mioupa <79833278+mioupa@users.noreply.github.com> Date: Thu, 12 Nov 2026 09:02:54 +0900 Subject: [PATCH 03/10] Add step, barh, stacked bar, histogram and colour-mapped scatter to settings and generated code (Phase 5c, G7) Hidden settings for each type are neither validated nor used. Default settings still generate byte-identical code (golden tests). Co-Authored-By: Claude Opus 5.5 --- js/defaults.js | 5 + py/mplgui/codegen.py | 250 +++++++++-- py/mplgui/dataprep.py | 230 +++++++++-- py/mplgui/runner.py | 49 ++- py/mplgui/settings.py | 89 +++- tests/unit/test_chart_types.py | 732 +++++++++++++++++++++++++++++++++ tests/unit/test_settings.py | 27 ++ 7 files changed, 1287 insertions(+), 95 deletions(-) create mode 100644 tests/unit/test_chart_types.py diff --git a/js/defaults.js b/js/defaults.js index e3ba3ad..6b3548f 100644 --- a/js/defaults.js +++ b/js/defaults.js @@ -39,6 +39,7 @@ export const DEFAULT_SERIES = { marker: "auto", alpha: 1, fill: { lower: "", upper: "", alpha: 0.25 }, + colorColumn: "", }; // 注釈(annotations[])1つの既定値。id は追加するときに a1, a2, ... を振る(削除しても再利用しない) @@ -88,6 +89,10 @@ export const DEFAULT_SETTINGS = { grid: { major: false, minor: false }, margins: { left: null, right: null, bottom: null, top: null }, spines: { top: true, right: true }, + step: { where: "post" }, + hist: { bins: null, density: false }, + colormap: "viridis", + colorbarLabel: "", }, 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 caad467..aa27620 100644 --- a/py/mplgui/codegen.py +++ b/py/mplgui/codegen.py @@ -21,6 +21,8 @@ SCRIPT_NAME = "plot.py" +XY_TYPES = {"line", "step", "scatter", "scatterColor"} # X と Y の組で描く種類(X が日時なら日時の軸、エラーバー・帯・近似曲線を使える) + GENERIC_ERROR_MESSAGE = "グラフを描画できませんでした。X列・Y列に指定した列の値の形式(数値と文字列の混在など)や、設定の値を確認してください。" TIGHT_LAYOUT_ERROR = "レイアウトの自動調整に失敗しました。余白を手動で指定するか、図の大きさ・フォントサイズを小さくしてください。" MARGIN_ERROR = "余白の設定を適用できませんでした。左 < 右、下 < 上 になるように、0〜1の値で指定してください。" @@ -213,8 +215,20 @@ def _emit_header( b.add(f'plt.rcParams["mathtext.fontset"] = {literal(latin.mathtext_fontset)} # 数式($...$)も Times 系の字形にする(STIX は matplotlib に同梱)') +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) + + +def _scale(settings: Settings, plan: PlotPlan, name: str) -> str: + """軸のスケール。横棒の縦軸(カテゴリ)は Y のスケールを使わない。""" + if plan.plot_type == "barh" and name == "y": + return "linear" + return getattr(settings.axes, name).scale + + def _uses_date_axis(plan: PlotPlan) -> bool: - return plan.datetime_x and plan.plot_type in {"line", "scatter"} + return plan.datetime_x and plan.plot_type in XY_TYPES def _font_list_literal() -> str: @@ -372,7 +386,7 @@ def _alpha_arg(p: SeriesPlan) -> str: # ---- band (G3) ---- -def _emit_band(b: _Builder, s: SeriesSettings, p: SeriesPlan) -> None: +def _emit_band(b: _Builder, s: SeriesSettings, p: SeriesPlan, step: str = "") -> None: """塗りつぶし帯(fill_between)。エラーバーと系列本体より先に描く(系列本体が上に来る)。""" fill = p.fill if fill is None: @@ -384,7 +398,8 @@ def _emit_band(b: _Builder, s: SeriesSettings, p: SeriesPlan) -> None: f'fill_upper = pd.to_numeric({p.data_var}.iloc[:, {fill.upper_index}], errors="coerce")' f" # 塗りつぶし帯の上端: {comment_text(fill.upper_label)}", f"{_target(p)}.fill_between(x[ok], fill_lower[ok], fill_upper[ok], color={literal(s.color)}, alpha={literal(fill.alpha)}, " - 'linewidth=0, label="_fill") # 塗りつぶし帯(凡例には出さない)', + + (f"step={literal(step)}, " if step else "") + + 'linewidth=0, label="_fill") # 塗りつぶし帯(凡例には出さない)' + ("(段に合わせる)" if step else ""), ) @@ -410,7 +425,7 @@ def _emit_band(b: _Builder, s: SeriesSettings, p: SeriesPlan) -> None: def _uses_poly_text(plan: PlotPlan) -> bool: - return plan.plot_type in {"line", "scatter"} 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"} for f in plan.fits) def _fit_label_expr(fit: FitPlan) -> str: @@ -466,7 +481,7 @@ def _emit_fits(b: _Builder, plan: PlotPlan, p: SeriesPlan) -> None: def _uses_error_function(plan: PlotPlan) -> bool: - return plan.plot_type in {"line", "scatter"} and any(p.has_points and (p.y_err or p.x_err) for p in plan.series) + return plan.plot_type in XY_TYPES and any(p.has_points and (p.y_err or p.x_err) for p in plan.series) def _error_names(err: ErrorPlan, owner: str = "") -> tuple[str, str]: @@ -536,18 +551,21 @@ def _bar_yerr_expr(err: ErrorPlan, owner: str = "") -> str: return plus if err.symmetric else f"[{minus}, {plus}]" -def _bar_error_args(s: SeriesSettings, p: SeriesPlan, owner: str = "") -> str: +def _bar_error_args(s: SeriesSettings, p: SeriesPlan, owner: str = "", *, horizontal: bool = False) -> str: + """ax.bar / ax.barh のエラーバーの引数。横棒(barh)は、Y 方向の指定を値の誤差として xerr で描く。""" if p.y_err is None: return "" width = literal(s.line_width) + keyword = "xerr" if horizontal else "yerr" return ( - f", yerr={_bar_yerr_expr(p.y_err, owner)}, capsize={literal(p.cap_size)}, ecolor=\"black\", " + f", {keyword}={_bar_yerr_expr(p.y_err, owner)}, capsize={literal(p.cap_size)}, ecolor=\"black\", " f'error_kw={{"elinewidth": {width}, "capthick": {width}}}' ) def _emit_line_series(b: _Builder, settings: Settings, plan: PlotPlan) -> None: ax2 = _Axes2State() + drawstyle = settings.plot.step_where if plan.plot_type == "step" else "" # step: 段の付き方(pre / mid / post) for i, (s, p) in enumerate(zip(settings.series, plan.series)): if i > 0: b.blank() # 系列ごとに1行あける @@ -560,12 +578,14 @@ def _emit_line_series(b: _Builder, settings: Settings, plan: PlotPlan) -> None: _emit_x_data(b, p) _emit_y_data(b, p) _emit_ok_mask(b) - _emit_band(b, s, p) + _emit_band(b, s, p, drawstyle) _emit_line_error_bars(b, s, p) marker = "" if p.marker: b.add("# 点の大きさ: 面積(scatter の s と同じ単位)の平方根を markersize(直径)にする") marker = f", marker={literal(p.marker)}, markersize={literal(p.marker_size)} ** 0.5" + if drawstyle: + marker += f", drawstyle={literal('steps-' + drawstyle)}" b.add(f"{_target(p)}.plot(x[ok], y[ok], {_style_args(s)}{marker}{_alpha_arg(p)}, label={literal(p.legend_label)})") _emit_fits(b, plan, p) @@ -608,6 +628,10 @@ def _emit_bar_x(b: _Builder, plan: PlotPlan) -> None: def _emit_bar_series(b: _Builder, settings: Settings, plan: PlotPlan) -> None: + """bar / barh。barh は同じ並べ方を横向きにする(ax.barh。複数系列は縦方向にずらし、エラーバーは xerr)。""" + horizontal = plan.plot_type == "barh" + func = "barh" if horizontal else "bar" + size_arg = "height" if horizontal else "width" ax2 = _Axes2State() if len(plan.series) == 1: s, p = settings.series[0], plan.series[0] @@ -620,49 +644,183 @@ def _emit_bar_series(b: _Builder, settings: Settings, plan: PlotPlan) -> None: if p.y_err is not None: with b.step(*_error_step(p, p.y_err)): _emit_error_columns(b, p, p.y_err) - b.add(f"{_target(p)}.bar(x[ok], y[ok], {_style_args(s)}{_alpha_arg(p)}, label={literal(p.legend_label)}{_bar_error_args(s, p)})") + b.add( + f"{_target(p)}.{func}(x[ok], y[ok], {_style_args(s)}{_alpha_arg(p)}, label={literal(p.legend_label)}" + f"{_bar_error_args(s, p, horizontal=horizontal)})" + ) return n = len(plan.series) - b.add("# 複数の系列を、X の値ごとに横に並べた棒グラフにする(X は共通)") + if horizontal: + b.add("# 複数の系列を、カテゴリごとに縦に並べた横棒グラフにする(カテゴリは X列で共通。下から上へ並ぶ)") + else: + b.add("# 複数の系列を、X の値ごとに横に並べた棒グラフにする(X は共通)") with b.step(GENERIC_ERROR_MESSAGE): - _emit_bar_x(b, plan) + _emit_bar_data(b, plan, error_bars=True) + b.add(f"{size_arg} = 0.8 / {n} # 棒1本の{'高さ' if horizontal else '幅'}") + for i, (s, p) in enumerate(zip(settings.series, plan.series)): + b.blank() + b.add(_series_comment(p)) + ax2.ensure(b, p) + b.add(f"offset = -0.4 + ({size_arg} / 2.0) + ({i} * {size_arg})") + b.add( + f'{_target(p)}.{func}(positions + offset, bar_data["y{p.number}"].fillna(0.0), {size_arg}={size_arg}, ' + f"{_style_args(s)}{_alpha_arg(p)}, label={literal(p.legend_label)}" + f"{_bar_error_args(s, p, f'y{p.number}', horizontal=horizontal)})" + ) + + +def _emit_bar_data(b: _Builder, plan: PlotPlan, *, error_bars: bool) -> None: + """棒の位置(positions)とカテゴリのラベル(x_labels)、系列ごとの値(bar_data)を作る。全系列が欠けている行は描かない。""" + _emit_bar_x(b, plan) + if error_bars: for p in plan.series: if p.y_err is not None: with b.step(*_error_step(p, p.y_err)): _emit_error_columns(b, p, p.y_err, f"y{p.number}") - b.add("bar_data = pd.DataFrame({") - b.add(' "x": x,') - for p in plan.series: - b.add(f' "y{p.number}": pd.to_numeric({p.data_var}.iloc[:, {p.y_index}], errors="coerce"), # {_column_comment(p, "y")}') - if p.y_err is not None and p.y_err.mode == "column": - for name in dict.fromkeys(_error_names(p.y_err, f"y{p.number}")): - b.add(f' "{name}": {name},') - b.add("})") - keys = ", ".join(literal(f"y{p.number}") for p in plan.series) - b.add(f'bar_data = bar_data.dropna(subset=[{keys}], how="all") # 全ての系列が欠けている行は描かない') + b.add("bar_data = pd.DataFrame({") + b.add(' "x": x,') + for p in plan.series: + b.add(f' "y{p.number}": pd.to_numeric({p.data_var}.iloc[:, {p.y_index}], errors="coerce"), # {_column_comment(p, "y")}') + if error_bars and p.y_err is not None and p.y_err.mode == "column": + for name in dict.fromkeys(_error_names(p.y_err, f"y{p.number}")): + b.add(f' "{name}": {name},') + b.add("})") + keys = ", ".join(literal(f"y{p.number}") for p in plan.series) + b.add(f'bar_data = bar_data.dropna(subset=[{keys}], how="all") # 全ての系列が欠けている行は描かない') + if error_bars: for p in plan.series: if p.y_err is not None and p.y_err.mode == "column": for name in dict.fromkeys(_error_names(p.y_err, f"y{p.number}")): b.add(f'bar_data["{name}"] = bar_data["{name}"].where(bar_data["y{p.number}"].notna()) # 棒を描かない行のエラーバーも描かない') - b.add("x_labels = [str(v) for v in bar_data[\"x\"]]") - b.add("positions = np.arange(len(x_labels))") - b.add(f"width = 0.8 / {n} # 棒1本の幅") - for i, (s, p) in enumerate(zip(settings.series, plan.series)): + b.add("x_labels = [str(v) for v in bar_data[\"x\"]]") + b.add("positions = np.arange(len(x_labels))") + + +def _emit_stacked_series(b: _Builder, settings: Settings, plan: PlotPlan) -> None: + """積み上げ棒(barStacked)。正の値と負の値は別に積む(段が重ならない)。欠けた値は 0 として積む。""" + b.add("# 複数の系列を、X の値ごとに縦に積んだ棒グラフにする(X は共通。正の値と負の値は別に積む。欠けた値は 0)") + with b.step(GENERIC_ERROR_MESSAGE): + _emit_bar_data(b, plan, error_bars=False) + b.add( + "stack_pos = np.zeros(len(positions)) # 正の値を積んだ高さ", + "stack_neg = np.zeros(len(positions)) # 負の値を積んだ深さ", + ) + for s, p in zip(settings.series, plan.series): b.blank() b.add(_series_comment(p)) + b.add( + f'v = bar_data["y{p.number}"].fillna(0.0).to_numpy()', + f"ax.bar(positions, v, bottom=np.where(v >= 0, stack_pos, stack_neg), width=0.8, " + f"{_style_args(s)}{_alpha_arg(p)}, label={literal(p.legend_label)})", + "stack_pos += np.where(v >= 0, v, 0.0)", + "stack_neg += np.where(v < 0, v, 0.0)", + ) + + +def _emit_hist_series(b: _Builder, settings: Settings, plan: PlotPlan) -> None: + """ヒストグラム(hist)。系列の Y 列の値の分布。区間は全系列で共通、複数系列は区間ごとに横に並べる。""" + hist = plan.hist + assert hist is not None + drawn: list[tuple[SeriesSettings, SeriesPlan]] = [] + for i, (s, p) in enumerate(zip(settings.series, plan.series)): + if i > 0: + 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("# 描ける値(数値の行)が無いため、この系列は描かない") + continue + with b.step(GENERIC_ERROR_MESSAGE): + b.add( + f'hist_{p.number} = pd.to_numeric({p.data_var}.iloc[:, {p.y_index}], errors="coerce").dropna()' + " # 数値にできない値・欠けた値は数えない" + ) + drawn.append((s, p)) + names = [f"hist_{p.number}" for _, p in drawn] + bins = literal(hist.bins) if hist.bins is not None else '"auto"' + values = names[0] if len(names) == 1 else f"np.concatenate([{', '.join(names)}])" + b.blank() + with b.step(GENERIC_ERROR_MESSAGE): + b.add(f"hist_bins = np.histogram_bin_edges({values}, bins={bins}) # 区間は全系列で共通") + density = literal(hist.density) + if len(drawn) == 1: + s, p = drawn[0] + b.add( + f"ax.hist({names[0]}, bins=hist_bins, density={density}, {_style_args(s)}{_alpha_arg(p)}, " + f"label={literal(p.legend_label)})" + ) + return + colors = "[" + ", ".join(literal(s.color) for s, _ in drawn) + "]" + labels = "[" + ", ".join(literal(p.legend_label) for _, p in drawn) + "]" + b.add( + f"_, _, hist_bars = ax.hist([{', '.join(names)}], bins=hist_bins, density={density}, color={colors}, label={labels})" + " # 区間ごとに系列を横に並べる" + ) + for k, (s, p) in enumerate(drawn): + b.add( + f"plt.setp(hist_bars[{k}], linewidth={literal(s.line_width)}, linestyle={literal(s.line_style)}{_alpha_arg(p)})" + f" # 系列{p.number}の棒の縁・不透明度" + ) + + +def _emit_scatter_color_series(b: _Builder, settings: Settings, plan: PlotPlan) -> None: + """色分け散布図(scatterColor)。点を色分けの列の値で塗る。色の範囲は全系列で共通、カラーバーは1本。 + + 凡例は系列を点の形で見分けるもの。点は色分けの値で塗るので、凡例用に灰色の見本(空の scatter)を足す。""" + colorbar = plan.colorbar + assert colorbar is not None + cmap = literal(colorbar.colormap) + ax2 = _Axes2State() + b.add( + "# 色の範囲: 全系列で共通(下で、描いた点の色の値の最小〜最大に決める)", + "color_norm = plt.Normalize()", + "color_all = [] # 系列ごとの、描いた点の色の値", + ) + for s, p in zip(settings.series, plan.series): + b.blank() + b.add(_series_comment(p) + f"、色 = {comment_text(p.color_label)}") + if not p.has_points: + b.add("# 描ける点(X・Y・色の値とも数値の行)が無いため、この系列は描かない") + continue + with b.step(GENERIC_ERROR_MESSAGE, f"系列{p.number}の色分けの列"): ax2.ensure(b, p) - b.add(f"offset = -0.4 + (width / 2.0) + ({i} * width)") + _emit_x_data(b, p) + _emit_y_data(b, p) + b.add(f'c = pd.to_numeric({p.data_var}.iloc[:, {p.color_index}], errors="coerce") # 色分けの列(数値にできない値は NaN)') + b.add("ok = x.notna() & y.notna() & c.notna() # X・Y・色の値のどれかが欠けている行は描かない") + _emit_band(b, s, p) + _emit_line_error_bars(b, s, p, zorder=1) + marker = f", marker={literal(p.marker)}" if p.marker else "" b.add( - f'{_target(p)}.bar(positions + offset, bar_data["y{p.number}"].fillna(0.0), width=width, ' - f"{_style_args(s)}{_alpha_arg(p)}, label={literal(p.legend_label)}{_bar_error_args(s, p, f'y{p.number}')})" + f"{_target(p)}.scatter(x[ok], y[ok], c=c[ok], cmap={cmap}, norm=color_norm, s={literal(p.marker_size)}{marker}" + f'{_alpha_arg(p)}, label="_color") # 点は色の値で塗る(凡例には出さない)', + f'{_target(p)}.scatter([], [], color="gray", s={literal(p.marker_size)}{marker}{_alpha_arg(p)}, ' + f"label={literal(p.legend_label)}) # 凡例用の見本(灰色。色はカラーバーで読む)", + "color_all.append(c[ok])", ) + _emit_fits(b, plan, p) + b.blank() + size = _label_size_expr(settings.plot.font_size) + with b.step("カラーバーを描けませんでした。カラーマップと色分けの列を確認してください。", "カラーマップ"): + b.add( + "# 色の範囲を、描いた点の色の値の最小〜最大に決めて、カラーバーを1本付ける", + "color_values = pd.concat(color_all)", + "color_norm.vmin, color_norm.vmax = float(color_values.min()), float(color_values.max())", + f"colorbar = fig.colorbar(plt.cm.ScalarMappable(norm=color_norm, cmap={cmap}), ax=ax)", + f"colorbar.set_label({literal(colorbar.label)}, fontsize=FONT_SIZE)", + f'colorbar.ax.tick_params(which="both", direction="in", labelsize={size})', + ) SERIES_EMITTERS: dict[str, Callable[[_Builder, Settings, PlotPlan], None]] = { "line": _emit_line_series, "scatter": _emit_scatter_series, "bar": _emit_bar_series, + "step": _emit_line_series, # line と同じ書き方に drawstyle を足す + "barh": _emit_bar_series, # bar を横向きにする + "barStacked": _emit_stacked_series, + "hist": _emit_hist_series, + "scatterColor": _emit_scatter_color_series, } @@ -769,7 +927,7 @@ def _uses_ticker(settings: Settings, plan: PlotPlan) -> bool: return any("ticker." in line for blk in _axis_blocks(settings, plan) for line in _axis_tick_lines(blk, settings, plan)) -def _scale_lines(blk: _AxisBlock, plan: PlotPlan) -> list[str]: +def _scale_lines(blk: _AxisBlock, settings: Settings, plan: PlotPlan) -> list[str]: """スケールと範囲。X が日時の列のときは、日時の範囲(pd.Timestamp)。""" var, which, axis = blk.var, blk.which, blk.axis if blk.plan.kind == "datetime": @@ -777,7 +935,7 @@ def _scale_lines(blk: _AxisBlock, plan: PlotPlan) -> list[str]: f"{k}=pd.Timestamp({literal(v)})" for k, v in (("left", blk.plan.date_min), ("right", blk.plan.date_max)) if v ] return [f"{var}.set_xlim({', '.join(limits)})"] if limits else [] - return _axis_lines(var, which, axis.scale, axis.min, axis.max) + return _axis_lines(var, which, _scale(settings, plan, blk.name), axis.min, axis.max) def _major_lines(blk: _AxisBlock, settings: Settings, plan: PlotPlan) -> list[str]: @@ -802,11 +960,11 @@ def _major_lines(blk: _AxisBlock, settings: Settings, plan: PlotPlan) -> list[st f"{axis_var}.set_major_formatter({formatter})", ] if ap.kind == "category": - if plan.plot_type == "bar" and len(plan.series) > 1: - return [] # 複数系列の棒は、棒の位置に目盛を付ける節(tick_step)で扱う + if _positions_form(plan): + 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 {"line", "scatter"} and plan.thin_categorical_x: + if plan.plot_type in XY_TYPES and plan.thin_categorical_x: return [ "# X が文字列の列: 目盛に X の値を出す(25個を超えるので間引く)", f"{axis_var}.set_major_locator(ticker.MaxNLocator(nbins=25, integer=True))", @@ -885,7 +1043,7 @@ def _emit_axes(b: _Builder, settings: Settings, plan: PlotPlan) -> None: # 軸ごとに: スケール → 範囲 → 主目盛・書式 → 副目盛 → 反転(スケールを変えると目盛の設定が戻るので、この順) for blk in _axis_blocks(settings, plan): - lines = _scale_lines(blk, plan) + lines = _scale_lines(blk, settings, plan) if lines: with b.step(axis_error_message(blk.label), f"{blk.label}軸の範囲"): b.add(*lines) @@ -894,22 +1052,28 @@ 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 == "bar" and len(plan.series) > 1: - step = plan.axes.x.major_step + if _positions_form(plan): + horizontal = plan.plot_type == "barh" + axis_name = "Y" if horizontal else "X" + what = "カテゴリの値" if horizontal else "X の値" + step = (plan.axes.y if horizontal else plan.axes.x).major_step if step is not None: b.add( - f"# 棒の位置に X の値を目盛として付ける(X軸の主目盛の間隔: {step}個おき)", + f"# 棒の位置に {what}を目盛として付ける({axis_name}軸の主目盛の間隔: {step}個おき)", f"tick_step = {literal(step)}", ) else: b.add( - "# 棒の位置に X の値を目盛として付ける(25個を超えるときは間引く)", + f"# 棒の位置に {what}を目盛として付ける(25個を超えるときは間引く)", "tick_step = max(1, len(positions) // 25)", ) - b.add( - "ax.set_xticks(positions[::tick_step])", - 'ax.set_xticklabels(x_labels[::tick_step], rotation=45, ha="right")', - ) + if horizontal: + b.add("ax.set_yticks(positions[::tick_step])", "ax.set_yticklabels(x_labels[::tick_step])") + else: + b.add( + "ax.set_xticks(positions[::tick_step])", + 'ax.set_xticklabels(x_labels[::tick_step], rotation=45, ha="right")', + ) size = _label_size_expr(plot.font_size) b.add("# 目盛は内向きにする", f'ax.tick_params(which="both", direction="in", labelsize={size})') @@ -917,7 +1081,7 @@ def _emit_axes(b: _Builder, settings: Settings, plan: PlotPlan) -> None: b.add(f'ax2.tick_params(which="both", direction="in", labelsize={size})') if not plot.grid_minor and not _per_axis_minor(plan): - if axes.x.scale == "log" or axes.y.scale == "log": + if _scale(settings, plan, "x") == "log" or _scale(settings, plan, "y") == "log": b.add("ax.minorticks_off() # 対数軸の補助目盛は出さない") if plan.uses_secondary and axes.y2.scale == "log": b.add("ax2.minorticks_off()") diff --git a/py/mplgui/dataprep.py b/py/mplgui/dataprep.py index 82e3dfe..fec7066 100644 --- a/py/mplgui/dataprep.py +++ b/py/mplgui/dataprep.py @@ -10,12 +10,13 @@ import re from dataclasses import dataclass, field, replace +import numpy as np import pandas as pd 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 AxisSettings, ErrorSpec, Settings, check_axis_range, validate_date_range +from .settings import BAR_LIKE_TYPES, MAX_HIST_BINS, AxisSettings, ErrorSpec, Settings, check_axis_range, validate_date_range from .settings import _DATE_EXAMPLE, _date_range_value, _to_float MAX_EXAMPLES = 3 @@ -227,7 +228,27 @@ class SeriesPlan: cap_size: float = 3.0 # エラーバーの端の線の長さ marker: str = "" # line は描く点の形("" = 点なし)、scatter は "" = 既定の丸(引数を足さない) alpha: float = 1.0 # 不透明度(1 のときはコードに書かない) - fill: FillPlan | None = None # 塗りつぶし帯(line / scatter のみ) + fill: FillPlan | None = None # 塗りつぶし帯(line / step / scatter / scatterColor のみ) + color_index: int | None = None # scatterColor の色分けの列番号 + color_label: str = "" # scatterColor の色分けの列の表示(「名前 [番号]」) + + +@dataclass(frozen=True) +class HistPlan: + """ヒストグラム(hist)。区間の端は生成コードが np.histogram_bin_edges で決める(ここでは検査と軸の範囲の見積もりだけ)。""" + + bins: int | None # None = 自動("auto") + density: bool + bin_count: int # 実際の区間の数 + max_height: float # 度数(density なら確率密度)の最大 + + +@dataclass(frozen=True) +class ColorbarPlan: + """色分け散布図(scatterColor)のカラーマップとカラーバーのラベル。""" + + colormap: str + label: str # 実際に使うラベル(設定が空なら系列1の色分けの列の表示) @dataclass(frozen=True) @@ -289,7 +310,9 @@ class PlotPlan: multi_source: bool = False # load.files が2つ以上(生成コードで DATA_FILE_N / dfN と書く) axes: AxesPlan = field(default_factory=AxesPlan) # 軸ごとの目盛の設定(効くものだけ) annotations: tuple[AnnotationPlan, ...] = () - fits: tuple[FitPlan, ...] = () # 近似曲線(line / scatter のみ) + fits: tuple[FitPlan, ...] = () # 近似曲線(line / step / scatter / scatterColor のみ) + hist: HistPlan | None = None # hist のときだけ + colorbar: ColorbarPlan | None = None # scatterColor のときだけ @property def plotted(self) -> tuple[SeriesPlan, ...]: @@ -413,9 +436,9 @@ def _marker_plan(series, plot_type: str) -> tuple[str, float]: 形を選んで点サイズが自動のときは、散布図と同じ面積 24 で描く。scatter の「自動」は引数を足さない。""" shape = series.marker - if plot_type == "scatter": + if plot_type in {"scatter", "scatterColor"}: return ("" if shape == "auto" else shape), series.effective_marker_size("scatter") - size = series.effective_marker_size("line") + size = series.effective_marker_size("line") # line と step if shape == "auto": return ("o" if size > 0 else ""), size if shape == "none": @@ -468,7 +491,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 == "bar": + if settings.plot.type in BAR_LIKE_TYPES: return [] return list(enumerate(settings.fits, start=1)) @@ -558,7 +581,10 @@ def _looks_like_date(text: str) -> bool: return True -def _plan_annotations(settings: Settings, x_kind: str, uses_secondary: bool, ext: "_Extents") -> tuple[AnnotationPlan, ...]: +def _plan_annotations( + settings: Settings, x_kind: str, uses_secondary: bool, ext: "_Extents", y_kind: str | None = None +) -> tuple[AnnotationPlan, ...]: + """y_kind は Y 軸の種類(横棒の縦軸は category / number)。None なら Y のスケール(number / log)から決める。""" out = [] y_log = {"y": settings.axes.y.scale == "log", "y2": settings.axes.y2.scale == "log"} for n, a in enumerate(settings.annotations, start=1): @@ -574,7 +600,8 @@ def xval(text: str, what: str = "X") -> float | str: return _annotation_value(text, n, what, kind=x_kind, log=False) def yval(text: str, what: str = "Y") -> float: - return _annotation_value(text, n, what, kind="log" if y_log[y_axis] else "number", log=False) # type: ignore[return-value] + kind = y_kind or ("log" if y_log[y_axis] else "number") + return _annotation_value(text, n, what, kind=kind, log=False) # type: ignore[return-value] def add_x(*values) -> None: if x_kind in {"number", "log"}: @@ -646,7 +673,7 @@ def plan_plot(data, settings: Settings) -> PlotPlan: NOT_LOADED_MESSAGE.format(n=numbers.get(sid, 1), name=names.get(sid, "")), field=f"系列{n}のデータ元" ) ids.append(sid) - if plot.type == "bar" and len(set(ids)) > 1: + if plot.type in {"bar", "barh", "barStacked"} and len(set(ids)) > 1: raise UserError(BAR_SOURCE_MESSAGE, field="データ元") order = [f.id for f in files if f.id in set(ids)] if files else list(dict.fromkeys(ids)) @@ -667,8 +694,10 @@ def plan_plot(data, settings: Settings) -> PlotPlan: for i, r in zip(idx, resolved): y_requests[i] = r dfs = [frames[sid] for sid in ids] - if plot.type in {"line", "scatter"}: + if plot.type in {"line", "step", "scatter", "scatterColor"}: plan = _plan_xy(dfs, settings, y_requests) + elif plot.type == "hist": + plan = _plan_hist(dfs, settings, y_requests) 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)) @@ -805,20 +834,49 @@ def _plan_axis( ) -def _plan_axes(settings: Settings, x_kind: str, uses_secondary: bool, ext: _Extents, categories: int) -> AxesPlan: +def _plan_axes( + settings: Settings, x_kind: str, uses_secondary: bool, ext: _Extents, categories: int, y_kind: str | None = None +) -> AxesPlan: + """y_kind は Y 軸の種類(横棒の縦軸は category / number。そのとき categories は Y 軸のカテゴリ数)。None なら Y のスケールから決める。""" axes = settings.axes - bar = settings.plot.type == "bar" + plot_type = settings.plot.type + bar = plot_type in {"bar", "barStacked", "hist"} # 縦向きの棒: Y 軸(値)の範囲に 0 を含める def num_kind(axis: AxisSettings) -> str: return "log" if axis.scale == "log" else "number" return AxesPlan( - x=_plan_axis(axes.x, x_kind, "X", ext, "x", categories=categories), - y=_plan_axis(axes.y, num_kind(axes.y), "Y", ext, "y", include_zero=bar), - y2=_plan_axis(axes.y2, num_kind(axes.y2), "第2Y", ext, "y2", include_zero=bar) if uses_secondary else None, + 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), + 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}の色分けの列" + idx = parse_column_index(requested) + if idx is None: + raise UserError(f"系列{n}の色分けの列を選んでください。", 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)だけで数える。""" + 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)}" + ) + warnings.append({"series": n, "message": message}) + return numeric + + def _plan_xy(dfs: list[pd.DataFrame], settings: Settings, y_requests: list[str]) -> PlotPlan: plot_type = settings.plot.type plans: list[SeriesPlan] = [] @@ -847,7 +905,21 @@ def _plan_xy(dfs: list[pd.DataFrame], settings: Settings, y_requests: list[str]) if y_dropped: warnings.append(dropped_warning(n, f"系列{n}({y_name})", y_dropped, y_examples, settings.load)) - has_points = bool((y_numeric.notna() & pd.notna(x_series)).any()) + point_ok = y_numeric.notna() & pd.notna(x_series) + color_index = None + color_label = "" + color_numeric = None + if plot_type == "scatterColor": + color_index = _color_column(df, series.color_column, n) + color_label = _label_for(df, color_index)[1] + if _is_datetime(df.iloc[:, color_index]): + raise UserError( + f"系列{n}の色分けの列({df.columns[color_index]})は日時の列です。色分けの列には数値の列を選んでください。", + field=f"系列{n}の色分けの列", + ) + color_numeric = _color_values(df, color_index, point_ok, n, settings.load, warnings) + point_ok = point_ok & color_numeric.notna() + has_points = bool(point_ok.any()) marker, marker_size = _marker_plan(series, plot_type) plans.append( SeriesPlan( @@ -869,10 +941,12 @@ def _plan_xy(dfs: list[pd.DataFrame], settings: Settings, y_requests: list[str]) datetime_x=datetime_x, marker=marker, alpha=series.alpha, + color_index=color_index, + color_label=color_label, ) ) if has_points: - ok = y_numeric.notna() & pd.notna(x_series) + ok = point_ok y_axis = "y2" if series.secondary_axis else "y" fill_plan = _plan_fill(df, series, n, ok, y_axis, ext, settings.load, warnings) for k, fit in fits_of[series.id]: @@ -934,7 +1008,11 @@ def _check_datetime_x(settings: Settings, plans: list[SeriesPlan]) -> None: def _plan_bar(df: pd.DataFrame, settings: Settings, y_requests: list[str]) -> PlotPlan: + """bar / barh / barStacked。barh は軸を入れ替えて描く(値は横軸 = X 軸、カテゴリは縦軸 = Y 軸)。""" plot = settings.plot + horizontal = plot.type == "barh" + stacked = plot.type == "barStacked" + val_axis, cat_axis = ("x", "y") if horizontal else ("y", "x") # 値の軸・カテゴリの軸(物理的な軸) x_req = plot.x_column.strip() if x_req: bar_x_index = resolve_column_index(df, x_req) @@ -984,21 +1062,28 @@ def _plan_bar(df: pd.DataFrame, settings: Settings, y_requests: list[str]) -> Pl if frame.empty: raise UserError(_no_data_message(warnings)) - if len(plans) == 1: + positions_form = stacked or len(plans) > 1 # 棒の位置(0, 1, 2, …)にカテゴリのラベルを付ける形 + if len(plans) == 1 and not stacked: has_points = bool((frame["y_0"].notna() & pd.notna(frame["x"])).any()) if not has_points: raise UserError(NO_DRAWABLE_DATA) bar_date_format = None if datetime_x: bar_date_format = settings.axes.x.date_format or auto_bar_date_format(x) - # 棒の位置(複数系列)か、文字列・日時の X はカテゴリの軸。数値の X・X なしの1系列は数値の軸 + # 棒の位置(複数系列・積み上げ)か、文字列・日時の X はカテゴリの軸。数値の X・X なしの1系列は数値の軸 ext = _Extents() - if len(plans) == 1: + if not positions_form: ok = frame["y_0"].notna() & frame["x"].notna() # 描く棒の行 else: ok = frame[y_keys].notna().any(axis=1) - for k in y_keys: - ext.add_values("y2" if plans[int(k[2:])].secondary else "y", frame[k][ok]) + if stacked: + values = frame[y_keys][ok].fillna(0.0) # 欠けた値は 0 として積む + positive = values.where(values > 0, 0.0).sum(axis=1) + negative = values.where(values < 0, 0.0).sum(axis=1) + ext.add(val_axis, min(float(negative.min()), 0.0), max(float(positive.max()), 0.0)) + else: + for k in y_keys: + ext.add_values(val_axis if horizontal else ("y2" if plans[int(k[2:])].secondary else "y"), frame[k][ok]) for i, series in enumerate(settings.series): spec = series.error_bars.y if spec.mode == "none": @@ -1006,19 +1091,83 @@ def _plan_bar(df: pd.DataFrame, settings: Settings, y_requests: list[str]) -> Pl k = f"y_{i}" rows = ok & frame[k].notna() # 棒を描く行(欠けた行は棒も誤差も描かない) y_err, plus, minus = _plan_error(df, spec, "y", i + 1, rows, settings.load, warnings) - _add_error_extent(ext, "y2" if plans[i].secondary else "y", frame[k][rows], _take(plus, rows), _take(minus, rows)) + axis = val_axis if horizontal else ("y2" if plans[i].secondary else "y") + _add_error_extent(ext, axis, frame[k][rows], _take(plus, rows), _take(minus, rows)) plans[i] = replace(plans[i], y_err=y_err, cap_size=series.error_bars.cap_size) x_text = datetime_x or not pd.api.types.is_numeric_dtype(x.dtype) - if len(plans) > 1 or x_text: - x_kind = "category" - categories = len(frame) if len(plans) > 1 else int(frame["x"][ok].nunique()) + if positions_form or x_text: + cat_kind = "category" + categories = len(frame) if positions_form else int(frame["x"][ok].nunique()) else: - x_kind = "log" if settings.axes.x.scale == "log" else "number" + cat_kind = "number" if horizontal else ("log" if settings.axes.x.scale == "log" else "number") categories = 0 - ext.add_values("x", frame["x"][ok]) + ext.add_values(cat_axis, frame["x"][ok]) + if horizontal: + axes_args = ("log" if settings.axes.x.scale == "log" else "number", ext, categories, cat_kind) # 縦軸はカテゴリ。Y のスケールは使わない + else: + axes_args = (cat_kind, ext, categories) return _finish( settings, plans, warnings, x_label, bar_x_index, datetime_x=datetime_x, bar_date_format=bar_date_format, - axes_args=(x_kind, ext, categories), + axes_args=axes_args, + ) + + +HIST_AUTO_BINS_MESSAGE = "区間の数が自動で{n} 個になりました({limit} 個まで)。「区間の数」を指定してください。" + + +def _plan_hist(dfs: list[pd.DataFrame], settings: Settings, y_requests: list[str]) -> PlotPlan: + """ヒストグラム。各系列の Y 列の値の分布(X 列は使わない)。区間は全系列で共通。""" + plot = settings.plot + plans: list[SeriesPlan] = [] + warnings: list[dict] = [] + values: list[pd.Series] = [] + 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() + if len(vals): + values.append(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=bool(len(vals)), + secondary=False, + alpha=series.alpha, + ) + ) + if not values: + raise UserError(_no_data_message(warnings)) + bins = plot.hist_bins + try: + edges = np.histogram_bin_edges(np.concatenate([v.to_numpy(dtype=float) for v in values]), bins=bins or "auto") + except ValueError as exc: + raise UserError( + "ヒストグラムの区間を決められませんでした(無限大の値が含まれていないか確認してください)。", field="区間の数", detail=str(exc) + ) from exc + bin_count = len(edges) - 1 + if bins is None and bin_count > MAX_HIST_BINS: + raise UserError(HIST_AUTO_BINS_MESSAGE.format(n=bin_count, limit=MAX_HIST_BINS), field="区間の数") + max_height = max(float(np.histogram(v.to_numpy(dtype=float), bins=edges, density=plot.hist_density)[0].max()) for v in values) + ext = _Extents() + ext.add("x", float(edges[0]), float(edges[-1])) + ext.add("y", 0.0, max_height) + return _finish( + settings, plans, warnings, "", None, axes_args=("log" if settings.axes.x.scale == "log" else "number", ext, 0), + hist=HistPlan(bins=bins, density=plot.hist_density, bin_count=bin_count, max_height=max_height), ) @@ -1032,20 +1181,31 @@ def _finish( datetime_x: bool = False, thin_categorical_x: bool = False, bar_date_format: str | None = None, - axes_args: tuple[str, _Extents, int] | None = None, + axes_args: tuple | None = None, # (X の軸の種類, _Extents, カテゴリ数[, Y の軸の種類(横棒の縦軸)]) fits: tuple[FitPlan, ...] = (), + hist: HistPlan | 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 = axes_args or ("number", _Extents(), 0) - annotations = _plan_annotations(settings, x_kind, uses_secondary, ext) # 範囲を ext に足すので、軸の計画より前 + x_kind, ext, categories, *rest = axes_args or ("number", _Extents(), 0) + y_kind = rest[0] if rest 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" + colorbar = None + if plot_type == "barh": # 軸ラベルの自動の値だけ入れ替える: 横軸 = 系列1のY列、縦軸 = X列 + 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": + colorbar = ColorbarPlan(settings.plot.colormap, settings.plot.colorbar_label or plans[0].color_label) return PlotPlan( skip_rows=settings.plot.skip_rows, plot_type=settings.plot.type, series=tuple(plans), x_label=x_label, - y_label=primary[0] if len(primary) == 1 else "values", + y_label=y_label, y2_label=(secondary[0] if len(secondary) == 1 else "values") if uses_secondary else None, bar_x_index=bar_x_index, plotted_count=sum(1 for p in plans if p.has_points), @@ -1054,7 +1214,9 @@ 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), + axes=_plan_axes(settings, x_kind, uses_secondary, ext, categories, y_kind), annotations=annotations, fits=fits, + hist=hist, + colorbar=colorbar, ) diff --git a/py/mplgui/runner.py b/py/mplgui/runner.py index e4db825..2ed71af 100644 --- a/py/mplgui/runner.py +++ b/py/mplgui/runner.py @@ -109,6 +109,39 @@ def _transform_kind(artist, ax) -> tuple[bool, bool]: return tuple(bool(v) for v in artist.get_transform().contains_branch_seperately(ax.transData)) +def _is_colorbar_axes(ax) -> bool: + """カラーバーの Axes か(fig.colorbar が作る Axes は `_colorbar` を持つ)。""" + return getattr(ax, "_colorbar", None) is not None + + +def _colorbar_summary(fig): + """カラーバー(あれば1本目)の {label, cmap, vmin, vmax}。無ければ None。""" + for ax in fig.axes: + cb = getattr(ax, "_colorbar", None) + if cb is not None: + return {"label": cb.ax.get_ylabel(), "cmap": cb.cmap.name, "vmin": float(cb.norm.vmin), "vmax": float(cb.norm.vmax)} + return None + + +def _bar_summary(ax) -> dict: + """棒(BarContainer)の要約: 向き別の棒の本数、容器ごとの棒の数、段になっている容器(棒の下端が 0 でないもの)の数。""" + vertical = horizontal = stacked = 0 + containers = [] + for c in ax.containers: + if type(c).__name__ != "BarContainer": + continue + horizontal_bars = getattr(c, "orientation", "vertical") == "horizontal" + patches = list(c.patches) + containers.append(len(patches)) + if horizontal_bars: + horizontal += len(patches) + stacked += any(abs(p.get_x()) > 1e-12 for p in patches) + else: + vertical += len(patches) + stacked += any(abs(p.get_y()) > 1e-12 for p in patches) + return {"vertical": vertical, "horizontal": horizontal, "containers": containers, "stacked": int(stacked)} + + def _series_lines(ax) -> list: """系列の線(エラーバー・近似曲線・注釈の線を除く)。""" return [ @@ -134,6 +167,8 @@ def _style_summary(ax) -> dict: series_lines = _series_lines(ax) scatters = [c for c in ax.collections if type(c).__name__ == "PathCollection" and not c.get_label().startswith("_")] return { + "drawstyles": [ln.get_drawstyle() for ln in series_lines], + "bars": _bar_summary(ax), "bands": sum(1 for c in ax.collections if c.get_label() == "_fill"), "markers": [str(ln.get_marker()) for ln in series_lines], "alphas": [ln.get_alpha() for ln in series_lines] + [c.get_alpha() for c in scatters], @@ -150,9 +185,20 @@ def _style_summary(ax) -> dict: def figure_summary(fig) -> list[dict]: - """Figure の中身の要約(軸ごと)。JSON にできる値だけで、E2E と生成コードの一致確認に使う。""" + """Figure の中身の要約(軸ごと)。JSON にできる値だけで、E2E と生成コードの一致確認に使う。 + + Phase 5c で足したキー(既存のキーの値は変えない): + - drawstyles: 系列の線の drawstyle("default" / "steps-pre" / "steps-mid" / "steps-post"。markers と同じ絞り込み) + - bars: {vertical, horizontal, containers, stacked}。BarContainer の棒の本数(縦向き・横向き)、容器ごとの棒の数、 + 棒の下端(横棒は左端)が 0 でない容器の数(積み上げ棒の2系列目以降)。ヒストグラムも BarContainer + - colorbar: カラーバーが無ければ null、あれば {label, cmap, vmin, vmax}。カラーバーの Axes は軸ごとの一覧に入れず、 + 元の Axes の項目として出す(色分け散布図は第2Y軸が無いので、最初の Axes に付く) + """ out = [] + colorbar = _colorbar_summary(fig) for ax in fig.axes: + if _is_colorbar_axes(ax): + continue legend = ax.get_legend() out.append( { @@ -183,6 +229,7 @@ def figure_summary(fig) -> list[dict]: "errorbars": sum(1 for line in ax.lines if line.get_label() == "_errorbar") + sum(1 for c in ax.containers if type(c).__name__ == "ErrorbarContainer"), **_style_summary(ax), + "colorbar": colorbar if not out else None, } ) return out diff --git a/py/mplgui/settings.py b/py/mplgui/settings.py index 11c6a3a..298c4c7 100644 --- a/py/mplgui/settings.py +++ b/py/mplgui/settings.py @@ -18,7 +18,14 @@ SCHEMA_VERSION = 4 -PLOT_TYPES = ("line", "scatter", "bar") +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 方向のエラーバーを使わない +STEP_WHERE_CHOICES = ("pre", "mid", "post") +COLORMAPS = ("viridis", "cividis", "plasma", "inferno", "magma", "coolwarm", "RdBu_r", "gray") +MAX_HIST_BINS = 1000 LINE_STYLES = ("solid", "dashed", "dashdot", "dotted") SCALES = ("linear", "log") SAVE_FORMATS = ("png", "jpg", "svg", "pdf") @@ -114,6 +121,7 @@ "marker": "auto", "alpha": 1, "fill": copy.deepcopy(_DEFAULT_FILL), + "colorColumn": "", } @@ -154,6 +162,10 @@ def default_settings() -> dict: "grid": {"major": False, "minor": False}, "margins": {"left": None, "right": None, "bottom": None, "top": None}, "spines": {"top": True, "right": True}, + "step": {"where": "post"}, + "hist": {"bins": None, "density": False}, + "colormap": "viridis", + "colorbarLabel": "", }, "axes": { "x": { @@ -252,6 +264,11 @@ class PlotSettings: margins: MarginSettings = field(default_factory=MarginSettings) spine_top: bool = True # 上の枠線を表示する spine_right: bool = True # 右の枠線を表示する(第2Y軸があるときは無視) + 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の色分けの列の名前) @dataclass(frozen=True) @@ -309,13 +326,14 @@ 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 のときだけ使う(必須) def effective_marker_size(self, plot_type: str) -> float: - """自動(None)は line=0 / それ以外=24。scatter で 0 以下なら 24 に補正する。""" + """自動(None)は line / step=0 / それ以外=24。scatter / scatterColor で 0 以下なら 24 に補正する。""" size = self.marker_size if size is None: - return 0.0 if plot_type == "line" else DEFAULT_SCATTER_MARKER_SIZE - if plot_type == "scatter" and size <= 0: + return 0.0 if plot_type in {"line", "step"} else DEFAULT_SCATTER_MARKER_SIZE + if plot_type in {"scatter", "scatterColor"} and size <= 0: return DEFAULT_SCATTER_MARKER_SIZE return float(size) @@ -577,12 +595,12 @@ def _parse_files(raw_files: Any) -> tuple[FileEntry, ...]: return tuple(out) -def _parse_axis(raw: dict, key: str, name: str, *, ticks: bool = True) -> AxisSettings: +def _parse_axis(raw: dict, key: str, name: str, *, ticks: bool = True, linear: bool = False) -> AxisSettings: """ticks が False のとき(使っていない第2Y軸)は、目盛の項目を検証せず既定値にする(隠れた不正な値で描画を止めないため)。""" axis = raw[key] lo = _number(axis["min"], f"{name}軸の最小値", default=None) hi = _number(axis["max"], f"{name}軸の最大値", default=None) - scale = _choice(axis["scale"], f"{name}軸スケール", SCALES) + scale = "linear" if linear else _choice(axis["scale"], f"{name}軸スケール", SCALES) # linear: スケールを隠している軸(横棒の縦軸) date_format = _date_format(axis["dateFormat"]) if key == "x" else "" base = AxisSettings(label=_string(axis["label"], f"{name}軸ラベル").strip(), scale=scale, min=lo, max=hi, date_format=date_format) if not ticks: @@ -729,10 +747,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: # 積み上げ棒・ヒストグラムはエラーバーを両方向とも隠すので、何も検証しない + return ErrorBarSettings() cap = _number(raw["capSize"], "エラーバーの端の長さ", default=3.0, minimum=0, maximum=MAX_CAP_SIZE, owner=owner) return ErrorBarSettings( - y=_parse_error_spec(raw["y"], "Y", owner), - x=ErrorSpec() if plot_type == "bar" else _parse_error_spec(raw["x"], "X", owner), # 棒グラフでは X 方向を隠すので使わない + 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 方向を隠す cap_size=cap, ) @@ -760,6 +780,16 @@ 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}色分けの列" + if value is None or (isinstance(value, str) and not value.strip()): + raise UserError(f"{owner}色分けの列を選んでください。", field=field_name) + if not isinstance(value, str) or not _COLUMN_RE.fullmatch(value.strip()): + raise UserError(f"{owner}「色分けの列」の指定が正しくありません。列を選び直してください。", field=field_name) + return value.strip() + + def _parse_series(raw_series: Any, plot_type: str = "line") -> tuple[SeriesSettings, ...]: if not isinstance(raw_series, list) or not raw_series: raise UserError("描画系列を1つ以上追加してください。", field="描画系列") @@ -780,13 +810,14 @@ def _parse_series(raw_series: Any, plot_type: str = "line") -> tuple[SeriesSetti marker = _number(s["markerSize"], "点サイズ", default=None, minimum=0, owner=owner) marker_shape = "auto" fill = FillSettings() - if plot_type != "bar": # 棒グラフでは点の形と塗りつぶし帯を隠すので、検証せず使わない + if plot_type not in BAR_LIKE_TYPES: # 棒グラフ・ヒストグラムでは点の形と塗りつぶし帯を隠すので、検証せず使わない marker_shape = _choice(s["marker"], "点の形", MARKERS, owner=owner, field_name=f"{owner}点の形") - if plot_type == "scatter" and marker_shape == "none": + 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 "" out.append( SeriesSettings( id=sid, @@ -797,12 +828,14 @@ def _parse_series(raw_series: Any, plot_type: str = "line") -> tuple[SeriesSetti line_style=_choice(s["lineStyle"], "線種", LINE_STYLES, owner=owner), marker_size=marker, label=_string(s["label"], "凡例名", owner=owner).strip(), - secondary_axis=_boolean(s["secondaryAxis"], "第2軸を使用", owner=owner), + # 横棒・積み上げ棒・ヒストグラム・色分け散布図では第2Y軸を隠す(false として扱い、検証しない) + secondary_axis=False if plot_type in NO_Y2_TYPES else _boolean(s["secondaryAxis"], "第2軸を使用", owner=owner), source=_string(s["source"], "データ元", owner=owner), error_bars=_parse_error_bars(s["errorBars"], plot_type, owner), marker=marker_shape, alpha=_number(s["alpha"], "不透明度", default=1.0, minimum=0, maximum=1, owner=owner, field_name=f"{owner}不透明度"), fill=fill, + color_column=color_column, ) ) return tuple(out) @@ -965,10 +998,23 @@ def parse_settings(raw: dict | None) -> Settings: if margins.bottom is not None and margins.top is not None and margins.bottom >= margins.top: raise UserError("余白は bottom < top になるように指定してください。", field="余白") + plot_type = _choice(p["type"], "プロット種別", PLOT_TYPES) + step_where, hist_bins, hist_density, colormap, colorbar_label = "post", None, False, "viridis", "" + if plot_type == "step": + step = p["step"] if isinstance(p["step"], dict) else {} + step_where = _choice(step.get("where", "post"), "段の付き方", STEP_WHERE_CHOICES) + elif plot_type == "hist": + 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": + colormap = _choice(p["colormap"], "カラーマップ", COLORMAPS) + colorbar_label = _string(p["colorbarLabel"], "カラーバーのラベル").strip() + plot = PlotSettings( - type=_choice(p["type"], "プロット種別", PLOT_TYPES), + type=plot_type, skip_rows=_integer(p["skipRows"], "除外する先頭行数", default=0, minimum=0), - x_column=_string(p["xColumn"], "X列").strip(), + x_column="" if plot_type == "hist" 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, @@ -980,14 +1026,23 @@ def parse_settings(raw: dict | None) -> Settings: margins=margins, spine_top=_boolean(spines.get("top", True), "上の枠線"), spine_right=_boolean(spines.get("right", True), "右の枠線"), + step_where=step_where, + hist_bins=hist_bins, + hist_density=hist_density, + colormap=colormap, + colorbar_label=colorbar_label, ) ax = merged["axes"] raw_series = raw.get("series", d["series"]) - y2_used = isinstance(raw_series, list) and any(isinstance(s, dict) and s.get("secondaryAxis") is True for s in raw_series) + y2_used = ( + plot.type not in NO_Y2_TYPES + and isinstance(raw_series, list) + and any(isinstance(s, dict) and s.get("secondaryAxis") is True for s in raw_series) + ) axes = AxesSettings( x=_parse_axis(ax, "x", "X"), - y=_parse_axis(ax, "y", "Y"), + y=_parse_axis(ax, "y", "Y", linear=plot.type == "barh"), # 横棒の縦軸はカテゴリなので、Y のスケールは使わない y2=_parse_axis(ax, "y2", "第2Y", ticks=y2_used), ) series = _parse_series(raw_series, plot.type) @@ -1001,8 +1056,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 == "bar" else _parse_fits(raw.get("fits"), {s.id for s in series}) + # 棒グラフ・ヒストグラムでは近似曲線を使わない(隠れているので検証しない) + fits = () if plot.type in BAR_LIKE_TYPES else _parse_fits(raw.get("fits"), {s.id for s in series}) save = _parse_save(merged["save"]) return Settings(version=SCHEMA_VERSION, load=load, plot=plot, axes=axes, series=series, save=save, annotations=annotations, fits=fits) diff --git a/tests/unit/test_chart_types.py b/tests/unit/test_chart_types.py new file mode 100644 index 0000000..0985bf4 --- /dev/null +++ b/tests/unit/test_chart_types.py @@ -0,0 +1,732 @@ +"""Phase 5c: グラフの種類 第1弾(G7: step / barh / barStacked / hist / scatterColor)。 + +生成コードを CPython(Agg)で実行して artist を検査し、「全体を実行した図」と「自動描画用の図」の要約の一致も確かめる。 +""" +import numpy as np +import pandas as pd +import pytest + +from mplgui.errors import UserError +from mplgui.settings import MAX_HIST_BINS, parse_settings +from style_helpers import Built, plan_of, raw_settings, series + +pytestmark = pytest.mark.unit + +CATS = ["A", "B", "C", "D", "E"] + + +def cf(): + """カテゴリ・正負と欠けた値・色の値(数値にできない値を含む)・数値の列。""" + return pd.DataFrame( + { + "cat": CATS, # 0 + "a": [3, -2, 5, np.nan, 1.0], # 1 + "b": [1, 2, -3, 4, 5.0], # 2 + "z": ["1", "2", "bad", "4", "5"], # 3: 色の値(3行目は数値にできない) + "t": [0.0, 1, 2, 3, 4], # 4 + } + ) + + +def settings_of(plot_type, **kw): + return parse_settings(raw_settings(plot_type=plot_type, **kw)) + + +def mutate_plot(**plot): + def fn(raw): + raw["plot"].update(plot) + + return fn + + +def build(tmp_path, plot_type, series_list, df=None, **plot): + def mutate(raw): + raw["plot"]["xColumn"] = plot.pop("xColumn", "__idx__0") if plot_type.startswith("bar") else "" + raw["plot"].update(plot) + + return Built(tmp_path, df=df if df is not None else cf(), series_list=series_list, plot_type=plot_type, mutate=mutate) + + +def colored(**kw): + return series(y=1, x=4, colorColumn="__idx__3", **kw) + + +def rects(ax, n=None): + """BarContainer の棒をすべて返す(容器の並び順)。""" + out = [] + for c in ax.containers: + if type(c).__name__ == "BarContainer": + out.append(list(c.patches)) + return out + + +# ---------------------------------------------------------------- 設定(settings) + + +def test_new_plot_types_accepted_and_defaults(): + for t in ("step", "barh", "barStacked", "hist"): + s = settings_of(t) + assert s.plot.type == t + d = parse_settings(raw_settings(plot_type="line")) + assert (d.plot.step_where, d.plot.hist_bins, d.plot.hist_density, d.plot.colormap, d.plot.colorbar_label) == ("post", None, False, "viridis", "") + assert d.series[0].color_column == "" + + +def test_step_hist_colormap_validated_only_for_own_type(): + bad = {"step": {"where": "zzz"}, "hist": {"bins": 0, "density": "x"}, "colormap": "nope", "colorbarLabel": 5} + for t in ("line", "scatter", "bar", "barh"): + parse_settings(raw_settings(plot_type=t, mutate=mutate_plot(**bad))) # 隠れているので、エラーにならない + with pytest.raises(UserError) as e: + parse_settings(raw_settings(plot_type="step", mutate=mutate_plot(step={"where": "zzz"}))) + assert e.value.field == "段の付き方" + with pytest.raises(UserError) as e: + parse_settings(raw_settings(plot_type="hist", mutate=mutate_plot(hist={"bins": 0, "density": False}))) + assert e.value.field == "区間の数" + with pytest.raises(UserError): + parse_settings(raw_settings(plot_type="hist", mutate=mutate_plot(hist={"bins": MAX_HIST_BINS + 1, "density": False}))) + with pytest.raises(UserError): + parse_settings(raw_settings(plot_type="hist", mutate=mutate_plot(hist={"bins": 3, "density": "yes"}))) + assert parse_settings(raw_settings(plot_type="hist", mutate=mutate_plot(hist={"bins": "12", "density": True}))).plot.hist_bins == 12 + with pytest.raises(UserError) as e: + parse_settings(raw_settings([colored()], plot_type="scatterColor", mutate=mutate_plot(colormap="nope"))) + assert e.value.field == "カラーマップ" + + +def test_color_column_required_only_for_scatter_color(): + parse_settings(raw_settings([series(colorColumn=123)], plot_type="scatter")) # 隠れている + with pytest.raises(UserError) as e: + parse_settings(raw_settings([series(), series()], plot_type="scatterColor")) + assert str(e.value) == "系列1の色分けの列を選んでください。" and e.value.field == "系列1の色分けの列" + with pytest.raises(UserError) as e: + parse_settings(raw_settings([colored(), series(colorColumn="")], plot_type="scatterColor")) + assert e.value.field == "系列2の色分けの列" + with pytest.raises(UserError) as e: + parse_settings(raw_settings([series(colorColumn="abc")], plot_type="scatterColor")) + assert e.value.field == "系列1の色分けの列" + + +def test_hidden_marker_fill_fits_error_bars_and_y2(): + bad_marker = {"marker": "zzz", "fill": {"lower": "x", "upper": ""}, "secondaryAxis": "yes", "errorBars": {"x": {"mode": "zzz"}, "y": {"mode": "zzz"}}} + fit = [{"series": "s1", "model": "zzz"}] + # バー系: 点の形・帯・X方向のエラーバー・近似曲線は隠れている + for t in ("bar", "barh", "barStacked", "hist"): + s = parse_settings(raw_settings([series(**{k: v for k, v in bad_marker.items() if k not in {"secondaryAxis", "errorBars"}})], plot_type=t, fits=fit)) + assert s.fits == () and s.series[0].marker == "auto" and not s.series[0].fill.enabled + # 第2Y軸は barh / barStacked / hist / scatterColor で隠れる + for t in ("barh", "barStacked", "hist"): + s = parse_settings(raw_settings([series(secondaryAxis="yes")], plot_type=t)) + assert s.series[0].secondary_axis is False + s = parse_settings(raw_settings([colored(secondaryAxis=True)], plot_type="scatterColor")) + assert s.series[0].secondary_axis is False + with pytest.raises(UserError): + parse_settings(raw_settings([series(secondaryAxis="yes")], plot_type="bar")) + # エラーバー: X は barh / barStacked / hist で隠れ、Y は barStacked / hist で隠れる。barh の Y は使う + bad_x = {"x": {"mode": "zzz"}} + parse_settings(raw_settings([series(errorBars=bad_x)], plot_type="barh")) + bad_y = {"y": {"mode": "zzz"}} + parse_settings(raw_settings([series(errorBars=bad_y)], plot_type="barStacked")) + parse_settings(raw_settings([series(errorBars=bad_y)], plot_type="hist")) + with pytest.raises(UserError): + parse_settings(raw_settings([series(errorBars=bad_y)], plot_type="barh")) + with pytest.raises(UserError): + parse_settings(raw_settings([series(errorBars=bad_x)], plot_type="step")) + # 点の形「なし」は scatterColor でもエラー、step では使える + with pytest.raises(UserError): + parse_settings(raw_settings([colored(marker="none")], plot_type="scatterColor")) + parse_settings(raw_settings([series(marker="none")], plot_type="step")) + + +def test_effective_marker_size_step_and_scatter_color(): + s = parse_settings(raw_settings([series()], plot_type="step")).series[0] + assert s.effective_marker_size("step") == 0.0 and s.effective_marker_size("scatterColor") == 24.0 + s2 = parse_settings(raw_settings([colored(markerSize=0)], plot_type="scatterColor")).series[0] + assert s2.effective_marker_size("scatterColor") == 24.0 + + +# ---------------------------------------------------------------- step + + +def test_step_drawstyle_and_where(tmp_path): + for where in ("pre", "mid", "post"): + bt = build(tmp_path, "step", [series(y=1, x=4)], step={"where": where}) + assert f'drawstyle="steps-{where}"' in bt.script.text + s = bt.check(lambda f: None) + assert s[0]["drawstyles"] == [f"steps-{where}"] + + +def test_step_default_post_and_line_unchanged(tmp_path): + assert "drawstyle" not in build(tmp_path, "line", [series(y=1, x=4)]).script.text + s = build(tmp_path, "step", [series(y=1, x=4)]).check(lambda f: None) + assert s[0]["drawstyles"] == ["steps-post"] and s[0]["markers"] == ["None"] + + +def test_step_band_markers_errorbars_and_y2(tmp_path): + df = cf() + df["lo"] = df["b"] - 1 + df["hi"] = df["b"] + 1 + sl = [ + series(y=2, x=4, fill={"lower": "__idx__5", "upper": "__idx__6", "alpha": 0.3}, marker="s", errorBars={"y": {"mode": "fixed", "value": 0.5}}), + series(y=1, x=4, secondaryAxis=True), + ] + bt = build(tmp_path, "step", sl, df=df, step={"where": "mid"}) + assert 'step="mid"' in bt.script.text + s = bt.check(lambda f: None) + assert s[0]["bands"] == 1 and s[0]["markers"] == ["s"] and s[0]["errorbars"] == 1 + assert len(s) == 2 and s[1]["markers"] == ["None"] + assert set(s[0]["drawstyles"]) == {"steps-mid"} + + +def test_step_fit_works(tmp_path): + bt = Built(tmp_path, df=cf(), series_list=[series(y=2, x=4)], plot_type="step", fits=[{"series": "s1"}]) + s = bt.check(lambda f: None) + assert s[0]["fitlines"] == 1 + + +# ---------------------------------------------------------------- barh + + +def test_barh_single_series(tmp_path): + bt = build(tmp_path, "barh", [series(y=1)]) + assert "ax.barh(" in bt.script.text and "ax.bar(" not in bt.script.text + + def fn(fig): + ax = fig.axes[0] + (bars,) = rects(ax) + assert [round(b.get_width(), 6) for b in bars] == [3.0, -2.0, 5.0, 1.0] # 欠けた行は描かない + assert [t.get_text() for t in ax.get_yticklabels()] == ["A", "B", "C", "E"] + assert ax.get_xlabel() == "a [1]" and ax.get_ylabel() == "cat" + + s = bt.check(fn) + assert s[0]["bars"]["horizontal"] == 4 and s[0]["bars"]["vertical"] == 0 + + +def test_barh_multi_series_offsets_vertical(tmp_path): + bt = build(tmp_path, "barh", [series(y=1), series(y=2)]) + assert "height = 0.8 / 2" in bt.script.text and "tick_step" in bt.script.text + + def fn(fig): + ax = fig.axes[0] + first, second = rects(ax) + assert len(first) == len(second) == 5 + assert all(abs(b.get_height() - 0.4) < 1e-9 for b in first) + assert first[0].get_y() < second[0].get_y() # 系列1は下、系列2は上 + assert [t.get_text() for t in ax.get_yticklabels()] == CATS + assert ax.get_xlabel() == "a [1]" and ax.get_ylabel() == "cat" + + bt.check(fn) + + +def test_barh_error_bars_use_xerr(tmp_path): + df = cf() + df["e"] = [0.5, 0.25, 1, 1, 0.1] + bt = build(tmp_path, "barh", [series(y=2, errorBars={"y": {"mode": "column", "column": "__idx__5"}})], df=df) + assert "xerr=" in bt.script.text and "yerr=" not in bt.script.text + s = bt.check(lambda f: None) + assert s[0]["errorbars"] >= 1 + bt = build(tmp_path, "barh", [series(y=1), series(y=2, errorBars={"y": {"mode": "fixed", "value": 1}})]) + assert "xerr=1" in bt.script.text + bt.check(lambda f: None) + + +def test_barh_axis_settings_are_physical(tmp_path): + def mutate(raw): + raw["plot"]["xColumn"] = "__idx__0" + raw["axes"]["x"]["label"] = "値" + raw["axes"]["y"]["label"] = "品目" + raw["axes"]["y"]["scale"] = "log" # 縦軸(カテゴリ)のスケールは使わない + raw["axes"]["x"]["min"] = -5 + raw["axes"]["x"]["max"] = 10 + + bt = Built(tmp_path, df=cf(), series_list=[series(y=1), series(y=2)], plot_type="barh", mutate=mutate) + assert "set_yscale" not in bt.script.text + + def fn(fig): + ax = fig.axes[0] + assert ax.get_xlabel() == "値" and ax.get_ylabel() == "品目" + assert ax.get_xlim() == (-5, 10) and ax.get_yscale() == "linear" + + bt.check(fn) + + +def test_barh_major_step_on_category_axis(tmp_path): + def mutate(raw): + raw["plot"]["xColumn"] = "__idx__0" + raw["axes"]["y"]["majorStep"] = 2 + + # 1系列(文字列のカテゴリ): Y 軸に MultipleLocator + bt = Built(tmp_path, df=cf(), series_list=[series(y=2)], plot_type="barh", mutate=mutate) + s = bt.check(lambda f: None) + assert s[0]["ymajor"] == "MultipleLocator" and "ticker.MultipleLocator(2)" in bt.script.text + # 複数系列: tick_step で間引く + bt = Built(tmp_path, df=cf(), series_list=[series(y=1), series(y=2)], plot_type="barh", mutate=mutate) + assert "tick_step = 2" in bt.script.text and "set_yticks(positions[::tick_step])" in bt.script.text + s = bt.check(lambda f: None) + assert s[0]["yticklabels"] == ["A", "C", "E"] + # 主目盛が多すぎるときのエラーは Y 軸 + def many(raw): + raw["plot"]["xColumn"] = "__idx__0" + raw["axes"]["y"]["majorStep"] = 1 + + big = pd.DataFrame({"cat": [f"c{i}" for i in range(400)], "v": range(400)}) + with pytest.raises(UserError) as e: + plan_of(df=big, series_list=[series(y=1), series(y=1)], plot_type="barh", mutate=many) + assert e.value.field == "Y軸の主目盛の間隔" + + +def test_barh_numeric_x_single_series_is_numeric_axis(tmp_path): + def mutate(raw): + raw["plot"]["xColumn"] = "__idx__4" + + bt = Built(tmp_path, df=cf(), series_list=[series(y=2)], plot_type="barh", mutate=mutate) + s = bt.check(lambda f: None) + assert s[0]["ylabel"] == "t" and s[0]["bars"]["horizontal"] == 5 + assert bt.plan.axes.y.kind == "number" + + +def test_barh_annotations_y_is_category_index(tmp_path): + ann = [ + {"kind": "hline", "y": "1.5"}, + {"kind": "vline", "x": "2"}, + {"kind": "text", "x": "2", "y": "3", "text": "メモ"}, + ] + bt = Built( + tmp_path, df=cf(), series_list=[series(y=1), series(y=2)], plot_type="barh", annotations=ann, + mutate=lambda raw: raw["plot"].update(xColumn="__idx__0"), + ) + assert [a.kind for a in bt.plan.annotations] == ["hline", "vline", "text"] + s = bt.check(lambda f: None) + assert s[0]["annotations"] == {"texts": 1, "hlines": 1, "vlines": 1, "hspans": 0, "vspans": 0} + with pytest.raises(UserError) as e: + plan_of(df=cf(), series_list=[series(y=1), series(y=2)], plot_type="barh", annotations=[{"kind": "hline", "y": "abc"}], mutate=lambda raw: raw["plot"].update(xColumn="__idx__0")) + assert e.value.field == "注釈1のY" and "カテゴリ" in str(e.value) + + +def test_barh_source_must_be_shared_and_x_axis_log_is_value_axis(tmp_path): + def mutate(raw): + raw["plot"]["xColumn"] = "__idx__0" + raw["axes"]["x"]["scale"] = "log" + + bt = Built(tmp_path, df=cf().assign(a=lambda d: d["a"].abs() + 1), series_list=[series(y=1)], plot_type="barh", mutate=mutate) + assert bt.check(lambda f: None)[0]["xscale"] == "log" + + +# ---------------------------------------------------------------- barStacked + + +def test_stacked_positive_negative_and_missing_as_zero(tmp_path): + bt = build(tmp_path, "barStacked", [series(y=1), series(y=2)]) + assert "stack_pos" in bt.script.text and "stack_neg" in bt.script.text + + def fn(fig): + ax = fig.axes[0] + first, second = rects(ax) + assert [b.get_y() for b in first] == [0, 0, 0, 0, 0] + assert [b.get_height() for b in first] == [3, -2, 5, 0, 1] # 欠けた値は 0 + # 正と負は別に積む: 行0 は 3 の上、行1 は系列1が負なので系列2(正)は 0 から、行2 は系列2が負なので 0 から下へ + assert [b.get_y() for b in second] == [3, 0, 0, 0, 1] + assert [b.get_height() for b in second] == [1, 2, -3, 4, 5] + assert [b.get_x() + b.get_width() / 2 for b in first] == [0, 1, 2, 3, 4] + assert [t.get_text() for t in ax.get_xticklabels()] == CATS + + s = bt.check(fn) + assert s[0]["bars"]["stacked"] == 1 and s[0]["bars"]["vertical"] == 10 + + +def test_stacked_negative_stack_depth(tmp_path): + df = pd.DataFrame({"cat": ["A", "B"], "p": [2.0, -1.0], "q": [-3.0, -2.0], "r": [4.0, 1.0]}) + bt = build(tmp_path, "barStacked", [series(y=1), series(y=2), series(y=3)], df=df) + + def fn(fig): + p, q, r = rects(fig.axes[0]) + assert [b.get_y() for b in q] == [0, -1] # 負の値は、負の段の下へ + assert [(b.get_y(), b.get_height()) for b in r] == [(2, 4), (0, 1)] + assert fig.axes[0].get_ylim()[0] <= -3 and fig.axes[0].get_ylim()[1] >= 6 # 積んだ合計が入る + + bt.check(fn) + ext = bt.plan.axes.y + assert ext.kind == "number" + + +def test_stacked_single_series_uses_positions_and_drops_all_missing_rows(tmp_path): + df = cf() + df.loc[3, ["a", "b"]] = np.nan + bt = build(tmp_path, "barStacked", [series(y=1)], df=df) + assert "positions" in bt.script.text and "bottom=" in bt.script.text + + def fn(fig): + (bars,) = rects(fig.axes[0]) + assert [round(b.get_height(), 6) for b in bars] == [3, -2, 5, 1] # Y が欠けた行は描かない + + bt.check(fn) + both = build(tmp_path, "barStacked", [series(y=1), series(y=2)], df=df) + + def fn2(fig): + assert [t.get_text() for t in fig.axes[0].get_xticklabels()] == ["A", "B", "C", "E"] # 全系列が欠けた行は描かない + + both.check(fn2) + + +def test_stacked_hides_error_bars_and_y2_and_requires_one_source(tmp_path): + s = parse_settings(raw_settings([series(errorBars={"y": {"mode": "fixed", "value": 1}}, secondaryAxis=True)], plot_type="barStacked")) + assert s.series[0].error_bars.y.mode == "none" and not s.series[0].secondary_axis + bt = build(tmp_path, "barStacked", [series(y=1, errorBars={"y": {"mode": "fixed", "value": 1}})]) + assert "yerr" not in bt.script.text + assert bt.plan.series[0].y_err is None + + +def test_stacked_tick_step(tmp_path): + def mutate(raw): + raw["plot"]["xColumn"] = "__idx__0" + raw["axes"]["x"]["majorStep"] = 2 + + bt = Built(tmp_path, df=cf(), series_list=[series(y=1), series(y=2)], plot_type="barStacked", mutate=mutate) + assert "tick_step = 2" in bt.script.text + assert bt.check(lambda f: None)[0]["xticklabels"] == ["A", "C", "E"] + + +# ---------------------------------------------------------------- hist + + +def hist_frame(n=200, seed=0): + rng = np.random.default_rng(seed) + return pd.DataFrame({"a": rng.normal(0, 1, n), "b": rng.normal(3, 2, n), "c": ["x"] * n}) + + +def test_hist_shared_bins_and_side_by_side(tmp_path): + df = hist_frame() + bt = Built(tmp_path, df=df, series_list=[series(y=0), series(y=1)], plot_type="hist", mutate=mutate_plot(hist={"bins": 8, "density": False})) + assert "np.histogram_bin_edges(np.concatenate([hist_1, hist_2]), bins=8)" in bt.script.text + assert 'hist_1 = pd.to_numeric(df.iloc[:, 0], errors="coerce").dropna()' in bt.script.text + edges = np.histogram_bin_edges(np.concatenate([df["a"], df["b"]]), bins=8) + + def fn(fig): + ax = fig.axes[0] + first, second = rects(ax) + assert len(first) == len(second) == 8 + counts = [sum(b.get_height() for b in c) for c in (first, second)] + assert counts == [200, 200] + width = edges[1] - edges[0] + assert all(abs(b.get_width() - 0.8 * width / 2) < 1e-9 for b in first) # 区間ごとに系列を横に並べる(幅は区間の 0.8 を系列数で割る) + assert second[0].get_x() > first[0].get_x() + assert ax.get_xlabel() == "a [0]" and ax.get_ylabel() == "度数" + + s = bt.check(fn) + assert s[0]["bars"]["containers"] == [8, 8] and bt.plan.hist.bin_count == 8 + + +def test_hist_auto_bins_single_series_and_density(tmp_path): + df = hist_frame() + bt = Built(tmp_path, df=df, series_list=[series(y=0)], plot_type="hist", mutate=mutate_plot(hist={"bins": None, "density": True})) + assert 'bins="auto"' in bt.script.text and "plt.setp" not in bt.script.text + assert "np.concatenate" not in bt.script.text + + def fn(fig): + ax = fig.axes[0] + (bars,) = rects(ax) + area = sum(b.get_height() * b.get_width() for b in bars) + assert abs(area - 1) < 1e-9 + assert ax.get_ylabel() == "確率密度" + + s = bt.check(fn) + assert s[0]["bars"]["containers"] == [len(np.histogram_bin_edges(df["a"], "auto")) - 1] + + +def test_hist_ignores_x_column_and_allows_different_sources(tmp_path): + df = hist_frame() + bt = Built(tmp_path, df=df, series_list=[series(y=0, x="__idx__99")], plot_type="hist") # X は隠れている(範囲外でもエラーにならない) + bt.check(lambda f: None) + # 長さの違う別のデータ元(行の対応は要らない) + from mplgui.dataprep import plan_plot + from mplgui.loader import load_file + + a = load_file(df[["a"]].to_csv(index=False).encode(), "a.csv", "", True).df + b = load_file(df[["b"]].head(50).to_csv(index=False).encode(), "b.csv", "", True).df + raw = raw_settings([series(y=0), series(y=0, source="d2")], plot_type="hist") + raw["load"]["files"] = [{"id": "d1", "name": "a.csv", "sheet": ""}, {"id": "d2", "name": "b.csv", "sheet": ""}] + plan = plan_plot({"d1": a, "d2": b}, parse_settings(raw)) + assert [s.data_var for s in plan.series] == ["df1", "df2"] + + +def test_hist_per_series_alpha_and_style(tmp_path): + bt = Built( + tmp_path, df=hist_frame(), series_list=[series(y=0, alpha=0.5, lineWidth=3), series(y=1)], plot_type="hist", + mutate=mutate_plot(hist={"bins": 5, "density": False}), + ) + assert bt.script.text.count("plt.setp(") == 2 and "alpha=0.5" in bt.script.text + + def fn(fig): + first, second = rects(fig.axes[0]) + assert first[0].get_alpha() == 0.5 and second[0].get_alpha() is None + assert first[0].get_linewidth() == 3 + + bt.check(fn) + + +def test_hist_auto_bins_over_limit_is_error(): + from mplgui.dataprep import plan_plot + + df = pd.DataFrame({"v": np.random.default_rng(1).lognormal(0, 3, 400000)}) # 裾が重く、自動の区間が 1000 を超える + with pytest.raises(UserError) as e: + plan_plot(df, parse_settings(raw_settings([series(y=0)], plot_type="hist"))) + assert e.value.field == "区間の数" and "1000 個まで" in str(e.value) and "1265 個" in str(e.value) and "指定してください" in str(e.value) + plan = plan_plot(df, parse_settings(raw_settings([series(y=0)], plot_type="hist", mutate=mutate_plot(hist={"bins": 50, "density": False})))) + assert plan.hist.bin_count == 50 + + +def test_hist_no_values_and_non_numeric_warning(tmp_path): + with pytest.raises(UserError) as e: + plan_of(df=hist_frame(), series_list=[series(y=2)], plot_type="hist") + assert "数値" in str(e.value) + df = hist_frame() + df["d"] = ["1", "2", "oops"] + ["3"] * 197 + plan = plan_of(df=df, series_list=[series(y=3), series(y=2)], plot_type="hist") + assert any("oops" in w["message"] and w["series"] == 1 for w in plan.warnings) + assert plan.series[1].has_points is False and plan.plotted_count == 1 + + +def test_hist_series_without_values_is_skipped_in_code(tmp_path): + df = hist_frame() + df["e"] = [None] * len(df) + bt = Built(tmp_path, df=df, series_list=[series(y=0), series(y=3)], plot_type="hist", mutate=mutate_plot(hist={"bins": 4, "density": False})) + assert "この系列は描かない" in bt.script.text and "plt.setp" not in bt.script.text + bt.check(lambda f: None) + + +def test_hist_extents_feed_tick_estimate(): + # Y の主目盛の本数の見積もりに、0 から最大の度数が使われる + with pytest.raises(UserError) as e: + plan_of(df=hist_frame(), series_list=[series(y=0)], plot_type="hist", mutate=lambda raw: raw["axes"]["y"].update(majorStep=0.01)) + assert e.value.field == "Y軸の主目盛の間隔" + plan = plan_of(df=hist_frame(), series_list=[series(y=0)], plot_type="hist", mutate=lambda raw: raw["axes"]["y"].update(majorStep=5)) + assert plan.hist.max_height > 0 and plan.axes.y.major_step == 5 + + +# ---------------------------------------------------------------- scatterColor + + +def test_scatter_color_range_shared_across_series_and_colorbar(tmp_path): + df = cf() + df["z2"] = [10.0, 20, 30, 40, 50] + sl = [colored(), series(y=2, x=4, colorColumn="__idx__5")] + bt = Built(tmp_path, df=df, series_list=sl, plot_type="scatterColor", mutate=mutate_plot(colormap="plasma", colorbarLabel="温度 (℃)")) + assert "color_norm" in bt.script.text and "plt.Normalize()" in bt.script.text + # データ由来の数値をリテラルにしない + for token in ("50", "10.0"): + assert f"vmax={token}" not in bt.script.text and f"vmin={token}" not in bt.script.text + + def fn(fig): + ax = fig.axes[0] + scatters = [c for c in ax.collections if c.get_label() == "_color"] + assert len(scatters) == 2 + assert all(c.get_cmap().name == "plasma" for c in scatters) + # 描いた点(X・Y・色がそろった点)の色の最小〜最大: 系列1は 3 行目(bad)と4行目(Y が欠け)を除く → {1,2,5}、系列2は 10..50 + assert scatters[0].get_clim() == (1.0, 50.0) and scatters[1].get_clim() == (1.0, 50.0) + assert sorted(scatters[0].get_array().tolist()) == [1.0, 2.0, 5.0] + + s = bt.check(fn) + assert s[0]["colorbar"] == {"label": "温度 (℃)", "cmap": "plasma", "vmin": 1.0, "vmax": 50.0} + assert len(s) == 1 # カラーバーの Axes は一覧に入れない + assert bt.plan.colorbar.label == "温度 (℃)" + + +def test_scatter_color_default_label_is_first_series_color_column(tmp_path): + bt = Built(tmp_path, df=cf(), series_list=[colored()], plot_type="scatterColor") + s = bt.check(lambda f: None) + assert s[0]["colorbar"]["label"] == "z [3]" and s[0]["colorbar"]["cmap"] == "viridis" + + +def test_scatter_color_range_excludes_undrawn_points(tmp_path): + df = cf() + df["z"] = [1, 2, 3, 100, 5] + df.loc[3, "a"] = np.nan # 値 100 の行は Y が欠けているので描かない + bt = Built(tmp_path, df=df, series_list=[colored()], plot_type="scatterColor") + s = bt.check(lambda f: None) + assert (s[0]["colorbar"]["vmin"], s[0]["colorbar"]["vmax"]) == (1.0, 5.0) + + +def test_scatter_color_legend_markers_are_gray_and_legend_rule_unchanged(tmp_path): + bt = Built(tmp_path, df=cf(), series_list=[colored(label="温度"), colored(label="")], plot_type="scatterColor", mutate=mutate_plot(legend={"location": "best"})) + + def fn(fig): + legend = fig.axes[0].get_legend() + assert [t.get_text() for t in legend.get_texts()] == ["温度", "a [1]"] + for handle in legend.legend_handles: + assert tuple(handle.get_facecolor()[0][:3]) == pytest.approx((0.5019607843137255, 0.5019607843137255, 0.5019607843137255)) + + bt.check(fn) + # 凡例の位置が「なし」なら出さない(scatter と同じ) + none = Built(tmp_path, df=cf(), series_list=[colored(label="温度")], plot_type="scatterColor", mutate=mutate_plot(legend={"location": "none"})) + none.check(lambda f: None) + with none.full() as run: + assert run.fig.axes[0].get_legend() is None + + +def test_scatter_color_marker_shape_and_alpha_in_legend(tmp_path): + bt = Built(tmp_path, df=cf(), series_list=[colored(marker="^", alpha=0.5)], plot_type="scatterColor") + assert 'marker="^"' in bt.script.text + s = bt.check(lambda f: None) + assert s[0]["alphas"] == [0.5] + + +def test_scatter_color_warns_once_per_series_with_examples_and_hints(tmp_path): + df = cf() + df["z"] = ["1", "2", "bad", "1,5", "5"] + df.loc[1, "z"] = None # 空欄は警告しない + plan = plan_of(df=df, series_list=[series(y=2, x=4, colorColumn="__idx__3"), series(y=2, x=4, colorColumn="__idx__3")], plot_type="scatterColor") + msgs = [w for w in plan.warnings if "色分け" in w["message"]] + assert [w["series"] for w in msgs] == [1, 2] + assert 'z' in msgs[0]["message"] and '"bad"' in msgs[0]["message"] and "その点は描きません" in msgs[0]["message"] + assert "小数点" in msgs[0]["message"] + assert "2件" in msgs[0]["message"] # bad と 1,5 だけ(空欄は数えない) + + +def test_scatter_color_errors(tmp_path): + df = cf() + df["d"] = pd.date_range("2026-01-01", periods=5).strftime("%Y-%m-%d") + with pytest.raises(UserError) as e: + plan_of(df=df, series_list=[series(y=1, x=4, colorColumn="__idx__5")], plot_type="scatterColor") + assert e.value.field == "系列1の色分けの列" and "日時" in str(e.value) + with pytest.raises(UserError) as e: + plan_of(df=df, series_list=[series(y=1, x=4, colorColumn="__idx__99")], plot_type="scatterColor") + assert e.value.field == "系列1の色分けの列" + all_bad = cf() + all_bad["z"] = ["x"] * 5 + with pytest.raises(UserError): + plan_of(df=all_bad, series_list=[colored()], plot_type="scatterColor") + + +def test_scatter_color_bands_errorbars_fits_use_drawn_points(tmp_path): + df = cf() + df["lo"] = df["b"] - 1 + df["hi"] = df["b"] + 1 + df["t"] = [0.0, 1, 2, 3, 5] + sl = [series(y=2, x=4, colorColumn="__idx__3", fill={"lower": "__idx__5", "upper": "__idx__6", "alpha": 0.2}, errorBars={"y": {"mode": "fixed", "value": 0.3}})] + bt = Built(tmp_path, df=df, series_list=sl, plot_type="scatterColor", fits=[{"series": "s1"}]) + s = bt.check(lambda f: None) + assert s[0]["bands"] == 1 and s[0]["errorbars"] == 1 and s[0]["fitlines"] == 1 + + +def test_scatter_color_datetime_x(tmp_path): + df = cf() + df["d"] = pd.date_range("2026-01-01", periods=5).strftime("%Y-%m-%d") + bt = Built(tmp_path, df=df, series_list=[series(y=1, x=5, colorColumn="__idx__4")], plot_type="scatterColor") + assert "mdates" in bt.script.text + bt.check(lambda f: None) + + +# ---------------------------------------------------------------- 全体と自動描画の一致・ステップ・注入 + + +@pytest.mark.parametrize("plot_type", ["step", "barh", "barStacked", "hist", "scatterColor", "bar", "scatter", "line"]) +def test_full_and_auto_summaries_match(tmp_path, plot_type): + sl = [colored(), series(y=2, x=4, colorColumn="__idx__3")] if plot_type == "scatterColor" else [series(y=1, x=4), series(y=2, x=4)] + if plot_type == "hist": + sl = [series(y=1), series(y=2)] + bt = build(tmp_path, plot_type, sl) + bt.check(lambda f: None) + + +def test_steps_registered_with_japanese_messages(tmp_path): + bt = build(tmp_path, "scatterColor", [colored()]) + messages = [s.message for s in bt.script.steps] + assert any("カラーバー" in m for m in messages) + fields = [s.field for s in bt.script.steps] + assert "系列1の色分けの列" in fields and "カラーマップ" in fields + assert build(tmp_path, "hist", [series(y=1)]).script.steps + + +def test_injection_in_column_names_labels(tmp_path): + import ast + + evil = '"); import os; os.system("echo hi") #' + df = pd.DataFrame({'c"\'\n' + evil: ["a", "b", "c"], "v" + evil: [1.0, 2, 3], "z" + evil: [1.0, 2, 3], "t": [0.0, 1, 2]}) + label = "'''\n" + evil + for plot_type in ("barh", "barStacked", "hist", "scatterColor", "step"): + sl = [series(y=1, x=3, label=label, colorColumn="__idx__2")] + bt = build(tmp_path, plot_type, sl, df=df, colorbarLabel=label) + calls = [n for n in ast.walk(ast.parse(bt.script.text)) if isinstance(n, ast.Call) and getattr(n.func, "attr", "") == "system"] + assert not calls # 注入された文字列は、文字列のリテラルの中にだけ現れる + with bt.full() as run: + assert run.fig is not None + assert "echo hi" not in run.output + + +def test_colormap_injection_is_rejected_by_validation(): + with pytest.raises(UserError): + parse_settings(raw_settings([colored()], plot_type="scatterColor", mutate=mutate_plot(colormap='viridis"); import os #'))) + + +# ---------------------------------------------------------------- 追加の確認(隠れた設定・scatterColor の端の場合) + + +def test_barh_hides_y_scale(tmp_path): + def mutate(raw): + raw["plot"]["xColumn"] = "__idx__0" + y = raw["axes"]["y"] + y.update(scale="log", min=-1, max=10, minorTicks="on", minorDivisions=3, majorStep=2) + + bt = Built(tmp_path, df=cf(), series_list=[series(y=1), series(y=2)], plot_type="barh", mutate=mutate) + assert "set_yscale" not in bt.script.text and "set_ylim(bottom=-1.0, top=10.0)" in bt.script.text + s = bt.check(lambda f: None) + assert s[0]["yscale"] == "linear" + # 不正なスケールの値も検証しない。バー(縦)では今までどおり検証する + raw = raw_settings([series(y=1)], plot_type="barh", mutate=lambda r: r["axes"]["y"].update(scale="zzz")) + assert parse_settings(raw).axes.y.scale == "linear" + with pytest.raises(UserError): + parse_settings(raw_settings([series(y=1)], plot_type="bar", mutate=lambda r: r["axes"]["y"].update(scale="zzz"))) + with pytest.raises(UserError): + parse_settings(raw_settings([series(y=1)], plot_type="bar", mutate=lambda r: r["axes"]["y"].update(scale="log", min=-1))) + + +def test_stacked_and_hist_do_not_validate_error_bars_at_all(): + bad = {"capSize": 999, "y": {"mode": "zzz"}, "x": {"mode": "zzz"}} + for t in ("barStacked", "hist"): + s = parse_settings(raw_settings([series(errorBars=bad)], plot_type=t)).series[0] + assert s.error_bars.y.mode == "none" and s.error_bars.x.mode == "none" and s.error_bars.cap_size == 3.0 + with pytest.raises(UserError): + parse_settings(raw_settings([series(errorBars={"capSize": 999})], plot_type="barh")) + + +def test_hist_does_not_resolve_or_validate_x_columns(tmp_path): + bt = Built( + tmp_path, df=hist_frame(), series_list=[series(y=0, x="__idx__99")], plot_type="hist", + mutate=lambda raw: raw["plot"].update(xColumn="__idx__99"), + ) + bt.check(lambda f: None) + assert parse_settings(raw_settings([series(y=0)], plot_type="hist", mutate=lambda raw: raw["plot"].update(xColumn=5))).plot.x_column == "" + # line / step などでは今までどおり X列を解決する + with pytest.raises(UserError): + plan_of(df=hist_frame(), series_list=[series(y=0, x="__idx__99")], plot_type="step") + + +def test_scatter_color_all_equal_colors_no_warning(tmp_path): + import warnings + + df = cf() + df["z"] = [7.0] * 5 + bt = Built(tmp_path, df=df, series_list=[colored()], plot_type="scatterColor") + with warnings.catch_warnings(): + warnings.simplefilter("error") + warnings.filterwarnings("ignore", message=".*missing from.*") + warnings.filterwarnings("ignore", message=".*non-interactive.*") + s = bt.check(lambda f: None) + with bt.full() as run: + run.fig.canvas.draw() + assert s[0]["colorbar"]["vmin"] <= 7.0 <= s[0]["colorbar"]["vmax"] # 範囲が1点のときは matplotlib が少し広げる + + +def test_scatter_color_series_without_points_is_skipped_everywhere(tmp_path): + df = cf() + df["w"] = ["x"] * 5 # 全部数値にできない色の値 + sl = [colored(label="描く"), series(y=2, x=4, colorColumn="__idx__5", label="描かない")] + bt = Built(tmp_path, df=df, series_list=sl, plot_type="scatterColor") + assert "この系列は描かない" in bt.script.text + + def fn(fig): + ax = fig.axes[0] + assert len([c for c in ax.collections if c.get_label() == "_color"]) == 1 + assert [t.get_text() for t in ax.get_legend().get_texts()] == ["描く"] + + s = bt.check(fn) + assert s[0]["colorbar"]["vmin"] == 1.0 + assert bt.script.text.count("ax.scatter([]") == 1 diff --git a/tests/unit/test_settings.py b/tests/unit/test_settings.py index 5f4cb4c..9725ee0 100644 --- a/tests/unit/test_settings.py +++ b/tests/unit/test_settings.py @@ -864,3 +864,30 @@ def test_annotation_and_fit_lists_must_be_lists(): def test_annotation_ids_are_made_unique(): s = parse_settings({"annotations": [{"id": "a1", "y": 1}, {"id": "a1", "y": 2}, {"y": 3}]}) assert len({a.id for a in s.annotations}) == 3 + + +# ---------------------------------------------------------------- Phase 5c: グラフの種類(G7)の項目 + + +def test_5c_plot_defaults(): + d = default_settings() + assert d["plot"]["step"] == {"where": "post"} + assert d["plot"]["hist"] == {"bins": None, "density": False} + assert (d["plot"]["colormap"], d["plot"]["colorbarLabel"]) == ("viridis", "") + assert d["series"][0]["colorColumn"] == "" + + +def test_5c_new_types_and_hidden_settings(): + for t in ("step", "barh", "barStacked", "hist"): + raw = default_settings() + raw["plot"]["type"] = t + assert parse_settings(raw).plot.type == t + raw = default_settings() + raw["plot"]["type"] = "line" + raw["plot"].update(step={"where": "x"}, hist={"bins": -1}, colormap="zzz") # 隠れているので検証しない + s = parse_settings(raw).plot + assert (s.step_where, s.hist_bins, s.colormap) == ("post", None, "viridis") + raw["plot"]["type"] = "scatterColor" + with pytest.raises(UserError) as e: + parse_settings(raw) + assert e.value.field == "カラーマップ" From e7a22923cc0a59f21cdf69668852ef98c779f796 Mon Sep 17 00:00:00 2001 From: mioupa <79833278+mioupa@users.noreply.github.com> Date: Thu, 12 Nov 2026 09:11:46 +0900 Subject: [PATCH 04/10] Add computed columns to settings, the plot plan and generated code (Phase 5c, G6) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Each source's computed columns are appended after its file columns, after skipRows, and are written as a 「計算した列」 section only when present. Auto-render injects a copy of a source that gets computed columns. Co-Authored-By: Claude Opus 5.5 --- js/defaults.js | 4 + py/mplgui/api.py | 8 +- py/mplgui/codegen.py | 34 ++ py/mplgui/dataprep.py | 100 ++++- py/mplgui/settings.py | 64 ++- tests/unit/test_computed.py | 611 +++++++++++++++++++++++++++++ tests/unit/test_defaults_parity.py | 9 +- tests/unit/test_settings.py | 2 +- 8 files changed, 823 insertions(+), 9 deletions(-) create mode 100644 tests/unit/test_computed.py diff --git a/js/defaults.js b/js/defaults.js index 6b3548f..b1799df 100644 --- a/js/defaults.js +++ b/js/defaults.js @@ -64,6 +64,9 @@ 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" }; +// 計算した列(computed[])1つの既定値。id は追加するときに c1, c2, ... を振る(削除しても再利用しない) +export const DEFAULT_COMPUTED = { id: "", source: "", name: "", expr: "" }; + export const DEFAULT_SETTINGS = { version: SCHEMA_VERSION, load: { @@ -102,5 +105,6 @@ export const DEFAULT_SETTINGS = { series: [DEFAULT_SERIES], annotations: [], fits: [], + computed: [], save: { filename: "", format: "png", transparent: false, dpi: 300, svgText: "path" }, }; diff --git a/py/mplgui/api.py b/py/mplgui/api.py index 91c62c0..1a573ff 100644 --- a/py/mplgui/api.py +++ b/py/mplgui/api.py @@ -252,10 +252,16 @@ def _run(settings: Settings | None, code: str | None, *, file_format: str, trans 編集モード(code が文字列): そのスクリプトを、アップロードしたファイルのある作業フォルダで実行する。設定は使わない。""" if code is None: plan, script = _generate(settings) + # 計算した列は生成コードが df.insert で足すので、そのデータ元はコピーを渡す(描画のたびに列が増えるのを防ぐ) + with_computed = {c.data_id for c in plan.computed} + injected = { + src.var: SESSION.sources[src.id].df.copy() if src.id in with_computed else SESSION.sources[src.id].df + for src in plan.sources + } try: result = run_to_image( script.auto_render_text(), file_format=file_format, transparent=transparent, dpi=dpi, svg_text=svg_text, - injected={src.var: SESSION.sources[src.id].df for src in plan.sources}, + injected=injected, ) except ScriptError as err: raise _step_error(script, err) from err diff --git a/py/mplgui/codegen.py b/py/mplgui/codegen.py index aa27620..da33f10 100644 --- a/py/mplgui/codegen.py +++ b/py/mplgui/codegen.py @@ -13,6 +13,7 @@ from dataclasses import dataclass from typing import Callable +from . import expr as expr_module from .dataprep import AnnotationPlan, AxisPlan, ErrorPlan, FitPlan, PlotPlan, SeriesPlan from .fonts import LATIN_FONTS, SANS_SERIF_PRIORITY from .formats import FORMATS, build_filename, savefig_kwargs, savefig_rc @@ -315,6 +316,37 @@ def _emit_skip_rows(b: _Builder, plan: PlotPlan) -> None: b.add("# 先頭の行は除外しない(全ての行を使う)") +def _emit_computed(b: _Builder, plan: PlotPlan) -> None: + """「計算した列」の節(計算した列があるときだけ)。式と名前はコメントにだけ comment_text() を通して写し、 + コードには式の木から決まった形で書く(名前は literal())。""" + b.section("計算した列") + b.add( + 'with np.errstate(divide="ignore", invalid="ignore", over="ignore"):' + " # 0 での割り算などは警告を出さず、下で NaN にする" + ) + for i, c in enumerate(plan.computed): + if i > 0: + b.add("") + v = c.data_var + where = f"データ{next(s.number for s in plan.sources if s.id == c.data_id)}の" if plan.multi_source else "" + message = f"計算した列{c.number}({c.name})を計算できませんでした。式を確認してください。" + with b.step(message, f"計算した列{c.number}の式"): + b.add( + f" # 計算した列{c.number}: {comment_text(c.name)}(式: {comment_text(c.expr)})→ {where}列 [{c.index}]" + ) + for k, label in c.refs: + b.add(f" col{k} = pd.to_numeric({v}.iloc[:, {k}], errors=\"coerce\").astype(float) # {comment_text(label)}") + code = expr_module.to_code(c.node, lambda k: f"col{k}", lambda x: literal(float(x))) + if expr_module.is_series(c.node): + b.add(f" calc = {code}") + else: + b.add(f" calc = pd.Series({code}, index={v}.index, dtype=float)") + b.add( + f" {v}.insert({v}.shape[1], {literal(c.name)}, " + "calc.replace([np.inf, -np.inf], np.nan), allow_duplicates=True)" + ) + + def _emit_figure(b: _Builder, settings: Settings) -> None: b.section("図と軸") fig = settings.plot.figure @@ -1195,6 +1227,8 @@ def generate_script(settings: Settings, source, plan: PlotPlan) -> GeneratedScri b.add(*POLY_TEXT_FUNCTION) _emit_load(b, plan, infos) _emit_skip_rows(b, plan) + if plan.computed: + _emit_computed(b, plan) _emit_figure(b, settings) _emit_series(b, settings, plan) if plan.annotations: diff --git a/py/mplgui/dataprep.py b/py/mplgui/dataprep.py index fec7066..21afb8c 100644 --- a/py/mplgui/dataprep.py +++ b/py/mplgui/dataprep.py @@ -13,6 +13,7 @@ import numpy as np import pandas as pd +from . import expr as expr_module from .errors import UserError from .loader import is_blank_cell as _is_blank_cell from .loader import looks_numeric as _looks_numeric @@ -313,12 +314,27 @@ class PlotPlan: fits: tuple[FitPlan, ...] = () # 近似曲線(line / step / scatter / scatterColor のみ) hist: HistPlan | None = None # hist のときだけ colorbar: ColorbarPlan | None = None # scatterColor のときだけ + computed: tuple["ComputedPlan", ...] = () # 計算した列(描画に使うデータ元のものだけ。カードの順) @property def plotted(self) -> tuple[SeriesPlan, ...]: return tuple(s for s in self.series if s.has_points) +@dataclass(frozen=True) +class ComputedPlan: + """計算した列1つ(描画に使うデータ元のものだけ)。codegen が「計算した列」の節を書くのに使う。""" + + number: int # カード番号(computed の位置 + 1) + name: str # 列の見出し(名前、無ければ「計算N」) + expr: str # 利用者が書いた式(コメントにだけ使う) + node: object # expr.parse の結果 + data_id: str + data_var: str # "df" または "dfN" + index: int # 計算後の列番号(ファイルの列の後ろ) + refs: tuple[tuple[int, str], ...] = () # 式が使うファイルの列(番号、コメント用の「列 [i]: 名前」) + + MAX_CATEGORY_TICKS = 25 # X が文字列の列のとき、目盛に出すカテゴリの最大数 Y_DATETIME_MESSAGE = "系列{n}: Y列({name})は日時の列です。Y列には数値の列を選んでください。" @@ -650,6 +666,78 @@ def add_y(*values) -> None: BAR_SOURCE_MESSAGE = "棒グラフでは、すべての系列に同じデータ元を選んでください。" +COMPUTED_REF_COMPUTED = "計算した列{n}の式: {pos}文字目: 計算した列([{k}])は、ほかの計算した列の式には使えません。" +COMPUTED_REF_MISSING = "計算した列{n}の式: {pos}文字目: 列 [{k}] はありません(データの列は [0]〜[{last}] です)。" +COMPUTED_REF_DATETIME = "計算した列{n}の式: {pos}文字目: 列 [{k}]({name})は日時の列なので、計算に使えません。" +COMPUTED_INVALID = "計算した列{n}({name}): 0 での割り算・負の数の平方根などで計算できなかった値が{count}件あったため、欠損として扱います。" + + +def _apply_computed( + frames: dict[str, pd.DataFrame], default_id: str, settings: Settings, var_of: dict[str, str] +) -> tuple[tuple[ComputedPlan, ...], list[dict]]: + """データ元ごとに(skipRows を除いた)DataFrame の末尾へ、計算した列をカードの順に足す(frames を書き換える)。 + + 描画に使わないデータ元の計算した列は計算しない。計算した列は、ファイルの列だけを参照できる。""" + items = [(n, c, c.source or default_id) for n, c in enumerate(settings.computed, start=1)] + file_count = {sid: frame.shape[1] for sid, frame in frames.items()} + count_of: dict[str, int] = {} + for _, _, sid in items: + count_of[sid] = count_of.get(sid, 0) + 1 + plans: list[ComputedPlan] = [] + warnings: list[dict] = [] + done: dict[str, int] = {} + for n, c, sid in items: + if sid not in frames: + continue + frame = frames[sid] + total = file_count[sid] + index = total + done.get(sid, 0) + done[sid] = done.get(sid, 0) + 1 + name = c.name or f"計算{n}" + field_name = f"計算した列{n}の式" + refs = expr_module.column_refs(c.expr_node) + for k, pos in sorted(refs, key=lambda r: r[1]): + if k >= total + count_of[sid]: + raise UserError(COMPUTED_REF_MISSING.format(n=n, pos=pos, k=k, last=total - 1), field=field_name) + if k >= total: + raise UserError(COMPUTED_REF_COMPUTED.format(n=n, pos=pos, k=k), field=field_name) + if _is_datetime(frame.iloc[:, k]): + raise UserError( + COMPUTED_REF_DATETIME.format(n=n, pos=pos, k=k, name=str(frame.columns[k])), field=field_name + ) + columns: dict[int, pd.Series] = {} + for k in expr_module.column_indices(c.expr_node): + raw = frame.iloc[:, k] + _, count, examples = coerce_numeric(raw) + if count: + ex = ", ".join(f'"{e}"' for e in examples) + warnings.append( + { + "series": 0, + "message": f"計算した列{n}({name}): 列「{frame.columns[k]}」[{k}] に数値にできない値が{count}件あったため、" + f"欠損として計算します(例: {ex})。{load_hint(examples, settings.load)}", + } + ) + columns[k] = pd.to_numeric(raw, errors="coerce").astype(float) + result, invalid = expr_module.evaluate(c.expr_node, columns, frame.index) + if invalid: + warnings.append({"series": 0, "message": COMPUTED_INVALID.format(n=n, name=name, count=invalid)}) + frame.insert(frame.shape[1], name, result, allow_duplicates=True) + plans.append( + ComputedPlan( + number=n, + name=name, + expr=c.expr, + node=c.expr_node, + data_id=sid, + data_var=var_of[sid], + index=index, + refs=tuple((k, f"列 [{k}]: {frame.columns[k]}") for k in expr_module.column_indices(c.expr_node)), + ) + ) + return tuple(plans), warnings + + def plan_plot(data, settings: Settings) -> PlotPlan: """データと設定から描画計画を作る。データ由来の問題は UserError にする。 @@ -688,11 +776,12 @@ def plan_plot(data, settings: Settings) -> PlotPlan: var_of = {src.id: src.var for src in sources} y_requests = [""] * len(settings.series) - for sid in order: + for sid in order: # Y の自動割り当ては、ファイルの列だけを見る(計算した列を足す前) idx = [i for i, x in enumerate(ids) if x == sid] resolved = resolve_y_indices(frames[sid], [settings.series[i].y for i in idx]) for i, r in zip(idx, resolved): y_requests[i] = r + computed, computed_warnings = _apply_computed(frames, default_id, settings, var_of) dfs = [frames[sid] for sid in ids] if plot.type in {"line", "step", "scatter", "scatterColor"}: plan = _plan_xy(dfs, settings, y_requests) @@ -701,7 +790,14 @@ def plan_plot(data, settings: Settings) -> PlotPlan: 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)) - return replace(plan, series=series, sources=sources, multi_source=multi) + return replace( + plan, + series=series, + sources=sources, + multi_source=multi, + computed=computed, + warnings=tuple(computed_warnings) + tuple(plan.warnings), + ) # ---------------------------------------------------------------- axes (ticks) diff --git a/py/mplgui/settings.py b/py/mplgui/settings.py index 298c4c7..6a80877 100644 --- a/py/mplgui/settings.py +++ b/py/mplgui/settings.py @@ -14,6 +14,7 @@ from matplotlib.colors import is_color_like +from . import expr as expr_module from .errors import UserError SCHEMA_VERSION = 4 @@ -72,6 +73,8 @@ FIT_SHOWS = ("legend", "text", "none") MAX_ANNOTATIONS = 50 MAX_FITS = 20 +MAX_COMPUTED = 20 +MAX_COMPUTED_NAME = 50 MAX_ANNOTATION_TEXT = 200 _DATE_INPUT_RE = re.compile(r"(\d{4})([-/])(\d{1,2})\2(\d{1,2})(?:[ T](\d{1,2}):(\d{2})(?::(\d{2}))?)?") DATE_RANGE_LABEL = "X軸の範囲(日時)" @@ -104,6 +107,7 @@ "fontSize": None, "label": "", } +_DEFAULT_COMPUTED = {"id": "", "source": "", "name": "", "expr": ""} _DEFAULT_FIT = {"id": "f1", "series": "s1", "model": "linear", "degree": 2, "show": "legend", "color": "", "lineStyle": "dashed"} _DEFAULT_SERIES = { @@ -130,6 +134,11 @@ def default_annotation() -> dict: return copy.deepcopy(_DEFAULT_ANNOTATION) +def default_computed() -> dict: + """計算した列1つの既定値(js/defaults.js の DEFAULT_COMPUTED と同一)。""" + return copy.deepcopy(_DEFAULT_COMPUTED) + + def default_fit() -> dict: """近似曲線1つの既定値(js/defaults.js の DEFAULT_FIT と同一)。""" return copy.deepcopy(_DEFAULT_FIT) @@ -178,6 +187,7 @@ def default_settings() -> dict: "series": [copy.deepcopy(_DEFAULT_SERIES)], "annotations": [], "fits": [], + "computed": [], "save": {"filename": "", "format": "png", "transparent": False, "dpi": DEFAULT_DPI, "svgText": "path"}, } @@ -370,6 +380,17 @@ class FitSettings: line_style: str = "dashed" +@dataclass(frozen=True) +class ComputedSettings: + """計算した列1つ。式は解釈済み(expr_node)で、設定の検証の時点で構文の誤りを UserError にする。""" + + id: str = "c1" + source: str = "" # "" = load.files の先頭 + name: str = "" # "" = 「計算N」 + expr: str = "" + expr_node: Any = field(default=None, compare=False, repr=False) + + @dataclass(frozen=True) class SaveSettings: filename: str = "" @@ -389,6 +410,7 @@ class Settings: save: SaveSettings = field(default_factory=SaveSettings) annotations: tuple[AnnotationSettings, ...] = () fits: tuple[FitSettings, ...] = () + computed: tuple[ComputedSettings, ...] = () @property def uses_secondary_axis(self) -> bool: @@ -958,6 +980,40 @@ def _parse_fits(raw: Any, series_ids: set[str]) -> tuple[FitSettings, ...]: return tuple(out) +def _parse_computed(raw: Any, file_ids: set[str]) -> tuple[ComputedSettings, ...]: + if raw is None: + return () + if not isinstance(raw, list): + raise UserError("「計算した列」の値が不正です。", field="計算した列") + if len(raw) > MAX_COMPUTED: + raise UserError(f"計算した列は{MAX_COMPUTED}個までです。", field="計算した列") + out = [] + used_ids: set[str] = set() + for i, given in enumerate(raw): + n = i + 1 + owner = f"計算した列{n}の" + c = _merge(_DEFAULT_COMPUTED, given) + cid = c["id"] if isinstance(c["id"], str) and c["id"] and c["id"] not in used_ids else f"c{n}" + while cid in used_ids: + cid += "_" + used_ids.add(cid) + source = _string(c["source"], "データ元", owner=owner) + if source and source not in file_ids: + raise UserError(f"計算した列{n}のデータ元が見つかりません。データ元を選び直してください。", field=f"計算した列{n}のデータ元") + name = _string(c["name"], "名前", owner=owner).strip() + if len(name) > MAX_COMPUTED_NAME: + raise UserError(f"{owner}「名前」は{MAX_COMPUTED_NAME}文字以内で入力してください。", field=f"計算した列{n}の名前") + expr = _string(c["expr"], "式", owner=owner) + if not expr.strip(): + raise UserError(f"計算した列{n}の式を入力してください。", field=f"計算した列{n}の式") + try: + node = expr_module.parse(expr) + except expr_module.ExprError as e: + raise UserError(f"計算した列{n}の式: {e}", field=f"計算した列{n}の式") from None + out.append(ComputedSettings(id=cid, source=source, name=name, expr=expr, expr_node=node)) + return tuple(out) + + def parse_settings(raw: dict | None) -> Settings: """設定 dict を検証し、型付きの Settings にする。欠けているキーは既定値で補う。 @@ -1059,8 +1115,14 @@ def parse_settings(raw: dict | None) -> Settings: # 棒グラフ・ヒストグラムでは近似曲線を使わない(隠れているので検証しない) fits = () if plot.type in BAR_LIKE_TYPES else _parse_fits(raw.get("fits"), {s.id for s in series}) + # 計算した列は常に表示されるので、グラフの種類によらず検証する + computed = _parse_computed(raw.get("computed"), file_ids) + save = _parse_save(merged["save"]) - return Settings(version=SCHEMA_VERSION, load=load, plot=plot, axes=axes, series=series, save=save, annotations=annotations, fits=fits) + return Settings( + version=SCHEMA_VERSION, load=load, plot=plot, axes=axes, series=series, save=save, + annotations=annotations, fits=fits, computed=computed, + ) def _figure_length(value: Any, label: str, default: float, unit: str) -> float: diff --git a/tests/unit/test_computed.py b/tests/unit/test_computed.py new file mode 100644 index 0000000..600ad82 --- /dev/null +++ b/tests/unit/test_computed.py @@ -0,0 +1,611 @@ +"""Phase 5c: 計算した列(G6)。設定・列の番号・計算(skipRows の後)・警告とエラー・生成コード・自動描画のコピー。""" +import contextlib +import json +import warnings + +import numpy as np +import pandas as pd +import pytest + +from mplgui import api, dataprep +from mplgui.codegen import generate_script +from mplgui.dataprep import plan_plot, slice_skip_rows +from mplgui.errors import UserError +from mplgui.loader import load_file +from mplgui.runner import figure_summary, run_script +from mplgui.settings import MAX_COMPUTED, default_computed, default_settings, parse_settings + +pytestmark = pytest.mark.unit + +N = 10 + + +def frame(): + t = np.arange(N, dtype=float) + return pd.DataFrame({"t": t, "v": t * 2 + 10, "lo": t * 2 + 8, "hi": t * 2 + 13, "w": 100 - t * 3.0}) + + +def other_frame(): + t = np.arange(N, dtype=float) + return pd.DataFrame({"a": t, "b": t**2, "c": t + 0.5}) + + +def s(y, x=0, **kw): + d = {"x": f"__idx__{x}", "y": f"__idx__{y}"} + d.update(kw) + return d + + +def comp(expr, name="", source="", **kw): + return {"name": name, "expr": expr, "source": source, **kw} + + +def make_raw(series_list, computed, plot_type="line", files=None, **plot): + raw = default_settings() + raw["series"] = series_list + raw["computed"] = computed + raw["plot"]["type"] = plot_type + raw["plot"].update(plot) + if files: + raw["load"]["files"] = [{"id": i, "name": n, "sheet": ""} for i, n, _ in files] + return raw + + +class Built: + """1 つ以上の CSV を読み込み、描画計画・スクリプトを作る。files は [(id, ファイル名, DataFrame)]。""" + + def __init__(self, tmp_path, raw, files=None): + files = files or [("d1", "d.csv", frame())] + self.dir = tmp_path + self.loaded = {} + for fid, name, df in files: + df.to_csv(tmp_path / name, index=False, encoding="utf-8") + self.loaded[fid] = load_file((tmp_path / name).read_bytes(), name, "", True) + self.settings = parse_settings(raw) + self.plan = plan_plot({fid: ld.df for fid, ld in self.loaded.items()}, self.settings) + self.script = generate_script(self.settings, {fid: ld.source for fid, ld in self.loaded.items()}, self.plan) + + @contextlib.contextmanager + def full(self): + with _strict_warnings(), run_script(self.script.text, cwd=self.dir) as run: + yield run + + @contextlib.contextmanager + def auto(self): + with_computed = {c.data_id for c in self.plan.computed} + injected = { + src.var: self.loaded[src.id].df.copy() if src.id in with_computed else self.loaded[src.id].df + for src in self.plan.sources + } + with _strict_warnings(), run_script(self.script.auto_render_text(), injected=injected) as run: + yield run + + def summaries(self): + with self.full() as run: + full = figure_summary(run.fig) + with self.auto() as run: + auto = figure_summary(run.fig) + assert full == auto + return full + + +@contextlib.contextmanager +def _strict_warnings(): + """pandas の警告(SettingWithCopy など)を例外にする。フォントの警告だけは無視する。""" + with warnings.catch_warnings(): + warnings.simplefilter("error") + warnings.filterwarnings("ignore", message=".*missing from.*") + yield + + +def ydata(ax, i=0): + return ax.lines[i].get_ydata() + + +# ---------------------------------------------------------------- 設定 + + +def test_defaults_and_missing_keys(): + assert default_computed() == {"id": "", "source": "", "name": "", "expr": ""} + assert default_settings()["computed"] == [] + assert parse_settings(default_settings()).computed == () + st = parse_settings(make_raw([s(1)], [{"expr": "[1] * 2"}])) + c = st.computed[0] + assert (c.id, c.source, c.name, c.expr) == ("c1", "", "", "[1] * 2") + assert c.expr_node is not None + # computed キーが無い設定(v3 や 5b までの設定)は計算した列なし + raw = default_settings() + del raw["computed"] + assert parse_settings(raw).computed == () + + +def test_limit_is_twenty(): + ok = [comp("[1]")] * MAX_COMPUTED + assert len(parse_settings(make_raw([s(1)], ok)).computed) == MAX_COMPUTED + with pytest.raises(UserError) as e: + parse_settings(make_raw([s(1)], ok + [comp("[1]")])) + assert str(e.value) == "計算した列は20個までです。" + + +def test_ids_are_renumbered_when_blank_or_duplicated(): + raw = make_raw([s(1)], [comp("[1]", id="c5"), comp("[1]", id="c5"), comp("[1]", id=""), comp("[1]", id="c2"), comp("[1]", id=7)]) + ids = [c.id for c in parse_settings(raw).computed] + assert ids == ["c5", "c2", "c3", "c4", "c5_"] # 重複・空・文字列でない id は位置で振り直し、それも重なれば「_」を足す + assert parse_settings(make_raw([s(1)], [comp("[1]", id="c9"), comp("[1]", id="c4")])).computed[1].id == "c4" + + +def test_name_length_and_strip(): + ok = parse_settings(make_raw([s(1)], [comp("[1]", name=" あ" * 1 + "x" * 49 + " ")])).computed[0] + assert len(ok.name) == 50 + with pytest.raises(UserError) as e: + parse_settings(make_raw([s(1)], [comp("[1]"), comp("[1]", name="x" * 51)])) + assert e.value.field == "計算した列2の名前" + + +def test_empty_expression_and_types(): + with pytest.raises(UserError) as e: + parse_settings(make_raw([s(1)], [comp("[1]"), comp(" ")])) + assert str(e.value) == "計算した列2の式を入力してください。" and e.value.field == "計算した列2の式" + with pytest.raises(UserError): + parse_settings(make_raw([s(1)], [{"expr": 5}])) + with pytest.raises(UserError): + parse_settings(make_raw([s(1)], "x")) + + +def test_syntax_error_message_and_field(): + with pytest.raises(UserError) as e: + parse_settings(make_raw([s(1)], [comp("max([1]")])) + assert e.value.field == "計算した列1の式" + assert str(e.value).startswith("計算した列1の式: ") and "文字目: " in str(e.value) + assert "閉じ括弧" in str(e.value) + + +def test_unknown_source(): + raw = make_raw([s(1)], [comp("[1]", source="d9")], files=[("d1", "a.csv", None)]) + with pytest.raises(UserError) as e: + parse_settings(raw) + assert e.value.field == "計算した列1のデータ元" and str(e.value).startswith("計算した列1のデータ元が見つかりません。") + raw["computed"][0]["source"] = "d1" + assert parse_settings(raw).computed[0].source == "d1" + raw["load"]["files"] = [] # ファイルの一覧が空なら、空でない source は見つからない + with pytest.raises(UserError): + parse_settings(raw) + + +@pytest.mark.parametrize("plot_type", ["line", "step", "scatter", "scatterColor", "bar", "barh", "barStacked", "hist"]) +def test_always_validated_for_every_plot_type(plot_type): + raw = make_raw([s(1, colorColumn="__idx__2")], [comp("")], plot_type=plot_type) + with pytest.raises(UserError) as e: + parse_settings(raw) + assert e.value.field == "計算した列1の式" + + +# ---------------------------------------------------------------- 列の番号 + + +def test_single_file_numbering_order_and_names(tmp_path): + raw = make_raw([s(5), s(6)], [comp("[1] / max([1])", name="比"), comp("[4] * 2")]) + b = Built(tmp_path, raw) + assert [(c.number, c.name, c.index, c.data_var) for c in b.plan.computed] == [(1, "比", 5, "df"), (2, "計算2", 6, "df")] + with b.full() as run: + ax = run.fig.axes[0] + v = frame()["v"].to_numpy() + assert np.allclose(ydata(ax, 0), v / v.max()) + assert np.allclose(ydata(ax, 1), frame()["w"].to_numpy() * 2) + df = run.namespace["df"] + assert list(df.columns[5:]) == ["比", "計算2"] + b.summaries() + + +def test_card_number_is_position_in_whole_list_across_sources(tmp_path): + files = [("d1", "a.csv", frame()), ("d2", "b.csv", other_frame())] + raw = make_raw( + [s(5, source="d1"), s(3, x=0, source="d2"), s(4, x=0, source="d2")], + [comp("[1] * 2", source="d1"), comp("[1] + [2]", source="d2"), comp("[0] - [1]", source="d1"), comp("[2] * 10", source="d2")], + files=files, + ) + b = Built(tmp_path, raw, files) + got = {(c.number, c.data_id): (c.index, c.name, c.data_var) for c in b.plan.computed} + assert got == { + (1, "d1"): (5, "計算1", "df1"), + (2, "d2"): (3, "計算2", "df2"), + (3, "d1"): (6, "計算3", "df1"), + (4, "d2"): (4, "計算4", "df2"), + } + with b.full() as run: + ax = run.fig.axes[0] + assert np.allclose(ydata(ax, 0), frame()["v"].to_numpy() * 2) + assert np.allclose(ydata(ax, 1), (other_frame()["b"] + other_frame()["c"]).to_numpy()) + assert np.allclose(ydata(ax, 2), other_frame()["c"].to_numpy() * 10) + b.summaries() + assert "df1.insert" in b.script.text and "df2.insert" in b.script.text + + +def test_all_column_kinds_resolve_to_computed_columns(tmp_path): + computed = [comp("[0] * 2"), comp("[1] + 1"), comp("[2] + 1"), comp("[3] + 1"), comp("abs([4]) / 10")] + raw = make_raw( + [ + s( + 6, + x=5, + errorBars={"y": {"mode": "column", "column": "__idx__9"}, "x": {"mode": "column", "column": "__idx__9"}}, + fill={"lower": "__idx__7", "upper": "__idx__8", "alpha": 0.25}, + ) + ], + computed, + ) + b = Built(tmp_path, raw) + assert b.plan.series[0].x_index == 5 and b.plan.series[0].y_index == 6 + summary = b.summaries()[0] + assert summary["bands"] == 1 and summary["errorbars"] == 2 + with b.full() as run: + assert np.allclose(run.fig.axes[0].lines[-1].get_xdata(), frame()["t"].to_numpy() * 2) + + +def test_scatter_color_column_can_be_computed(tmp_path): + raw = make_raw([s(1, x=0, colorColumn="__idx__5")], [comp("[4] / 2")], plot_type="scatterColor") + b = Built(tmp_path, raw) + summary = b.summaries()[0] + w = frame()["w"].to_numpy() / 2 + assert summary["colorbar"]["vmin"] == pytest.approx(w.min()) and summary["colorbar"]["vmax"] == pytest.approx(w.max()) + + +def test_bar_x_column_can_be_computed(tmp_path): + raw = make_raw([s(1)], [comp("[0] * 10")], plot_type="bar", xColumn="__idx__5") + b = Built(tmp_path, raw) + assert b.plan.bar_x_index == 5 + b.summaries() + with b.full() as run: # 数値の X 列の単独の棒は、数値の位置に棒を置く + centers = sorted(p.get_x() + p.get_width() / 2 for p in run.fig.axes[0].patches) + assert np.allclose(centers, np.arange(N) * 10.0) + + +def test_auto_y_assignment_ignores_computed_columns(tmp_path): + base = Built(tmp_path, make_raw([{"x": "__idx__0", "y": ""}, {"x": "__idx__0", "y": ""}], [])) + with_c = Built(tmp_path, make_raw([{"x": "__idx__0", "y": ""}, {"x": "__idx__0", "y": ""}], [comp("[1] * 2")])) + assert [p.y_index for p in with_c.plan.series] == [p.y_index for p in base.plan.series] + # 文字列の列が先頭にあり、計算した列だけが数値、というデータでも、自動の Y はファイルの列から選ぶ + df = pd.DataFrame({"name": ["a", "b", "c"], "v": [1.0, 2.0, 3.0]}) + raw = make_raw([{"x": "", "y": ""}], [comp("[1] * 2")]) + b = Built(tmp_path, raw, [("d1", "t.csv", df)]) + assert b.plan.series[0].y_index == 1 + + +# ---------------------------------------------------------------- 計算 + + +def test_computed_after_skip_rows_uses_remaining_rows_only(tmp_path): + raw = make_raw([s(5), s(6)], [comp("[1] / max([1])"), comp("[1] - first([1])")], skipRows=3) + b = Built(tmp_path, raw) + v = frame()["v"].to_numpy()[3:] + with b.full() as run: + ax = run.fig.axes[0] + assert np.allclose(ydata(ax, 0), v / v.max()) and ydata(ax, 0)[-1] == pytest.approx(1.0) + assert np.allclose(ydata(ax, 1), v - v[0]) and ydata(ax, 1)[0] == 0 + assert len(run.namespace["df"]) == N - 3 + b.summaries() + + +def test_skip_rows_error_comes_before_computation(tmp_path): + raw = make_raw([s(1)], [comp("[1] / max([1])")], skipRows=N) + df = frame() + loaded = load_file(df.to_csv(index=False).encode(), "d.csv", "", True) + with pytest.raises(UserError) as e: + plan_plot(loaded.df, parse_settings(raw)) + assert e.value.field == "除外する先頭行数" + + +def test_non_numeric_values_warn_with_hints_and_become_nan(): + df = pd.DataFrame({"t": [0.0, 1, 2, 3], "x": ["1,234", "2", "abc", ""]}) + raw = make_raw([s(2)], [comp("[1] * 2", name="倍")]) + plan = plan_plot(df, parse_settings(raw)) + (w,) = plan.warnings + assert w["message"].startswith("計算した列1(倍): 列「x」[1] に数値にできない値が2件あったため、欠損として計算します(例: ") + assert '"1,234"' in w["message"] and '"abc"' in w["message"] + assert "桁区切りのカンマなら" in w["message"] + # 小数点カンマのヒント + df2 = pd.DataFrame({"t": [0.0, 1], "x": ["1,5", "2"]}) + (w2,) = plan_plot(df2, parse_settings(make_raw([s(2)], [comp("[1]")]))).warnings + assert "小数点がカンマなら" in w2["message"] + # 空欄だけなら警告しない + df3 = pd.DataFrame({"t": [0.0, 1], "x": ["", "2"]}) + assert plan_plot(df3, parse_settings(make_raw([s(2)], [comp("[1]")]))).warnings == () + + +def test_non_numeric_warning_counts_only_rows_after_skip_rows(): + df = pd.DataFrame({"t": [0.0, 1, 2, 3], "x": ["bad", "bad", "2", "3"]}) + raw = make_raw([s(2)], [comp("[1]")], skipRows=2) + assert plan_plot(df, parse_settings(raw)).warnings == () + + +def test_invalid_count_warning(): + df = pd.DataFrame({"t": [0.0, 1, 2, 3], "x": [0.0, 1, 0, -4]}) + raw = make_raw([s(2), s(3)], [comp("1 / [1]", name="逆数"), comp("sqrt([1])")]) + plan = plan_plot(df, parse_settings(raw)) + assert [w["message"] for w in plan.warnings] == [ + "計算した列1(逆数): 0 での割り算・負の数の平方根などで計算できなかった値が2件あったため、欠損として扱います。", + "計算した列2(計算2): 0 での割り算・負の数の平方根などで計算できなかった値が1件あったため、欠損として扱います。", + ] + # 入力が欠損のときは数えない + df2 = pd.DataFrame({"t": [0.0, 1], "x": [np.nan, 2.0]}) + assert plan_plot(df2, parse_settings(make_raw([s(2)], [comp("1 / [1]")]))).warnings == () + + +def test_series_using_computed_y_has_no_extra_dropped_warning(): + df = pd.DataFrame({"t": [0.0, 1, 2, 3], "x": ["1", "oops", "3", "4"]}) + plan = plan_plot(df, parse_settings(make_raw([s(2)], [comp("[1] * 2")]))) + assert len(plan.warnings) == 1 and plan.warnings[0]["message"].startswith("計算した列1(計算1):") + assert plan.series[0].has_points + + +def test_datetime_column_reference_is_error(): + df = pd.DataFrame({"when": pd.to_datetime(["2026-01-01", "2026-01-02"]), "v": [1.0, 2.0]}) + with pytest.raises(UserError) as e: + plan_plot(df, parse_settings(make_raw([s(1)], [comp("[0] + 1")]))) + assert str(e.value) == "計算した列1の式: 1文字目: 列 [0](when)は日時の列なので、計算に使えません。" + assert e.value.field == "計算した列1の式" + + +def test_out_of_range_reference_is_error(): + with pytest.raises(UserError) as e: + plan_plot(frame(), parse_settings(make_raw([s(1)], [comp("[1] + [7]")]))) + assert str(e.value) == "計算した列1の式: 7文字目: 列 [7] はありません(データの列は [0]〜[4] です)。" + # 計算した列が 1 つしかないときの [6] は、範囲外 + with pytest.raises(UserError) as e: + plan_plot(frame(), parse_settings(make_raw([s(1)], [comp("[6]")]))) + assert "列 [6] はありません" in str(e.value) + + +def test_reference_to_another_computed_column_is_specific_error(): + raw = make_raw([s(1)], [comp("[1] * 2"), comp("[5] + 1")]) + with pytest.raises(UserError) as e: + plan_plot(frame(), parse_settings(raw)) + assert str(e.value) == "計算した列2の式: 1文字目: 計算した列([5])は、ほかの計算した列の式には使えません。" + assert e.value.field == "計算した列2の式" + # 自分自身も、後ろの計算した列も同じ + for expr in ("[5] + 1", "[6] + 1"): + with pytest.raises(UserError) as e: + plan_plot(frame(), parse_settings(make_raw([s(1)], [comp(expr), comp("[1]")]))) + assert "ほかの計算した列の式には使えません" in str(e.value) + + +def test_scalar_expression_broadcasts(tmp_path): + raw = make_raw([s(5)], [comp("max([1]) - min([1])")]) + b = Built(tmp_path, raw) + with b.full() as run: + v = frame()["v"] + assert np.allclose(ydata(run.fig.axes[0]), v.max() - v.min()) + assert len(run.namespace["df"]) == N and run.namespace["df"].shape[1] == 6 + assert "pd.Series(" in b.script.text + b.summaries() + + +# ---------------------------------------------------------------- 生成コード + + +def test_generated_values_equal_dataprep_values(tmp_path): + exprs = ["[1] / max([1])", "rolling_mean([4], 3)", "diff([1])", "cumsum([4])", "1 / ([1] - 10)", "sqrt([4] - 90)", "[1] - first([1])", "-2 ** [0] + mean([1])"] + df = frame() + df.loc[3, "v"] = np.nan + raw = make_raw([s(5)], [comp(e) for e in exprs], skipRows=2) + b = Built(tmp_path, raw, [("d1", "d.csv", df)]) + frames = {"d1": slice_skip_rows(b.loaded["d1"].df, 2)} + dataprep._apply_computed(frames, "d1", b.settings, {"d1": "df"}) + expected = frames["d1"].iloc[:, 5:] + with b.full() as run: + got = run.namespace["df"].iloc[:, 5:] + assert got.shape == expected.shape == (N - 2, len(exprs)) + for i in range(len(exprs)): + pd.testing.assert_series_equal(got.iloc[:, i], expected.iloc[:, i], check_names=False) + assert not np.isinf(got.iloc[:, i].to_numpy()).any() + b.summaries() + + +def test_section_only_with_computed_columns_and_numbering(tmp_path): + none = Built(tmp_path, make_raw([s(1)], [])) + assert "計算した列" not in none.script.text and none.script.text.count("# ==== ") == 8 + some = Built(tmp_path, make_raw([s(5)], [comp("[1] * 2")], skipRows=1)) + t = some.script.text + assert "# ==== 3. 計算した列 ====" in t and "# ==== 4. 図と軸 ====" in t + assert t.index("2. 描画に使う行") < t.index("3. 計算した列") < t.index("4. 図と軸") + assert 'with np.errstate(divide="ignore", invalid="ignore", over="ignore")' in t + assert 'df.insert(df.shape[1], "計算1", calc.replace([np.inf, -np.inf], np.nan), allow_duplicates=True)' in t + # 計算した列が無い設定の生成コードは、計算した列の項目に影響されない + assert generate_script(none.settings, none.loaded["d1"].source, none.plan).text == none.script.text + + +def test_steps_report_failed_computed_column(tmp_path): + b = Built(tmp_path, make_raw([s(5)], [comp("[1]", name="甲"), comp("[4] * 2", name="乙")])) + steps = [st for st in b.script.steps if st.field and st.field.startswith("計算した列")] + assert [st.field for st in steps] == ["計算した列1の式", "計算した列2の式"] + assert steps[1].message == "計算した列2(乙)を計算できませんでした。式を確認してください。" + lines = b.script.text.split("\n") + assert any("col4" in ln for ln in lines[steps[1].start - 1 : steps[1].end]) + + +NASTY_NAMES = [ + 'x"); import os; ("', + "a'b\"c", + "x\nimport os\nprint(1)", + "x\\", + "x
import os
y", + "\\n#", + "x\r\ny\x0b", +] + + +@pytest.mark.parametrize("name", NASTY_NAMES) +def test_name_injection(tmp_path, name): + raw = make_raw([s(5)], [comp("[1] * 2", name=name)]) + b = Built(tmp_path, raw) + compile(b.script.text, "", "exec") # 構文として壊れていない + with b.full() as run: + assert "os" not in run.namespace + assert run.namespace["df"].columns[5] == b.settings.computed[0].name # 名前は文字列としてそのまま入る + assert run.namespace["df"].shape[1] == 6 + # コメントの行が増えていない(改行が空白になっている): 注入した行が単独の文になっていない + assert not any(line.strip().startswith(("import os", "print(1)")) for line in b.script.text.split("\n")) + b.summaries() + + +@pytest.mark.parametrize("expr", ["[1]\n+ 1", "[1]\t* 2", " [1] + 1"]) +def test_expression_whitespace_variants_cannot_break_comments(tmp_path, expr): + raw = make_raw([s(5)], [comp(expr)]) + try: + b = Built(tmp_path, raw) + except UserError: + return # 受け付けない書き方なら、コードにならない + comment = [ln for ln in b.script.text.split("\n") if "計算した列1:" in ln] + assert len(comment) == 1 + compile(b.script.text, "", "exec") + with b.full() as run: + assert run.namespace["df"].shape[1] == 6 + + +@pytest.mark.parametrize("expr", ['[1]); import os; (', '"); import os; ("', "[1] # \n import os", "__import__('os')", "[1]; import os", "[1] + 'a'"]) +def test_expression_with_code_is_rejected(expr): + with pytest.raises(UserError) as e: + parse_settings(make_raw([s(1)], [comp(expr)])) + assert e.value.field == "計算した列1の式" + + +def test_expression_text_only_appears_in_comments(tmp_path): + raw = make_raw([s(5)], [comp(" [1] / max( [1] ) ")]) + b = Built(tmp_path, raw) + for line in b.script.text.split("\n"): + if "[1] / max( [1] )" in line: + assert line.lstrip().startswith("#") + + +def test_unused_source_is_not_computed_or_emitted(tmp_path): + files = [("d1", "a.csv", frame()), ("d2", "b.csv", other_frame())] + # d2 の計算した列は、d2 の列にない [9] を参照している(使わないデータ元なので、データの検査はしない) + raw = make_raw([s(5, source="d1")], [comp("[1] * 2", source="d1"), comp("[9] * 2", source="d2")], files=files) + b = Built(tmp_path, raw, files) + assert [c.data_id for c in b.plan.computed] == ["d1"] + assert "df2" not in b.script.text and "DATA_FILE_2" not in b.script.text + assert b.script.text.count("df1.insert") == 1 + b.summaries() + # 構文の誤りは、使わないデータ元でも設定の検証で止まる + raw["computed"][1]["expr"] = "[9] *" + with pytest.raises(UserError): + parse_settings(raw) + # すべて使わないデータ元なら、計算した列の節は出ない + raw2 = make_raw([s(1, source="d1")], [comp("[9]", source="d2")], files=files) + b2 = Built(tmp_path, raw2, files) + assert b2.plan.computed == () and "計算した列" not in b2.script.text + + +def test_computed_on_default_source_follows_first_file(tmp_path): + files = [("d1", "a.csv", frame()), ("d2", "b.csv", other_frame())] + raw = make_raw([s(5, source="d1")], [comp("[1] * 2")], files=files) # source 空 = 先頭のファイル + b = Built(tmp_path, raw, files) + assert b.plan.computed[0].data_id == "d1" and b.plan.computed[0].data_var == "df1" + + +def test_bad_reference_in_used_source_names_that_source_columns(tmp_path): + files = [("d1", "a.csv", frame()), ("d2", "b.csv", other_frame())] + raw = make_raw([s(1, source="d1"), s(3, source="d2")], [comp("[1] + [4]", source="d2")], files=files) + with pytest.raises(UserError) as e: + Built(tmp_path, raw, files) + assert "列 [4] はありません(データの列は [0]〜[2] です)" in str(e.value) + + +# ---------------------------------------------------------------- 新しいグラフの種類と計算した列 + + +def test_step_with_computed_y(tmp_path): + raw = make_raw([s(5)], [comp("cumsum([1])")], plot_type="step") + b = Built(tmp_path, raw) + summary = b.summaries()[0] + assert summary["drawstyles"] == ["steps-post"] + with b.full() as run: + assert np.allclose(ydata(run.fig.axes[0]), np.cumsum(frame()["v"].to_numpy())) + + +def test_hist_with_computed_y(tmp_path): + raw = make_raw([{"x": "", "y": "__idx__5"}], [comp("[1] - mean([1])")], plot_type="hist") + b = Built(tmp_path, raw) + summary = b.summaries()[0] + assert summary["bars"]["vertical"] > 0 + v = frame()["v"].to_numpy() + with b.full() as run: + heights = sum(p.get_height() for p in run.fig.axes[0].patches) + assert heights == N and run.fig.axes[0].get_xlim()[0] <= (v - v.mean()).min() + + +def test_scatter_color_with_computed_y_and_color(tmp_path): + raw = make_raw([s(5, x=0, colorColumn="__idx__6")], [comp("[1] * 3"), comp("[4] / 100")], plot_type="scatterColor") + b = Built(tmp_path, raw) + summary = b.summaries()[0] + assert summary["colorbar"]["vmax"] == pytest.approx(1.0) + + +def test_barh_and_stacked_with_computed_y(tmp_path): + for plot_type in ("barh", "barStacked", "bar"): + raw = make_raw([s(5), s(6)], [comp("[1] / 10"), comp("[4] / 10")], plot_type=plot_type, xColumn="__idx__0") + Built(tmp_path, raw).summaries() + + +def test_computed_with_no_series_data_source_error_is_unchanged(): + raw = make_raw([s(1)], [comp("[1]")], files=[("d1", "a.csv", None)]) + with pytest.raises(UserError) as e: + plan_plot({"d2": frame()}, parse_settings(raw)) + assert "読み込めていません" in str(e.value) or "データ" in str(e.value) + + +# ---------------------------------------------------------------- api(自動描画はコピーを渡す) + + +@pytest.fixture +def session(tmp_path): + api.SESSION.forget() + api.SESSION.workdir = tmp_path + yield api.SESSION + api.SESSION.forget() + api.SESSION.workdir = None + + +@pytest.mark.parametrize("skip", [0, 2]) +def test_auto_render_does_not_grow_the_session_dataframe(session, skip): + raw = make_raw([s(5)], [comp("[1] / max([1])", name="比")], skipRows=skip) + csv = frame().to_csv(index=False).encode() + r = json.loads(api.load_file_json("d.csv", csv, json.dumps(raw))) + assert r["ok"] + before = session.sources["d1"].df.copy() + shape = session.sources["d1"].df.shape + summaries = [] + for _ in range(3): + out = json.loads(api.render_json(json.dumps(raw))) + assert out["ok"], out + summaries.append(out["summary"]) + assert session.sources["d1"].df.shape == shape == (N, 5) + pd.testing.assert_frame_equal(session.sources["d1"].df, before) + assert summaries[0] == summaries[1] == summaries[2] + assert "df.insert" in out["code"] + # 保存・コピー・コードだけの更新も同じ + assert json.loads(api.script_json(json.dumps(raw)))["code"] == out["code"] + assert json.loads(api.save_json(json.dumps(raw)))["ok"] + assert session.sources["d1"].df.shape == shape + + +def test_api_two_files_only_copies_sources_with_computed(session): + files = [("d1", "a.csv", frame()), ("d2", "b.csv", other_frame())] + raw = make_raw([s(5, source="d1"), s(2, source="d2")], [comp("[1] * 2", source="d1")], files=files) + for fid, name, df in files: + assert json.loads(api.load_file_json(name, df.to_csv(index=False).encode(), json.dumps(raw), fid))["ok"] + for _ in range(2): + out = json.loads(api.render_json(json.dumps(raw))) + assert out["ok"], out + assert session.sources["d1"].df.shape == (N, 5) and session.sources["d2"].df.shape == (N, 3) + + +def test_api_reports_computed_errors_with_field(session): + raw = make_raw([s(1)], [comp("[1] * 2")]) + assert json.loads(api.load_file_json("d.csv", frame().to_csv(index=False).encode(), json.dumps(raw)))["ok"] + raw["computed"][0]["expr"] = "[1] * (2" + out = json.loads(api.render_json(json.dumps(raw))) + assert out["ok"] is False and out["error"]["field"] == "計算した列1の式" + raw["computed"][0]["expr"] = "[1] + [8]" + out = json.loads(api.render_json(json.dumps(raw))) + assert out["ok"] is False and "列 [8] はありません" in out["error"]["message"] diff --git a/tests/unit/test_defaults_parity.py b/tests/unit/test_defaults_parity.py index ef866f5..7c73332 100644 --- a/tests/unit/test_defaults_parity.py +++ b/tests/unit/test_defaults_parity.py @@ -6,7 +6,7 @@ import pytest -from mplgui.settings import default_annotation, default_fit, default_settings +from mplgui.settings import default_annotation, default_computed, default_fit, default_settings pytestmark = pytest.mark.unit @@ -37,10 +37,11 @@ def test_js_and_python_element_defaults_match(tmp_path): module = tmp_path / "defaults.mjs" module.write_text((REPO / "js" / "defaults.js").read_text(encoding="utf-8"), encoding="utf-8") script = ( - f"import {{ DEFAULT_ANNOTATION, DEFAULT_FIT }} from {json.dumps(module.as_uri())}; " - "console.log(JSON.stringify([DEFAULT_ANNOTATION, DEFAULT_FIT]));" + f"import {{ DEFAULT_ANNOTATION, DEFAULT_FIT, DEFAULT_COMPUTED }} from {json.dumps(module.as_uri())}; " + "console.log(JSON.stringify([DEFAULT_ANNOTATION, DEFAULT_FIT, DEFAULT_COMPUTED]));" ) out = subprocess.run(["node", "--input-type=module", "-e", script], capture_output=True, text=True, check=True, timeout=30) - annotation, fit = json.loads(out.stdout) + annotation, fit, computed = json.loads(out.stdout) assert annotation == default_annotation() assert fit == default_fit() + assert computed == default_computed() diff --git a/tests/unit/test_settings.py b/tests/unit/test_settings.py index 9725ee0..478de75 100644 --- a/tests/unit/test_settings.py +++ b/tests/unit/test_settings.py @@ -20,7 +20,7 @@ def test_defaults_are_complete_and_parse(): d = default_settings() assert d["version"] == SCHEMA_VERSION == 4 - assert set(d) == {"version", "load", "plot", "axes", "series", "annotations", "fits", "save"} + assert set(d) == {"version", "load", "plot", "axes", "series", "annotations", "fits", "computed", "save"} assert set(d["axes"]) == {"x", "y", "y2"} s = parse_settings(d) assert s.plot.type == "line" and s.plot.font_size == 15 and s.plot.figure.width == 8 and s.plot.figure.height == 6 From a62297c1b9c6ed3798f7004124b7f86ae6b33f13 Mon Sep 17 00:00:00 2001 From: mioupa <79833278+mioupa@users.noreply.github.com> Date: Thu, 12 Nov 2026 09:23:22 +0900 Subject: [PATCH 05/10] Add the chart-type selector, type-specific settings and the colour column to the UI (Phase 5c, G7) js/chart-types.js holds the per-type rules shared by every show/hide decision (same rules as settings.py). barh treats the vertical axis as the category axis in ticks and annotations. Co-Authored-By: Claude Opus 5.5 --- index.html | 50 ++++- js/chart-types.js | 26 +++ js/presets.js | 6 +- js/state.js | 3 +- js/ui/annotations.js | 10 +- js/ui/axisTicks.js | 6 +- js/ui/fits.js | 3 +- js/ui/forms.js | 5 + js/ui/series.js | 104 ++++++--- tests/e2e/helpers.py | 17 ++ tests/e2e/test_chart_types.py | 303 ++++++++++++++++++++++++++ tests/e2e/test_codegen_consistency.py | 53 +++++ tests/e2e/test_fits.py | 2 +- tests/fixtures/README.md | 1 + tests/fixtures/chart_types.csv | 13 ++ tests/fixtures/make_fixtures.py | 14 ++ tests/unit/test_js_modules.py | 10 +- 17 files changed, 582 insertions(+), 44 deletions(-) create mode 100644 js/chart-types.js create mode 100644 tests/e2e/test_chart_types.py create mode 100644 tests/fixtures/chart_types.csv diff --git a/index.html b/index.html index 5a58a72..85af1d8 100644 --- a/index.html +++ b/index.html @@ -135,9 +135,55 @@

Matplotlib GUI

+ + + + + + + + + + +
@@ -296,7 +342,7 @@

Matplotlib GUI

-
+
-
+
@@ -208,7 +239,11 @@ const cardHtml = (series, plotType) => {
-
+ +