diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 43e15a8..b9edadd 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -32,8 +32,8 @@ jobs: # push では実行しない(pull_request と手動実行のみ) if: github.event_name == 'pull_request' || github.event_name == 'workflow_dispatch' runs-on: ubuntu-latest - # 全件で 30 分を超える(Phase 4 で 28 分、Phase 5a で約 36 分)。余裕を持たせる - timeout-minutes: 60 + # 全件で 30 分を超える(Phase 4 で 28 分、Phase 5a で約 36 分、Phase 5c で約 43 分)。余裕を持たせる + timeout-minutes: 90 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: diff --git a/AGENTS.md b/AGENTS.md index 25f4edf..0238520 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,7 +1,7 @@ # matplotlib GUI 引き継ぎ資料(AI エージェント向け) 要件の正は `docs/REQUIREMENTS.md`。このファイルと食い違う場合は REQUIREMENTS.md を優先する。 -この資料は Phase 5c(データの扱いの拡張: 計算した列・グラフの種類 第1弾。5b の系列のスタイル・注釈・近似曲線、5a のエラーバー・目盛の詳細・枠線・日時の X の範囲と、Phase 4 のデータ取り込みを含む)完了時点の実装を説明する。各 Phase の完了時に実装に合わせて更新すること(要件 A11)。 +この資料は Phase 5d(グラフの種類 第2弾・任意関数のフィッティング: 箱ひげ図・バイオリン図・ヒートマップ・任意の式の近似曲線。5c の計算した列・グラフの種類 第1弾、5b の系列のスタイル・注釈・近似曲線、5a のエラーバー・目盛の詳細・枠線・日時の X の範囲と、Phase 4 のデータ取り込みを含む)完了時点の実装を説明する。各 Phase の完了時に実装に合わせて更新すること(要件 A11)。 ## 1. ゴールと前提 @@ -18,7 +18,8 @@ - CDN の URL はすべてバージョン固定にする。`tests/unit/test_cdn_pinning.py` が `index.html`・`js/`・`css/`・`py/` の全 URL を走査して強制する。取得しない説明リンクの `matplotlib.org` は、バージョンを含むパス(`/3.10.8/...`)だけ許可する。 - Phase 5a でグラフの表現が広がった(PR 5a。G1・G2)。系列ごとのエラーバー(Y・X 方向、固定値か列、上下で別の値も可。端の長さ)、軸ごと(X / Y / 第2Y)の目盛の詳細(主目盛の間隔、副目盛の表示・なし・分割数、ラベルの書式、軸の反転)、上と右の枠線の切替、X が日時の列のときの X 軸の日時の範囲(`axes.x.dateMin` / `dateMax`)。画面で隠した設定は図に使わない(値は残る。要件 §2.2)。いずれも設定 → 生成コード → 実行の1本の経路に載り、設定が既定のときの生成コードは Phase 4 と1文字も変わらない(ゴールデンテストで確認)。注釈・近似曲線は 5b で入った(次の項目)。 - Phase 5b でグラフの表現がさらに広がった(PR 5b。G3・G4・G5)。系列のスタイル(点の形、不透明度、2列の間を塗りつぶす帯、系列の並べ替え(↑ ↓)と複製)、注釈(文字・水平線・垂直線・横の帯・縦の帯。最大 50 個)、近似曲線(系列ごとの1次式・多項式。式と R² を凡例か図の中に出せる。最大 20 本)と、それらを置く左パネルの「注釈・解析」の区分(`#sectionAnalysis`)。画面で隠した設定は図に使わない(要件 §2.2)。いずれも設定 → 生成コード → 実行の1本の経路に載り、設定が既定のときの生成コードは Phase 4 と1文字も変わらない(ゴールデンテストで確認。スキーマは version 4 のまま)。式の列(G6)とグラフの種類(G7)は 5c で入った(次の項目)。 -- Phase 5c でデータの扱いが広がった(PR 5c。G6・G7)。グラフの種類(G7)は、段グラフ(`step`)、横棒(`barh`)、積み上げ棒(`barStacked`)、ヒストグラム(`hist`)、色分け散布図(`scatterColor`)が加わった。種類ごとの設定(段の付き方、区間の数と確率密度、カラーマップとカラーバーのラベル、系列の色分けの列)と、「計算した列」(G6。式で新しい列を作り、系列の X・Y・エラーバー・帯・色分けの列に選べる)も加わった。式は `py/mplgui/expr.py` が自前で解釈する(`eval` を使わない)。画面で隠した設定は図に使わない(種類ごとに使わない設定は値を残して検証しない。要件 §2.2)。いずれも設定 → 生成コード → 実行の1本の経路に載り、設定が既定のときの生成コードは Phase 4 と1文字も変わらない(ゴールデンテストで確認。スキーマは version 4 のまま)。次は 5d(G8–G10。`docs/REQUIREMENTS.md`)。 +- Phase 5c でデータの扱いが広がった(PR 5c。G6・G7)。グラフの種類(G7)は、段グラフ(`step`)、横棒(`barh`)、積み上げ棒(`barStacked`)、ヒストグラム(`hist`)、色分け散布図(`scatterColor`)が加わった。種類ごとの設定(段の付き方、区間の数と確率密度、カラーマップとカラーバーのラベル、系列の色分けの列)と、「計算した列」(G6。式で新しい列を作り、系列の X・Y・エラーバー・帯・色分けの列に選べる)も加わった。式は `py/mplgui/expr.py` が自前で解釈する(`eval` を使わない)。画面で隠した設定は図に使わない(種類ごとに使わない設定は値を残して検証しない。要件 §2.2)。いずれも設定 → 生成コード → 実行の1本の経路に載り、設定が既定のときの生成コードは Phase 4 と1文字も変わらない(ゴールデンテストで確認。スキーマは version 4 のまま)。グラフの種類 第2弾と任意関数のフィッティングは 5d で入った(次の項目)。 +- Phase 5d でグラフの種類と近似曲線が広がった(PR 5d。G8・G10。G9(サブプロット)は 5e に分けた)。グラフの種類 第2弾(G8)は、箱ひげ図(`box`)、バイオリン図(`violin`)、ヒートマップ(`heatmap`)が加わった。箱ひげ図・バイオリン図は系列ごとに1つの箱・胴を左から並べ(横軸は系列の名前。向きは縦だけ、凡例なし)、箱・胴の塗りは系列の色、外れ値の点と平均の印(箱)、中央値の線と平均の線(バイオリン)を切り替えられる。ヒートマップは X・Y・値の3列の縦長の表から格子を作り(同じ X・Y の組は平均、系列は1つ。画面の欄名は「値の列」)、カラーマップとカラーバーのラベルは色分け散布図と共有する。任意関数のフィッティング(G10)は、近似曲線のモデルに「任意の式」(変数 `x`、パラメータ `a`〜`e`、初期値の既定 1)が加わり、scipy の `curve_fit` で当てはめる。scipy は Pyodide 同梱のパッケージで、任意の式を使うときだけ初回に読み込む(約 14 MB。起動時には読み込まない)。式は `py/mplgui/expr.py` の `parse_model` が自前で解釈する(`eval` を使わない)。画面で隠した設定は図に使わない(種類ごとの規則は `js/chart-types.js` と `settings.py` の定数で揃える。要件 §2.2)。いずれも設定 → 生成コード → 実行の1本の経路に載り、設定が既定のときの生成コードは Phase 4 と1文字も変わらない(ゴールデンテストで確認。スキーマは version 4 のまま)。次は 5e(G9 サブプロット。`docs/REQUIREMENTS.md`・`docs/PHASE5_DESIGN.md` §7.5。詳しい設計は 5d のマージ後に相談する)。 ## 2. ファイル構成 @@ -28,8 +29,8 @@ | `pyscript.toml` | PyScript 設定(パッケージ、`packages_cache`、`[files]` による Python ファイルの配置) | | `css/style.css` | スタイル | | `js/main.js` | エントリ。UI を設定オブジェクトに結び付ける | -| `js/defaults.js` | 設定の既定値(`DEFAULT_SETTINGS`、`SCHEMA_VERSION` = 4)、UD カラーの色(`PALETTE`)。Phase 5b: `DEFAULT_SERIES` に `marker` / `alpha` / `fill`、`DEFAULT_ANNOTATION` / `DEFAULT_FIT`(要素 1 つの既定値)、`DEFAULT_SETTINGS` に `annotations: []` / `fits: []` Phase 5c: `DEFAULT_SERIES` に `colorColumn`、`DEFAULT_COMPUTED`、`DEFAULT_SETTINGS.plot` に `step` / `hist` / `colormap` / `colorbarLabel`、`computed: []`。 | -| `js/chart-types.js` | グラフの種類ごとに使う設定の規則(`PLOT_TYPES`、`usesSeriesX` / `usesGlobalX` / `usesMarker` / `usesFill` / `usesFits` / `usesXErrors` / `usesYErrors` / `usesY2` / `usesColorColumn` / `usesStep` / `usesHist`、`isLineLike` / `isScatterLike`)。純粋な ES module(DOM にも state にも触れない)。画面の出し分けはすべてここを見る。`settings.py` の `BAR_LIKE_TYPES` / `NO_Y2_TYPES` / `NO_Y_ERROR_TYPES` と揃えること | +| `js/defaults.js` | 設定の既定値(`DEFAULT_SETTINGS`、`SCHEMA_VERSION` = 4)、UD カラーの色(`PALETTE`)。Phase 5b: `DEFAULT_SERIES` に `marker` / `alpha` / `fill`、`DEFAULT_ANNOTATION` / `DEFAULT_FIT`(要素 1 つの既定値)、`DEFAULT_SETTINGS` に `annotations: []` / `fits: []` Phase 5c: `DEFAULT_SERIES` に `colorColumn`、`DEFAULT_COMPUTED`、`DEFAULT_SETTINGS.plot` に `step` / `hist` / `colormap` / `colorbarLabel`、`computed: []`。 Phase 5d: `DEFAULT_SETTINGS.plot` に `box: {fliers: true, means: false}` / `violin: {medians: true, means: false}`、`DEFAULT_FIT` に `expr: ""` / `initial: {a: 1, … e: 1}`。 | +| `js/chart-types.js` | グラフの種類ごとに使う設定の規則(`PLOT_TYPES`、`usesSeriesX` / `usesGlobalX` / `usesMarker` / `usesFill` / `usesFits` / `usesXErrors` / `usesYErrors` / `usesY2` / `usesColorColumn` / `usesStep` / `usesHist`、`isLineLike` / `isScatterLike`)。純粋な ES module(DOM にも state にも触れない)。画面の出し分けはすべてここを見る。`settings.py` の `XY_TYPES` / `BOX_TYPES` / `CATEGORY_BAR_TYPES` / `SERIES_X_TYPES` / `NO_Y2_TYPES` / `NO_Y_ERROR_TYPES` / `COLOR_COLUMN_TYPES` と揃えること(`test_chart_types.py` が node で比べる)。Phase 5d: `PLOT_TYPES` に `box` / `violin` / `heatmap`、`usesColormap`(色分け・ヒートマップ)、`usesBox` / `usesViolin` / `isBoxLike` / `isHeatmap`、`usesColor` / `usesLineWidth` / `usesLineStyle`(ヒートマップは色・線幅・線種を、箱ひげ・バイオリンは線種を使わない)が増え、`usesSeriesX` はヒートマップも、`usesColorColumn` はヒートマップ(値の列)も真、`usesMarker` / `usesFill` / `usesFits` / `usesXErrors` は XY の種類だけ、`usesY2` / `usesYErrors` は box / violin / heatmap で偽になった | | `js/computed-refs.js` | 計算した列の番号(ファイルの列数 + そのデータ元の中での位置)と、番号が変わったときの列の参照の付け替え(`computedIndex`、`remapReferences`、`removeComputedColumn`、`changeComputedSource`、`shiftForFileColumnChange`、`releaseComputedSources`。規則は §5)。参照は系列の x / y / 色分けの列 / エラーバーの列 / 帯の列と、系列1のデータ元の `plot.xColumn` | | `js/ui/computed.js` | 計算した列のカード(`#computedList`。`#addComputedBtn`)。カードは state の `computed` から描き、名前・式の入力中の欄は作り直さない(`syncComputed`。`addVisibilityHook` に登録)。雛形のボタン(正規化・オフセット・移動平均)と番号の表示。`renderComputedList`、`bindComputed` | | `js/units.js` | 図サイズの単位(`UNITS`、`UNIT_NAMES`、`UNIT_STEP`)と換算 `convertLength(value, from, to)`(mm を介し、to の単位で丸める: in 3 桁 / cm 2 桁 / mm 1 桁)。純粋な ES module | @@ -37,7 +38,7 @@ | `js/presets.js` | スタイルプリセット(`PRESETS`: standard / paper1 / paper2 / slide)、`planPreset`(適用内容を計算するだけ)、`newSeriesDefaults`(直前のプリセットを新しい系列へ)。名前は設定に入れない Phase 5c: 点サイズの規則に `isScatterLike`(`scatter` と `scatterColor`)を使う(`chart-types.js` を import)。 | | `js/code-state.js` | Pythonコードタブの状態(モード `sync` / `edit`、直近に生成したコードとその世代、「最新でない」印 `isCodeStale` / `setCodeStale`)。設定オブジェクトには入れない | | `js/state.js` | 設定オブジェクトの保持・更新・購読(`getSettings`、`setPath`、`updateSeries`、`addSeries`、`removeSeries`、`applyPalette`、`setFileSheet`、`setLastPreset` / `getLastPreset`、`subscribe`、`toJson`)。直近に適用したプリセットはセッション中だけここに持つ。Phase 5b: `moveSeries(id, delta)`、`duplicateSeries(id)`(全設定を写し、id と色(現在のパレットの未使用の色)だけ新しくして直後に入れる。近似曲線は写さない)、`removeSeries(id)`(その系列の近似曲線も消し、消した本数を返す。系列が1つだけ・見つからないときは -1)、`addAnnotation` / `updateAnnotation` / `removeAnnotation`、`addFit` / `updateFit` / `removeFit`。注釈と近似曲線の id は連番(`a1`…、`f1`…)で、削除しても再利用しない。通知の `kind` は `annotation-list` / `annotation-field` / `fit-list` / `fit-field`(一覧の変更とフィールドの変更)。`removeSeries` で近似曲線が消えたときは `series-list` に続けて `fit-list` を通知する Phase 5c: `addComputed` / `updateComputed` / `removeComputed`(id は `c1`…で再利用しない。上限 `MAX_COMPUTED` = 20。通知の `kind` は `computed-list` / `computed-field`)。`hasSecondaryAxis` は、第2Y軸を使わない種類(`chart-types.js` の `usesY2`)では偽。 | -| `js/bridge.js` | Python(`window.mplgui`)の唯一の窓口。読込・描画・保存・コピー(`makeClipboardImage`)・コードだけの更新(`script`)の制御、世代管理、日本語・欧文フォント取得の起動と待ち。読み込んだファイル(データN)ごとの状態(`File`・バイト列・貼り付けか・`loading` / `ready` / `error`・結果)を持ち、ファイルの追加・置き換え・削除(`selectFiles` / `selectFile` / `removeFile`)、読込の予約(`scheduleLoad`。ファイルごと)、最後のファイルを外したときの初期状態への復帰、コードの「最新でない」印を扱う。Phase 5b: `addNote(message)`(画面の操作の注意を、次の描画結果の警告に1度だけ添える。系列の削除で近似曲線が消えたとき、データ元の変更・列の消失で帯の列を戻したときに使う) Phase 5c: ファイルの削除・置き換えのとき、そのファイルをデータ元にしていた計算した列を先頭のファイルに戻す(`computed-refs.js` の `releaseComputedSources`。注意は `addNote` で添える)。 | +| `js/bridge.js` | Python(`window.mplgui`)の唯一の窓口。読込・描画・保存・コピー(`makeClipboardImage`)・コードだけの更新(`script`)の制御、世代管理、日本語・欧文フォント取得の起動と待ち。読み込んだファイル(データN)ごとの状態(`File`・バイト列・貼り付けか・`loading` / `ready` / `error`・結果)を持ち、ファイルの追加・置き換え・削除(`selectFiles` / `selectFile` / `removeFile`)、読込の予約(`scheduleLoad`。ファイルごと)、最後のファイルを外したときの初期状態への復帰、コードの「最新でない」印を扱う。Phase 5b: `addNote(message)`(画面の操作の注意を、次の描画結果の警告に1度だけ添える。系列の削除で近似曲線が消えたとき、データ元の変更・列の消失で帯の列を戻したときに使う) Phase 5c: ファイルの削除・置き換えのとき、そのファイルをデータ元にしていた計算した列を先頭のファイルに戻す(`computed-refs.js` の `releaseComputedSources`。注意は `addNote` で添える)。 Phase 5d: scipy の読み込み(`scipyState`(`idle` / `loading` / `ready` / `failed`。``)、`needsScipy(code)`、`ensureScipyFor(code)`。GUI 同期で任意の式の近似曲線があるとき、または編集モードのコードが `import scipy` / `from scipy` を持つときだけ、`render` / `save` / `copyImage` の前に `ensureScipy` を呼ぶ。`script` からは呼ばない。読み込み中は進捗バナーとステータスに「scipy を読み込み中…(初回のみ。約 14 MB)」)。最後のファイルを外したときの初期状態への復帰で `scipyState` を `idle` に戻す。 | | `js/startup-progress.js` | Python 起動中の段階表示。Resource Timing(`PerformanceObserver`、取得済みエントリを含む)から Pyodide 本体(`pyodide.asm.wasm`・`python_stdlib.zip`)→ パッケージ wheel(pandas / matplotlib)→ 初期化(`/py/main.py` の取得)を推定する | | `js/font-cache.js` | フォントの取得と Cache Storage への保存。種類(`japanese` / `arimo` / `tinos`)ごとの URL(`FONT_URLS`)、種類ごとに1セッション1回の取得、旧 OTF のキャッシュ削除 | | `js/ui/codeTab.js` | Pythonコードタブ(行番号、モード別のボタン、コピー、.py 保存、Ctrl/Cmd+Enter) | @@ -48,27 +49,27 @@ | `js/ui/dateFormat.js` | 軸・目盛区分の X 軸の日時の書式(`#xDateFormat` のプリセットと「任意」の `#xDateFormatCustom`)。値は `axes.x.dateFormat` に書く。表示の可否(`#xDateFormatGroup`)は `series.js` が決める | | `js/ui/axisTicks.js` | 軸・目盛区分の、目盛の入力欄・日時の範囲(`#xDateRangeGroup`)・枠線の表示と無効の切り替え(`syncAxisTicks(xKind)`)。軸の種類(`number` / `log` / `datetime` / `category`)は渡された `xKind`(`series.js` の `xAxisKind`)と、Y / 第2Y のスケールで決める。値は消さない(隠すだけで、Python も使わない)。設定の値は `forms.js` が結ぶ Phase 5c: `syncAxisTicks(xKind, yKind)`(`yKind` は `series.js` の `yAxisKind()`。横棒の縦軸はカテゴリなので「何個おき」を出し、対数でない)。 | | `js/ui/annotations.js` | 注釈のカード(`#annotationList`。`#addAnnotationBtn`)。カードは state の `annotations` から描き、種類ごとに使う入力欄だけを出す(`SHOWN`。Python の使う項目と同じ規則)。X の入力欄の例・補足は軸の種類(`series.js` の `xAxisKind`)で変える(数値 / 日時 / 文字列は何番目か)。`syncAnnotations`(入力中の欄を作り直さずに表示を同期する。`addVisibilityHook` に登録)、`renderAnnotationList`、`bindAnnotations` Phase 5c: Y の例・補足を `yAxisKind()` で変える(横棒の縦軸は何番目のカテゴリか)。 | -| `js/ui/fits.js` | 近似曲線のカード(`#fitList`。`#addFitBtn`)。系列の選択肢は `seriesDisplayName` で作り、系列の追加・削除・並べ替え・名前の変更に追従する。線の色は「系列の色」か「色を選ぶ」(`colorPickerHtml`)。棒グラフでは一覧と追加ボタンを隠して `#fitBarNote` を出す。`syncFits`(`addVisibilityHook` に登録。追加ボタンの上限による無効化も、注釈の分とあわせてここで行う)、`renderFitList`、`bindFits` Phase 5c: 近似曲線を使わない種類は `chart-types.js` の `usesFits` で決める(棒グラフ・横棒・積み上げ・hist は一覧と追加ボタンを隠し、`#fitBarNote` は「棒グラフ・ヒストグラムでは近似曲線を使えません。」)。 | +| `js/ui/fits.js` | 近似曲線のカード(`#fitList`。`#addFitBtn`)。系列の選択肢は `seriesDisplayName` で作り、系列の追加・削除・並べ替え・名前の変更に追従する。線の色は「系列の色」か「色を選ぶ」(`colorPickerHtml`)。棒グラフでは一覧と追加ボタンを隠して `#fitBarNote` を出す。`syncFits`(`addVisibilityHook` に登録。追加ボタンの上限による無効化も、注釈の分とあわせてここで行う)、`renderFitList`、`bindFits` Phase 5c: 近似曲線を使わない種類は `chart-types.js` の `usesFits` で決める(棒グラフ・横棒・積み上げ・hist は一覧と追加ボタンを隠し、`#fitBarNote` は「棒グラフ・ヒストグラムでは近似曲線を使えません。」)。 Phase 5d: 近似のモデルに「任意の式」(`custom`)を足した(式 `fit--expr`・補足 `-expr-help`・初期値 `-initial-a`〜`-initial-e`。`usedParams(expr)` が式の中の単独の a〜e だけを数えて、使うパラメータの初期値だけ出す)。近似曲線を使わない種類は箱ひげ・バイオリン・ヒートマップも(`#fitBarNote` は「棒グラフ・ヒストグラム・箱ひげ図・バイオリン図・ヒートマップでは近似曲線を使えません。」)。 | | `js/ui/panelSections.js` | 設定パネルの区分(`details.panel-section`)の折りたたみ。状態は localStorage(キー `mplgui.panelSections`、`{区分の id: 開いているか}`)だけに持ち、設定オブジェクトには入れない。localStorage が使えなくても動く(すべて開く) | | `js/ui/styleSection.js` | 体裁区分: プリセットの「適用」、カラーパレット、図サイズの単位切替(数値を換算し、ラベルと step を単位に合わせる) | | `js/ui/saveSection.js` | 保存区分: DPI(72 / 150 / 300 / 600 のセレクトと「任意」の入力欄)。値は `save.dpi`(数値)に書く | | `js/ui/clipboard.js` | 「クリップボードにコピー」。`` を更新する | -| `js/ui/*.js`(上記以外) | 画面部品(`colorPicker`、`dataPreview`(先頭100行、前置き行の枠、日時の列の印)、`fileInfo`(選択中のファイル名と文字コードの表示)、`forms`、`notify`、`plotView`(画像と `data-summary`)、`progress`、`saveFormat`(形式に応じた透過の可否と、SVG の文字・PDF の説明の出し分け)、`series`(系列カード。複数ファイルのときはデータ元の選択と、データ元ごとの列の選択肢。X の日時の列の有無)、`tabs`)。Phase 5a で `series`: 系列カードに折りたためる「エラーバー」(`.series-errorbars`。Y 方向・X 方向のブロックと端の長さ。開閉は系列 id ごとにセッション中だけ覚える)、`xAxisKind`(X 軸の種類を、列の `kind` / `numericLike` から Python と同じ規則で決める。export)、データ元を替えたとき誤差の列を空に戻す。`forms`: 目盛・日時の範囲・枠線の入力欄を `FIELDS` に足した Phase 5b で `series`: 点の形・不透明度・塗りつぶし帯(`.series-fill`。開閉は系列 id ごとにセッション中だけ覚える)・↑ ↓・複製のコントロール、`seriesDisplayName(series)`(凡例名、無ければ Y 列の表示。export)、`addVisibilityHook(fn)`(`syncVisibility` の最後に呼ぶ関数を足す。注釈・近似曲線の同期を、循環 import なしで登録する)、データ元を替えたときと、列が無くなったとき(`reconcileColumns`)に帯の列を空に戻して `addNote` で知らせる。`colorPicker`: `colorPickerHtml(idBase, color, extraClass)`(系列以外のカードでも色の選択を使う)、色のパネルを閉じる処理を系列一覧だけでなくページ全体に広げた Phase 5c で `series`: 種類ごとの欄の出し分け(`chart-types.js` を見る)、色分けの列(`series--color-column`)、`yAxisKind()`(export。横棒の縦軸の種類)、`fileColumnCount(id)`(export。データ元のファイルの列数)、`columnsOf`(ファイルの列 + 計算した列。選択肢を作る・検証する唯一の場所)、読み込み直しでファイルの列数が変わったとき `shiftForFileColumnChange` を `reconcileColumns` の前に呼ぶ。点の形・点サイズ・帯・X 方向のエラーバーは line / step / scatter / 色分けだけ、第2Y軸は `usesY2`、点サイズの自動は `isLineLike`(line / step)が 0。 | -| `py/main.py` | PyScript のエントリ。JS と `mplgui` の橋渡しだけを書く(`window.mplgui` の登録(`loadFile` / `removeSource` / `clearSources` / `render` / `save` / `copyImage` / `script` / `registerFont` など)、Excel 用ライブラリの遅延導入、作業フォルダ `api.SESSION.workdir` の設定) | -| `py/mplgui/settings.py` | 設定スキーマ(version 4)、既定値、検証、日本語エラー(凍結 dataclass へ変換。`FileEntry`、読込設定の検証、`axes.x.dateFormat`、目盛・枠線・日時の範囲・エラーバー)、`migrate_settings`(v1 → v2 → v3 → v4)。Phase 5b: 系列の `marker` / `alpha` / `fill`(`FillSettings`)、`AnnotationSettings` / `FitSettings`(`Settings.annotations` / `fits`)、`default_annotation()` / `default_fit()`(JS の既定値と `test_defaults_parity.py` で比べる)、`_parse_fill` / `_parse_annotations` / `_parse_fits`。定数 `MAX_ANNOTATIONS`(50)・`MAX_FITS`(20)。`_number` / `_choice` に `field_name` を足した(`field` を表示名と別にできる) Phase 5c: `PLOT_TYPES` に `step` / `barh` / `barStacked` / `hist` / `scatterColor`、種類ごとの規則の定数(`BAR_LIKE_TYPES` / `NO_Y2_TYPES` / `NO_Y_ERROR_TYPES`、`STEP_WHERE_CHOICES`、`COLORMAPS`、`MAX_HIST_BINS`)、`PlotSettings` の `step_where` / `hist_bins` / `hist_density` / `colormap` / `colorbar_label`、`SeriesSettings.color_column`(`_parse_color_column`)、`ComputedSettings`(`expr_node` に解釈済みの式)と `_parse_computed` / `default_computed()`、`MAX_COMPUTED`(20)。`_parse_axis` に `linear`(横棒の縦軸)、`effective_marker_size` は step を line と、scatterColor を scatter と同じに扱う。 | +| `js/ui/*.js`(上記以外) | 画面部品(`colorPicker`、`dataPreview`(先頭100行、前置き行の枠、日時の列の印)、`fileInfo`(選択中のファイル名と文字コードの表示)、`forms`、`notify`、`plotView`(画像と `data-summary`)、`progress`、`saveFormat`(形式に応じた透過の可否と、SVG の文字・PDF の説明の出し分け)、`series`(系列カード。複数ファイルのときはデータ元の選択と、データ元ごとの列の選択肢。X の日時の列の有無)、`tabs`)。Phase 5a で `series`: 系列カードに折りたためる「エラーバー」(`.series-errorbars`。Y 方向・X 方向のブロックと端の長さ。開閉は系列 id ごとにセッション中だけ覚える)、`xAxisKind`(X 軸の種類を、列の `kind` / `numericLike` から Python と同じ規則で決める。export)、データ元を替えたとき誤差の列を空に戻す。`forms`: 目盛・日時の範囲・枠線の入力欄を `FIELDS` に足した Phase 5b で `series`: 点の形・不透明度・塗りつぶし帯(`.series-fill`。開閉は系列 id ごとにセッション中だけ覚える)・↑ ↓・複製のコントロール、`seriesDisplayName(series)`(凡例名、無ければ Y 列の表示。export)、`addVisibilityHook(fn)`(`syncVisibility` の最後に呼ぶ関数を足す。注釈・近似曲線の同期を、循環 import なしで登録する)、データ元を替えたときと、列が無くなったとき(`reconcileColumns`)に帯の列を空に戻して `addNote` で知らせる。`colorPicker`: `colorPickerHtml(idBase, color, extraClass)`(系列以外のカードでも色の選択を使う)、色のパネルを閉じる処理を系列一覧だけでなくページ全体に広げた Phase 5c で `series`: 種類ごとの欄の出し分け(`chart-types.js` を見る)、色分けの列(`series--color-column`)、`yAxisKind()`(export。横棒の縦軸の種類)、`fileColumnCount(id)`(export。データ元のファイルの列数)、`columnsOf`(ファイルの列 + 計算した列。選択肢を作る・検証する唯一の場所)、読み込み直しでファイルの列数が変わったとき `shiftForFileColumnChange` を `reconcileColumns` の前に呼ぶ。点の形・点サイズ・帯・X 方向のエラーバーは line / step / scatter / 色分けだけ、第2Y軸は `usesY2`、点サイズの自動は `isLineLike`(line / step)が 0。 Phase 5d で `series`: 種類ごとの欄の出し分けに box / violin / heatmap を足した(`#boxGroup` / `#violinGroup` / `#colorMapGroup`(ヒートマップでも出す)/ `#xScaleGroup`(箱ひげ・バイオリン、X が文字列のヒートマップで隠す)/ `#yScaleGroup`(横棒、Y が文字列のヒートマップで隠す)、系列カードの `.series-color-wrap` / `.series-line-width-wrap` / `.series-line-style-wrap`、ヒートマップでは色分けの列のラベル(`.series-color-column-label`)を「値の列」にする)。`xAxisKind()` は箱ひげ・バイオリンでカテゴリ、ヒートマップは X が文字列の列ならカテゴリ。`yAxisKind()` はヒートマップの Y が文字列の列ならカテゴリ。`forms` に `#boxFliers` / `#boxMeans` / `#violinMedians` / `#violinMeans`(`plot.box.*` / `plot.violin.*`)を足した。 | +| `py/main.py` | PyScript のエントリ。JS と `mplgui` の橋渡しだけを書く(`window.mplgui` の登録(`loadFile` / `removeSource` / `clearSources` / `render` / `save` / `copyImage` / `script` / `registerFont` など)、Excel 用ライブラリの遅延導入、作業フォルダ `api.SESSION.workdir` の設定) Phase 5d: `ensureScipy`(`_ensure_scipy`。`importlib.util.find_spec` で入っていれば何もしない。無ければ `pyodide_js.loadPackage(to_js(["scipy"]))` を1つの task で共有し、失敗したら次回は再試行する。失敗は `field` が「近似曲線」の `UserError` の JSON)を `window.mplgui` に足した。 | +| `py/mplgui/settings.py` | 設定スキーマ(version 4)、既定値、検証、日本語エラー(凍結 dataclass へ変換。`FileEntry`、読込設定の検証、`axes.x.dateFormat`、目盛・枠線・日時の範囲・エラーバー)、`migrate_settings`(v1 → v2 → v3 → v4)。Phase 5b: 系列の `marker` / `alpha` / `fill`(`FillSettings`)、`AnnotationSettings` / `FitSettings`(`Settings.annotations` / `fits`)、`default_annotation()` / `default_fit()`(JS の既定値と `test_defaults_parity.py` で比べる)、`_parse_fill` / `_parse_annotations` / `_parse_fits`。定数 `MAX_ANNOTATIONS`(50)・`MAX_FITS`(20)。`_number` / `_choice` に `field_name` を足した(`field` を表示名と別にできる) Phase 5c: `PLOT_TYPES` に `step` / `barh` / `barStacked` / `hist` / `scatterColor`、種類ごとの規則の定数(`BAR_LIKE_TYPES` / `NO_Y2_TYPES` / `NO_Y_ERROR_TYPES`、`STEP_WHERE_CHOICES`、`COLORMAPS`、`MAX_HIST_BINS`)、`PlotSettings` の `step_where` / `hist_bins` / `hist_density` / `colormap` / `colorbar_label`、`SeriesSettings.color_column`(`_parse_color_column`)、`ComputedSettings`(`expr_node` に解釈済みの式)と `_parse_computed` / `default_computed()`、`MAX_COMPUTED`(20)。`_parse_axis` に `linear`(横棒の縦軸)、`effective_marker_size` は step を line と、scatterColor を scatter と同じに扱う。 Phase 5d: `PLOT_TYPES` に `box` / `violin` / `heatmap`、種類ごとの規則の定数を `XY_TYPES` / `BOX_TYPES` / `CATEGORY_BAR_TYPES` / `SERIES_X_TYPES` / `NO_Y2_TYPES` / `NO_Y_ERROR_TYPES` / `COLOR_COLUMN_TYPES` に分け(5c の `BAR_LIKE_TYPES` は廃止。`js/chart-types.js` と揃える)、`HEATMAP_SERIES_MESSAGE`・`MAX_HEATMAP_SIZE`(500)、`PlotSettings` の `box_fliers` / `box_means` / `violin_medians` / `violin_means`、`FIT_MODELS` に `custom`、`FitSettings` の `expr` / `expr_node` / `params` / `initial`(`_parse_fits` が `expr.parse_model` で検証)、`_parse_color_column` の `what`(ヒートマップは「値の列」)、`_parse_axis(linear=)` を箱ひげ・バイオリンの X にも使う。 | | `py/mplgui/loader.py` | バイト列から DataFrame(文字コード判定、区切り文字、読込設定(`skip_lines` / `thousands` / `decimal` / `comment`)、xlsx のシート、日時の列の認識、プレビューと前置き行)。読込結果に `SourceInfo`(ファイル名、種別(csv / txt / tsv / xlsx)、文字コード、区切り文字、ヘッダの有無、読込設定、シート名とシート一覧、日時に変換した列 `datetime_columns`、貼り付けたデータか `pasted`)を付ける。`SourceInfo.read_kwargs()` が `pd.read_csv` / `pd.read_excel` の引数の唯一の定義で、loader と codegen が共有する。`split_lines`(pandas と同じく `\r` / `\n` / `\r\n` だけで行を分ける)、`detect_datetime_columns` / `convert_datetime` / `apply_datetime_columns`、`open_excel`(`pd.ExcelFile`)も持つ。Phase 5a: `columns[].numericLike`(`looks_numeric`: 文字列の列でも空欄以外の半数以上が数値に読めるか)を足した。`looks_numeric` / `is_blank_cell` は dataprep と共有する(X が文字列の列かの判定が画面と Python で一致する) | -| `py/mplgui/dataprep.py` | DataFrame(または `{ファイル id: DataFrame}`)を見て決める処理。`plan_plot` が描画計画 `PlotPlan` を作る(データ元ごとの `skipRows` と Y 列の自動割り当て、X の数値変換・日時・文字列の別、描ける点の有無、A7 の警告(桁区切り・小数点のヒント付き)、日時の X の検査、データ由来の日本語 `UserError`)。描画に使うデータ元は `PlotPlan.sources`(`PlanSource`: id・番号・変数名・ファイル名)と `SeriesPlan.data_id` / `data_var` に持つ。Phase 5a: `AxisPlan` / `AxesPlan`(軸ごとに効く目盛の設定だけ。軸の種類・主目盛の間隔・副目盛・書式・反転・日時の範囲)を `PlotPlan.axes` に持つ。`ErrorPlan`(`SeriesPlan.y_err` / `x_err`、`cap_size`)。目盛の本数の見積もり(`MAX_MAJOR_TICKS` = 100。超えると日本語の `UserError`)。X の数値の範囲の検査(`settings.check_axis_range`)は、X が日時でないときだけここで行う(日時のときは `validate_date_range`)。Phase 5b: `FillPlan`(`SeriesPlan.fill`。帯の列番号・コメント用の列の表示・不透明度)、`SeriesPlan.marker` / `alpha`(`_marker_plan` が点の形と点サイズを決める)、`AnnotationPlan`(`PlotPlan.annotations`。位置を軸の種類で解釈した値。`_plan_annotations`)、`FitPlan`(`PlotPlan.fits`。`_build_fit_plans`、データの検査 `_check_fit_data`)。注釈の位置と帯の端の値は `_Extents` に足し、主目盛の本数の見積もりに含める Phase 5c: `HistPlan`(区間の数・確率密度・度数の最大。`_plan_hist`)、`ColorbarPlan`(`PlotPlan.hist` / `colorbar`)、`SeriesPlan.color_index` / `color_label`(`_color_column` / `_color_values`)、`ComputedPlan`(`PlotPlan.computed`。`_apply_computed`)。棒の計画(`_plan_bars`)は bar / barh / barStacked を扱い(積み上げの高さを範囲に含める。横棒は軸を入れ替える)、`_plan_axes` / `_plan_annotations` に `y_kind`(横棒の縦軸は category)を足した。`plan_plot` は、`skipRows` を除いたデータ元に計算した列を足してから系列の計画を作る(Y の自動割り当てはファイルの列だけを見る)。 | -| `py/mplgui/expr.py` | 計算した列(G6)の式の解釈・評価・コード生成。標準ライブラリ・numpy・pandas だけに依存する純粋なモジュール。`eval` / `exec` / `compile` / `ast` を使わず、自前の字句解析と再帰下降の構文解析(`parse`、誤りは位置付きの `ExprError`)。`evaluate`(値と計算できなかった行数)と `to_code`(同じ意味の pandas / numpy の式)は意味を揃える。定数の畳み込み、`column_refs` / `column_indices` / `is_series`(§4.1) | -| `py/mplgui/codegen.py` | 設定・`SourceInfo`(または `{ファイル id: SourceInfo}`)・`PlotPlan` から matplotlib スクリプトを生成する(`generate_script`)。純粋な関数。Phase 5a: 目盛・反転・日時の範囲は軸ごとの関数(`_axis_blocks` が Axes の変数名 `ax` / `ax2` を持つ `_AxisBlock` を作り、`_axis_tick_lines` などが変数名を引数で受ける)。枠線は `_emit_spines`。エラーバーは `draw_error_bars` の定義(使うときだけ冒頭に書く)と `_emit_line_error_bars`、棒グラフは `ax.bar` の `yerr`。Phase 5b: セクション番号の自動採番(`_Builder.section(title)` が呼んだ順に振る)、`_emit_annotations`(「注釈」節)、`_emit_band`、点の形・不透明度(`_alpha_arg`)、`_emit_fits` と `POLY_TEXT_FUNCTION`(`poly_text`)、凡例を出すかの判定に注釈の凡例名と近似曲線を含めた、手順(`Step`)に「系列Nの塗りつぶし帯」「注釈N」「近似曲線N」を足した Phase 5c: `XY_TYPES`(line / step / scatter / scatterColor)、`SERIES_EMITTERS` に step(`_emit_line_series` + `drawstyle`)/ barh(`_emit_bar_series` を向きつきに)/ `_emit_stacked_series` / `_emit_hist_series` / `_emit_scatter_color_series`、「計算した列」の節 `_emit_computed`(`expr.to_code` を使う)、`_positions_form`、`_scale`(横棒の縦軸は linear)、`_emit_band` の `step` 引数。 | +| `py/mplgui/dataprep.py` | DataFrame(または `{ファイル id: DataFrame}`)を見て決める処理。`plan_plot` が描画計画 `PlotPlan` を作る(データ元ごとの `skipRows` と Y 列の自動割り当て、X の数値変換・日時・文字列の別、描ける点の有無、A7 の警告(桁区切り・小数点のヒント付き)、日時の X の検査、データ由来の日本語 `UserError`)。描画に使うデータ元は `PlotPlan.sources`(`PlanSource`: id・番号・変数名・ファイル名)と `SeriesPlan.data_id` / `data_var` に持つ。Phase 5a: `AxisPlan` / `AxesPlan`(軸ごとに効く目盛の設定だけ。軸の種類・主目盛の間隔・副目盛・書式・反転・日時の範囲)を `PlotPlan.axes` に持つ。`ErrorPlan`(`SeriesPlan.y_err` / `x_err`、`cap_size`)。目盛の本数の見積もり(`MAX_MAJOR_TICKS` = 100。超えると日本語の `UserError`)。X の数値の範囲の検査(`settings.check_axis_range`)は、X が日時でないときだけここで行う(日時のときは `validate_date_range`)。Phase 5b: `FillPlan`(`SeriesPlan.fill`。帯の列番号・コメント用の列の表示・不透明度)、`SeriesPlan.marker` / `alpha`(`_marker_plan` が点の形と点サイズを決める)、`AnnotationPlan`(`PlotPlan.annotations`。位置を軸の種類で解釈した値。`_plan_annotations`)、`FitPlan`(`PlotPlan.fits`。`_build_fit_plans`、データの検査 `_check_fit_data`)。注釈の位置と帯の端の値は `_Extents` に足し、主目盛の本数の見積もりに含める Phase 5c: `HistPlan`(区間の数・確率密度・度数の最大。`_plan_hist`)、`ColorbarPlan`(`PlotPlan.hist` / `colorbar`)、`SeriesPlan.color_index` / `color_label`(`_color_column` / `_color_values`)、`ComputedPlan`(`PlotPlan.computed`。`_apply_computed`)。棒の計画(`_plan_bars`)は bar / barh / barStacked を扱い(積み上げの高さを範囲に含める。横棒は軸を入れ替える)、`_plan_axes` / `_plan_annotations` に `y_kind`(横棒の縦軸は category)を足した。`plan_plot` は、`skipRows` を除いたデータ元に計算した列を足してから系列の計画を作る(Y の自動割り当てはファイルの列だけを見る)。 Phase 5d: `HeatmapPlan`(`PlotPlan.heatmap`。X・Y が文字列の列か・Y を数値に変換するか・X・Y の異なる値の数・重複の件数。`_plan_heatmap`)、`_plan_box`(箱ひげ・バイオリン。系列ごとの Y 列の有限の値だけで描けるかを決める。`SeriesPlan.has_points`)、`FitPlan` に `model` / `expr` / `node` / `params` / `p0`(任意の式。点の数の検査はパラメータの数 + 1 個)、`ColorbarPlan` はヒートマップでも作る(`SeriesPlan.color_index` / `color_label` は値の列)。`plan_plot` は、ヒートマップで系列が2つ以上のとき系列ごとの検証より先にエラーにする。`_plan_axes` に `y_categories`(ヒートマップの Y のカテゴリ数)を足した。 | +| `py/mplgui/expr.py` | 計算した列(G6)の式の解釈・評価・コード生成。標準ライブラリ・numpy・pandas だけに依存する純粋なモジュール。`eval` / `exec` / `compile` / `ast` を使わず、自前の字句解析と再帰下降の構文解析(`parse`、誤りは位置付きの `ExprError`)。`evaluate`(値と計算できなかった行数)と `to_code`(同じ意味の pandas / numpy の式)は意味を揃える。定数の畳み込み、`column_refs` / `column_indices` / `is_series`(§4.1) Phase 5d: 近似の式(G10)の入口 `parse_model`(変数 `x`、パラメータ `a`〜`e`(`MODEL_VARIABLE` / `MODEL_PARAMS`)、`Var` ノード。列・集計・系列の処理・知らない名前は日本語の `ExprError`。`x` と、パラメータ1つ以上が必須)、`model_params`(使ったパラメータ。a〜e の順)、`model_to_code`(numpy の式)、`model_to_text`(図のラベル用の整えた式)、`evaluate_model`(`model_to_code` と同じ意味)。 | +| `py/mplgui/codegen.py` | 設定・`SourceInfo`(または `{ファイル id: SourceInfo}`)・`PlotPlan` から matplotlib スクリプトを生成する(`generate_script`)。純粋な関数。Phase 5a: 目盛・反転・日時の範囲は軸ごとの関数(`_axis_blocks` が Axes の変数名 `ax` / `ax2` を持つ `_AxisBlock` を作り、`_axis_tick_lines` などが変数名を引数で受ける)。枠線は `_emit_spines`。エラーバーは `draw_error_bars` の定義(使うときだけ冒頭に書く)と `_emit_line_error_bars`、棒グラフは `ax.bar` の `yerr`。Phase 5b: セクション番号の自動採番(`_Builder.section(title)` が呼んだ順に振る)、`_emit_annotations`(「注釈」節)、`_emit_band`、点の形・不透明度(`_alpha_arg`)、`_emit_fits` と `POLY_TEXT_FUNCTION`(`poly_text`)、凡例を出すかの判定に注釈の凡例名と近似曲線を含めた、手順(`Step`)に「系列Nの塗りつぶし帯」「注釈N」「近似曲線N」を足した Phase 5c: `XY_TYPES`(line / step / scatter / scatterColor)、`SERIES_EMITTERS` に step(`_emit_line_series` + `drawstyle`)/ barh(`_emit_bar_series` を向きつきに)/ `_emit_stacked_series` / `_emit_hist_series` / `_emit_scatter_color_series`、「計算した列」の節 `_emit_computed`(`expr.to_code` を使う)、`_positions_form`、`_scale`(横棒の縦軸は linear)、`_emit_band` の `step` 引数。 Phase 5d: `BOX_TYPES` / `NO_SERIES_LEGEND_TYPES`(box / violin / heatmap は系列を凡例に出さない)、`SERIES_EMITTERS` に `_emit_box_series`(box / violin)/ `_emit_heatmap_series`、`_emit_heatmap_ticks`、`_emit_custom_fit`(`curve_fit` と有限の確認)、`_custom_label_expr`、`_uses_custom_fit`(任意の式の近似曲線があるときだけ冒頭に `from scipy.optimize import curve_fit` と「必要なライブラリ」への scipy の追記)。 | | `py/mplgui/formats.py` | 保存形式の表(`FORMATS`)、保存解像度の既定値(`DEFAULT_SAVE_DPI` = 300。実際の値は `save.dpi`)、`build_filename`、`savefig_kwargs`、形式ごとの rcParams(`savefig_rc`)、PNG / JPG の画素数の上限(`MAX_RASTER_PIXELS`、`MAX_RASTER_SIDE`、`raster_pixels`、`check_raster_size`)。runner と codegen が共有する | -| `py/mplgui/runner.py` | スクリプトの実行(`run_script` / `run_to_image`)、Figure → 画像(PNG/JPG/SVG/PDF。`savefig_rc` を `rc_context` で適用、画素数の検査)、図の要約(`figure_summary`)、実行時エラーの整形、数式の誤りの判定(`is_mathtext_error`、`MathtextError`)。`figure_summary` に、`yticklabels` / `xinverted` / `yinverted` / `spines` / `xmajor` / `ymajor` / `xminor` / `yminor` / `xformatter` / `yformatter` / `yoffset`(軸の端の ×10^n)/ `errorbars`(エラーバーの本数)を足した。Phase 5b: `figure_summary` に `bands` / `markers` / `alphas` / `annotations`(`texts` / `hlines` / `vlines` / `hspans` / `vspans`)/ `fitlines` / `fittexts` を足した(`_style_summary`。§4) Phase 5c: `figure_summary` に `drawstyles` / `bars` / `colorbar` を足し、カラーバーの Axes を軸の一覧から除く(§4)。 | +| `py/mplgui/runner.py` | スクリプトの実行(`run_script` / `run_to_image`)、Figure → 画像(PNG/JPG/SVG/PDF。`savefig_rc` を `rc_context` で適用、画素数の検査)、図の要約(`figure_summary`)、実行時エラーの整形、数式の誤りの判定(`is_mathtext_error`、`MathtextError`)。`figure_summary` に、`yticklabels` / `xinverted` / `yinverted` / `spines` / `xmajor` / `ymajor` / `xminor` / `yminor` / `xformatter` / `yformatter` / `yoffset`(軸の端の ×10^n)/ `errorbars`(エラーバーの本数)を足した。Phase 5b: `figure_summary` に `bands` / `markers` / `alphas` / `annotations`(`texts` / `hlines` / `vlines` / `hspans` / `vspans`)/ `fitlines` / `fittexts` を足した(`_style_summary`。§4) Phase 5c: `figure_summary` に `drawstyles` / `bars` / `colorbar` を足し、カラーバーの Axes を軸の一覧から除く(§4)。 Phase 5d: `figure_summary` に `boxes` / `violins` / `meshes` を足し、箱ひげ図の線(ラベル `_box`)を `markers` / `alphas` / `drawstyles` から除く(§4)。実行時の ImportError / ModuleNotFoundError の案内に「scipy は任意の式の近似曲線でも使えます」を足した。 | | `py/mplgui/fonts.py` | フォントの登録と rcParams。日本語の一覧 `SANS_SERIF_PRIORITY`(先頭は Noto Sans JP)と、欧文フォントの表 `LATIN_FONTS`(Arimo / Tinos の表示名・候補名・mathtext フォントセット)が唯一の定義で、生成スクリプトもこれを使う。`register_font_bytes(data, kind=)` は種類(`japanese` / `arimo` / `tinos`)ごとに1回だけ登録する | | `py/mplgui/errors.py` | `UserError`(利用者が直せるエラー) | -| `py/mplgui/api.py` | JS から呼ばれる JSON 入出力の関数(`render_json` / `save_json` / `copy_image_json` / `script_json` など)。読込済みデータ(`SESSION`。ファイル id ごとの `LoadedSource`(`df`・`SourceInfo`・書き出したファイル)と、xlsx の `ExcelFile` のキャッシュ(同じバイト列の間だけ)。`remove_source_json` / `clear_sources_json` も持つ)と、アップロードしたファイルの作業フォルダへの書き出しを持つ Phase 5c: `_run` は、計算した列があるデータ元の DataFrame をコピーして注入する(生成コードの `df.insert` が読込済みのデータを書き換えない)。 | +| `py/mplgui/api.py` | JS から呼ばれる JSON 入出力の関数(`render_json` / `save_json` / `copy_image_json` / `script_json` など)。読込済みデータ(`SESSION`。ファイル id ごとの `LoadedSource`(`df`・`SourceInfo`・書き出したファイル)と、xlsx の `ExcelFile` のキャッシュ(同じバイト列の間だけ)。`remove_source_json` / `clear_sources_json` も持つ)と、アップロードしたファイルの作業フォルダへの書き出しを持つ Phase 5c: `_run` は、計算した列があるデータ元の DataFrame をコピーして注入する(生成コードの `df.insert` が読込済みのデータを書き換えない)。 Phase 5d: `_require_scipy(plan)`(任意の式の近似曲線があるのに scipy が無いとき、`render` / `save` / `copyImage` が日本語の `UserError`(`field` は「近似曲線N」)を返す。ブラウザでは JS が先に `ensureScipy` を呼ぶ)。 | | `py/mplgui/runtime.py` | 警告フィルタ(起動時) | -| `tests/unit/` | 単体テスト(CPython、Agg)。`test_js_modules.py` は node で純粋な JS モジュール(units / palettes / presets / state)を検査する。Phase 5b: `test_series_style.py`・`test_annotations.py`・`test_fits.py`、共通の補助 `style_helpers.py` が増えた Phase 5c: `test_expr.py`・`test_chart_types.py`・`test_computed.py` が増えた。 | -| `tests/e2e/` | E2E テスト(pytest-playwright、Chromium)。`run_script_summary.py` は、生成スクリプトを CPython で実行して図の要約を出す補助(一致確認用)。Phase 5a: `test_ticks.py`・`test_errorbars.py`・`test_codegen_consistency.py` が増えた。Phase 5b: `test_series_style.py`・`test_annotations.py`・`test_fits.py` が増えた Phase 5c: `test_chart_types.py`・`test_computed.py` が増えた。 | -| `tests/fixtures/` | 合成テストデータ(`make_fixtures.py` が生成。説明は `README.md`。Phase 4 で `preamble` / `european` / `thousands` / `comments` / `datetime` / `datetime_iso_tz` / `dates_ja` などを追加)。Phase 5a で `errorbars.csv`(エラーバー用)を追加 Phase 5b で `band.csv`(帯・近似曲線・注釈用)を追加 Phase 5c で `chart_types.csv`(グラフの種類・計算した列用。category / a / b / c / err / m の 6 列 12 行)を追加。 | +| `tests/unit/` | 単体テスト(CPython、Agg)。`test_js_modules.py` は node で純粋な JS モジュール(units / palettes / presets / state)を検査する。Phase 5b: `test_series_style.py`・`test_annotations.py`・`test_fits.py`、共通の補助 `style_helpers.py` が増えた Phase 5c: `test_expr.py`・`test_chart_types.py`・`test_computed.py` が増えた。 Phase 5d: `test_expr.py`(モデルの式の分)・`test_chart_types.py`(box / violin / heatmap)・`test_fits.py`(任意の式。scipy が要る)が増えた。 | +| `tests/e2e/` | E2E テスト(pytest-playwright、Chromium)。`run_script_summary.py` は、生成スクリプトを CPython で実行して図の要約を出す補助(一致確認用)。Phase 5a: `test_ticks.py`・`test_errorbars.py`・`test_codegen_consistency.py` が増えた。Phase 5b: `test_series_style.py`・`test_annotations.py`・`test_fits.py` が増えた Phase 5c: `test_chart_types.py`・`test_computed.py` が増えた。 Phase 5d: `test_chart_types.py`・`test_custom_fit.py` が増えた。`test_custom_fit.py` と `test_codegen_consistency.py` の `fit_custom` は scipy を実際に取得する(インターネット接続が必要)。 | +| `tests/fixtures/` | 合成テストデータ(`make_fixtures.py` が生成。説明は `README.md`。Phase 4 で `preamble` / `european` / `thousands` / `comments` / `datetime` / `datetime_iso_tz` / `dates_ja` などを追加)。Phase 5a で `errorbars.csv`(エラーバー用)を追加 Phase 5b で `band.csv`(帯・近似曲線・注釈用)を追加 Phase 5c で `chart_types.csv`(グラフの種類・計算した列用。category / a / b / c / err / m の 6 列 12 行)を追加。 Phase 5d で `grid.csv`(ヒートマップ用。縦長の格子の表で、x(0〜3)/ y(0〜2)/ z(値)/ xname(文字列 A〜D)/ yname(文字列 P〜R)の 5 列 12 行)を追加。 | | `tests/unit/golden/`、`tests/unit/golden_cases.py` | Phase 4 のコードで生成した既定の設定の出力(`*.py.txt`)と、その構成の定義。`test_codegen_compat.py` が、既定の設定の生成コードが Phase 4 と1文字も変わらないことを確かめる(line / scatter / bar / 対数 / 日時 / 文字列の X / 2ファイル) | | `tests/perf/bench.py` | 起動・描画の計測。結果は `docs/PERFORMANCE.md` | | `.github/workflows/tests.yml` | CI | @@ -107,9 +108,15 @@ - Phase 5c で足した項目と既定値(スキーマは version 4 のまま。新しい項目は既定値で補われ、既定の設定の生成コードは Phase 4 と1文字も変わらない。JS の `DEFAULT_SERIES` / `DEFAULT_COMPUTED` と Python の `default_settings()` / `default_computed()` は一致させる): - `plot.type`: 選択肢に `step` / `barh` / `barStacked` / `hist` / `scatterColor` を足した(`line` / `scatter` / `bar` はそのまま)。`plot.step`(`{where: "post"}`。`pre` / `mid` / `post`。誤りは「段の付き方」)、`plot.hist`(`{bins: null, density: false}`。`bins` は null(自動。numpy の `"auto"`)か 1〜1000 の整数(`MAX_HIST_BINS`。誤りは「区間の数」)、`density` は真偽)、`plot.colormap`(`viridis`。`viridis` / `cividis` / `plasma` / `inferno` / `magma` / `coolwarm` / `RdBu_r` / `gray`。誤りは「カラーマップ」)、`plot.colorbarLabel`(`""` は系列1の色分けの列の表示)。それぞれ、その種類のときだけ検証して使う(`PlotSettings.step_where` / `hist_bins` / `hist_density` / `colormap` / `colorbar_label`)。 - `series[].colorColumn`(`""`): `__idx__N` だけ。`scatterColor` のときだけ検証して使い、必須(未選択は「系列Nの色分けの列を選んでください。」、形が不正は「系列Nの色分けの列」)。 - - 種類ごとに隠す設定(検証せず使わない。画面の出し分けは `js/chart-types.js` と同じ規則): `BAR_LIKE_TYPES`(bar / barh / barStacked / hist)は点の形・塗りつぶし帯・X 方向のエラーバー・近似曲線を使わない。`NO_Y2_TYPES`(barh / barStacked / hist / scatterColor)は第2Y軸を使わない(`secondaryAxis` は false として扱い、第2Y軸の目盛・注釈の `axis` も第1Y軸)。`NO_Y_ERROR_TYPES`(barStacked / hist)はエラーバーを両方向とも使わない。barh は Y 軸のスケール(対数)を使わない(`_parse_axis(linear=True)`。縦軸はカテゴリ)。hist は X列(`plot.xColumn`)を使わず、系列の X 列も使わない。step は line と同じ扱い(点サイズの自動は 0)、scatterColor は scatter と同じ扱い(点の形「なし」はエラー。点サイズの自動は 24)。軸の設定は物理的な軸のまま持つ(barh の `axes.x` = 横軸 = 値、`axes.y` = 縦軸 = カテゴリ。自動の軸ラベルだけ入れ替える: 横軸は系列1のY列の名前、縦軸は X列の名前。hist の自動ラベルは、横軸が系列1のY列の名前、縦軸が「度数」か「確率密度」)。 + - 種類ごとに隠す設定(5c の時点の規則。`BAR_LIKE_TYPES` は 5d で `XY_TYPES` などに分けて廃止した。下の Phase 5d の項目を見る。検証せず使わない。画面の出し分けは `js/chart-types.js` と同じ規則): `BAR_LIKE_TYPES`(bar / barh / barStacked / hist)は点の形・塗りつぶし帯・X 方向のエラーバー・近似曲線を使わない。`NO_Y2_TYPES`(barh / barStacked / hist / scatterColor)は第2Y軸を使わない(`secondaryAxis` は false として扱い、第2Y軸の目盛・注釈の `axis` も第1Y軸)。`NO_Y_ERROR_TYPES`(barStacked / hist)はエラーバーを両方向とも使わない。barh は Y 軸のスケール(対数)を使わない(`_parse_axis(linear=True)`。縦軸はカテゴリ)。hist は X列(`plot.xColumn`)を使わず、系列の X 列も使わない。step は line と同じ扱い(点サイズの自動は 0)、scatterColor は scatter と同じ扱い(点の形「なし」はエラー。点サイズの自動は 24)。軸の設定は物理的な軸のまま持つ(barh の `axes.x` = 横軸 = 値、`axes.y` = 縦軸 = カテゴリ。自動の軸ラベルだけ入れ替える: 横軸は系列1のY列の名前、縦軸は X列の名前。hist の自動ラベルは、横軸が系列1のY列の名前、縦軸が「度数」か「確率密度」)。 - `computed[]`(既定は空。上限 `MAX_COMPUTED` = 20。超えると「計算した列は20個までです。」): `{id, source, name, expr}`。`id` は `c1`、`c2`、…(JS が払い出し、削除しても再利用しない。Python は重複・空なら振り直す)、`source` は `load.files` の id(`""` は先頭。無い id は「計算した列Nのデータ元が見つかりません。…」。`field` は「計算した列Nのデータ元」)、`name` は 50 文字まで(`""` は「計算N」。超えると「計算した列Nの名前」)、`expr` は空だとエラー(「計算した列Nの式を入力してください。」)、構文の誤りは `settings` が `expr.parse` で検証し、「計算した列Nの式: 5文字目: …」の `UserError`(`field` は「計算した列Nの式」)にする。計算した列は常に画面に出るので、グラフの種類によらず検証する。`ComputedSettings.expr_node` が解釈済みの式の木。 - 計算した列の番号: そのデータ元のファイルの列の後ろに、`computed` の順(そのデータ元のものだけ)に足す。ファイルの列が 5 個なら最初の計算した列は `[5]`(設定では `__idx__5`。今までどおり列番号)。式の中の `[N]` や列記号 `A`(= `[0]`)は、ファイルの列だけを指せる(計算した列を参照するとエラー)。描画に使わないデータ元の計算した列は計算しない。計算は `skipRows` を除いた行で行う。 +- Phase 5d で足した項目と既定値(スキーマは version 4 のまま。新しい項目は既定値で補われ、既定の設定の生成コードは Phase 4 と1文字も変わらない。JS の `DEFAULT_SETTINGS` / `DEFAULT_FIT` と Python の `default_settings()` / `_DEFAULT_FIT` は一致させる): + - `plot.type`: 選択肢に `box` / `violin` / `heatmap` を足した。`plot.box`(`{fliers: true, means: false}`。外れ値の点・平均の印。誤りは「外れ値の点」「平均の印」)と `plot.violin`(`{medians: true, means: false}`。中央値の線・平均の線。誤りは「中央値の線」「平均の線」)は、それぞれ box / violin のときだけ検証して使う(`PlotSettings.box_fliers` / `box_means` / `violin_medians` / `violin_means`)。`plot.colormap` / `plot.colorbarLabel` はヒートマップでも使う(色分け散布図と共有。`COLOR_COLUMN_TYPES`)。 + - `series[].colorColumn`: ヒートマップでも使い、必須(画面の欄名は「値の列」。未選択は「系列Nの値の列を選んでください。」、形が不正は「系列Nの値の列」。`_parse_color_column(..., what)`)。 + - 種類ごとに隠す設定(5c の `BAR_LIKE_TYPES` は廃止し、定数を次に分けた。`js/chart-types.js` と揃える): `XY_TYPES`(line / step / scatter / scatterColor)だけが点の形・塗りつぶし帯・X 方向のエラーバー・近似曲線を使う(それ以外では検証せず使わない。近似曲線は `fits` ごと `()` にする)。`BOX_TYPES`(box / violin)は系列ごとに1つの箱・胴で、X列(`plot.xColumn`)と系列の X 列を使わず、点サイズ・線種を使わない(`marker=None`、線種は solid)。X 軸のスケールを使わない(`_parse_axis(linear=True)`。横軸は系列の名前)。`CATEGORY_BAR_TYPES`(bar / barStacked / barh)は X列を使う。`SERIES_X_TYPES`(XY_TYPES + heatmap)は系列ごとの X 列を使う。`NO_Y2_TYPES` に box / violin / heatmap を足した(第2Y軸を使わない)。`NO_Y_ERROR_TYPES` に box / violin / heatmap を足した(エラーバーを両方向とも使わない)。heatmap は X列を使わず、色・線幅・線種・点サイズを使わない(カラーマップを使う。検証せず、色は既定値)。不透明度はどれも使う。自動の軸ラベル: box / violin の横軸は空、縦軸は系列が1つならその Y 列の名前(2つ以上は空)。heatmap は横軸が系列1のX列の名前、縦軸が Y 列の名前(`SeriesPlan` の通常の規則)。 + - ヒートマップの系列は1つだけ(2つ以上は「ヒートマップは系列1つで描きます。系列を1つにしてください。」。定数 `HEATMAP_SERIES_MESSAGE`、`field` は「系列」。系列ごとの検証(値の列の未選択など)より先に返す)。X・Y の異なる値の上限は `MAX_HEATMAP_SIZE` = 500(それぞれ。超えるとエラー。§7)。 + - `fits[]`: `model` に `custom`(任意の式)を足した(`FIT_MODELS` = `linear` / `poly` / `custom`)。`expr`(`""`。`custom` のときだけ使う。200 文字まで、空は「近似曲線Nの式を入力してください。」。構文は `expr.parse_model` で検証し、誤りは「近似曲線Nの式: 5文字目: …」。`field` は「近似曲線Nの式」)、`initial`(`{a: 1, b: 1, c: 1, d: 1, e: 1}`。式が使うパラメータの分だけ、有限の数かを検証する。誤りは「近似曲線Nの初期値(a)」)。`custom` では `degree` を使わない(検証しない)。`FitSettings.expr_node`(解釈済みの式)/ `params`(式が使うパラメータ。a〜e の順)/ `initial`(その初期値)。 - パレットの色、プリセットの値、単位の換算は JS だけが持つ(`js/palettes.js`、`js/presets.js`、`js/units.js`)。プリセット名は設定に入れない。「適用」は図サイズ・単位・フォントサイズ・各系列の線幅と点サイズを個別の設定に書き込むだけで、直近のプリセットは `state.js` がセッション中だけ覚える(新しい系列に、線幅と、scatter のときの点サイズを引き継ぐ)。点サイズは、プリセットが自動(標準)なら全系列を自動に戻し、数値なら scatter か点サイズを入力済みの系列だけ書き換える。パレットの切替(`state.applyPalette`)は、全系列を系列の順に新しいパレットの色で塗り直してから `plot.palette` を書く。新しい系列の既定色は現在のパレットの未使用色。 - 系列: `id`、`x`、`y`、`color`、`lineWidth`、`lineStyle`、`markerSize`、`label`、`secondaryAxis`、`source`、`errorBars`(Phase 5a)、`marker` / `alpha` / `fill`(Phase 5b)。`markerSize: null` は「自動」(line は 0、scatter は 24)。ユーザーが数値を入れたら自動切替の対象外。 - Pythonコードタブの状態(モード `sync` / `edit`、生成したコード)は設定オブジェクトに入れず、`js/code-state.js` に持つ。編集モードのコード本文は、`render` / `save` の別引数 `code` で渡す。「使用する」(`useCustomCode`)は廃止した。 @@ -121,6 +128,7 @@ Python が登録し、登録後に `mplgui-ready` イベントを送る。引数 | 関数 | 引数 | 戻り値(`ok: true` のとき) | |---|---|---| | `ensureExcel()` | なし(非同期) | `{ok}`。初回の .xlsx 読込前に openpyxl を導入する | +| `ensureScipy()` | なし(非同期) | `{ok}`。任意の式の近似曲線(G10)を使う前に、scipy を Pyodide 同梱のパッケージとして読み込む(約 14 MB。2回目以降は何もしない。同時の呼び出しは1つの読み込みを共有する)。失敗は `{ok: false, error: {message: "scipy を読み込めませんでした。…", field: "近似曲線", detail}}` で、次の呼び出しで再試行する。`bridge.js` が、GUI 同期で任意の式の近似曲線があるとき、または編集モードのコードが scipy を import するときだけ、`render` / `save` / `copyImage` の前に呼ぶ(§5。`script` では呼ばない)。`render` / `save` / `copyImage` は、任意の式の近似曲線があるのに scipy が無いと「scipy を読み込めていません。…」(`api._require_scipy`)を返す | | `loadFile(name, bytes, loadJson, sourceId, pasted)` | ファイル名、内容、`{version, load}`、データ元の id(省略時 `d1`)、貼り付けたデータか(省略時 false) | `{encoding, columns, preview, sheets, sheet, warnings}`。.xlsx は `encoding: null`、`sheets` はシート名の配列(xlsx 以外は `[]`)、`sheet` は読んだシート名(xlsx 以外は `null`)。`columns` の各要素は `{value, label, kind, numericLike}`(`kind` は `datetime` / `number` / `text`。`numericLike` は `loader.looks_numeric`: 文字列の列でも空欄以外の半数以上が数値に読めるか。JS の `xAxisKind` が、X が文字列の列かの判定に使う)。`preview` は `{columns, columnKinds, rows, …, preamble: {lines, total}}`(`preamble` は読み飛ばした行の先頭最大20行と総数。`skipLines` が 0 のときは空) | | `render(settingsJson, code)` | 設定 JSON、`code`(null または文字列) | `code` が null: `{image, code, output, summary, seriesCount, skipRows, warnings}`。文字列: `{image, output, summary}` | | `save(settingsJson, code)` | 同上 | `{filename, mime, dataUri, output}` | @@ -138,6 +146,7 @@ Python が登録し、登録後に `mplgui-ready` イベントを送る。引数 - `figure_summary` の 5b のキーの数え方と注意(`runner._style_summary`): 線は `transform` で分ける(`axhline` は Y だけ、`axvline` は X だけデータ座標。両方データ座標の線が系列の線)。`markers` / `alphas` の線は、エラーバー(`_errorbar`)・近似曲線・注釈の線を除いた系列の線だけ。近似曲線の線は、ラベルが `_fit` か `$R^2$ = ` を含む線。近似曲線の式の文字は、`y = ` と `$R^2$ = ` を両方含む文字として判定する(同じ並びを含む利用者の注釈の文字は、式として数えてしまう)。`annotations.texts` は `ax.texts` から式の文字を引いた数で、図の中の割合で置いた文字も含む。`hspans` / `vspans` は `ax.patches` を `transform` で数える(棒グラフの棒は数えない)。 - `code` が文字列(編集モード。`save` / `copyImage` も同様): そのスクリプトを丸ごと、アップロードしたファイルのある作業フォルダ(`SESSION.workdir`)で実行する。`render` は設定を読まない(設定が不正でも、読込済みデータが無くても動く)。`save` は保存設定(`save.*`)だけを `settings.parse_save_settings` で検証して使う(描画設定が不正でも、編集したコードの図は保存できる)。GUI の設定をコードの結果に上書き適用することはしない(A8)。 - Phase 5c で `figure_summary` に足したキー(既存のキーの値は変えない。`runner._style_summary` と `figure_summary`): `drawstyles`(系列の線の `get_drawstyle()`。`markers` と同じ絞り込み)、`bars`(`{vertical, horizontal, containers, stacked}`。`BarContainer` の棒の本数(縦向き・横向き。ヒストグラムの棒も含む)、容器ごとの棒の数、棒の下端(横棒は左端)が 0 でない容器の数)、`colorbar`(カラーバーが無ければ `null`、あれば `{label, cmap, vmin, vmax}`)。カラーバーの Axes(`fig.colorbar` が作る、`_colorbar` を持つ Axes)は軸ごとの一覧に入れず、元の Axes の項目として出す(色分け散布図は第2Y軸が無いので、最初の Axes の項目だけに `colorbar` が入り、ほかの Axes は `null`)。色分け散布図の凡例用の灰色の見本(空の `scatter`。ラベルは系列の凡例名)は、`collections`(系列ごとに本体と見本の 2 つ)と `alphas`(scatter の分として、見本の不透明度)に数えられる。本体のラベルは `_color` なので凡例にも `alphas` にも入らない。計算した列の警告は `{series: 0, message}`(系列に属さない警告)。`script` / `render` が失敗したときの手順の `field` は「計算した列Nの式」(codegen の `Step`)。 +- Phase 5d で `figure_summary` に足したキー(既存のキーの値は変えない。`runner._style_summary` と `figure_summary`): `boxes`(ラベルが `_box` の patch の数 = 箱ひげ図の箱の数。生成コードが箱ひげ図の部品(箱・ひげ・端・中央値・外れ値・平均)すべてに `_box` のラベルを付ける。箱ひげ図の線は `_AUX_LINE_LABELS` に `_box` を足したので、`markers` / `alphas` / `drawstyles` には数えない(`lines` には数える)。`alphas` は箱の不透明度を含まない)、`violins`(ラベルが `_violin` の collection の数 = バイオリンの胴の数。中央値・端の線は `LineCollection` で `collections` に数える)、`meshes`(`QuadMesh` の数 = ヒートマップの `pcolormesh`)。ヒートマップのカラーバーは色分け散布図と同じく `colorbar`(`{label, cmap, vmin, vmax}`)に出す。 - `loadFile` は、読み込んだファイルを元のファイル名(フォルダ部分は除く)で作業フォルダに書き出す(同じ id の前のファイルは消す。失敗したらその id の読込済みデータと書き出したファイルを破棄する)。貼り付けたデータは `pasted_data.tsv`(UTF-8、タブ区切り)という名前のファイルとして同じ経路で読む。こうして、表示中のスクリプトの `pd.read_csv("ファイル名", ...)` がそのまま動く(P5)。 - 読込の規則(`loader.load_file`): 拡張子は `.csv` / `.txt` / `.tsv` / `.xlsx`(それ以外は「対応していない拡張子です。xlsx/csv/txt/tsvを選択してください。」)。区切り文字の既定は拡張子で決まる(csv はカンマ、txt は空白、tsv はタブ。自動判定はしない)。pandas に渡す引数は `SourceInfo.read_kwargs()`(csv: `sep`・`header`・`skiprows`・`thousands`・`decimal`・`comment`・`engine="python"`。xlsx: `sheet_name`・`header`・`skiprows`・`thousands`・`decimal`・`comment`)。xlsx のシートは `loadJson` の `load.files` のうち `sourceId` の項目から決め(無ければ先頭)、無い名前は「シート「X」がファイルにありません。…」(`field` は「シート」)。`pd.ExcelFile` は同じバイト列の間だけ id ごとにキャッシュする(シートの切替を速くする)。 - 読込のエラーと警告(利用者に案内する): 区切りが空白で `thousands` が空白、`comment` が区切り文字と同じ、は `UserError`。列数が揃わない `ParserError` と、`skipLines` が大きすぎてデータが無いときは、「ヘッダより前に読み飛ばす行数」を案内する文を添える。小数点と区切り文字が同じ記号(1文字の区切りで `decimal == sep`)はエラーにせず警告にする(引用符で囲まれた値は読めるため)。結果が1列で先頭のデータ行に `;` かタブがあれば、区切り文字の指定漏れの警告(`DELIMITER_HINT`)を返す。前置き行は、csv / txt / tsv ではデコード後のテキストを `split_lines`、xlsx では先頭 `skipLines` 行をタブでつないで作る。 @@ -197,7 +206,16 @@ Python が登録し、登録後に `mplgui-ready` イベントを送る。引数 - `expr.py`(標準ライブラリ・numpy・pandas だけ。`eval` / `exec` / `compile` / `ast` を使わない): `parse(text)` が自前の字句解析と再帰下降の構文解析で式の木(`Number` / `Column` / `Unary` / `Binary` / `Call`。各ノードは種類 `const` / `scalar` / `series` を持つ)を返し、誤りは `ExprError`(1 始まりの文字位置付き)。文法は、数、列(`[N]` と大文字の列記号 `A` = `[0]`)、`+ - * /`、`**` と `^`、括弧、単項マイナス(優先順位と結合は Python と同じ)、要素ごとの関数 `abs sqrt exp log log10 sin cos tan`、集計 `min max mean median std first last`、系列の処理 `rolling_mean(式, 窓の幅)`(窓の幅は 1〜1000 の整数の定数)・`diff`・`cumsum`。式は 200 文字・入れ子 30 まで、列を 1 つ以上含む。`evaluate(node, columns, index)` が `(float の Series, 計算できなかった行数)` を返し、`to_code` が同じ意味の pandas / numpy の式の文字列を返す(意味は両者で揃える)。定数だけの部分(`2 * 3` や `sqrt(4)`)は構文解析の時点で畳み込み、有限でない定数(`1 / 0` など)は「計算できない定数があります」の `ExprError`。`column_refs`(列の参照と位置)・`column_indices`・`is_series` は dataprep と codegen が使う。`settings._parse_computed` が構文まで検証して `ComputedSettings.expr_node` に木を持たせ、`dataprep._apply_computed` がデータ元ごとの(`skipRows` を除いた)DataFrame の末尾に計算した列を足す。 - **安全性(必須)**: 列名・タイトル・ラベル・色・ファイル名・文字コード・シート名・コメント記号・日時の書式・貼り付けたデータのファイル名などは信頼できない入力で、実行されるコードに入る。値は必ず `literal()`(str / int / 有限の float / bool / None だけを `repr` で出す。他の型は例外)を通して書き出し、コメントに入れる文字列は必ず `comment_text()`(改行・制御文字を空白にする)を通す。f 文字列などで、これ以外の方法で信頼できない文字列をコードに埋め込まないこと。`tests/unit/test_codegen.py`(と `test_load_options.py` / `test_datetime.py` / `test_multi_source.py` / `test_paste_tsv.py`)の注入テストが、シート名・ファイル名・コメント記号・日時の書式・列名で検査する。 - GUI の設定を、ユーザーが編集したコードの結果に上書き適用しない(A8)。編集モードのコードは、設定を使わずそのまま実行する。 -- 機能追加(Phase 5〜)の手順(5a で足した軸ごと・系列ごとの機能の足し方を含む): 描画の種類は `SERIES_EMITTERS`(プロット種別 → 系列の出力関数)に追加する。出力関数は `_Builder` に行を足し、失敗しうる行は `with b.step(メッセージ, field)` で包む。軸・グリッド・余白などは対応する `_emit_*` 関数に足す。データを見ないと決められないこと(列の割り当て、変換の要否、警告、データ由来のエラー)は `dataprep` の `PlotPlan` / `SeriesPlan` に項目を足して渡す(データ元ごとに違うことは `SeriesPlan.data_id` / `data_var` と `PlotPlan.sources` に持つ。読込の仕方に関わる引数は `SourceInfo.read_kwargs()` に足し、codegen の `_READ_COMMENTS` にコメントを足す)。設定項目を足すときは JS の `defaults.js` と `settings.py` の両方に足す。生成するコードは pandas / matplotlib / numpy だけを使う(ローカルの Python でそのまま動かすため)。新しい行を足したら、単体テストで「全体を実行した図」と「自動描画用の図」が一致することも確かめる。保存形式ごとの rcParams は `formats.savefig_rc` に足す(runner と codegen が同じ表を使う)。欧文フォントを足すときは `fonts.LATIN_FONTS`・`FONT_FILENAMES`、JS の `font-cache.js` の `FONT_URLS`・`bridge.js` の `LATIN_NAMES`、`settings.LATIN_FONTS`、`index.html` の選択肢を揃える。 軸ごとの機能は、`settings._parse_axis` に項目(隠れる条件では検証しない)、`dataprep._plan_axis` / `AxisPlan` に「その軸の種類で効く値」(使えない組み合わせは `UserError`)、`codegen` の `_axis_tick_lines` に `_AxisBlock`(Axes の変数名を引数で受ける。`ax` 固定の書き方を増やさない)を足す。系列ごとの付属物(エラーバーなど)は、`settings` の系列の項目 → `dataprep` の `SeriesPlan` の項目(列は系列のデータ元の `df.iloc[:, N]` から解決し、データ元を替えたら JS が列を空に戻す)→ `SERIES_EMITTERS` の各関数から呼ぶ小さな関数、の順に足し、描く順は「付属物 → 系列本体」にする。画面で隠す条件は、JS(`syncVisibility` / `axisTicks.js`)と Python(settings / dataprep)で同じ規則にし、隠した設定は図に使わない。軸の種類の規則を変えたら `series.js` の `xAxisKind` も揃える。既定の設定の出力が変わらないことを、ゴールデンテストで確かめる。 注釈・近似曲線のような設定のトップレベルの一覧(5b)は、`settings` に要素の dataclass と `_parse_*`(上限、id の重複の振り直し、隠れる条件では検証しない)、`dataprep` に解釈済みの値を持つ `*Plan`(位置の解釈・データ由来の検査はここ。範囲に効くものは `_Extents` に足す)と `PlotPlan` の項目、`codegen` に `_emit_*`(新しい節は `b.section(タイトル)` を呼ぶだけで番号は自動。節が増えても、その機能を使わないときの出力は変えない)と `Step` を足す。JS は `defaults.js` に要素の既定値、`state.js` に追加・更新・削除と通知の `kind`(一覧と項目を分ける。id は連番で再利用しない)、`js/ui/` にカード(`addVisibilityHook` で表示の同期を登録)、`main.js` の購読に一覧の再描画を足す。画面に出す要素の id は `<種類>--<項目>`。`runner._style_summary` に数えるキーを足して、E2E の一致確認(`test_codegen_consistency.py` の `EXACT_KEYS`)に加える。 Phase 5c: 新しいグラフの種類は、`SERIES_EMITTERS` に出力関数を足し、種類ごとに使う設定の規則を `settings.py` の定数(`BAR_LIKE_TYPES` / `NO_Y2_TYPES` / `NO_Y_ERROR_TYPES`。第2Y軸・エラーバー・点の形・近似曲線を使うか)と `js/chart-types.js` に足す(この2つは必ず揃える)。種類ごとの計画は `PlotPlan` の小さな dataclass(`HistPlan` / `ColorbarPlan`)、軸の種類の違い(横棒の縦軸など)は `dataprep._plan_axes` の `y_kind` に持たせ、`_Extents` を種類に合わせる。種類ごとの設定は `plot.*` に足し、隠れる種類では検証せず使わない。計算した列の関数を足すときは `expr.py` の `ELEMENTWISE` / `AGGREGATES` / `SERIES_FUNCS` に足し、`evaluate` と `to_code` の両方に同じ意味で実装する(`test_expr.py` が実行結果の一致を確かめる)。 +- Phase 5d のグラフの種類(G8。`SERIES_EMITTERS` に `box` / `violin` / `heatmap`。`codegen.BOX_TYPES` = box / violin、`NO_SERIES_LEGEND_TYPES` = box / violin / heatmap は系列を凡例に出さない): + - `box`・`violin`(`_emit_box_series`): `positions = np.arange(N)`、`x_labels = [<系列の凡例名>, …]`(目盛のラベル)。系列ごとに `values = pd.to_numeric(df.iloc[:, N], errors="coerce").replace([np.inf, -np.inf], np.nan).dropna()`、描けない系列(値が無い。バイオリンは2個未満)はコメントだけ残して位置を空ける。`box` は `bp = ax.boxplot([values], positions=[i], widths=0.6, patch_artist=True, manage_ticks=False, showfliers=..., showmeans=..., boxprops={"facecolor": 系列の色, "edgecolor": "black", "linewidth": 線幅[, "alpha": ...]}, whiskerprops/capprops/medianprops=黒, flierprops=…, meanprops=…)` と `for artists in bp.values(): plt.setp(artists, label="_box")`(凡例に出さない。`figure_summary` の `boxes` はこのラベルの patch を数える)。`violin` は `vp = ax.violinplot([values], positions=[i], widths=0.8, showmedians=..., showmeans=..., showextrema=True)`、胴は `body.set(facecolor=色, edgecolor=色, linewidth=, alpha=, label="_violin")`、端の線(`cbars` / `cmins` / `cmaxes`)は系列の色、中央値・平均の線(`cmedians` / `cmeans`)は黒。最後に `ax.set_xlim(-0.5, N - 0.5)`。横軸は `_scale()` が linear(カテゴリ)、目盛は棒グラフの位置の目盛と同じ節(`tick_step`。コメントは「箱の位置に 系列の名前を目盛として付ける」)。第2Y軸・エラーバー・帯・近似曲線は使わない。 + - `heatmap`(`_emit_heatmap_series`。系列は1つ): `x`(`_emit_x_data`。文字列の列は後述)、`y`(数値に読める文字列の列は `pd.to_numeric(..., errors="coerce")`)、`c = pd.to_numeric(df.iloc[:, N], errors="coerce")`(値の列)、`ok = x.notna() & y.notna() & c.notna()`、`heat = pd.DataFrame({"x": x[ok], "y": y[ok], "z": c[ok]})`。X・Y が文字列の列のときは `heat["x"], x_cats = pd.factorize(heat["x"])`(現れた順)と `x_cats = [str(v) for v in x_cats]`(Y も同様)。`grid = heat.pivot_table(index="y", columns="x", values="z", aggfunc="mean")`、`mesh = ax.pcolormesh(grid.columns.to_numpy(), grid.index.to_numpy(), grid.to_numpy(), cmap=<カラーマップ>, shading="nearest"[, alpha=])`、`colorbar = fig.colorbar(mesh, ax=ax)` と `set_label()`、目盛は内向き。文字列の軸の目盛は `_emit_heatmap_ticks`(`x_tick_step` / `y_tick_step` に、主目盛の間隔か `max(1, len(cats) // 25)`。X のラベルは 45 度)。失敗しうる行は手順「ヒートマップの格子を作れませんでした。X・Y・値の列を確認してください。」(`field` は「系列1の値の列」)と「ヒートマップを描けませんでした。カラーマップと値の列を確認してください。」(`field` は「カラーマップ」)。 +- Phase 5d の任意の式の近似曲線(G10。`_emit_custom_fit`。系列本体の直後に、今までの近似曲線と同じ位置): 冒頭の import に、任意の式の近似曲線があるときだけ `from scipy.optimize import curve_fit` を足し(line / step / scatter / 色分けのときだけ。「必要なライブラリ」のコメントにも scipy を足す)、`poly_text` の定義(`_needs_poly_text`)は任意の式の近似曲線だけでは書かない。近似曲線ごとに、コメント付きの `def fit_model_N(x, a, b, c): # 近似曲線Nの式: <利用者の式>`(引数は式が使うパラメータだけ、a〜e の順)と ` return <式>`(`expr.model_to_code` が解釈した木から書く。利用者の文字列は `comment_text()` を通してコメントにだけ入る)、続けて手順(`Step`。メッセージ「近似曲線N: 式を当てはめられませんでした。初期値を変えてみてください。」、`field` は「近似曲線Nの初期値」)の中に: + - `fit_params, _ = curve_fit(fit_model_N, x[ok], y[ok], p0=[…], maxfev=10000)` + - `fit_y = fit_model_N(x[ok], *fit_params)`、`if not np.all(np.isfinite(fit_y)): raise ValueError("当てはめた式の値が有限ではありません")`(初期値のところで式が有限でない値になると、`curve_fit` は黙って初期値を返すことがあるため、この確認で手順のメッセージに置き換える) + - `r2 = 1 - np.sum((y[ok] - fit_y) ** 2) / np.sum((y[ok] - y[ok].mean()) ** 2)`、`x_fit = np.linspace(x[ok].min(), x[ok].max(), 200)` + - `.plot(x_fit, fit_model_N(x_fit, *fit_params), color=, linewidth=, linestyle=, label=…)`。ラベルは、`show` が `legend` なら `"<名前>の近似: y = <式> (" + ", ".join(f"{name} = {value:.4g}" for name, value in zip([…], fit_params)) + f"、$R^2$ = {r2:.4f})"`(式は `expr.model_to_text` が木から整えた文字で、例 `a*exp(-b*x) + c`、べき乗は `^`。パラメータは実行時に `fit_params` から有効数字4桁)、それ以外は `"_fit"`。`show` が `text` なら続けて `ax.text(0.03, y, <同じ文字>, transform=ax.transAxes, va="top", ...)`(`y` の並びは既存の近似曲線と同じ規則)。第2Y軸の系列は `ax2` に描く。 + - `expr.py` の近似の式の入口(`parse_model(text)`。標準ライブラリ・numpy・pandas だけ。`eval` を使わない): 字句解析を `model=True` で行い、変数 `x` とパラメータ `a`〜`e`(`Var` ノード。`x` は `series`、a〜e は `scalar`)、数、`+ - * /`、`**`(`^`)、括弧、要素ごとの関数(`abs sqrt exp log log10 sin cos tan`)だけを受ける。列(`[N]`・大文字の列記号)は「近似の式では列は使えません(変数は x、パラメータは a〜e です)。」、集計・系列の処理は「「name」は近似の式では使えません。使える関数: …」、知らない名前は「「name」は使えません。使える名前は x と a〜e です」(どれも位置付きの `ExprError`)。式に `x` が無い、パラメータが1つも無いのもエラー。`model_params(node)`(使ったパラメータ、a〜e の順)、`model_to_code`(numpy の式。名前は x, a〜e のまま)、`model_to_text`(図のラベル用の整えた式)、`evaluate_model(node, x, params)`(`model_to_code` と同じ意味。numpy で評価)。`settings._parse_fits` が `parse_model` で検証して `FitSettings.expr_node` / `params` / `initial`(式が使うパラメータの分)を持たせ、`dataprep` の `FitPlan`(`model` / `expr` / `node` / `params` / `p0`)に渡す。 +- 機能追加(Phase 5〜)の手順(5a で足した軸ごと・系列ごとの機能の足し方を含む): 描画の種類は `SERIES_EMITTERS`(プロット種別 → 系列の出力関数)に追加する。出力関数は `_Builder` に行を足し、失敗しうる行は `with b.step(メッセージ, field)` で包む。軸・グリッド・余白などは対応する `_emit_*` 関数に足す。データを見ないと決められないこと(列の割り当て、変換の要否、警告、データ由来のエラー)は `dataprep` の `PlotPlan` / `SeriesPlan` に項目を足して渡す(データ元ごとに違うことは `SeriesPlan.data_id` / `data_var` と `PlotPlan.sources` に持つ。読込の仕方に関わる引数は `SourceInfo.read_kwargs()` に足し、codegen の `_READ_COMMENTS` にコメントを足す)。設定項目を足すときは JS の `defaults.js` と `settings.py` の両方に足す。生成するコードは pandas / matplotlib / numpy だけを使う(ローカルの Python でそのまま動かすため)。新しい行を足したら、単体テストで「全体を実行した図」と「自動描画用の図」が一致することも確かめる。保存形式ごとの rcParams は `formats.savefig_rc` に足す(runner と codegen が同じ表を使う)。欧文フォントを足すときは `fonts.LATIN_FONTS`・`FONT_FILENAMES`、JS の `font-cache.js` の `FONT_URLS`・`bridge.js` の `LATIN_NAMES`、`settings.LATIN_FONTS`、`index.html` の選択肢を揃える。 軸ごとの機能は、`settings._parse_axis` に項目(隠れる条件では検証しない)、`dataprep._plan_axis` / `AxisPlan` に「その軸の種類で効く値」(使えない組み合わせは `UserError`)、`codegen` の `_axis_tick_lines` に `_AxisBlock`(Axes の変数名を引数で受ける。`ax` 固定の書き方を増やさない)を足す。系列ごとの付属物(エラーバーなど)は、`settings` の系列の項目 → `dataprep` の `SeriesPlan` の項目(列は系列のデータ元の `df.iloc[:, N]` から解決し、データ元を替えたら JS が列を空に戻す)→ `SERIES_EMITTERS` の各関数から呼ぶ小さな関数、の順に足し、描く順は「付属物 → 系列本体」にする。画面で隠す条件は、JS(`syncVisibility` / `axisTicks.js`)と Python(settings / dataprep)で同じ規則にし、隠した設定は図に使わない。軸の種類の規則を変えたら `series.js` の `xAxisKind` も揃える。既定の設定の出力が変わらないことを、ゴールデンテストで確かめる。 注釈・近似曲線のような設定のトップレベルの一覧(5b)は、`settings` に要素の dataclass と `_parse_*`(上限、id の重複の振り直し、隠れる条件では検証しない)、`dataprep` に解釈済みの値を持つ `*Plan`(位置の解釈・データ由来の検査はここ。範囲に効くものは `_Extents` に足す)と `PlotPlan` の項目、`codegen` に `_emit_*`(新しい節は `b.section(タイトル)` を呼ぶだけで番号は自動。節が増えても、その機能を使わないときの出力は変えない)と `Step` を足す。JS は `defaults.js` に要素の既定値、`state.js` に追加・更新・削除と通知の `kind`(一覧と項目を分ける。id は連番で再利用しない)、`js/ui/` にカード(`addVisibilityHook` で表示の同期を登録)、`main.js` の購読に一覧の再描画を足す。画面に出す要素の id は `<種類>--<項目>`。`runner._style_summary` に数えるキーを足して、E2E の一致確認(`test_codegen_consistency.py` の `EXACT_KEYS`)に加える。 Phase 5c: 新しいグラフの種類は、`SERIES_EMITTERS` に出力関数を足し、種類ごとに使う設定の規則を `settings.py` の定数(5c の時点は `BAR_LIKE_TYPES` / `NO_Y2_TYPES` / `NO_Y_ERROR_TYPES`。5d で分けた。第2Y軸・エラーバー・点の形・近似曲線を使うか)と `js/chart-types.js` に足す(この2つは必ず揃える)。種類ごとの計画は `PlotPlan` の小さな dataclass(`HistPlan` / `ColorbarPlan`)、軸の種類の違い(横棒の縦軸など)は `dataprep._plan_axes` の `y_kind` に持たせ、`_Extents` を種類に合わせる。種類ごとの設定は `plot.*` に足し、隠れる種類では検証せず使わない。計算した列の関数を足すときは `expr.py` の `ELEMENTWISE` / `AGGREGATES` / `SERIES_FUNCS` に足し、`evaluate` と `to_code` の両方に同じ意味で実装する(`test_expr.py` が実行結果の一致を確かめる)。 Phase 5d: 種類ごとの規則は `settings.py` の `XY_TYPES`(点の形・帯・X 方向のエラーバー・近似曲線を使う)・`BOX_TYPES`・`CATEGORY_BAR_TYPES`・`SERIES_X_TYPES`・`NO_Y2_TYPES`・`NO_Y_ERROR_TYPES`・`COLOR_COLUMN_TYPES` と `js/chart-types.js` を必ず揃える(`test_chart_types.py` が node で比べる。5c の `BAR_LIKE_TYPES` は廃止した。新しい種類が「XY の種類でない」ことで自動的に隠れるようにする)。系列ごとに1つの図形を描く種類(箱ひげ・バイオリン)は、`dataprep` で `_plan_box` のように系列ごとの計画を作り、横軸を `axes_args=("category", ext, 系列の数)` で渡す。近似曲線のモデルを足すときは、`settings.FIT_MODELS`、`dataprep.FitPlan`、`codegen` の `_emit_fits`(系列本体の直後。任意の式のように別の emitter に分けてよい)、JS の `fits.js` を足す。scipy のような実行時に読み込む依存は、`py/main.py` の `ensure*`(名前で `loadPackage`)、`bridge.js` の `needs*` / `ensure*For`(`script` からは呼ばない)、`api._require_*`(読み込めていないときの日本語のエラー)の3点を揃える。 - 生成スクリプトの保存ファイル名(`savefig` の引数)は `formats.build_filename` で決める。保存形式・解像度・形式ごとの rcParams は `formats.savefig_kwargs`(解像度は `save.dpi`)/ `formats.savefig_rc` で、GUI の「保存」と同じにする。 ### runner(スクリプトの実行) @@ -231,7 +249,10 @@ Python が登録し、登録後に `mplgui-ready` イベントを送る。引数 - 図サイズの単位を替えると、入力欄の数値を換算し(`convertLength`。空欄・不正な入力はそのまま)、図の大きさは変えない。ラベル(`図幅(inch)` など)と step は単位に合わせる。プリセットの「適用」は値を書き込むだけで、描画は通常の変更どおり。パレットを替えると、色の選択肢と各系列の色を描き直す。 - 「クリップボードにコピー」(`clipboard.js`): 保存 DPI の PNG を `copyImage` で作り、`ClipboardItem` に `Promise` として渡して `navigator.clipboard.write` する(Safari がクリックの中での呼び出しを要求するため、クリックの処理では何も `await` せずに `write` を呼び、画像は渡した Promise の中で作る)。対応は `window.isSecureContext`(https または localhost)、`navigator.clipboard.write`、`ClipboardItem`(`ClipboardItem.supports("image/png")` があれば true)。編集モードでは編集中のコードの図をコピーする。 - E2E が使う状態は `` の data 属性: `data-app-state`(`starting` / `ready` / `failed`)、`data-data-state`(`none` / `loading` / `ready` / `error`)、`data-render-state`(`idle` / `pending` / `rendering`)、`data-render-generation`、`data-font-state`(日本語フォント。`idle` / `loading` / `ready` / `failed`)、`data-latin-font-state`(選択中の欧文フォント。`idle`(標準を選択中)/ `loading` / `ready` / `failed`)、`data-copy-state`(`idle` / `copying` / `done` / `failed` / `unsupported`)、`data-load-count`(読み込めたデータ元がある読込のまとまりの完了ごとに増える。ファイルを外しただけ・全ファイルの失敗では増えない)。複数ファイルのとき、`data-data-state` は読込中が1つでもあれば `loading`、読込中がなく失敗が1つでもあれば `error`、すべて成功なら `ready`、ファイルが無ければ `none`。表示中の画像は `#plotArea img` の `data-generation` と `data-summary`(`figure_summary` の JSON)を持つ。ステータスは `#status` の `data-kind`。Pythonコードタブ用に、`` の `data-code-mode`(`sync` / `edit`)、`#customPyCode`(textarea)の `data-generation`(表示中のコードを生成した世代。GUI 同期のとき、同じ世代の画像と対応する)、`#codeOutput` の `data-kind`(`ok` / `error`)、`#codeSyncStatus` の `data-state`(`sync` / `edit`)、`#customPyCode` の `data-stale`(最新でないときだけ `true`)、`#codeStaleNote` がある。Phase 4 の画面の id: データ読み込み区分の `#fileInput` / `#addFileBtn` / `#addFileInput` / `#fileList` / `#pasteArea` / `#savePastedBtn` / `#sheetGroup` / `#sheetSelect` / `#skipLines`(+ `#skipLinesHelp`)/ `#thousands` / `#decimal` / `#commentChar` / `#parseDates`、系列区分の `#skipRowsHelp` / 系列カードの `series--source`、軸・目盛区分の `#xDateFormatGroup` / `#xDateFormat` / `#xDateFormatCustom`、データ確認の `#dataPreamble` / `#previewSource`(+ `#previewSourceGroup`)、ドロップの `#dropOverlay` / `#dropLoad` / `#dropReplace` / `#dropAdd`。 -- Phase 5c の画面(グラフの種類は `#plotType`。選択肢は line / step / scatter / scatter(色分け)/ bar / bar(積み上げ)/ barh(横棒)/ hist(ヒストグラム)。既存の選択肢の表示は変えていない): 種類ごとの欄は「系列」区分の「グラフの種類」の下に、その種類のときだけ出す(`series.js` の `syncVisibility`。規則は `js/chart-types.js` だけが持ち、Python の `BAR_LIKE_TYPES` / `NO_Y2_TYPES` / `NO_Y_ERROR_TYPES` と揃える)。`#stepGroup` / `#stepWhere`(step)、`#histGroup` / `#histBins`(空欄 = 自動)/ `#histDensity`(hist)、`#colorMapGroup` / `#colorMap` / `#colorbarLabel`(色分け)。Y 軸のスケールの行は `#yScaleGroup`(barh では隠す)。系列カードは `series--color-column`(`.series-color-column-wrap`。色分けのときだけ。「(選択してください)」あり)、点サイズの欄を `.series-marker-size-wrap`、第2Y軸の欄を `.series-y2-wrap` で包み、種類ごとに隠す。点の形・点サイズ・帯は line / step / scatter / 色分けだけ(棒グラフ・横棒・積み上げ・hist では隠す)。X 方向のエラーバーも同じ。エラーバーの折りたたみ(`.series-errorbars`)ごと隠すのは積み上げ棒と hist。X列(`#xColumn`)は bar / 積み上げ / barh、hist は系列の X 列も X列も使わない。第2Y軸は bar / line / step / scatter だけ(`state.hasSecondaryAxis` も、使わない種類では値が残っていても偽)。点の形が「なし」のときに点サイズを無効にするのは line / step。近似曲線の一覧と追加ボタンは、棒グラフ・横棒・積み上げ・hist では隠し、`#fitBarNote`(「棒グラフ・ヒストグラムでは近似曲線を使えません。」)を出す。横棒の縦軸の種類は `series.js` の `yAxisKind()`(`number` / `log` / `category`。横棒はカテゴリ、1系列で X列が数値なら number)、積み上げ棒の X は常にカテゴリ、横棒と hist の `xAxisKind` は数値 / 対数。`syncAxisTicks(xKind, yKind)` は `yKind` を受けて横棒の縦軸に「何個おき」を出す。注釈の Y の例と補足も `yKind` で変わる(横棒の縦軸は「何番目のカテゴリか」)。データ元を替えると色分けの列も空に戻し、読み込み直しで列が無くなったときも `reconcileColumns` が空に戻す。 +- Phase 5d の画面(`#plotType` の選択肢に box(箱ひげ図)/ violin(バイオリン図)/ heatmap(ヒートマップ)を足した。既存の選択肢の表示は変えていない。規則は `js/chart-types.js` だけが持つ): `#boxGroup`(`#boxFliers` 外れ値を表示 / `#boxMeans` 平均を表示。box のときだけ)、`#violinGroup`(`#violinMedians` 中央値の線を表示 / `#violinMeans` 平均の線を表示。violin のときだけ)、`#colorMapGroup`(カラーマップ・カラーバーのラベル)は色分け散布図に加えてヒートマップでも出す。X 軸のスケールの行は `#xScaleGroup`(箱ひげ・バイオリンでは隠す。ヒートマップは X が文字列の列のとき隠す)、Y 軸のスケールの行 `#yScaleGroup` は横棒に加えて、ヒートマップで Y が文字列の列のときも隠す。系列カードは、色の欄を `.series-color-wrap`、線幅を `.series-line-width-wrap`、線種を `.series-line-style-wrap` で包み(ヒートマップは色・線幅・線種を隠し、箱ひげ・バイオリンは線種を隠す)、色分けの列の選択(`series--color-column`)のラベル(`.series-color-column-label`)はヒートマップでは「値の列」にする。点の形・点サイズ・帯・X 方向のエラーバー・近似曲線は line / step / scatter / 色分けだけ(`usesMarker` / `usesFill` / `usesXErrors` / `usesFits`)、箱ひげ・バイオリン・ヒートマップはエラーバーの折りたたみごと・第2Y軸も隠す。箱ひげ・バイオリンは系列の X 列も X列も使わない(横軸は系列の名前)、ヒートマップは系列ごとの X 列を使う(`usesSeriesX`)。`xAxisKind()` は箱ひげ・バイオリンでカテゴリ、ヒートマップは X が文字列の列ならカテゴリ(それ以外は数値 / 対数)、`yAxisKind()` はヒートマップの Y が文字列の列ならカテゴリ。ヒートマップの系列は1つだけ(2つ以上は Python がエラーにする。画面は系列の追加を止めない)。近似曲線を使わない種類(棒・横棒・積み上げ・hist・箱ひげ・バイオリン・ヒートマップ)の `#fitBarNote` は「棒グラフ・ヒストグラム・箱ひげ図・バイオリン図・ヒートマップでは近似曲線を使えません。」。 +- 任意の式の近似曲線(G10)の画面: 近似曲線カードの `fit--model` に「任意の式」(`custom`)を足した。`custom` のときだけ、式の入力 `fit--expr`(placeholder「例: a*exp(-b*x) + c」。200 文字まで)、補足 `fit--expr-help`(「変数は x、パラメータは a〜e です。使える関数: abs sqrt exp log log10 sin cos tan。べき乗は ^ か ** で書きます。」)、初期値の入力 `fit--initial-a`〜`-initial-e`(式が使っているパラメータの分だけ表示。使っているかは `fits.js` の `usedParams(expr)` が、単独の a〜e を数えて決める。`exp` や `1e3` の中の e は数えない。既定値 1)が出る(`.fit-custom-wrap` / `.fit-initial-item`)。多項式の次数 `-degree` は `poly` のときだけ。 +- scipy の読み込み(G10。`bridge.js` の `ensureScipyFor(code)`。`` = `idle` / `loading` / `ready` / `failed`): 読み込むのは、GUI 同期で任意の式の近似曲線(`model` が `custom`。`usesFits(plot.type)` の種類のときだけ)があるとき、または編集モードで実行するコードが `import scipy` / `from scipy` の行を持つときだけ(`needsScipy`)。`render` / `save` / `copyImage` の前に呼び、`script`(コードだけの更新)からは呼ばない。同時の呼び出しは1つの Promise を共有し、読み込み中は進捗バナーとステータスに「scipy を読み込み中…(初回のみ。約 14 MB)」と出す。失敗したら(`failed`)、Python の error(または「scipy を読み込めませんでした。…」)をエラー表示にし、GUI 同期ではコードに「最新でない」印を付ける。失敗しても次の要求でもう一度試す。任意の式を使わないときは、scipy を取りにいかない(`data-scipy-state` は `idle` のまま)。最後のファイルを外したときの初期状態への復帰で `idle` に戻す(読み込み済みの scipy は Python 側に残るので、Python の `ensureScipy` は2回目以降すぐ成功する)。 +- Phase 5c の画面(グラフの種類は `#plotType`。選択肢は line / step / scatter / scatter(色分け)/ bar / bar(積み上げ)/ barh(横棒)/ hist(ヒストグラム)。既存の選択肢の表示は変えていない): 種類ごとの欄は「系列」区分の「グラフの種類」の下に、その種類のときだけ出す(`series.js` の `syncVisibility`。規則は `js/chart-types.js` だけが持ち、Python の `XY_TYPES` / `NO_Y2_TYPES` / `NO_Y_ERROR_TYPES` などと揃える。5c の時点では `BAR_LIKE_TYPES`)。`#stepGroup` / `#stepWhere`(step)、`#histGroup` / `#histBins`(空欄 = 自動)/ `#histDensity`(hist)、`#colorMapGroup` / `#colorMap` / `#colorbarLabel`(色分け)。Y 軸のスケールの行は `#yScaleGroup`(barh では隠す)。系列カードは `series--color-column`(`.series-color-column-wrap`。色分けのときだけ。「(選択してください)」あり)、点サイズの欄を `.series-marker-size-wrap`、第2Y軸の欄を `.series-y2-wrap` で包み、種類ごとに隠す。点の形・点サイズ・帯は line / step / scatter / 色分けだけ(棒グラフ・横棒・積み上げ・hist では隠す)。X 方向のエラーバーも同じ。エラーバーの折りたたみ(`.series-errorbars`)ごと隠すのは積み上げ棒と hist。X列(`#xColumn`)は bar / 積み上げ / barh、hist は系列の X 列も X列も使わない。第2Y軸は bar / line / step / scatter だけ(`state.hasSecondaryAxis` も、使わない種類では値が残っていても偽)。点の形が「なし」のときに点サイズを無効にするのは line / step。近似曲線の一覧と追加ボタンは、棒グラフ・横棒・積み上げ・hist では隠し、`#fitBarNote`(「棒グラフ・ヒストグラムでは近似曲線を使えません。」)を出す。横棒の縦軸の種類は `series.js` の `yAxisKind()`(`number` / `log` / `category`。横棒はカテゴリ、1系列で X列が数値なら number)、積み上げ棒の X は常にカテゴリ、横棒と hist の `xAxisKind` は数値 / 対数。`syncAxisTicks(xKind, yKind)` は `yKind` を受けて横棒の縦軸に「何個おき」を出す。注釈の Y の例と補足も `yKind` で変わる(横棒の縦軸は「何番目のカテゴリか」)。データ元を替えると色分けの列も空に戻し、読み込み直しで列が無くなったときも `reconcileColumns` が空に戻す。 - 計算した列(G6)の画面: 「注釈・解析」区分の「計算した列」(`#computedLabel`、`#computedList`、`#addComputedBtn`、補足 `#computedHelp`)。カードは `computed-`(state の `computed` から描く。入力中の欄は作り直さない)、入力欄は `computed--source`(データ元。2ファイル以上のときだけ表示)/ `-name`(名前。placeholder は「計算N」)/ `-expr`(式)/ `-remove`、雛形のボタン `-tpl-normalize`(`[N] / max([N])`)/ `-tpl-offset`(`[N] - first([N])`)/ `-tpl-rolling`(`rolling_mean([N], 5)`。N は系列1の Y 列(同じデータ元でファイルの列のとき)か、なければ 1)、番号の表示 `-index`(「列 [k] として使えます」。ファイルが未読込なら「ファイルを読み込むと番号が決まります」)。追加ボタンは 20 個で無効になる。計算した列は、系列の X・Y・エラーバー・帯・色分けの列の選択肢に「名前 [k](計算)」として、そのデータ元のファイルの列の後ろに出る(`series.js` の `columnsOf` が「ファイルの列 + 計算した列」を返す。選択肢を作る・検証するのはここだけ。`fileColumnCount(id)` はファイルの列数)。データ確認の表には出さない。通知の `kind` は `computed-list`(カードの増減。`main.js` がカードを描き直し、系列の選択肢も作り直す)と `computed-field`(名前・式・データ元の変更。表示を同期し、選択肢を更新する)で、`routeChange` では通常の変更(250 ms 後に再描画。編集モードでは何もしない)。 - 計算した列の番号の付け替え(`js/computed-refs.js`): 計算した列の番号は「ファイルの列数 + そのデータ元の計算した列の中での位置」で、変わるたびに、列を参照している設定(系列の x / y / 色分けの列 / エラーバーの列 / 帯の列と、系列1のデータ元の `plot.xColumn`)を `remapReferences(sourceId, fn)`(`fn(k)` が新しい番号、null で空に戻す。origin は `reconcile`)で付け替える。空に戻した系列には `addNote` で警告を添える(「系列N: 計算した列「name」を削除したため(データ元を替えたため)、その列を使っていた設定を空に戻しました。」)。(1) 削除(`removeComputedColumn`): その列を参照していた設定を空に戻し、後ろの計算した列の参照は 1 つ詰める。(2) データ元の変更(`changeComputedSource`): 元のデータ元からは削除と同じ付け替え、新しいデータ元では、後ろの参照を +1 する。(3) 読み直しでファイルの列数が oldF → newF になったとき(`shiftForFileColumnChange`。`series.js` が `reconcileColumns` より前に呼ぶ): 計算した列を指す参照は同じだけずらして計算した列を指したままにする。列が減ったとき(newF < oldF)は、無くなったファイルの列 [newF, oldF) への参照が新しい計算した列の範囲に入って有効と見なされないよう、計算した列の個数だけずらして範囲の外へ出し、`reconcileColumns` に空へ戻させる。(4) ファイルの削除・置き換え(`bridge.js`。`releaseComputedSources`): そのファイルをデータ元にしていた計算した列は、データ元を先頭のファイル(`""`)に戻し、「計算した列N: データ元のファイルを外したため、データ元を先頭のファイルに戻しました。」を添える。 @@ -239,6 +260,7 @@ Python が登録し、登録後に `mplgui-ready` イベントを送る。引数 - PyScript 2026.7.3(Pyodide 314.0.3 / Python 3.14)。`pyscript.toml` は `packages = ["pandas", "matplotlib"]`、`packages_cache = "passthrough"`(micropip を使わない)。 - openpyxl と et_xmlfile は Pyodide 同梱ではないので、初めて .xlsx を読むときに `py/main.py` が、バージョン固定の wheel URL(`files.pythonhosted.org`)を `pyodide_js.loadPackage` に渡して導入する。起動時には導入しない。 +- scipy(Phase 5d, G10。任意の式の近似曲線だけが使う)は Pyodide 同梱のパッケージ(scipy 1.18.0。依存は numpy だけで、numpy は読み込み済み)で、起動時には取得しない。初めて必要になったときに `py/main.py` の `ensureScipy()` が `pyodide_js.loadPackage(to_js(["scipy"]))` と名前で読み込む(wheel 1つ、約 14 MB。取得先は Pyodide の版を含む jsDelivr のパス(`/pyodide/v314.0.3/full/`)で、Pyodide がハッシュも確かめる)。openpyxl と違い、リポジトリに URL を書かないので `test_cdn_pinning.py` は変えていない。読み込みの流れは §5。ブラウザのキャッシュに残れば、2回目以降はダウンロードしない(初回だけインターネット接続が要る)。 - matplotlib のバックエンドは Agg(`py/main.py` で `matplotlib.use("Agg")`。pyplot を import する前に指定する)。 - 日本語フォントは、固定 URL の jsDelivr(`@expo-google-fonts/noto-sans-jp@0.4.4/400Regular/NotoSansJP_400Regular.ttf`、約5.7 MB。TrueType 版 Noto Sans JP)から取得し、Cache Storage(キャッシュ名 `mplgui-fonts-v1`)に保存する。2回目以降の訪問ではダウンロードしない。取得はセッション中1回で、失敗しても再試行せず、警告を1度だけ出してフォールバックフォントで続行する。 - Noto Sans CJK JP の OTF(CFF 形式、約16 MB)から替えた理由: matplotlib 3.10 は CFF 形式のフォントを `pdf.fonttype=42` で正しく埋め込めない(TrueType 用の FontFile2 に CFF を入れ、PDF が壊れる)。TrueType 版は同じデザイン・同じ文字幅。ハングルと中国語専用の漢字は含まれない(JIS 第1〜第4水準は含む)。旧 OTF のキャッシュ(URL `noto-cjk@Sans2.004/...NotoSansCJKjp-Regular.otf`)が `mplgui-fonts-v1` に残っていたら、日本語フォントの取得時に1回だけ削除する(失敗は無視する)。matplotlib に登録するフォント名は `Noto Sans JP`(`SANS_SERIF_PRIORITY` の先頭)。 @@ -258,6 +280,10 @@ Python が登録し、登録後に `mplgui-ready` イベントを送る。引数 - 色分けの列(`scatterColor`): 数値にできない値があれば、系列ごとに警告(「系列N: 色分けの列「name」[i] に数値にできない値がN件あったため、その点は描きません(例: …)」。桁区切り・小数点のヒント付き。空欄は警告しない。件数と例は描く行だけで数える。`dataprep._color_values`)。色分けの列が未選択(「系列Nの色分けの列を選んでください。」)、範囲外、日時の列(「色分けの列には数値の列を選んでください」)はエラー(`field` は「系列Nの色分けの列」)。 - ヒストグラム: 区間の数が自動で 1000 個を超えるときはエラー(「区間の数が自動でN 個になりました(1000 個まで)。「区間の数」を指定してください。」。`field` は「区間の数」。指定した区間の数は設定側で 1〜1000 を検証)。Y 列が日時はエラー。数値にできない値は系列ごとの警告(line と同じ形)。 - 計算した列(`dataprep._apply_computed`): 数値にできない値は、式が使う列ごとに警告(「計算した列N(name): 列「…」[i] に数値にできない値がN件あったため、欠損として計算します(例: …)」。ヒント付き)。0 での割り算・負の数の平方根などで入力は数なのに計算できなかった値は、件数の警告(`COMPUTED_INVALID`)。どちらも `series` は 0(どの系列にも属さない警告)。エラー(`field` は「計算した列Nの式」): 構文の誤り(「5文字目: …」のように位置付き。`settings` の検証で出る)、範囲外の列(「列 [k] はありません(データの列は [0]〜[M] です)。」)、ほかの計算した列への参照、日時の列の参照。式の空欄・名前が 50 文字超・データ元が無い・20 個超も日本語のエラー(§3)。 +- Phase 5d の警告とエラー: + - 箱ひげ図・バイオリン図(`dataprep._plan_box`): Y 列の数値にできない値は系列ごとの警告(line と同じ形)。描ける値(数値の行)が無い系列は、位置を空けたまま描かず警告(「系列N: 描ける値(数値の行)が無いため、箱は描きません。」。バイオリンは「バイオリンは描きません」)。バイオリンは値が1個だけの系列も描かず警告(「系列N: 値が1個だけなので密度を推定できず、バイオリンは描きません。」)。どの系列も描けないときはエラー。Y 列が日時はエラー(「系列NのY列」)。値は有限のものだけを使う(inf は除く)。 + - ヒートマップ(`dataprep._plan_heatmap`): 同じ X・Y の組があれば、件数の警告(「系列N: 同じ X・Y の組がN件重複していたため、その平均を描きます。」)。値の列に数値にできない値があれば、系列の警告(「値の列「name」[i] に…その行は使いません」。桁区切り・小数点のヒント付き。空欄は警告しない)。X・Y の異なる値が 500 種類(`MAX_HEATMAP_SIZE`)を超えるとエラー(「ヒートマップのXの異なる値がN種類あります(500種類まで)。X列に格子の軸になる列を選んでいるか確認してください。」。`field` は「系列NのX列」「系列NのY列」)。X・Y・値の列が日時の列はエラー(X・Y は「系列N: X列(name)は日時の列です。ヒートマップでは日時の列を使えません。」、値の列は「値の列には数値の列を選んでください」。`field` は「系列NのX列」「系列NのY列」「系列Nの値の列」)。値の列の未選択は「系列Nの値の列を選んでください。」(`field` は「系列Nの値の列」)。系列が2つ以上は「ヒートマップは系列1つで描きます。系列を1つにしてください。」(`field` は「系列」。系列ごとの検証より先に出す)。描ける行が無いとエラー。 + - 任意の式の近似曲線: 式の空欄は「近似曲線Nの式を入力してください。」、構文の誤りは「近似曲線Nの式: 5文字目: …」(`field` は「近似曲線Nの式」。`x` を含まない・パラメータ(a〜e)が無い・列・集計・系列の処理・知らない名前もここ)、初期値が有限の数でないときは「近似曲線Nの初期値(a)」(`field` も同じ。式が使うパラメータの分だけ検証)。X の異なる値の数がパラメータの数 + 1 未満のときは dataprep が「近似曲線N: パラメータがM個の式で近似するには、X の異なる値が M+1 個以上必要です(今はK個)。」(`field` は「近似曲線Nの系列」)。実行時の失敗(`curve_fit` が収束しない RuntimeError、初期値で計算できない ValueError、当てはめた式の値が有限でないときに生成コードが出す ValueError)は、手順で「近似曲線N: 式を当てはめられませんでした。初期値を変えてみてください。」(`field` は「近似曲線Nの初期値」)。scipy が読み込めないときは「scipy を読み込めませんでした。インターネット接続を確かめてから、もう一度試してください。」(`field` は「近似曲線」。`ensureScipy` が返す)、読み込めていないのに `render` / `save` / `copyImage` が呼ばれたときは「scipy を読み込めていません。任意の式の近似曲線には scipy が必要です。ページを再読み込みして、もう一度試してください。」(`api._require_scipy`。`field` は「近似曲線N」)。 - 主目盛の間隔が小さすぎて目盛が 100 本(`dataprep.MAX_MAJOR_TICKS`)を超えるときは、警告ではなくエラー(「X軸の主目盛の間隔が小さすぎます(目盛が約N本になります。100本まで)。…」。`field` は「X軸の主目盛の間隔」など)。コードタブには「最新でない」印が付く。 - 数値に変換できず除外した値の例が「1,234」のような桁区切りの数で `thousands` がカンマでないとき、「1,5」のような小数点カンマで `decimal` がカンマでないときは、警告の文に「(桁区切りのカンマなら、「データ読み込み」の「桁区切り」をカンマにしてください)」「(小数点がカンマなら、「小数点」をカンマにしてください)」を添える(`dataprep.load_hint`。両方に当てはまる `1,234` は桁区切りのヒントだけ)。 - 日時の列の認識(`loader.detect_datetime_columns`。`load.parseDates` が true のときだけ。Excel の日付セル(もともと datetime の列)は設定にかかわらず日時): 読込後に数値でない文字列の列のうち、空欄以外の半数以上が数値に読める列は除く。書式は年が先頭の固定の候補だけ(日付 `%Y-%m-%d` / `%Y/%m/%d` / `%Y年%m月%d日`、時刻は無し / ` %H:%M` / ` %H:%M:%S` / ` %H:%M:%S.%f`、`%Y-%m-%d` には ISO の `T` 区切りも、時刻のあるものには末尾 `%z`(`Z` と `+09:00`)も)。前後の空白を除いた先頭 100 個の空欄以外の値の 90% 以上が読める書式のうち最も多く読めるものを選び、列全体でも 90% 以上が読めれば日時の列にする。月日の順が曖昧な `01/02/2024`、時刻だけ、年月だけは認識しない。読めない値は NaT にして、列ごとに警告(「列「name」[i]: 日時として読めない値がN件あったため、欠損として扱います(例: …)」。例は最大3件)。`%z` 付きは、全行が同じオフセットなら書かれた時刻のまま、混在していれば UTC にそろえて警告する。日時の列は `columns[].kind` が `datetime` になり、データ確認の列見出しに「日時」の印が付く。日時の X で描くときの検査は §4.1。 @@ -332,6 +358,14 @@ uv run pytest tests/e2e # E2E(Chromium とローカルの静的サー - `test_settings.py`: 5c の既定値と、新しい種類・隠れた設定の検証、`test_defaults_parity.py`: `DEFAULT_COMPUTED` も Python と比べる、`test_js_modules.py`: node で読み込む JS モジュールに `chart-types.js` を足した(`presets.js` と `state.js` が import するため)。 - Phase 5c で加えた E2E: `test_chart_types.py`(選択肢の既存の表示を変えず新しい種類が増える、種類ごとの欄の出し分け、種類を切り替えても隠した値が残る、step の `drawstyle`、barh の軸ラベルと縦軸の目盛の間隔、積み上げ棒の負の値、ヒストグラムの `data-summary` と X 列の非表示、区間の数のエラーと復帰、色分けの列が未選択のエラーと復帰、データ元を替えると色分けの列が戻る、隠れた不正な値が描画を止めない、編集モードで種類を替えても図もコードも変わらない、狭い画面)、`test_computed.py`(式を足して Y に使う、雛形のボタン、すべての列の選択肢に出る、削除で系列の列が戻り後ろの参照が詰まる、読み直しで列が増えても参照を保つ、列が減ったとき無くなった列への参照を空に戻す、式の誤りのエラーと復帰、ほかの計算した列への参照のエラー、2ファイルで2つ目のデータ元、追加ボタンの上限、編集モード、狭い画面)。`test_codegen_consistency.py` に、7 つの一致確認(`type_step` / `type_barh_err` / `type_bar_stacked` / `type_hist` / `type_scatter_color` / `computed_one_file` / `computed_two_files`)を足した(比べる要約に `drawstyles` / `bars` / `colorbar` を加えた。fixture は `chart_types.csv`)。 - `helpers.py` の Phase 5c 用ヘルパー: `set_plot_type`(種類を変えて読込・描画が一段落するまで待つ)、`plot_settings`(state の `plot`。隠した値が残っているかの確認)、`visible_ids`(id → 画面に出ているか)、`add_computed`(カードを足して名前・式・データ元を入れ、id を返す)、`computed_index_text`(`computed--index` の文)、`option_labels`(select の option の value → 表示)。 +- Phase 5d で加えた単体テスト: + - `test_expr.py`(モデルの式): `parse_model`(変数 `x` とパラメータ `a`〜`e`、`x` を含まない式・パラメータの無い式・列・集計・系列の処理・知らない名前のエラーと位置、`e` と `exp` と `1e-3` の区別、使ったパラメータの順 `model_params`)、`model_to_code` / `model_to_text` / `evaluate_model` の意味の一致。 + - `test_chart_types.py`(5d の分): box / violin / heatmap の受け入れと既定値、`plot.box` / `plot.violin` をその種類のときだけ検証すること、隠れる設定(点の形・帯・近似曲線・エラーバー・第2Y軸・ヒートマップの色・線幅・線種)を検証しないこと、`chart-types.js` と `settings.py` の規則の一致(node)、生成コードを実行した artist(箱の数・位置・外れ値と平均の切替・NaN と値の無い系列・バイオリンの胴と中央値の線・値が1個の系列・横軸がカテゴリ・注釈の X がカテゴリ番号・Y が日時のエラー・ヒートマップの集計と重複の警告・欠けたマス・文字列の X / Y・500 種類の上限・日時のエラー・値の列の必須と日時・系列2つのエラーが値の列より先に出ること・自動の軸ラベル)、「全体を実行した図」と「自動描画用の図」の要約の一致、コード注入。 + - `test_fits.py`(任意の式): scipy で直接当てはめた値との一致、表示の文字(`y = 式(a = …、R² = …)`)、初期値の検証と `field`、式の空欄・構文エラー、点の数がパラメータの数以下のエラー、収束しないとき・初期値で有限でなくなるときの手順のメッセージ、`from scipy.optimize import curve_fit` が任意の式のときだけ入ること、`poly_text` の定義が任意の式だけでは入らないこと、`api` の scipy が無いときのエラー(`_require_scipy`)、式の注入(コメントにだけ入る)。 + - `test_settings.py` / `test_defaults_parity.py`: 5d の既定値(`plot.box` / `plot.violin`、`fits[]` の `expr` / `initial`)と、JS と Python の一致。`test_runner.py`: `figure_summary` の `boxes` / `violins` / `meshes`、ImportError の案内。 +- Phase 5d で加えた E2E: `test_chart_types.py`(5d の分: box / violin の `data-summary` と切替、箱ひげの横軸がカテゴリで目盛・注釈の X が番号になること、ヒートマップの値の列の欄名と描画、値の列が未選択のエラーと復帰、系列が2つのエラーと復帰、文字列の軸でカテゴリの文言になること、編集モードで新しい種類へ切り替えても図もコードも変わらないこと)、`test_custom_fit.py`(カードの欄がモデルと式に追従する、任意の式がないとき scipy を取りにいかない、scipy を実際に読み込んで当てはめる・収束しないエラーと復帰、scipy の読込失敗(`page.route` で止める)、編集モードで `import scipy` するコードの実行前に読み込む)。`test_codegen_consistency.py` に、4 つの一致確認(`fit_custom` / `type_box` / `type_violin` / `type_heatmap`。fixture は `band.csv` / `chart_types.csv` / `grid.csv`)を足した(比べる要約に `boxes` / `violins` / `meshes` を加えた)。scipy を実際に読み込むテストは、Pyodide の scipy(約 14 MB)を取得するのでインターネット接続が必要。 + - `helpers.py` の Phase 5d 用ヘルパー: `scipy_state(page)`(``)、`wait_scipy_state(page, state, timeout)`(既定 300 秒)。 + - 開発環境の依存に `scipy==1.18.0` を足した(`pyproject.toml` の dev グループ。単体テストで任意の式の生成コードを実行する)。 - E2E は要素を id だけで選ぶ。`index.html` の id は安定させ、変えるときはテストも直す。アプリ固有の待機・操作は `tests/e2e/helpers.py` にまとめる。 - テストデータは `tests/fixtures/` の合成データだけ(公開リポジトリなので実データを置かない)。 - テスト用サーバー(`tests/e2e/server.py`)は listen backlog を 128 に広げている。既定の 5 だと、Chromium が ES モジュールを一斉に取得したときに接続が切れて、アプリが起動しないことがある。 @@ -344,6 +378,7 @@ uv run pytest tests/e2e # E2E(Chromium とローカルの静的サー - `test_cdn_pinning.py` は、フォント(`@expo-google-fonts/*@x.y.z`、`@fontsource/*@x.y.z`)の jsDelivr URL と、バージョン付きのパスの `matplotlib.org`(取得しない説明リンク)を許可する。新しい JS モジュール(`js/units.js`、`js/ui/dropPaste.js`、`js/ui/fileList.js` など)は静的ファイルとしてそのまま公開される(`pyscript.toml` は Python ファイルだけ)。Phase 4 では新しい Python モジュールも CDN も足していない(`pyscript.toml` と CI の変更なし)。 - 新しい Python モジュールを追加したら、`pyscript.toml` の `[files]` に必ず追加する(`tests/unit/test_pages_publish.py` が参照ファイルの公開を確認する)。 - Phase 5c で `py/mplgui/expr.py` を `pyscript.toml` の `[files]` に足した(新しい Python モジュールはこれだけ。CDN と CI の変更なし)。新しい JS モジュール(`js/chart-types.js`、`js/computed-refs.js`、`js/ui/computed.js`)は静的ファイルとしてそのまま公開される。 +- Phase 5d: 新しい Python モジュールも CDN の URL も足していない(`pyscript.toml` の変更なし。scipy は Pyodide 同梱のパッケージを名前で読むだけで、リポジトリに URL を書かないので `test_cdn_pinning.py` も変えていない。§6)。`pyproject.toml` の dev グループに `scipy==1.18.0`(ブラウザの Pyodide と同じ版。単体テストで生成コードを実行するため。実行時の依存ではない)を足した(`uv.lock` も更新)。E2E ジョブの `timeout-minutes` を 60 から 90 に上げた(Phase 5c で約 43 分かかった)。 - matplotlib 3.10 では `tight_layout()` 後に `PlaceHolderLayoutEngine` が残り、`savefig` が余分に全体を再描画する。`runner.drop_placeholder_layout_engine` がこれを外している(出力は同一)。 ## 12. 運用ルール(必須) @@ -405,3 +440,5 @@ uv run pytest tests/e2e # E2E(Chromium とローカルの静的サー - G6: 列は `[N]` か Excel の列記号(`A` = `[0]`)で参照する。式は許可した要素だけを自前で解釈し(`eval` を使わない)、生成コードは解釈した結果から決まった形で書く。 - 5b(2026-11-10): 系列の複製は全設定を写し、色だけパレットの未使用の色にして直後に入れる(近似曲線は写さない)。近似曲線の式は「温度の近似: y = 1.234x + 5.678(R² = 0.9981)」(係数は有効数字4桁、R² は小数4桁で固定。「図の中」は左上に並べる)。文字列の X・棒グラフの X では、注釈の X は「何番目のカテゴリか(0 始まり)」。画面の「透明度」は「不透明度」(0〜1、alpha と同じ向き)と表示する。 - 5c(2026-11-12): ヒストグラムの複数系列は区間ごとに横に並べる(区間は全系列で共通)。計算した列の式から、ほかの計算した列は参照できない(読み直しで列の数が変わると式の列番号を直せないため。複数の処理は1つの式に書く)。計算した列は「描画から除外する先頭行」を除いた行で計算し(集計もその行だけ)、データ確認タブには出さない。色分け散布図は、凡例の点を灰色にし、第2Y軸は使えず、色の範囲は全系列共通で自動(指定なし)。重さは普通の散布図と同じ見た目で作って計測し、1 秒を超えたら見直す。→ 計測で約 1.21 秒になったため、点の縁を描かず、縁の太さ(1.5 pt)の分だけ点の面積を大きくすることにした(約 0.94 秒。点の形が x / + のときは縁を描く。2026-11-12 にユーザーが決定)。 +- 5d・5e(2026-11-12): 5d を2本に分ける(5d: G8・G10、5e: G9。G9 は軸が1組という前提を全体で変え、G8 の種類もパネルに載せるため後にする。5e の詳しい設計は 5d のマージ後に相談)。ヒートマップは X・Y・値の3列から格子を作る(同じ組は平均、系列は1つ)。箱ひげ図・バイオリン図は系列ごとに左から並べ、塗りは系列の色、ひげは 1.5×IQR、外れ値は表示・平均は非表示が既定、縦向きだけ、凡例なし。任意関数のフィッティングは変数 `x` とパラメータ `a`〜`e`、初期値の既定 1、表示は「y = 式(a = …、R² = …)」。dev の依存に scipy を足す。 +- 5d の実装での決定(2026-11-12): バイオリン図の中央値・平均の線は黒にした(系列の色では、塗りつぶした胴(既定の不透明度 1)の上で見えないため。箱ひげ図の中央値の線と同じ。端の線は系列の色)。ヒートマップは系列が2つ以上のとき、系列ごとの検証(値の列が未選択など)より先に「ヒートマップは系列1つで描きます。系列を1つにしてください。」を返す(先に値の列のエラーが出ると、系列を足した直後に利用者が混乱するため)。任意の式の近似曲線は、`curve_fit` が収束しても、初期値のところで式が有限でない値になると初期値のまま黙って返すことがあるので、生成コードで当てはめた曲線の値が有限か確かめ、有限でなければ ValueError にする(手順で「式を当てはめられませんでした」に置き換わる)。 diff --git a/README.md b/README.md index b06a440..6200404 100644 --- a/README.md +++ b/README.md @@ -29,21 +29,23 @@ https://mioupa.github.io/matplotlib_gui/ を開いてください。`index.html` ## 主な機能 - 系列カード(複数系列、X/Y列、色、線幅、線種、点サイズ、凡例名)と、第2Y軸 -- プロット種別: line / step(段グラフ)/ scatter / scatter(色分け)/ bar / bar(積み上げ)/ barh(横棒)/ hist(ヒストグラム) +- プロット種別: line / step(段グラフ)/ scatter / scatter(色分け)/ bar / bar(積み上げ)/ barh(横棒)/ hist(ヒストグラム)/ box(箱ひげ図)/ violin(バイオリン図)/ heatmap(ヒートマップ) - 軸の対数表示と範囲指定、余白指定、主目盛線・副目盛線、凡例位置 - エラーバー: 系列ごとに、Y 方向・X 方向(棒グラフは Y 方向だけ)を「固定値」か「列で指定」から選びます。上下(左右)で別の値も指定でき、端の長さも変えられます。誤差の列が空欄・数値にできない値・負の値の点は、その点だけ描かず、警告で知らせます - 目盛の詳細: 「軸・目盛」の「X軸の目盛」「Y軸の目盛」「第2Y軸の目盛」で、主目盛の間隔(日時の X は「何日ごと」など単位つき、文字列の X は「何個おき」)、副目盛(自動・表示・なし、分割数)、数字の書式(小数の桁数・指数表記・10^n 表記)、軸の反転を指定します。対数軸では主目盛の間隔は使えません。間隔が小さすぎて目盛が 100 本を超えるときは、エラーで案内します - 上・右の枠線の表示・非表示(第2Y軸があるときは、右の枠線は消せません) - 系列のスタイル: 点の形(丸・四角・三角・ひし形・×・+・星・なし)、不透明度、塗りつぶし帯(下端と上端の2つの列の間を塗ります。誤差の大きさではなく、値そのものを指定します)。棒グラフでは、点の形と帯は使えません。帯の列に数値にできない値があるときは、その点で帯を切り、警告で知らせます。系列は「↑」「↓」で並べ替え、「複製」でコピーできます(複製は色だけパレットの未使用の色になります) - 注釈: 「注釈・解析」の区分で、文字・水平線・垂直線・横の帯(Y の範囲)・縦の帯(X の範囲)を図に加えます(50 個まで)。位置は軸の種類に合わせて入力します(日時の X は日付、文字列の X は何番目のカテゴリか(0 始まり))。文字は「図の中の割合」(0〜1)でも置けます。第2Y軸があるときは、Y を使う注釈を左右どちらの軸に置くか選べます。凡例名を入れた線・帯は、凡例にも出ます -- 近似曲線: 系列ごとに、最小二乗法で1次式か多項式(2〜6 次)をあてはめます(20 本まで)。式と決定係数 R² を、凡例か図の中(左上)に出せます。X が数値の系列だけが対象で、棒グラフでは使えません。対数軸でも、近似は軸の目盛ではなく元の値で行います +- 近似曲線: 系列ごとに、最小二乗法で1次式か多項式(2〜6 次)、または任意の式をあてはめます(20 本まで)。任意の式は、変数 `x` とパラメータ `a`〜`e`(式で使ったものだけ。初期値の既定は 1)で書き、使える関数は `abs` `sqrt` `exp` `log` `log10` `sin` `cos` `tan` です(例: `a*exp(-b*x) + c`)。任意の式の当てはめには scipy を使い、初めて「任意の式」を使ったときだけ読み込みます(約 14 MB。同じブラウザでは2回目以降はキャッシュを使います。初回はインターネット接続が必要です)。収束しないときは初期値を変えてください。生成した `.py` を手元で動かすには、scipy が必要です。式(任意の式ではパラメータの値も)と決定係数 R² を、凡例か図の中(左上)に出せます。X が数値の系列だけが対象で、棒グラフ・箱ひげ図・ヒートマップなどでは使えません。対数軸でも、近似は軸の目盛ではなく元の値で行います - グラフの種類(「系列」の「グラフの種類」で選びます): - step: 値が次の点まで続く段グラフです。段の付き方(次の点まで値を保つ / 前の点から値を保つ / 点と点の中間で切り替える)を選べます。点の形・エラーバー・塗りつぶし帯・近似曲線・第2Y軸は line と同じように使えます - barh(横棒): カテゴリを縦軸、値を横軸にした棒グラフです。複数系列は縦方向に並べます。Y 方向のエラーバーは、値の誤差として横向きに付きます。カテゴリは下から並ぶので、上から並べたいときは Y軸の反転を使ってください - bar(積み上げ): 複数系列を縦に積んだ棒グラフです。負の値は、正の値とは別に下へ積みます。欠けた値は 0 として積みます。エラーバーと第2Y軸は使えません - hist(ヒストグラム): 各系列の Y 列の値の分布を描きます。区間は全系列で共通で、複数系列は区間ごとに横に並べます。区間の数(空欄は自動。自動で 1000 個を超えるときは指定が必要)と、縦軸を確率密度にするかを選べます。X 列は使いません - scatter(色分け): 点を「色分けの列」の値で塗り、カラーバーを1本付けます。色の範囲は全系列で共通です。カラーマップとカラーバーのラベルを選べ、凡例の点は灰色です(色はカラーバーで読みます)。色分けの列に数値にできない値があるときは、その点を描かず、警告で知らせます。第2Y軸は使えません - - 種類によって使えない設定(棒グラフ・ヒストグラムの点の形・塗りつぶし帯・近似曲線など)は画面で隠れ、図にも使われません(値は残るので、種類を戻すと復活します) + - box(箱ひげ図)/ violin(バイオリン図): 系列ごとに Y 列の値の分布を1つずつ、左から系列の順に並べます(横軸は系列の名前。向きは縦だけで、凡例は出しません)。箱・胴の塗りは系列の色です。ひげは箱の端から 1.5×IQR まで。箱ひげ図は外れ値の点(既定は表示)と平均の印(既定は非表示)、バイオリン図は中央値の線(既定は表示)と平均の線(既定は非表示)を切り替えられます。数値にできない値は除いて警告し、描ける値が無い系列(バイオリンは値が2個未満)は位置を空けたまま描きません。エラーバー・第2Y軸・近似曲線は使えません + - heatmap(ヒートマップ): X・Y・値の3列の縦長の表から格子を作り、カラーマップで塗ります(系列は1つ。値の列は系列カードの「値の列」で選びます)。同じ X・Y の組は平均を描き、値の無いマスは塗りません。X・Y は数値か文字列の列で、異なる値はそれぞれ 500 種類までです。カラーマップとカラーバーのラベルは色分けの散布図と共通です + - 種類によって使えない設定(棒グラフ・ヒストグラム・箱ひげ図・ヒートマップなどの点の形・塗りつぶし帯・近似曲線など)は画面で隠れ、図にも使われません(値は残るので、種類を戻すと復活します) - 計算した列: 「注釈・解析」の「計算した列」で、式から新しい列を作り、系列の X・Y・エラーバー・帯・色分けの列に選べます(「名前 [番号](計算)」と表示されます。データ確認タブには出ません)。列は `[N]` か Excel の列記号(`A` = `[0]`、`B` = `[1]`)で参照します。使えるのは `+ - * /`、`^`(または `**`)、括弧、関数 `abs` `sqrt` `exp` `log`(自然対数)`log10` `sin` `cos` `tan`、集計 `min` `max` `mean` `median` `std` `first` `last`、`rolling_mean(式, 窓の幅)`(移動平均)・`diff`・`cumsum` です。「正規化」「オフセット」「移動平均」のボタンで、よく使う式の雛形を入れられます。計算は「描画から除外する先頭行」を除いた行で行い、数値にできない値や、0 での割り算などで計算できなかった値は欠損にして警告します。ほかの計算した列は参照できません。式の誤りは、何文字目かを添えて日本語で案内します(式は自前の解釈器で読み、`eval` では実行しません。生成した `.py` では、式の文字列はコメントにだけ入り、計算は pandas / numpy の式で書かれます)。20 個まで作れます - 保存: png / jpg / svg / pdf、背景透過。PNG・JPG は保存 DPI(72 / 150 / 300 / 600 または任意の値。既定は 300)を指定できます。プレビューは 100 dpi で表示します - PDF は文字をフォントとして埋め込みます(Type 42)。Illustrator などで文字を編集できます。SVG は、文字を「パスに変換」(既定。どの環境でも同じ見た目)か「テキストのまま」(編集できる。開く環境に同じフォントが無いと見た目が変わります)から選べます @@ -69,7 +71,7 @@ https://mioupa.github.io/matplotlib_gui/ を開いてください。`index.html` ### 書き出した .py をローカルで実行する 1. 書き出した `.py` を、データファイルと同じフォルダに置きます(スクリプトは元のファイル名でデータを読みます)。 -2. `pip install pandas matplotlib numpy` を実行します。`.xlsx` を読むときは `openpyxl` も入れます。 +2. `pip install pandas matplotlib numpy` を実行します。`.xlsx` を読むときは `openpyxl`、任意の式の近似曲線を使ったコードでは `scipy` も入れます。 3. `python plot.py` で実行します(ファイル名は書き出した名前に読み替えてください)。 日本語フォントは、見つかったものを使います。無い場合も実行はできますが、日本語は豆腐(□)で表示されます。欧文フォントを選んだ図は、Arimo / Tinos(または Arial / Times New Roman、Liberation)が入っていればそれを使い、無ければ日本語フォントで書きます。PDF の文字は TrueType 形式のフォントなら正しく埋め込まれます。macOS のヒラギノなど OpenType(CFF)形式のフォントでは、PDF の文字が正しく表示されないことがあります。そのときは Noto Sans JP(TrueType 版)を入れてください。 diff --git a/css/style.css b/css/style.css index a6af05c..da1b26f 100644 --- a/css/style.css +++ b/css/style.css @@ -1208,6 +1208,8 @@ button.series-color-chip.active { .ann-field[hidden], .ann-help[hidden], .fit-degree-wrap[hidden], +.fit-custom-wrap[hidden], +.fit-initial-item[hidden], .fit-color-picker-wrap[hidden], #fitList[hidden], #addFitBtn[hidden], @@ -1245,3 +1247,14 @@ button.series-color-chip.active { max-width: 100%; box-sizing: border-box; } + +.fit-initial-row { + display: flex; + flex-wrap: wrap; + gap: 8px; + margin-top: 4px; +} +.fit-initial-item { + flex: 1 1 64px; + min-width: 64px; +} diff --git a/docs/PERFORMANCE.md b/docs/PERFORMANCE.md index 94a9848..695dff9 100644 --- a/docs/PERFORMANCE.md +++ b/docs/PERFORMANCE.md @@ -524,3 +524,88 @@ Phase 3 後より 5% を超えて悪くなった既存項目は無い(日本 - コールド起動: 3,697 → 7,492 ms(最小 3,813 / 最大 15,336 ms)。ウォーム起動: 3,568 → 4,339 ms(最小 3,603 / 最大 5,017 ms)。保存(PNG、120 dpi): 243 → 265 ms(+9%。Phase 5a 後は 266 ms)。 - 該当する群(`--only old`)だけを、Phase 5b のコード(`4447cb2`)と現在のコードで続けて計測した(各 N=5。5b のコードは一時的な git worktree から配信し、計測後に削除した)。結果は同等だった: コールド起動 3,733 → 3,742 ms、ウォーム起動 3,526 → 3,561 ms(+1%)、保存(PNG、120 dpi)266 → 265 ms。同じ群のほかの項目も ±2% 以内(日本語フォントの追加待ちは 85 → 66 ms)。1回通しの計測で出た差は、その回のネットワーク(起動時に Pyodide とパッケージを CDN から取得する。最大値が 15 秒)とマシンの状態によるぶれで、5c のコードによる劣化ではない。5c で起動時に増えたのは、小さな JS モジュール3つと `py/mplgui/expr.py` の取得だけ。 - 残りの既存項目は ±5% 以内(改善した行も、回ごとのぶれの範囲)。Phase 5c は既定の設定の生成コードを変えない(ゴールデンテストで確認)ため、新しい機能を使わない描画の経路は変わっていない。 + +## Phase 5d 後 + +### 計測条件 + +| 項目 | 内容 | +|---|---| +| 日付 | 2026-11-12 | +| 対象 | `f93f0a8`(Phase 5d: 箱ひげ図・バイオリン図・ヒートマップ、任意の式の近似曲線)に、Phase 5d の計測行を追加した `tests/perf/bench.py` を組み合わせたもの。PyScript 2026.7.3 / Pyodide 314.0.3 | +| マシン | Mac16,10 / Apple M4 / メモリ 24 GB | +| OS | macOS 27.0.1 | +| ブラウザ | Chromium 153.0.8010.12(Playwright、ヘッドレス) | +| ネットワーク | 実ネットワーク(Phase 5c 後と同じ) | +| 配信 | ローカルの静的 HTTP サーバー(127.0.0.1、サブパスなし) | +| 反復 | 各項目 N=5、全項目を1回通しで計測。既存項目の計測方法は Phase 5c 後と同じ | + +追加した項目(`--only p5d`。既存項目の方法は変えていない。データは実行時に生成し、コミットしない): + +- 「箱ひげ図」「バイオリン図」: 既存の 10,000 行 × 6 列の CSV で、系列5本(Y = 列1〜5)をグラフの種類「box」「violin」にする。`data-summary` の `boxes`(`violins`)が 5 になるのを待ってから、既存の「設定変更」と同じ方法(タイトルの `input` → 新しい画像。デバウンス 250 ms 込みと除いた値)で測る。 +- 「ヒートマップ」: 100×100 の格子の縦長の表(x・y・z の 10,000 行)の CSV で、系列1本(X = 列0、Y = 列1、値の列 = 列2)をグラフの種類「heatmap」にする。`meshes` が 1 でカラーバーが出るのを待ってから、同じ方法で測る。 +- 「任意の式の近似曲線」: 既存の 10,000 行 × 6 列の CSV の line(系列5本)に、近似曲線を5本(各系列に任意の式 `a*x + b`、凡例に表示)付ける。`data-scipy-state` が `ready`、`fitlines` が 5 になるのを待ってから、同じ方法で測る。 +- 参考「scipy の初回読み込み」: データを読み込んだ新しいページで、近似曲線を1本足して任意の式 `a*x + b` に切り替えてから、近似曲線の付いた図が出るまで。回ごとに新しいページ(コンテキストは他の項目と同じく温めたもの。scipy は温めの段階では読み込まない)。 + +### 結果(ミリ秒、中央値 / 最小 / 最大) + +| 項目 | Phase 5c 後 | Phase 5d 後 | Phase 5c 後比 | +|---|---:|---:|---| +| コールド起動 | 7,492 | 3,743 / 3,693 / 6,766 | -50%(Phase 5c 後の値は回線のぶれ。下記) | +| ウォーム起動 | 4,339 | 3,553 / 3,543 / 3,557 | -18%(Phase 5c 後の値は回線のぶれ。下記) | +| 初回ファイル読込 → 最初のプロット | 187 | 182 / 181 / 184 | 同等(-3%) | +| 設定変更 → プロット更新(デバウンス込み) | 470 | 474 / 469 / 476 | 同等(+1%) | +| 同上(デバウンス 250ms 除く) | 220 | 224 / 219 / 226 | 同等(+2%) | +| 保存(PNG、クリック → ダウンロード開始。既定の 300 dpi) | 414 | 397 / 388 / 400 | 同等(-4%) | +| 初回 .xlsx 読込 → 最初のプロット | 340 | 334 / 331 / 336 | 同等(-2%) | +| 編集モードでの実行(Ctrl/Cmd+Enter → プロット更新) | 599 | 593 / 583 / 607 | 同等(-1%) | +| 保存(PNG、120 dpi) | 265 | 262 / 237 / 266 | 同等(-1%) | +| 保存(PNG、300 dpi。別測定) | 408 | 401 / 401 / 405 | 同等(-2%) | +| 欧文フォント選択 → プロット更新、初回(Arimo を jsDelivr から取得) | 472 | 472 / 453 / 473 | 同等(-0%) | +| 同上、Cache Storage にあるとき | 473 | 471 / 469 / 474 | 同等(-0%) | +| 参考: 欧文フォント初回の、選択 → `data-latin-font-state=ready` | 31 | 26 / 26 / 31 | 参考値(-15%) | +| クリップボードへのコピー(クリック → done、300 dpi) | 417 | 418 / 417 / 420 | 同等(+0%) | +| 日本語フォント取得、コールド(ナビゲーション開始 → `font-state=ready`) | 3,761 | 3,705 / 3,687 / 3,771 | 同等(-1%) | +| 同上、Python 準備完了からの追加待ち | 64 | 61 / 51 / 80 | 参考値(-4%) | +| 貼り付け(10,000 行 × 6 列)→ 最初のプロット | 188 | 186 / 186 / 188 | 同等(-1%) | +| 貼り付け(30 行 × 3 列)→ 最初のプロット | 137 | 136 / 134 / 139 | 同等(-1%) | +| xlsx(2 シート × 10,000 行)初回読込 → 最初のプロット | 865 | 856 / 848 / 867 | 同等(-1%) | +| xlsx のシート切り替え → プロット更新(系列5本) | 476 | 477 / 475 / 560 | 同等(+0%) | +| 日時の列を含む 10,000 行の読込 → 最初のプロット | 246 | 250 / 244 / 294 | 同等(+1%) | +| 同、X = 日時で設定変更 → プロット更新(デバウンス込み、系列5本) | 488 | 489 / 486 / 495 | 同等(+0%) | +| 同上(デバウンス 250ms 除く) | 238 | 239 / 236 / 245 | 同等(+0%) | +| 2ファイル(各 10,000 行)の読込 → 最初のプロット | 218 | 217 / 214 / 225 | 同等(-0%) | +| 2ファイルで設定変更 → プロット更新(デバウンス込み、系列2本) | 354 | 347 / 332 / 349 | 同等(-2%) | +| 同上(デバウンス 250ms 除く) | 104 | 97 / 82 / 99 | -7%(改善。回ごとのぶれの範囲) | +| エラーバー(系列5本すべて)の設定変更 → プロット更新 | 806 | 801 / 792 / 838 | 同等(-1%) | +| 同(デバウンス除く) | 556 | 551 / 542 / 588 | 同等(-1%) | +| 目盛・枠線を設定した設定変更 → プロット更新 | 505 | 504 / 499 / 507 | 同等(-0%) | +| 同(デバウンス除く) | 255 | 254 / 249 / 257 | 同等(-0%) | +| 帯・近似曲線・注釈(系列5本すべてに帯と近似曲線、注釈3つ)の設定変更 → プロット更新 | 707 | 703 / 693 / 720 | 同等(-1%) | +| 同(デバウンス除く) | 457 | 453 / 443 / 470 | 同等(-1%) | +| 色分け散布図(系列5本、色分けの列5つ、凡例あり)の設定変更 → プロット更新 | 941 | 950 / 937 / 959 | 同等(+1%) | +| 同(デバウンス除く) | 691 | 700 / 687 / 709 | 同等(+1%) | +| ヒストグラム(系列5本、区間は自動)の設定変更 → プロット更新 | 416 | 416 / 414 / 417 | 同等(-0%) | +| 同(デバウンス除く) | 166 | 166 / 164 / 167 | 同等(-0%) | +| 計算した列(正規化5つ)を Y にした line(系列5本)の設定変更 → プロット更新 | 482 | 480 / 477 / 485 | 同等(-0%) | +| 同(デバウンス除く) | 232 | 230 / 227 / 235 | 同等(-1%) | +| 箱ひげ図(系列5本)の設定変更 → プロット更新 | (項目なし) | 342 / 339 / 345 | 新項目(line 5 系列の 474 ms に対して -131 ms) | +| 同(デバウンス除く) | (項目なし) | 92 / 89 / 95 | 新項目(line 5 系列の 224 ms に対して -131 ms) | +| バイオリン図(系列5本)の設定変更 → プロット更新 | (項目なし) | 390 / 388 / 391 | 新項目(line 5 系列の 474 ms に対して -84 ms) | +| 同(デバウンス除く) | (項目なし) | 140 / 138 / 141 | 新項目(line 5 系列の 224 ms に対して -84 ms) | +| ヒートマップ(10,000 行を 100×100 の格子に)の設定変更 → プロット更新 | (項目なし) | 356 / 355 / 357 | 新項目(line 5 系列の 474 ms に対して -117 ms) | +| 同(デバウンス除く) | (項目なし) | 106 / 105 / 107 | 新項目(line 5 系列の 224 ms に対して -117 ms) | +| 任意の式の近似曲線(line 5 系列それぞれに `a*x + b`)の設定変更 → プロット更新 | (項目なし) | 488 / 486 / 494 | 新項目(line 5 系列の 474 ms に対して +15 ms) | +| 同(デバウンス除く) | (項目なし) | 238 / 236 / 244 | 新項目(line 5 系列の 224 ms に対して +15 ms) | +| 参考: scipy の初回読み込み(近似曲線を任意の式にしてから、図が出るまで) | (項目なし) | 1,662 / 1,638 / 1,690 | 新項目(参考値。回線に左右される) | + +### 要件の確認 + +要件「設定変更後 1 秒以内の再描画(10,000 行 × 5 系列)」: 既存の設定変更は、デバウンス 250 ms を含めて中央値 474 ms で、**満たしている**。新しい種類は、箱ひげ図が中央値 342 ms、バイオリン図が 390 ms、ヒートマップ(10,000 行、100×100 の格子)が 356 ms、任意の式の近似曲線(5 系列)が 488 ms で、いずれも**満たしている**。色分け散布図(950 ms)、エラーバー(801 ms)、帯・近似曲線・注釈(703 ms)も引き続き満たしている。 + +### 分析 + +- **箱ひげ図・バイオリン図・ヒートマップ**: 描く図形が、箱・胴・格子のマスだけなので、line(10,000 点 × 5 本。凡例の位置「best」の探索を含む)より軽い(-84〜-131 ms)。バイオリン図は密度の推定(系列ごとに 10,000 点 × 100 点)の分だけ箱ひげ図より重い(+48 ms)。 +- **任意の式の近似曲線**: line 5 系列に対して +15 ms。`curve_fit` の計算は数 ms で、増えた分の大半は近似曲線の線5本と凡例の項目。 +- **scipy の初回読み込み**: 5 回とも 1.6〜1.7 秒(中央値 1,662 ms)。1回目は scipy の wheel(約 14 MB)を jsDelivr から取得し、2回目以降は同じコンテキストの HTTP キャッシュから読める可能性があるが、回ごとの差は小さかった(1回目 1,690 ms)。この回線では取得は速く、時間の大半は wheel の展開と scipy の読み込みと考えられる(推定)。遅い回線では取得の分だけ延びる。起動時と、任意の式を使わない描画では scipy を読み込まない(E2E で確認)。 +- **既存項目**: 5% を超えて悪くなった行は無い。コールド起動(3,743 ms)とウォーム起動(3,553 ms)は、Phase 5c 後の1回通しの値(回線のぶれ。Phase 5c 後の分析を参照)より小さく、Phase 5b 後(3,697 / 3,568 ms)や Phase 5c 後の A/B の値(3,742 / 3,561 ms)と同等。コールド起動の最大 6,766 ms は1回目(回線のぶれ)。2ファイルの設定変更(デバウンス除く)の -7% は回ごとのぶれの範囲。Phase 5d は既定の設定の生成コードを変えない(ゴールデンテストで確認)ため、新しい機能を使わない描画の経路は変わっていない。 diff --git a/docs/PHASE5_DESIGN.md b/docs/PHASE5_DESIGN.md index 43713da..9b695ac 100644 --- a/docs/PHASE5_DESIGN.md +++ b/docs/PHASE5_DESIGN.md @@ -565,3 +565,159 @@ ax.plot(x_fit, fit(x_fit), color="#FF4B00", linewidth=2.0, linestyle="dashed", l 2. **計算した列からほかの計算した列は参照できない**、でよいか(読み直しで列の数が変わったとき、式の中の列番号は直せないため。「正規化してから移動平均」は `rolling_mean([1] / max([1]), 5)` のように1つの式に書ける)。 3. **計算する行**: 「描画から除外する先頭行」を除いた行で計算する(`max` や `first` もその行だけ)。データ確認タブには計算した列を出さない。これでよいか。 4. **色分け散布図**: 凡例の点は灰色、第2Y軸は使えない、色の範囲は全系列共通で自動(範囲の指定は無し)。重さは §6.6 のとおり計測してから判断する。これでよいか。 + +--- + +## 7. 5d の詳細(G8 グラフの種類 第2弾、G9 サブプロット、G10 任意関数のフィッティング) + +作成: 2026-11-12。2026-11-12 にユーザーが承認(§7.8 はすべて提案どおり。5d と 5e に分け、ヒートマップは案 H2)。 + +### 7.0 準備 + +- PR #7(5b)は main にマージ済み。#8(5c)は CI の実行中で、まだマージしていない。5d は `phase5c-data` から `phase5d-more` を作って進め、PR は #8 のマージ後に main 向きで作る(#6 のように main 以外にマージされるのを防ぐため)。 +- スキーマは v4 のまま、項目を足す(§2.1)。新しい項目の既定値では、生成コードは Phase 4 と1文字も変わらない(ゴールデンテスト)。 +- scipy(G10、U5): Pyodide 314.0.3 の同梱パッケージに scipy 1.18.0 がある。依存は numpy だけで、numpy は読み込み済みなので、初めて使うときに取得するのは wheel 1つ(約 14.0 MB)。`pyodide_js.loadPackage(["scipy"])` と名前で読むと、取得先は Pyodide の版を含む jsDelivr の URL(`/pyodide/v314.0.3/full/`)で、ハッシュも確かめられる。リポジトリに URL を書かないので、`test_cdn_pinning.py` は変えなくてよい。 +- 開発環境には scipy が無い。単体テストで生成コードを実行するため、`pyproject.toml` の dev グループに `scipy==1.18.0`(ブラウザと同じ版)を足す(実行時には使わない。openpyxl と同じ扱い)。 +- CPython での実測(10,000 行 × 5 系列、8×6 inch、dpi 100、PNG まで、中央値): 箱ひげ図 22 ms、バイオリン図 43 ms、ヒートマップ(10,000 行を 100×100 の格子に集計 + `pcolormesh` + カラーバー)31 ms。参考: 今の line(5 本、凡例の位置 best)198 ms。`curve_fit`(`a*exp(-b*x)+c`、10,000 点 × 5 系列)6 ms。2×2 のサブプロット(線 8 本)154 ms(1つの軸に 8 本だと 299 ms。凡例の位置の探索が軸ごとに小さくなるため)。 + +### 7.1 PR の分け方(提案: 5d と 5e に分ける) + +| PR | 内容 | +|---|---| +| **5d** | G8(箱ひげ図・バイオリン図・ヒートマップ)、G10(任意関数のフィッティング) | +| **5e** | G9(サブプロット) | + +- G9 は、今のコード生成の「軸は `ax` と `ax2` の1組」という前提を、ほぼすべての出力(系列・注釈・近似曲線・軸・グリッドと凡例・カラーバー・ヒストグラムの共通の区間)で変える。G8 の新しい種類もパネルに載せる必要があるので、G8 の後にまとめて作るほうが作り直しが無い。 +- G8・G10 は、今の構造にグラフの種類と近似のモデルを足すだけで済む。 +- 5e の詳しい設計は、5d のマージ後に改めて相談する(§7.5 は方針だけ)。 + +### 7.2 追加する設定項目(v4 に足す) + +| キー | 既定値 | 受け付ける値・検証 | +|---|---|---| +| `plot.type` | `"line"` | `box` / `violin` / `heatmap` を足す | +| `plot.box` | `{fliers: true, means: false}` | 外れ値の点を描くか、平均の印を描くか(真偽)。`box` のときだけ使う | +| `plot.violin` | `{medians: true, means: false}` | 中央値の線・平均の線を描くか(真偽)。`violin` のときだけ使う | +| `plot.colormap` / `plot.colorbarLabel` | 今のまま | `heatmap` でも使う(色分け散布図と共有) | +| `series[].colorColumn` | 今のまま | `heatmap` でも使い、必須(ヒートマップの値。画面の欄名は「値の列」にする) | +| `fits[].model` | `"linear"` | `custom`(任意の式)を足す | +| `fits[].expr` | `""` | 任意の式。`custom` のときだけ使う。200 文字まで、空はエラー(「近似曲線Nの式を入力してください。」) | +| `fits[].initial` | `{a: 1, b: 1, c: 1, d: 1, e: 1}` | パラメータの初期値。式で使うパラメータの分だけ検証する(有限の数。誤りは「近似曲線Nの初期値(a)」) | + +### 7.3 G8 グラフの種類 第2弾 + +種類ごとに使う設定(§2.2。§6.2 の表に3列を足す): + +| 設定 | box | violin | heatmap | +|---|---|---|---| +| 系列の X 列 | – | – | ○ | +| X列(全系列共通。`#xColumn`) | – | – | – | +| Y 列 | ○(箱にする値) | ○(胴にする値) | ○ | +| 色分けの列(「値の列」) | – | – | ○(必須) | +| 点の形・点サイズ | – | – | – | +| 線幅 | ○(箱の縁・ひげ) | ○(胴の縁) | – | +| 線種 | – | – | – | +| 色 | ○(箱の塗り) | ○(胴の塗り) | –(カラーマップを使う) | +| 不透明度 | ○ | ○ | ○ | +| エラーバー・塗りつぶし帯・第2Y軸・近似曲線 | – | – | – | +| 注釈 | ○ | ○ | ○ | + +1. **箱ひげ図(`box`)**: 系列ごとに1つの箱を、左から系列の順に 0, 1, 2, … の位置に描く(`ax.boxplot(..., positions=[0, 1, …], tick_labels=[凡例名, …], patch_artist=True)`。`tick_labels` は matplotlib 3.9 からの名前)。 + - 箱の塗りは系列の色と不透明度、縁・ひげ・中央値の線は黒。ひげは matplotlib の既定(箱の端から 1.5×IQR まで)。外れ値の点と平均の印は `plot.box` で切り替える。 + - 値は `pd.to_numeric(...).dropna()` にしてから渡す(NaN が混ざると中央値が NaN になるため)。数値にできない値は、今の系列と同じ形で警告する。値が無い系列は、位置を空けたまま描かない(警告)。 +2. **バイオリン図(`violin`)**: 同じ並べ方で、系列ごとに `ax.violinplot(..., positions=[i])` を呼ぶ(系列ごとに色を付けやすい)。 + - 胴の塗りは系列の色と不透明度。端の線も系列の色。密度の推定は matplotlib の既定(Scott の方法、100 点)。 + - 実装時の変更: 中央値・平均の線は黒にした(系列の色では、塗りつぶした胴(既定の不透明度 1)の上で見えないため。箱ひげ図の中央値の線と同じ)。 + - 値が 2 個未満の系列は、密度を推定できないので描かない(警告)。 + - 箱ひげ図・バイオリン図の軸: + - 横軸はカテゴリ(系列の凡例名)。目盛は「何個おき」、注釈の X は「何番目か(0 始まり)」で、棒グラフと同じ。 + - 縦軸は数値か対数。Y が日時の列はエラーにする。 + - 系列ごとにデータ元が違ってもよい(ヒストグラムと同じ)。 + - 自動の軸ラベルは、横軸が空。縦軸は、系列が1つならその Y 列の名前、2つ以上なら空。 + - 凡例は出さない(名前は目盛に出る)。向きは縦だけ(横向きは作らない)。 +3. **ヒートマップ(`heatmap`)**: データの形は §7.8 の 2 で決める。推奨は案 H2(X・Y・値の3列の縦長の表から格子を作る)。 + ```python + heat = pd.DataFrame({"x": x[ok], "y": y[ok], "z": c[ok]}).pivot_table(index="y", columns="x", values="z", aggfunc="mean") + mesh = ax.pcolormesh(heat.columns.to_numpy(), heat.index.to_numpy(), heat.to_numpy(), cmap="viridis", shading="nearest") + colorbar = fig.colorbar(mesh, ax=ax) + ``` + - 同じ X・Y の組が複数あれば、平均を描く(件数を警告)。値の無いマスは塗らない。 + - X・Y は数値の列か文字列の列(文字列は現れた順にカテゴリとして並べる)。日時の列は 5d では使えない(日本語のエラー)。 + - X・Y の異なる値は、それぞれ 500 種類まで。多すぎるとマスが細かくなりすぎるうえ、格子でないデータを選んだ取り違えのことが多い。超えたら日本語のエラーにする(上限は計測して見直す)。 + - 系列は1つだけ。2つ以上はエラー(「ヒートマップは系列1つで描きます。」)。ヒートマップを並べるのは G9(5e)のパネルで行う。 + - H2 を推奨する理由: 色分け散布図と同じ3列(X・Y・色分けの列)を使うので、種類を切り替えても設定がそのまま使える。測定の格子(走査したマップなど)の縦長の表をそのまま描ける。 + - 案 H1(行列の表): 表を行列として扱い、系列の Y 列を左から並べて列にし、行は X列(`#xColumn`)の値にする。「1列目が軸、残りの列が測定値」の表(分光の時間変化など)に向く。ただし列が多いと、系列を1つずつ足すことになる。 + +### 7.4 G10 任意関数のフィッティング + +- 近似曲線のモデルに「任意の式」(`custom`)を足す。 +- 式は G6 の解釈器(`expr.py`)に「モデルの式」の入口(`parse_model`)を足して解釈する。 + - 使えるもの: 変数 `x`、パラメータ `a`〜`e`(式で使ったものだけ。1つ以上)、数、`+ - * /`、`**`(`^`)、括弧、要素ごとの関数(`abs sqrt exp log log10 sin cos tan`)。 + - 集計・系列の処理・列の参照は、日本語のエラーにする。`x` を含まない式もエラー。 +- 生成コード(近似曲線を描く位置は今と同じく、系列本体の直後): + ```python + def fit_model_1(x, a, b, c): # 近似曲線1の式: a * exp(-b * x) + c + return a * np.exp(-b * x) + c + fit_params, _ = curve_fit(fit_model_1, x[ok], y[ok], p0=[1.0, 1.0, 1.0], maxfev=10000) + r2 = 1 - np.sum((y[ok] - fit_model_1(x[ok], *fit_params)) ** 2) / np.sum((y[ok] - y[ok].mean()) ** 2) + x_fit = np.linspace(x[ok].min(), x[ok].max(), 200) + ax.plot(x_fit, fit_model_1(x_fit, *fit_params), color=..., linewidth=..., linestyle=..., label=...) + ``` + - 関数の本体は、解釈した木から決まった形で書く(`to_code`)。利用者が書いた式の文字列は、`comment_text()` を通してコメントにだけ入る。 + - `from scipy.optimize import curve_fit` は、任意の式の近似曲線があるときだけ冒頭の import に足す。「使い方」に scipy が要ることを書く。 + - 実装時の追加: `curve_fit` は、初期値のところで式が有限でない値になると、収束したように見せて初期値を黙って返すことがある。そこで `fit_y = fit_model_N(x[ok], *fit_params)` が有限か確かめ(`np.isfinite`)、有限でなければ ValueError にして、上の手順のメッセージに置き換える。 +- 表示: 「温度の近似: y = a*exp(-b*x) + c(a = 1.234, b = 0.5678, c = 9.012、R² = 0.9981)」。 + - 式は、解釈した木から整えた形で書く(利用者の文字列そのままではない)。 + - パラメータは有効数字4桁で、実行時に `fit_params` から作る。 + - 表示先(凡例・図の中・なし)は今と同じ。 +- エラー: + - 収束しない(`curve_fit` の RuntimeError)、初期値で計算できない値になる(ValueError)は、手順(`Step`)で「近似曲線N: 式を当てはめられませんでした。初期値を変えてみてください。」に置き換える。 + - 点の数がパラメータの数以下のときは、dataprep が先に日本語のエラーにする。 + - X が日時・文字列の系列などは、今の近似曲線と同じ。 +- scipy の読み込み(U5): openpyxl と同じく、初めて必要になったときだけ `ensureScipy()` で読み込む。 + - GUI 同期では、描画・保存・コピーの前に、任意の式の近似曲線が使われていれば読み込む。進捗には「scipy を読み込み中…(初回のみ)」と出す。 + - 編集モードでは、コードに `import scipy` / `from scipy` があれば、実行前に読み込む。 + - 読み込めなければ、日本語のエラーにする(「scipy を読み込めませんでした。インターネット接続を確かめてください。」)。 + - コードだけの更新(`script`)では読み込まない。runner の ImportError の案内に scipy を足す。 + +### 7.5 G9 サブプロット(5e。方針だけ) + +- 図の分け方は `plot.layout = {rows, cols}`(1〜4。既定は 1×1 で、今と同じ)。 +- 系列ごとにパネルを選ぶ(`series[].panel`)。注釈もパネルを選ぶ。近似曲線は系列のパネルに描く。 +- 生成コードは、`fig, axs = plt.subplots(行, 列, squeeze=False)` の後、パネルごとの節で `ax = axs[0, 1]` と置き直す。系列・注釈・軸・グリッドと凡例は、今の書き方をそのまま使う(第2Y軸もパネルごとに `ax2 = ax.twinx()`)。1×1 のときは、今のコードと1文字も変えない。 +- 軸の設定(スケール・範囲・目盛)は全パネル共通。タイトルと軸ラベルは、パネルごとに上書きできる。グラフの種類も全パネル共通。 +- (a)(b) のラベルは各パネルの左上に置く(`ax.set_title("(a)", loc="left")`。注釈の数え方を変えないため)。 +- 詳しい設計(系列の無いパネル、色分け散布図のカラーバー、ヒストグラムの区間をパネルで共有するか、など)は、5d のマージ後に相談する。 + +### 7.6 性能の見込み + +- 箱ひげ図・バイオリン図・ヒートマップは、今の line(5 系列)より軽い(§7.0 の実測)。 +- 任意の式の近似曲線の計算は数 ms。初回だけ scipy の取得(約 14 MB)と読み込みに数秒かかる。 +- 計測(`--only p5d`): + - 箱ひげ図・バイオリン図(10,000 行 × 5 系列)の設定変更 → 再描画。 + - ヒートマップ(10,000 行を 100×100 の格子に)の設定変更 → 再描画。 + - 任意の式の近似曲線(5 系列)の設定変更 → 再描画。 + - scipy の初回読み込み(近似曲線を「任意の式」にしてから、図が出るまで)。参考値で、ネットワークに左右される。 + +### 7.7 テスト + +- 単体: + - `test_expr.py`(モデルの式): `x` と `a`〜`e`、使えない要素のエラー、`e` と `exp` と `1e-3` の区別、使ったパラメータの順。 + - `test_chart_types.py`: box / violin / heatmap の artist、隠れる設定、NaN と値の無い系列、ヒートマップの集計・欠けたマス・上限・文字列の軸、自動のラベル、注釈の X。 + - `test_fits.py`(任意の式): scipy で直接当てはめた値との一致、表示の文字、収束しないときの手順のメッセージ、点の不足、注入。 + - どれも「全体を実行した図」と「自動描画用の図」が一致することを確かめる。既定の設定はゴールデンテストで確かめる。 +- `figure_summary` に、箱・バイオリンを数えるキーを足す(例 `boxes` / `violins`。ヒートマップは `colorbar` と `meshes`)。 +- E2E: + - 種類ごとの欄の出し分けと `data-summary`。 + - ヒートマップの値の列が未選択のときと、系列が2つのときのエラーと復帰。 + - 任意の式の近似曲線(scipy を実際に読み込む。インターネット接続が必要)。 + - 編集モードで scipy を import するコード。 + - 狭い画面。 + - 一致確認に box / violin / heatmap / 任意の式を足す。 + +### 7.8 確認したいこと + +1. **PR の分け方**: 5d(G8・G10)と 5e(G9)に分けてよいか(§7.1。推奨)。分けない場合は、G9 の詳細もこの設計に足す。 +2. **ヒートマップのデータの形**: 案 H2(X・Y・値の3列の縦長の表から格子を作る。推奨)か、案 H1(系列の Y 列を並べて行列にする)か(§7.3)。 +3. **箱ひげ図・バイオリン図の見た目**: 箱・胴の塗りは系列の色。ひげは 1.5×IQR。外れ値は表示・平均は非表示が既定。向きは縦だけで、凡例は出さない。これでよいか。 +4. **任意の式**: パラメータは `a`〜`e` の5つまで、初期値の既定は 1、表示は「y = 式(a = …, b = …、R² = …)」。開発用の依存に scipy を足す。これでよいか。 diff --git a/docs/REQUIREMENTS.md b/docs/REQUIREMENTS.md index f404442..36d43cf 100644 --- a/docs/REQUIREMENTS.md +++ b/docs/REQUIREMENTS.md @@ -63,7 +63,7 @@ ### 2.5 Phase 5 の決定事項(2026-11-10 にユーザーが決定) -- PR を4本に分ける。5a: G1・G2。5b: G3・G4・G5 と「注釈・解析」の区分。5c: G6・G7。5d: G8–G10。「注釈・解析」の区分は、中身が入る 5b で作る(空の区分を作らないため)。 +- PR を4本に分ける。5a: G1・G2。5b: G3・G4・G5 と「注釈・解析」の区分。5c: G6・G7。5d: G8–G10。「注釈・解析」の区分は、中身が入る 5b で作る(空の区分を作らないため)。→ 5d を2本に分けた(2026-11-12)。5d: G8・G10、5e: G9(下記)。 - 設定スキーマを version 4 にする(5a)。5b〜5d は v4 に項目を足す。新しい項目の既定値は、どれも v3 の出力を変えない値にする。v3 からの移行は version を上げるだけ。後の PR で既存の項目の意味を変えるときは、version 5 にする。 - 画面で隠した設定(グラフの種類や軸の種類で使えない設定)は図に使わない。値は消さないので、戻せば効く。表示している設定どうしが組み合わせとして使えないときは、日本語のエラーで案内する。 - エラーバー(G1): @@ -91,6 +91,11 @@ - 計算した列は「描画から除外する先頭行」を除いた行で計算する(`max` や `first` などの集計も、その行だけを使う)。データ確認タブには計算した列を出さない(読み込んだファイルの内容だけを出す)。 - 色分け散布図: 凡例の点は灰色にする(色はカラーバーで読む)。第2Y軸は使えない(カラーバーと第2Y軸の位置がずれるため)。色の範囲は全系列で共通にし、自動で決める(範囲の指定は無し)。描画の重さは、普通の散布図と同じ見た目で作ってブラウザで計測し、1 秒を超えたら見直す。 - 色分け散布図の点は、縁を描かない(2026-11-12 にユーザーが決定)。点ごとに色が違うと matplotlib が点の縁を1点ずつ描くため、10,000 行 × 5 系列の再描画がブラウザで約 1.21 秒かかり、1 秒を超えた。縁を描かず、縁の太さ(1.5 pt)の分だけ点の面積を大きくして、見た目の点の大きさを普通の散布図にそろえる(約 0.94 秒)。点の形が「x」「+」のときは、線だけでできた点なので、縁を描く(今までの描き方)。 +- 5d・5e(G8–G10、2026-11-12): + - PR を 5d(G8 グラフの種類 第2弾、G10 任意関数のフィッティング)と 5e(G9 サブプロット)に分ける。G9 は図の軸が1組という前提をコード生成のほぼすべてで変え、G8 の新しい種類もパネルに載せる必要があるため、G8 の後に作る。5e の詳しい設計は、5d のマージ後に相談する。 + - ヒートマップは、X・Y・値の3列(縦長の表)から格子を作る(色分け散布図と同じ3列)。同じ X・Y の組は平均を描き、値の無いマスは塗らない。系列は1つだけ。 + - 箱ひげ図・バイオリン図は、系列ごとに1つずつ左から並べる。箱・胴の塗りは系列の色、ひげは箱の端から 1.5×IQR まで、外れ値は表示・平均は非表示が既定。向きは縦だけで、凡例は出さない(名前は目盛に出す)。 + - 任意関数のフィッティングの式は、変数 `x` とパラメータ `a`〜`e`(5つまで)で書く。初期値の既定は 1。表示は「y = 式(a = …, b = …、R² = …)」。開発用の依存(単体テスト用)に scipy を足す(ブラウザと同じ版。実行時は U5 のとおり使うときだけ読み込む)。 --- diff --git a/index.html b/index.html index dfeedaf..a9bd4f9 100644 --- a/index.html +++ b/index.html @@ -140,6 +140,9 @@

Matplotlib GUI

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

Matplotlib GUI

+ + + + +
-
+
@@ -411,8 +428,11 @@ export const syncVisibility = () => { const type = settings.plot.type; setHidden("stepGroup", !usesStep(type)); setHidden("histGroup", !usesHist(type)); - setHidden("colorMapGroup", !usesColorColumn(type)); - setHidden("yScaleGroup", type === "barh"); // 横棒の縦軸はカテゴリ(Y のスケールは使わない) + setHidden("boxGroup", !usesBox(type)); + setHidden("violinGroup", !usesViolin(type)); + setHidden("colorMapGroup", !usesColormap(type)); + setHidden("xScaleGroup", isBoxLike(type) || (isHeatmap(type) && xAxisKind() === "category")); // 箱ひげ・バイオリンの横軸はカテゴリ(X のスケールは使わない) + setHidden("yScaleGroup", type === "barh" || (isHeatmap(type) && yAxisKind() === "category")); // 横棒の縦軸はカテゴリ(Y のスケールは使わない) const globalX = document.getElementById("globalXGroup"); if (globalX) globalX.style.display = usesGlobalX(type) ? "" : "none"; for (const group of document.querySelectorAll("#seriesList .series-x-wrap")) { @@ -431,6 +451,11 @@ export const syncVisibility = () => { set(".series-fill", !typeUsesFill(type)); set(".series-y2-wrap", !usesY2(type)); set(".series-color-column-wrap", !usesColorColumn(type)); + set(".series-color-wrap", !usesColor(type)); + set(".series-line-width-wrap", !usesLineWidth(type)); + set(".series-line-style-wrap", !usesLineStyle(type)); + const colorLabel = item.querySelector(".series-color-column-label"); + if (colorLabel) colorLabel.textContent = isHeatmap(type) ? "値の列" : "色分けの列"; // 点の形が「なし」の折れ線(line / step)は点サイズを使わない const size = item.querySelector(".series-marker-size"); if (size && s) size.disabled = isLineLike(type) && s.marker === "none"; diff --git a/py/main.py b/py/main.py index 1eaf3a0..d48eb33 100644 --- a/py/main.py +++ b/py/main.py @@ -72,6 +72,45 @@ async def _ensure_excel(): return json.dumps({"ok": False, "error": err.to_dict()}, ensure_ascii=False) +_SCIPY_STATE = {"ready": False, "task": None} + + +def _scipy_available(): + import importlib.util + + return importlib.util.find_spec("scipy") is not None + + +async def _install_scipy(): + import pyodide_js + + # scipy は Pyodide 同梱のパッケージなので、名前だけで読み込める(初回は約 14 MB を取得する) + await pyodide_js.loadPackage(to_js(["scipy"])) + + +async def _ensure_scipy(): + """任意の式の近似曲線を使う前に JS から呼ぶ。2回目以降は何もしない。戻り値は JSON 文字列。""" + if _SCIPY_STATE["ready"] or _scipy_available(): + _SCIPY_STATE["ready"] = True + return json.dumps({"ok": True}) + try: + if _SCIPY_STATE["task"] is None: + _SCIPY_STATE["task"] = asyncio.ensure_future(_install_scipy()) + await _SCIPY_STATE["task"] + if not _scipy_available(): + raise RuntimeError("scipy を導入後も import できません") + _SCIPY_STATE["ready"] = True + return json.dumps({"ok": True}) + except Exception as exc: + _SCIPY_STATE["task"] = None # 次回は再試行する + err = UserError( + "scipy を読み込めませんでした。インターネット接続を確かめてから、もう一度試してください。", + field="近似曲線", + detail=f"{type(exc).__name__}: {exc}", + ) + return json.dumps({"ok": False, "error": err.to_dict()}, ensure_ascii=False) + + def _load_file(name, data, load_settings_json, source_id=None, pasted=None): # source_id / pasted は JS が渡さない(null / undefined)ときは既定値 return api.load_file_json( @@ -121,6 +160,7 @@ def _script_filename(save_filename): # create_proxy の参照を保持しておく(GC されると JS から呼べなくなる) _PROXIES = { "ensureExcel": create_proxy(_ensure_excel), + "ensureScipy": create_proxy(_ensure_scipy), "loadFile": create_proxy(_load_file), "removeSource": create_proxy(_remove_source), "clearSources": create_proxy(_clear_sources), diff --git a/py/mplgui/api.py b/py/mplgui/api.py index 1a573ff..0808d57 100644 --- a/py/mplgui/api.py +++ b/py/mplgui/api.py @@ -8,6 +8,7 @@ import base64 import dataclasses import hashlib +import importlib.util import json import struct import traceback @@ -247,11 +248,22 @@ def _generate(settings: Settings): return plan, generate_script(settings, infos, plan) +def _require_scipy(plan) -> None: + """任意の式の近似曲線があるのに scipy が無いときは、日本語のエラーにする(ブラウザでは JS が先に ensureScipy を呼ぶ)。""" + custom = [f.number for f in plan.fits if f.model == "custom"] + if custom and importlib.util.find_spec("scipy") is None: + raise UserError( + "scipy を読み込めていません。任意の式の近似曲線には scipy が必要です。ページを再読み込みして、もう一度試してください。", + field=f"近似曲線{custom[0]}", + ) + + def _run(settings: Settings | None, code: str | None, *, file_format: str, transparent: bool, dpi: int, svg_text: str = "path"): """GUI 同期(code が None): 設定から生成したスクリプトを、読込済みの df で実行する(読込・保存の行は空にする)。 編集モード(code が文字列): そのスクリプトを、アップロードしたファイルのある作業フォルダで実行する。設定は使わない。""" if code is None: plan, script = _generate(settings) + _require_scipy(plan) # 計算した列は生成コードが df.insert で足すので、そのデータ元はコピーを渡す(描画のたびに列が増えるのを防ぐ) with_computed = {c.data_id for c in plan.computed} injected = { diff --git a/py/mplgui/codegen.py b/py/mplgui/codegen.py index 3446e54..e0bd0b7 100644 --- a/py/mplgui/codegen.py +++ b/py/mplgui/codegen.py @@ -24,6 +24,8 @@ LINE_ONLY_MARKERS = {"x", "+"} # 線だけでできた点の形(縁を描かないと見えない) XY_TYPES = {"line", "step", "scatter", "scatterColor"} # X と Y の組で描く種類(X が日時なら日時の軸、エラーバー・帯・近似曲線を使える) +BOX_TYPES = {"box", "violin"} # 系列ごとに1つの箱・胴を描く種類(横軸は系列の名前) +NO_SERIES_LEGEND_TYPES = {"box", "violin", "heatmap"} # 系列を凡例に出さない種類(名前は目盛に出る・カラーバーで読む) GENERIC_ERROR_MESSAGE = "グラフを描画できませんでした。X列・Y列に指定した列の値の形式(数値と文字列の混在など)や、設定の値を確認してください。" TIGHT_LAYOUT_ERROR = "レイアウトの自動調整に失敗しました。余白を手動で指定するか、図の大きさ・フォントサイズを小さくしてください。" @@ -179,10 +181,11 @@ def _emit_header( f"「{comment_text(src.filename)}」" + ("(貼り付けたデータを保存したもの)" if src.pasted else "") for src in sources ) usage = f"# 使い方: データファイル {names} を、このスクリプトと同じフォルダに置いて、python {SCRIPT_NAME} で実行します。" + custom_fit = plan is not None and _uses_custom_fit(plan) b.add( "# matplotlib GUI が生成したスクリプト", usage, - "# 必要なライブラリ: pandas, matplotlib, numpy", + "# 必要なライブラリ: pandas, matplotlib, numpy" + (", scipy(任意の式の近似曲線。pip install scipy)" if custom_fit else ""), ) if plan is not None and _uses_date_axis(plan): b.add("import matplotlib.dates as mdates") @@ -194,6 +197,10 @@ def _emit_header( b.add( "import numpy as np", "import pandas as pd", + ) + if custom_fit: + b.add("from scipy.optimize import curve_fit") + b.add( "", "# 日本語フォント: 一覧の先頭から、見つかったものを使う。", "# どれも無い環境では DejaVu Sans になる(日本語は豆腐になるが、実行はできる)", @@ -219,13 +226,17 @@ def _emit_header( def _positions_form(plan: PlotPlan) -> bool: """棒を位置(0, 1, 2, …)に置き、カテゴリのラベルを付ける形(複数系列の棒・横棒、積み上げ棒)。""" - return plan.plot_type == "barStacked" or (plan.plot_type in {"bar", "barh"} and len(plan.series) > 1) + return plan.plot_type in {"barStacked"} | BOX_TYPES or (plan.plot_type in {"bar", "barh"} and len(plan.series) > 1) def _scale(settings: Settings, plan: PlotPlan, name: str) -> str: """軸のスケール。横棒の縦軸(カテゴリ)は Y のスケールを使わない。""" if plan.plot_type == "barh" and name == "y": return "linear" + if plan.plot_type in BOX_TYPES and name == "x": + return "linear" # 横軸はカテゴリ(系列の名前) + if plan.plot_type == "heatmap" and name in {"x", "y"} and getattr(plan.axes, name).kind == "category": + return "linear" # 文字列の列の軸はカテゴリ return getattr(settings.axes, name).scale @@ -458,7 +469,48 @@ def _emit_band(b: _Builder, s: SeriesSettings, p: SeriesPlan, step: str = "") -> def _uses_poly_text(plan: PlotPlan) -> bool: - return plan.plot_type in XY_TYPES and any(f.show in {"legend", "text"} for f in plan.fits) + return plan.plot_type in XY_TYPES and any(f.show in {"legend", "text"} and f.model != "custom" for f in plan.fits) + + +def _uses_custom_fit(plan: PlotPlan) -> bool: + return plan.plot_type in XY_TYPES and any(f.model == "custom" for f in plan.fits) + + +def _custom_label_expr(fit: FitPlan) -> str: + """任意の式の近似曲線の凡例・図の中の文字を作る式(パラメータは実行時に fit_params から作る)。""" + names = "[" + ", ".join(literal(name) for name in fit.params) + "]" + head = literal(f"{fit.label_prefix}: y = {expr_module.model_to_text(fit.node)}(") + return f'{head} + ", ".join(f"{{name}} = {{value:.4g}}" for name, value in zip({names}, fit_params)) + f"、$R^2$ = {{r2:.4f}})"' + + +def _emit_custom_fit(b: _Builder, p: SeriesPlan, fit: FitPlan) -> None: + params = ", ".join(fit.params) + func = f"fit_model_{fit.number}" + body = expr_module.model_to_code(fit.node, lambda v: literal(float(v))) + p0 = "[" + ", ".join(literal(float(v)) for v in fit.p0) + "]" + b.add( + f"# 近似曲線{fit.number}: 系列{p.number}({comment_text(fit.series_label)})に任意の式を当てはめる(最小二乗。scipy の curve_fit)", + f"def {func}(x, {params}): # 近似曲線{fit.number}の式: {comment_text(fit.expr)}", + f" return {body}", + ) + with b.step(f"近似曲線{fit.number}: 式を当てはめられませんでした。初期値を変えてみてください。", f"近似曲線{fit.number}の初期値"): + b.add( + f"fit_params, _ = curve_fit({func}, x[ok], y[ok], p0={p0}, maxfev=10000) # 初期値 p0 から当てはめる(パラメータは {params} の順)", + f"fit_y = {func}(x[ok], *fit_params) # 当てはめた曲線の、データの X での値", + "if not np.all(np.isfinite(fit_y)): # 初期値のところで計算できない値になると、curve_fit は黙って初期値を返すことがある", + ' raise ValueError("当てはめた式の値が有限ではありません")', + "r2 = 1 - np.sum((y[ok] - fit_y) ** 2) / np.sum((y[ok] - y[ok].mean()) ** 2) # 決定係数 R²", + "x_fit = np.linspace(x[ok].min(), x[ok].max(), 200) # 近似曲線を描く X(データの範囲を 200 点)", + ) + style = f"color={literal(fit.color)}, linewidth={literal(fit.line_width)}, linestyle={literal(fit.line_style)}" + label = _custom_label_expr(fit) if fit.show == "legend" else '"_fit"' + b.add(f"{fit.target}.plot(x_fit, {func}(x_fit, *fit_params), {style}, label={label})") + if fit.show == "text": + y_pos = literal(round(0.97 - 0.07 * fit.text_index, 2)) + b.add( + f"{fit.target}.text(0.03, {y_pos}, {_custom_label_expr(fit)}, transform={fit.target}.transAxes, va=\"top\", " + f"color={literal(fit.color)}, fontsize=FONT_SIZE) # 近似曲線の式を図の中(左上)に書く" + ) def _fit_label_expr(fit: FitPlan) -> str: @@ -470,6 +522,9 @@ def _emit_fits(b: _Builder, plan: PlotPlan, p: SeriesPlan) -> None: for fit in plan.fits: if fit.series_number != p.number: continue + if fit.model == "custom": + _emit_custom_fit(b, p, fit) + continue with b.step(f"近似曲線{fit.number}を描けませんでした。近似曲線の設定とデータを確認してください。", f"近似曲線{fit.number}"): kind = "1 次式" if fit.degree == 1 else f"{fit.degree} 次式" b.add( @@ -856,6 +911,120 @@ def _emit_scatter_color_series(b: _Builder, settings: Settings, plan: PlotPlan) ) +def _emit_box_series(b: _Builder, settings: Settings, plan: PlotPlan) -> None: + """箱ひげ図(box)・バイオリン図(violin)。系列ごとに Y 列の値の分布を1つ、左から系列の順(0, 1, 2, …)に描く。 + + 系列の名前は目盛のラベル(x_labels)になる。値が無い系列(バイオリンは2個未満)は、位置を空けたまま描かない。""" + violin = plan.plot_type == "violin" + n = len(plan.series) + plot = settings.plot + if violin: + b.add("# バイオリン図: 系列ごとに1つの胴を、左から系列の順(0, 1, 2, …)に描く(値が2個未満の系列は描かない)") + else: + b.add("# 箱ひげ図: 系列ごとに1つの箱を、左から系列の順(0, 1, 2, …)に描く(箱の端はひげまで 1.5×IQR。外れ値は点)") + labels = ", ".join(literal(p.legend_label) for p in plan.series) + b.add( + f"positions = np.arange({n}) # {'胴' if violin else '箱'}の位置(系列の順に 0, 1, 2, …)", + f"x_labels = [{labels}] # 目盛のラベル(系列の凡例名)", + ) + for s, p in zip(settings.series, plan.series): + i = p.number - 1 + b.blank() + b.add(f"# 系列{p.number}{'' if p.data_var == 'df' else f'({p.data_var})'}: Y = {_column_comment(p, 'y')}") + if not p.has_points: + b.add(f"# 描ける値が無い({'2個未満' if violin else '数値の行が無い'})ため、この系列は描かない(位置は空けておく)") + continue + width, color = literal(s.line_width), literal(s.color) + alpha = f', "alpha": {literal(p.alpha)}' if p.alpha != 1.0 else "" + with b.step(GENERIC_ERROR_MESSAGE): + b.add( + f'values = pd.to_numeric({p.data_var}.iloc[:, {p.y_index}], errors="coerce").replace([np.inf, -np.inf], np.nan).dropna()' + " # 数値にできない値・欠けた値は使わない" + ) + if violin: + b.add( + f"vp = ax.violinplot([values], positions=[{i}], widths=0.8, showmedians={literal(plot.violin_medians)}, " + f"showmeans={literal(plot.violin_means)}, showextrema=True)", + 'for body in vp["bodies"]:', + f' body.set(facecolor={color}, edgecolor={color}, linewidth={width}, alpha={literal(p.alpha)}, label="_violin")' + " # 胴(凡例には出さない)", + 'for key in ("cbars", "cmins", "cmaxes"): # 端の線は系列の色。中央値・平均の線は、胴の上でも見えるように黒', + f" vp[key].set(color={color}, linewidth={width})", + 'for key in ("cmedians", "cmeans"):', + " if key in vp:", + f' vp[key].set(color="black", linewidth={width})', + ) + else: + line = f'{{"color": "black", "linewidth": {width}}}' + b.add( + f"bp = ax.boxplot([values], positions=[{i}], widths=0.6, patch_artist=True, manage_ticks=False, " + f"showfliers={literal(plot.box_fliers)}, showmeans={literal(plot.box_means)},", + f' boxprops={{"facecolor": {color}, "edgecolor": "black", "linewidth": {width}{alpha}}},', + f" whiskerprops={line}, capprops={line}, medianprops={line},", + ' flierprops={"marker": "o", "markersize": 4, "markerfacecolor": "none", "markeredgecolor": "black"},', + ' meanprops={"marker": "D", "markersize": 6, "markerfacecolor": "white", "markeredgecolor": "black"})', + 'for artists in bp.values():', + ' plt.setp(artists, label="_box") # 凡例には出さない(ラベルが _ で始まる)', + ) + b.blank() + b.add(f"ax.set_xlim(-0.5, {n} - 0.5) # 横軸は系列の数に合わせる") + + +def _emit_heatmap_series(b: _Builder, settings: Settings, plan: PlotPlan) -> None: + """ヒートマップ(heatmap)。X・Y・値の3列の縦長の表から格子を作り、pcolormesh で描く(系列は1つ)。""" + p, hm, colorbar = plan.series[0], plan.heatmap, plan.colorbar + assert hm is not None and colorbar is not None + cmap = literal(colorbar.colormap) + b.add(f"# 系列1: X = {_column_comment(p, 'x')}、Y = {_column_comment(p, 'y')}、値 = {comment_text(p.color_label)}") + with b.step("ヒートマップの格子を作れませんでした。X・Y・値の列を確認してください。", "系列1の値の列"): + _emit_x_data(b, p) + if hm.y_convert: + b.add(f'y = pd.to_numeric({p.data_var}.iloc[:, {p.y_index}], errors="coerce") # 数値にできない値は NaN にする') + else: + b.add(f"y = {p.data_var}.iloc[:, {p.y_index}]") + b.add( + f'c = pd.to_numeric({p.data_var}.iloc[:, {p.color_index}], errors="coerce") # 値の列(数値にできない値は NaN)', + "ok = x.notna() & y.notna() & c.notna() # X・Y・値のどれかが欠けている行は使わない", + 'heat = pd.DataFrame({"x": x[ok], "y": y[ok], "z": c[ok]})', + ) + if hm.x_text: + b.add('heat["x"], x_cats = pd.factorize(heat["x"]) # X が文字列: 現れた順にカテゴリの番号にする') + b.add("x_cats = [str(v) for v in x_cats] # 目盛のラベル") + if hm.y_text: + b.add('heat["y"], y_cats = pd.factorize(heat["y"]) # Y が文字列: 現れた順にカテゴリの番号にする') + b.add("y_cats = [str(v) for v in y_cats] # 目盛のラベル") + b.add('grid = heat.pivot_table(index="y", columns="x", values="z", aggfunc="mean") # 格子にする(同じ X・Y の組は平均。値の無いマスは NaN)') + alpha = f", alpha={literal(p.alpha)}" if p.alpha != 1.0 else "" + size = _label_size_expr(settings.plot.font_size) + with b.step("ヒートマップを描けませんでした。カラーマップと値の列を確認してください。", "カラーマップ"): + b.add( + f'mesh = ax.pcolormesh(grid.columns.to_numpy(), grid.index.to_numpy(), grid.to_numpy(), cmap={cmap}, shading="nearest"{alpha})' + " # 値の無いマスは塗らない", + "colorbar = fig.colorbar(mesh, ax=ax)", + f"colorbar.set_label({literal(colorbar.label)}, fontsize=FONT_SIZE)", + f'colorbar.ax.tick_params(which="both", direction="in", labelsize={size})', + ) + + +def _emit_heatmap_ticks(b: _Builder, plan: PlotPlan) -> None: + """ヒートマップで、X・Y が文字列の列のとき、目盛にカテゴリの名前を付ける(主目盛の間隔か、25個を超えるときの間引き)。""" + hm = plan.heatmap + assert hm is not None + for which, text, ap in (("x", hm.x_text, plan.axes.x), ("y", hm.y_text, plan.axes.y)): + if not text: + continue + name = which.upper() + if ap.major_step is not None: + b.add(f"# {name} の目盛にカテゴリの名前を付ける({name}軸の主目盛の間隔: {ap.major_step}個おき)", f"{which}_tick_step = {literal(ap.major_step)}") + else: + b.add(f"# {name} の目盛にカテゴリの名前を付ける(25個を超えるときは間引く)", f"{which}_tick_step = max(1, len({which}_cats) // 25)") + b.add(f"ax.set_{which}ticks(np.arange(len({which}_cats))[::{which}_tick_step])") + if which == "x": + b.add('ax.set_xticklabels(x_cats[::x_tick_step], rotation=45, ha="right")') + else: + b.add("ax.set_yticklabels(y_cats[::y_tick_step])") + + SERIES_EMITTERS: dict[str, Callable[[_Builder, Settings, PlotPlan], None]] = { "line": _emit_line_series, "scatter": _emit_scatter_series, @@ -865,6 +1034,9 @@ def _emit_scatter_color_series(b: _Builder, settings: Settings, plan: PlotPlan) "barStacked": _emit_stacked_series, "hist": _emit_hist_series, "scatterColor": _emit_scatter_color_series, + "box": _emit_box_series, + "violin": _emit_box_series, + "heatmap": _emit_heatmap_series, } @@ -1004,8 +1176,8 @@ def _major_lines(blk: _AxisBlock, settings: Settings, plan: PlotPlan) -> list[st f"{axis_var}.set_major_formatter({formatter})", ] if ap.kind == "category": - if _positions_form(plan): - return [] # 棒の位置に目盛を付ける節(tick_step)で扱う + if _positions_form(plan) or plan.plot_type == "heatmap": + return [] # 棒(箱)の位置・ヒートマップのカテゴリに目盛を付ける節(tick_step)で扱う if ap.major_step is not None: return [f"{axis_var}.set_major_locator(ticker.MultipleLocator({literal(ap.major_step)})) # {label}軸の主目盛: {ap.major_step}個おきにラベルを出す"] if plan.plot_type in XY_TYPES and plan.thin_categorical_x: @@ -1075,6 +1247,10 @@ def _emit_spines(b: _Builder, settings: Settings, plan: PlotPlan) -> None: b.add('ax.spines["right"].set_visible(False) # 右の枠線を消す') +def _position_word(plan: PlotPlan) -> str: + return {"box": "箱", "violin": "胴"}.get(plan.plot_type, "棒") + + def _emit_axes(b: _Builder, settings: Settings, plan: PlotPlan) -> None: b.section("軸(ラベル・スケール・範囲・目盛)") plot, axes = settings.plot, settings.axes @@ -1096,19 +1272,21 @@ def _emit_axes(b: _Builder, settings: Settings, plan: PlotPlan) -> None: with b.step(tick_error_message(blk.label), f"{blk.label}軸の目盛"): b.add(*ticks) + if plan.plot_type == "heatmap": + _emit_heatmap_ticks(b, plan) if _positions_form(plan): horizontal = plan.plot_type == "barh" axis_name = "Y" if horizontal else "X" - what = "カテゴリの値" if horizontal else "X の値" + what = "カテゴリの値" if horizontal else ("系列の名前" if plan.plot_type in BOX_TYPES else "X の値") step = (plan.axes.y if horizontal else plan.axes.x).major_step if step is not None: b.add( - f"# 棒の位置に {what}を目盛として付ける({axis_name}軸の主目盛の間隔: {step}個おき)", + f"# {_position_word(plan)}の位置に {what}を目盛として付ける({axis_name}軸の主目盛の間隔: {step}個おき)", f"tick_step = {literal(step)}", ) else: b.add( - f"# 棒の位置に {what}を目盛として付ける(25個を超えるときは間引く)", + f"# {_position_word(plan)}の位置に {what}を目盛として付ける(25個を超えるときは間引く)", "tick_step = max(1, len(positions) // 25)", ) if horizontal: @@ -1153,7 +1331,9 @@ def _emit_grid_and_legend(b: _Builder, settings: Settings, plan: PlotPlan) -> No if plot.legend_location == "none": b.add("# 凡例は表示しない") return - labelled = any(p.has_points and p.legend_label and not p.legend_label.startswith("_") for p in plan.series) + labelled = plan.plot_type not in NO_SERIES_LEGEND_TYPES and any( + p.has_points and p.legend_label and not p.legend_label.startswith("_") for p in plan.series + ) labelled = labelled or any(a.label and not a.label.startswith("_") for a in plan.annotations) labelled = labelled or any(f.show == "legend" for f in plan.fits) if not labelled: diff --git a/py/mplgui/dataprep.py b/py/mplgui/dataprep.py index 21afb8c..4d6204f 100644 --- a/py/mplgui/dataprep.py +++ b/py/mplgui/dataprep.py @@ -17,7 +17,7 @@ from .errors import UserError from .loader import is_blank_cell as _is_blank_cell from .loader import looks_numeric as _looks_numeric -from .settings import BAR_LIKE_TYPES, MAX_HIST_BINS, AxisSettings, ErrorSpec, Settings, check_axis_range, validate_date_range +from .settings import HEATMAP_SERIES_MESSAGE, MAX_HEATMAP_SIZE, MAX_HIST_BINS, XY_TYPES, AxisSettings, ErrorSpec, Settings, check_axis_range, validate_date_range from .settings import _DATE_EXAMPLE, _date_range_value, _to_float MAX_EXAMPLES = 3 @@ -205,6 +205,12 @@ class FitPlan: label_prefix: str # 凡例・図の中の文字の先頭(「温度の近似」) text_index: int # show が text の近似曲線のうちの順番(0 始まり。それ以外は -1) target: str # ax / ax2 + # 任意の式(model が custom)のとき: 解釈済みの式の木・使うパラメータ(a〜e の順)・初期値 + model: str = "poly" # linear / poly / custom + expr: str = "" + node: object = field(default=None, compare=False, repr=False) + params: tuple[str, ...] = () + p0: tuple[float, ...] = () @dataclass(frozen=True) @@ -230,8 +236,8 @@ class SeriesPlan: marker: str = "" # line は描く点の形("" = 点なし)、scatter は "" = 既定の丸(引数を足さない) alpha: float = 1.0 # 不透明度(1 のときはコードに書かない) fill: FillPlan | None = None # 塗りつぶし帯(line / step / scatter / scatterColor のみ) - color_index: int | None = None # scatterColor の色分けの列番号 - color_label: str = "" # scatterColor の色分けの列の表示(「名前 [番号]」) + color_index: int | None = None # scatterColor の色分けの列番号(heatmap では値の列番号) + color_label: str = "" # scatterColor の色分けの列(heatmap では値の列)の表示(「名前 [番号]」) @dataclass(frozen=True) @@ -244,9 +250,21 @@ class HistPlan: max_height: float # 度数(density なら確率密度)の最大 +@dataclass(frozen=True) +class HeatmapPlan: + """ヒートマップ(heatmap)。X・Y が文字列の列か(現れた順のカテゴリにする)、数値に変換する列か、格子の大きさ。""" + + x_text: bool + y_text: bool + y_convert: bool # Y を pd.to_numeric で変換する(X は SeriesPlan.convert_x) + x_count: int # X の異なる値の数 + y_count: int + duplicates: int # 同じ X・Y の組の重複の件数(平均を描く) + + @dataclass(frozen=True) class ColorbarPlan: - """色分け散布図(scatterColor)のカラーマップとカラーバーのラベル。""" + """色分け散布図(scatterColor)・ヒートマップ(heatmap)のカラーマップとカラーバーのラベル。""" colormap: str label: str # 実際に使うラベル(設定が空なら系列1の色分けの列の表示) @@ -313,7 +331,8 @@ class PlotPlan: annotations: tuple[AnnotationPlan, ...] = () fits: tuple[FitPlan, ...] = () # 近似曲線(line / step / scatter / scatterColor のみ) hist: HistPlan | None = None # hist のときだけ - colorbar: ColorbarPlan | None = None # scatterColor のときだけ + colorbar: ColorbarPlan | None = None # scatterColor / heatmap のときだけ + heatmap: HeatmapPlan | None = None # heatmap のときだけ computed: tuple["ComputedPlan", ...] = () # 計算した列(描画に使うデータ元のものだけ。カードの順) @property @@ -335,6 +354,7 @@ class ComputedPlan: refs: tuple[tuple[int, str], ...] = () # 式が使うファイルの列(番号、コメント用の「列 [i]: 名前」) +HEATMAP_DATETIME_MESSAGE = "系列{n}: {what}({name})は日時の列です。ヒートマップでは日時の列を使えません。" MAX_CATEGORY_TICKS = 25 # X が文字列の列のとき、目盛に出すカテゴリの最大数 Y_DATETIME_MESSAGE = "系列{n}: Y列({name})は日時の列です。Y列には数値の列を選んでください。" @@ -507,7 +527,7 @@ def _plan_fill(df: pd.DataFrame, series, n: int, ok: pd.Series, y_axis: str, ext def _plan_fits(settings: Settings) -> list[tuple[int, object]]: """(近似曲線の番号, FitSettings) を、系列の番号ごとに引けるように並べる。棒グラフでは使わない。""" - if settings.plot.type in BAR_LIKE_TYPES: + if settings.plot.type not in XY_TYPES: return [] return list(enumerate(settings.fits, start=1)) @@ -523,9 +543,16 @@ def _check_fit_data(n: int, fit, p: "SeriesPlan", x: pd.Series, y: pd.Series) -> if p.categorical_x: raise _fit_error(n, "X が文字列の列の系列は近似できません。") distinct = int(pd.Series(x).nunique()) - need = fit.degree + 1 - if distinct < need: - raise _fit_error(n, f"{fit.degree}次式で近似するには、X の異なる値が{need}個以上必要です(今は{distinct}個)。") + if fit.model == "custom": + need = len(fit.params) + 1 + if distinct < need: + raise _fit_error( + n, f"パラメータが{len(fit.params)}個の式で近似するには、X の異なる値が{need}個以上必要です(今は{distinct}個)。" + ) + else: + need = fit.degree + 1 + if distinct < need: + raise _fit_error(n, f"{fit.degree}次式で近似するには、X の異なる値が{need}個以上必要です(今は{distinct}個)。") if int(pd.Series(y).nunique()) < 2: raise _fit_error(n, "Y の値がすべて同じなので、近似できません(決定係数 R² を計算できません)。") @@ -553,6 +580,11 @@ def _build_fit_plans(settings: Settings, plans: list["SeriesPlan"]) -> tuple[Fit label_prefix=f"{base}の近似", text_index=text_index if fit.show == "text" else -1, target="ax2" if sp.secondary else "ax", + model=fit.model, + expr=fit.expr, + node=fit.expr_node, + params=fit.params, + p0=fit.initial, ) ) if fit.show == "text": @@ -753,6 +785,8 @@ def plan_plot(data, settings: Settings) -> PlotPlan: default_id = files[0].id if files else next(iter(data)) multi = len(files) >= 2 + if plot.type == "heatmap" and len(settings.series) > 1: + raise UserError(HEATMAP_SERIES_MESSAGE, field="系列") ids: list[str] = [] # 系列ごとのデータ元 for n, s in enumerate(settings.series, start=1): sid = s.source or default_id @@ -787,6 +821,10 @@ def plan_plot(data, settings: Settings) -> PlotPlan: plan = _plan_xy(dfs, settings, y_requests) elif plot.type == "hist": plan = _plan_hist(dfs, settings, y_requests) + elif plot.type in {"box", "violin"}: + plan = _plan_box(dfs, settings, y_requests) + elif plot.type == "heatmap": + plan = _plan_heatmap(dfs[0], settings, y_requests[0]) else: plan = _plan_bar(dfs[0], settings, y_requests) series = tuple(replace(sp, data_id=sid, data_var=var_of[sid]) for sp, sid in zip(plan.series, ids)) @@ -931,9 +969,11 @@ def _plan_axis( def _plan_axes( - settings: Settings, x_kind: str, uses_secondary: bool, ext: _Extents, categories: int, y_kind: str | None = None + settings: Settings, x_kind: str, uses_secondary: bool, ext: _Extents, categories: int, y_kind: str | None = None, + y_categories: int | None = None, ) -> AxesPlan: - """y_kind は Y 軸の種類(横棒の縦軸は category / number。そのとき categories は Y 軸のカテゴリ数)。None なら Y のスケールから決める。""" + """y_kind は Y 軸の種類(横棒の縦軸は category / number。そのとき categories は Y 軸のカテゴリ数)。None なら Y のスケールから決める。 + y_categories があるとき(ヒートマップ)は、categories が X 軸、y_categories が Y 軸のカテゴリ数。""" axes = settings.axes plot_type = settings.plot.type bar = plot_type in {"bar", "barStacked", "hist"} # 縦向きの棒: Y 軸(値)の範囲に 0 を含める @@ -941,33 +981,39 @@ def _plan_axes( def num_kind(axis: AxisSettings) -> str: return "log" if axis.scale == "log" else "number" + if y_categories is not None: + x_cat, y_cat = categories, y_categories + else: + x_cat, y_cat = (0 if y_kind else categories), (categories if y_kind == "category" else 0) return AxesPlan( - x=_plan_axis(axes.x, x_kind, "X", ext, "x", categories=0 if y_kind else categories, include_zero=plot_type == "barh"), - y=_plan_axis(axes.y, y_kind or num_kind(axes.y), "Y", ext, "y", categories=categories if y_kind == "category" else 0, include_zero=bar), + x=_plan_axis(axes.x, x_kind, "X", ext, "x", categories=x_cat, include_zero=plot_type == "barh"), + y=_plan_axis(axes.y, y_kind or num_kind(axes.y), "Y", ext, "y", categories=y_cat, include_zero=bar), y2=_plan_axis(axes.y2, num_kind(axes.y2), "第2Y", ext, "y2", include_zero=plot_type == "bar") if uses_secondary else None, ) -def _color_column(df: pd.DataFrame, requested: str, n: int) -> int: - field_name = f"系列{n}の色分けの列" +def _color_column(df: pd.DataFrame, requested: str, n: int, what: str = "色分けの列") -> int: + field_name = f"系列{n}の{what}" idx = parse_column_index(requested) if idx is None: - raise UserError(f"系列{n}の色分けの列を選んでください。", field=field_name) + raise UserError(f"系列{n}の{what}を選んでください。", field=field_name) if idx >= len(df.columns): raise UserError(_column_out_of_range(idx, len(df.columns)), field=field_name) return idx -def _color_values(df: pd.DataFrame, idx: int, mask: pd.Series, n: int, load, warnings: list[dict]) -> pd.Series: - """色分けの列を数値にする(数値にできない値は NaN。空欄も NaN で、警告しない)。警告の件数と例は、描く行(mask)だけで数える。""" +def _color_values( + df: pd.DataFrame, idx: int, mask: pd.Series, n: int, load, warnings: list[dict], what: str = "色分けの列", skipped: str = "その点は描きません" +) -> pd.Series: + """色分けの列(heatmap では値の列)を数値にする(数値にできない値は NaN。空欄も NaN で、警告しない)。警告の件数と例は、描く行(mask)だけで数える。""" raw = df.iloc[:, idx] numeric, _, _ = coerce_numeric(raw) _, count, examples = coerce_numeric(raw[mask.reindex(df.index, fill_value=False)]) if count: ex = ", ".join(f'"{e}"' for e in examples) message = ( - f"系列{n}: 色分けの列「{df.columns[idx]}」[{idx}] に数値にできない値が{count}件あったため、" - f"その点は描きません(例: {ex})。{load_hint(examples, load)}" + f"系列{n}: {what}「{df.columns[idx]}」[{idx}] に数値にできない値が{count}件あったため、" + f"{skipped}(例: {ex})。{load_hint(examples, load)}" ) warnings.append({"series": n, "message": message}) return numeric @@ -1267,6 +1313,140 @@ def _plan_hist(dfs: list[pd.DataFrame], settings: Settings, y_requests: list[str ) +BOX_NO_VALUES = "系列{n}: 描ける値(数値の行)が無いため、{what}は描きません。" +VIOLIN_FEW_VALUES = "系列{n}: 値が1個だけなので密度を推定できず、バイオリンは描きません。" + + +def _plan_box(dfs: list[pd.DataFrame], settings: Settings, y_requests: list[str]) -> PlotPlan: + """箱ひげ図(box)・バイオリン図(violin)。系列ごとに Y 列の値の分布を1つ、左から系列の順(0, 1, 2, …)に描く。 + + 値が無い系列(バイオリンは2個未満)は、位置を空けたまま描かない(警告)。X 列は使わない。""" + violin = settings.plot.type == "violin" + what = "バイオリン" if violin else "箱" + plans: list[SeriesPlan] = [] + warnings: list[dict] = [] + ext = _Extents() + for n, (df, series, y_request) in enumerate(zip(dfs, settings.series, y_requests), start=1): + y_index = resolve_column_index(df, y_request) + y_name, data_label = _label_for(df, y_index) + if _is_datetime(df.iloc[:, y_index]): + raise UserError(Y_DATETIME_MESSAGE.format(n=n, name=y_name), field=f"系列{n}のY列") + numeric, dropped, examples = coerce_numeric(df.iloc[:, y_index]) + if dropped: + warnings.append(dropped_warning(n, f"系列{n}({y_name})", dropped, examples, settings.load)) + vals = numeric.dropna() + vals = vals[np.isfinite(vals.to_numpy(dtype=float))] + drawable = len(vals) >= (2 if violin else 1) + if not drawable: + warnings.append({"series": n, "message": (VIOLIN_FEW_VALUES if len(vals) == 1 and violin else BOX_NO_VALUES).format(n=n, what=what)}) + else: + ext.add_values("y", vals) + plans.append( + SeriesPlan( + number=n, + y_index=y_index, + y_name=y_name, + x_index=None, + x_label="", + data_label=data_label, + legend_label=series.label or data_label, + convert_x=False, + categorical_x=False, + marker_size=series.effective_marker_size("bar"), + has_points=drawable, + secondary=False, + alpha=series.alpha, + ) + ) + if not any(p.has_points for p in plans): + raise UserError(_no_data_message(warnings)) + return _finish(settings, plans, warnings, "", None, axes_args=("category", ext, len(plans))) + + +def _plan_heatmap(df: pd.DataFrame, settings: Settings, y_request: str) -> PlotPlan: + """ヒートマップ。X・Y・値(色分けの列)の3列の縦長の表から格子を作る(案 H2)。系列は1つだけ。 + + X・Y は数値の列か文字列の列(文字列は現れた順のカテゴリ)。日時の列は使えない。同じ X・Y の組は平均を描く。""" + series = settings.series[0] + n = 1 + warnings: list[dict] = [] + x_index = resolve_column_index(df, series.x) if series.x else None + x_label = str(df.columns[x_index]) if x_index is not None else "index" + y_index = resolve_column_index(df, y_request) + y_name, data_label = _label_for(df, y_index) + x_series = df.iloc[:, x_index] if x_index is not None else pd.Series(df.index) + y_series = df.iloc[:, y_index] + if _is_datetime(x_series): + raise UserError(HEATMAP_DATETIME_MESSAGE.format(n=n, what="X列", name=x_label), field=f"系列{n}のX列") + if _is_datetime(y_series): + raise UserError(HEATMAP_DATETIME_MESSAGE.format(n=n, what="Y列", name=y_name), field=f"系列{n}のY列") + convert_x = convert_y = False + if x_index is not None and not pd.api.types.is_numeric_dtype(x_series.dtype) and _looks_numeric(x_series): + convert_x = True + x_series, dropped, examples = coerce_numeric(x_series) + if dropped: + warnings.append(dropped_warning(n, f"系列{n}のX列({x_label})", dropped, examples, settings.load)) + if not pd.api.types.is_numeric_dtype(y_series.dtype) and _looks_numeric(y_series): + convert_y = True + y_series, dropped, examples = coerce_numeric(y_series) + if dropped: + warnings.append(dropped_warning(n, f"系列{n}のY列({y_name})", dropped, examples, settings.load)) + x_text = not pd.api.types.is_numeric_dtype(x_series.dtype) + y_text = not pd.api.types.is_numeric_dtype(y_series.dtype) + + value_index = _color_column(df, series.color_column, n, "値の列") + value_label = _label_for(df, value_index)[1] + if _is_datetime(df.iloc[:, value_index]): + raise UserError( + f"系列{n}の値の列({df.columns[value_index]})は日時の列です。値の列には数値の列を選んでください。", field=f"系列{n}の値の列" + ) + present = y_series.notna() & x_series.notna() + values = _color_values(df, value_index, present, n, settings.load, warnings, "値の列", "その行は使いません") + ok = present & values.notna() + if not bool(ok.any()): + raise UserError(_no_data_message(warnings)) + heat = pd.DataFrame({"x": x_series[ok], "y": y_series[ok]}) + x_count, y_count = int(heat["x"].nunique()), int(heat["y"].nunique()) + for count, which, field_name in ((x_count, "X", f"系列{n}のX列"), (y_count, "Y", f"系列{n}のY列")): + if count > MAX_HEATMAP_SIZE: + raise UserError( + f"ヒートマップの{which}の異なる値が{count}種類あります({MAX_HEATMAP_SIZE}種類まで)。" + f"{which}列に格子の軸になる列を選んでいるか確認してください。", + field=field_name, + ) + duplicates = int(heat.duplicated(["x", "y"]).sum()) + if duplicates: + warnings.append({"series": n, "message": f"系列{n}: 同じ X・Y の組が{duplicates}件重複していたため、その平均を描きます。"}) + ext = _Extents() + if not x_text: + ext.add_values("x", x_series[ok]) + if not y_text: + ext.add_values("y", y_series[ok]) + x_kind = "category" if x_text else ("log" if settings.axes.x.scale == "log" else "number") + y_kind = "category" if y_text else ("log" if settings.axes.y.scale == "log" else "number") + plan = SeriesPlan( + number=n, + y_index=y_index, + y_name=y_name, + x_index=x_index, + x_label=x_label, + data_label=data_label, + legend_label=series.label or data_label, + convert_x=convert_x, + categorical_x=x_text, + marker_size=series.effective_marker_size("bar"), + has_points=True, + secondary=False, + alpha=series.alpha, + color_index=value_index, + color_label=value_label, + ) + return _finish( + settings, [plan], warnings, x_label, None, axes_args=(x_kind, ext, x_count if x_text else 0, y_kind, y_count if y_text else 0), + heatmap=HeatmapPlan(x_text=x_text, y_text=y_text, y_convert=convert_y, x_count=x_count, y_count=y_count, duplicates=duplicates), + ) + + def _finish( settings: Settings, plans: list[SeriesPlan], @@ -1277,15 +1457,17 @@ def _finish( datetime_x: bool = False, thin_categorical_x: bool = False, bar_date_format: str | None = None, - axes_args: tuple | None = None, # (X の軸の種類, _Extents, カテゴリ数[, Y の軸の種類(横棒の縦軸)]) + axes_args: tuple | None = None, # (X の軸の種類, _Extents, カテゴリ数[, Y の軸の種類(横棒の縦軸・ヒートマップ)[, Y のカテゴリ数(ヒートマップ)]]) fits: tuple[FitPlan, ...] = (), hist: HistPlan | None = None, + heatmap: HeatmapPlan | None = None, ) -> PlotPlan: primary = [p.data_label for p in plans if not p.secondary] secondary = [p.data_label for p in plans if p.secondary] uses_secondary = any(p.secondary and p.has_points for p in plans) x_kind, ext, categories, *rest = axes_args or ("number", _Extents(), 0) y_kind = rest[0] if rest else None + y_categories = rest[1] if len(rest) > 1 else None annotations = _plan_annotations(settings, x_kind, uses_secondary, ext, y_kind) # 範囲を ext に足すので、軸の計画より前 plot_type = settings.plot.type y_label = primary[0] if len(primary) == 1 else "values" @@ -1294,8 +1476,10 @@ def _finish( x_label, y_label = plans[0].data_label, x_label elif plot_type == "hist": x_label, y_label = plans[0].data_label, "確率密度" if settings.plot.hist_density else "度数" - elif plot_type == "scatterColor": + elif plot_type in {"scatterColor", "heatmap"}: colorbar = ColorbarPlan(settings.plot.colormap, settings.plot.colorbar_label or plans[0].color_label) + elif plot_type in {"box", "violin"}: # 横軸は系列の名前(目盛)。縦軸は、系列が1つならその Y 列の名前 + x_label, y_label = "", plans[0].data_label if len(plans) == 1 else "" return PlotPlan( skip_rows=settings.plot.skip_rows, plot_type=settings.plot.type, @@ -1310,9 +1494,10 @@ def _finish( datetime_x=datetime_x, thin_categorical_x=thin_categorical_x, bar_date_format=bar_date_format, - axes=_plan_axes(settings, x_kind, uses_secondary, ext, categories, y_kind), + axes=_plan_axes(settings, x_kind, uses_secondary, ext, categories, y_kind, y_categories), annotations=annotations, fits=fits, hist=hist, colorbar=colorbar, + heatmap=heatmap, ) diff --git a/py/mplgui/expr.py b/py/mplgui/expr.py index eeabdff..5f74f9c 100644 --- a/py/mplgui/expr.py +++ b/py/mplgui/expr.py @@ -27,6 +27,11 @@ _NAME_HINT = "列は [N] か大文字の列記号(A, B, …)で、関数は max( のように書いてください" _CONST_MESSAGE = "計算できない定数があります(0 での割り算など)" +MODEL_VARIABLE = "x" +MODEL_PARAMS = ("a", "b", "c", "d", "e") +_MODEL_NAME_HINT = "使える名前は x と a〜e です" +_MODEL_COLUMN_MESSAGE = "近似の式では列は使えません(変数は x、パラメータは a〜e です)。" + _KIND_ORDER = {"const": 0, "scalar": 1, "series": 2} @@ -86,7 +91,16 @@ class Call: kind: str = field(default="const", compare=False, repr=False) -Node = Number | Column | Unary | Binary | Call +@dataclass(frozen=True) +class Var: + """近似の式(モデル)の変数 x とパラメータ a〜e。""" + + name: str + pos: int + kind: str = field(default="scalar", compare=False, repr=False) + + +Node = Number | Column | Unary | Binary | Call | Var # ---- 字句解析 --------------------------------------------------------------- @@ -128,7 +142,7 @@ def _excel_index(letters: str) -> int: return n - 1 -def _tokenize(s: str) -> list[_Tok]: +def _tokenize(s: str, model: bool = False) -> list[_Tok]: toks: list[_Tok] = [] n = len(s) i = 0 @@ -142,6 +156,8 @@ def _tokenize(s: str) -> list[_Tok]: toks.append(_Tok("num", m.group(), pos, float(m.group()))) i = m.end() elif c == "[": + if model: + raise ExprError(_MODEL_COLUMN_MESSAGE, pos) m = _COLUMN.match(s, i) if m is None: raise ExprError("列は [0] のように、角括弧の中に番号を書いてください", pos) @@ -154,6 +170,10 @@ def _tokenize(s: str) -> list[_Tok]: while j < n and s[j] in " \t": j += 1 paren = j < n and s[j] == "(" + if model: + _model_ident(toks, name, pos, paren) + i = m.end() + continue if name.isalpha() and name.isupper(): if paren: raise ExprError(f"関数名は小文字で書いてください({name.lower()})", pos) @@ -195,6 +215,29 @@ def _tokenize(s: str) -> list[_Tok]: return toks +def _model_ident(toks: list[_Tok], name: str, pos: int, paren: bool) -> None: + if name.isalpha() and name.isupper() and not paren and len(name) <= 3: + raise ExprError(_MODEL_COLUMN_MESSAGE, pos) + if name in ELEMENTWISE: + if not paren: + raise ExprError( + f"「{name}」は関数です。{name}( のように、括弧で値を指定してください", pos + ) + toks.append(_Tok("func", name, pos, name)) + elif name in AGGREGATES or name in SERIES_FUNCS: + raise ExprError( + f"「{name}」は近似の式では使えません。使える関数: {', '.join(ELEMENTWISE)}", pos + ) + elif paren: + raise ExprError( + f"「{name}」という関数はありません。使える関数: {', '.join(ELEMENTWISE)}", pos + ) + elif name == MODEL_VARIABLE or name in MODEL_PARAMS: + toks.append(_Tok("var", name, pos, name)) + else: + raise ExprError(f"「{name}」は使えません。{_MODEL_NAME_HINT}", pos) + + # ---- ノードの生成(種類の判定と定数の畳み込み) -------------------------------- @@ -293,7 +336,7 @@ def leave(self) -> None: self.depth -= 1 def _is_value_start(self, t: _Tok) -> bool: - return t.kind in ("num", "col", "func", "(") + return t.kind in ("num", "col", "func", "var", "(") def _unexpected(self, lparen: _Tok | None) -> ExprError: """式の途中で、演算子や閉じ括弧でないものが来たときの誤り。""" @@ -368,6 +411,9 @@ def atom(self) -> Node: if t.kind == "col": self.advance() return Column(t.value, t.pos) + if t.kind == "var": + self.advance() + return Var(t.value, t.pos, "series" if t.value == MODEL_VARIABLE else "scalar") if t.kind == "func": self.advance() lp = self.advance() # tokenizer guarantees "(" @@ -411,6 +457,26 @@ def parse(text: str) -> Node: return node +def parse_model(text: str) -> Node: + """近似の式(変数 x、パラメータ a〜e)を解釈する。""" + if len(text) > MAX_LENGTH: + raise ExprError(f"式は{MAX_LENGTH}文字までです") + s = _normalize(text) + if not s.strip(" \t"): + raise ExprError("式を入力してください") + toks = _tokenize(s, model=True) + try: + node = _Parser(toks).parse_top() + except RecursionError: + raise ExprError(_DEPTH_MESSAGE) from None + names = _var_names(node) + if MODEL_VARIABLE not in names: + raise ExprError("式に x を含めてください。") + if not any(p in names for p in MODEL_PARAMS): + raise ExprError("式にパラメータ(a〜e)を1つ以上含めてください。") + return node + + # ---- 木の調査 --------------------------------------------------------------- @@ -424,6 +490,23 @@ def _children(node: Node) -> tuple: return () +def _var_names(node: Node) -> set[str]: + names: set[str] = set() + stack = [node] + while stack: + n = stack.pop() + if isinstance(n, Var): + names.add(n.name) + stack.extend(_children(n)) + return names + + +def model_params(node: Node) -> tuple[str, ...]: + """式で使っているパラメータ(a〜e の順。1つにつき1回)。""" + names = _var_names(node) + return tuple(p for p in MODEL_PARAMS if p in names) + + def column_refs(node: Node) -> tuple[tuple[int, int], ...]: refs: list[tuple[int, int]] = [] stack = [node] @@ -540,6 +623,8 @@ def go(nd: Node) -> tuple[str, int]: if isinstance(nd, Number): s = number(float(nd.value)) return s, (_P_UNARY if s.startswith("-") else _P_ATOM) + if isinstance(nd, Var): + return nd.name, _P_ATOM if isinstance(nd, Column): return column_var(nd.index), _P_ATOM if isinstance(nd, Unary): @@ -577,3 +662,68 @@ def go(nd: Node) -> tuple[str, int]: return f"{base}.{name}()", _P_ATOM return go(node)[0] + + +def model_to_code(node: Node, number: Callable[[float], str]) -> str: + """近似の式の numpy コード(名前は x, a〜e のまま。入力文字列は写さない)。""" + return to_code(node, lambda i: "", number) + + +def _format_number(v: float) -> str: + return "%.15g" % v + + +def model_to_text(node: Node) -> str: + """図のラベル用の、木から整えた式(ASCII だけ。例: a*exp(-b*x) + c)。""" + + def go(nd: Node) -> tuple[str, int]: + if isinstance(nd, Number): + s = _format_number(float(nd.value)) + return s, (_P_UNARY if s.startswith("-") else _P_ATOM) + if isinstance(nd, Var): + return nd.name, _P_ATOM + if isinstance(nd, Unary): + s, p = go(nd.operand) + if p <= _P_UNARY: + s = f"({s})" + return f"-{s}", _P_UNARY + if isinstance(nd, Binary): + op = nd.op + prec = _OP_PREC[op] + ls, lp = go(nd.left) + rs, rp = go(nd.right) + if op == "**": + lparen, rparen = lp <= _P_POW, rp < _P_UNARY + else: + lparen, rparen = lp < prec, rp <= prec + if lparen: + ls = f"({ls})" + if rparen: + rs = f"({rs})" + if op in ("+", "-"): + return f"{ls} {op} {rs}", prec + return f"{ls}{'^' if op == '**' else op}{rs}", prec + s, _ = go(nd.args[0]) + return f"{nd.name}({s})", _P_ATOM + + return go(node)[0] + + +def evaluate_model(node: Node, x, params: Mapping[str, float]) -> np.ndarray: + """近似の式を numpy で評価する(model_to_code と同じ意味)。""" + xs = np.asarray(x, dtype=float) + ps = {k: np.float64(v) for k, v in params.items()} + + def go(nd: Node): + if isinstance(nd, Number): + return float(nd.value) + if isinstance(nd, Var): + return xs if nd.name == MODEL_VARIABLE else ps[nd.name] + if isinstance(nd, Unary): + return -go(nd.operand) + if isinstance(nd, Binary): + return _BINARY_OPS[nd.op](go(nd.left), go(nd.right)) + return getattr(np, nd.name)(go(nd.args[0])) + + with np.errstate(all="ignore"): + return np.broadcast_to(np.asarray(go(node), dtype=float), xs.shape).copy() diff --git a/py/mplgui/runner.py b/py/mplgui/runner.py index 2ed71af..7d440fa 100644 --- a/py/mplgui/runner.py +++ b/py/mplgui/runner.py @@ -93,7 +93,7 @@ def _offset_text(axis) -> str: return str(get_offset()) if get_offset is not None else "" -_AUX_LINE_LABELS = {"_errorbar", "_fit"} +_AUX_LINE_LABELS = {"_errorbar", "_fit", "_box"} # _box: 箱ひげ図のひげ・端・中央値・外れ値・平均の線 def _is_fit_label(label: str) -> bool: @@ -181,6 +181,9 @@ def _style_summary(ax) -> dict: }, "fitlines": sum(1 for ln in lines if _is_fit_label(ln.get_label())), "fittexts": fit_texts, + "boxes": sum(1 for p in ax.patches if p.get_label() == "_box"), + "violins": sum(1 for c in ax.collections if c.get_label() == "_violin"), + "meshes": sum(1 for c in ax.collections if type(c).__name__ == "QuadMesh"), } @@ -192,7 +195,13 @@ def figure_summary(fig) -> list[dict]: - bars: {vertical, horizontal, containers, stacked}。BarContainer の棒の本数(縦向き・横向き)、容器ごとの棒の数、 棒の下端(横棒は左端)が 0 でない容器の数(積み上げ棒の2系列目以降)。ヒストグラムも BarContainer - colorbar: カラーバーが無ければ null、あれば {label, cmap, vmin, vmax}。カラーバーの Axes は軸ごとの一覧に入れず、 - 元の Axes の項目として出す(色分け散布図は第2Y軸が無いので、最初の Axes に付く) + 元の Axes の項目として出す(色分け散布図・ヒートマップは第2Y軸が無いので、最初の Axes に付く) + + Phase 5d で足したキー(既存のキーの値は変えない): + - boxes: 箱ひげ図の箱の数(ラベルが `_box` の patch。生成コードが箱ひげ図の部品すべてにこのラベルを付ける)。 + 箱ひげ図の線(ひげ・端・中央値・外れ値・平均)も `_box` なので、markers / alphas / drawstyles には数えない(lines には数える) + - violins: バイオリン図の胴の数(ラベルが `_violin` の collection。中央値・端の線は LineCollection で collections に数える) + - meshes: ヒートマップ(pcolormesh)の QuadMesh の数 """ out = [] colorbar = _colorbar_summary(fig) @@ -243,8 +252,8 @@ def figure_summary(fig) -> list[dict]: (SyntaxError, "書き方(文法)が正しくありません"), (NameError, "定義されていない名前を使っています"), (FileNotFoundError, "ファイルが見つかりません"), - (ModuleNotFoundError, "読み込めないライブラリがあります(使えるのは pandas, matplotlib, numpy です)"), - (ImportError, "読み込めないライブラリや名前があります(使えるのは pandas, matplotlib, numpy です)"), + (ModuleNotFoundError, "読み込めないライブラリがあります(使えるのは pandas, matplotlib, numpy です。scipy は任意の式の近似曲線でも使えます)"), + (ImportError, "読み込めないライブラリや名前があります(使えるのは pandas, matplotlib, numpy です。scipy は任意の式の近似曲線でも使えます)"), (KeyError, "存在しないキー(列名など)を指定しています"), (IndexError, "範囲の外の位置を指定しています"), (TypeError, "型が合わない操作をしています"), diff --git a/py/mplgui/settings.py b/py/mplgui/settings.py index 6a80877..c5972bf 100644 --- a/py/mplgui/settings.py +++ b/py/mplgui/settings.py @@ -19,14 +19,20 @@ SCHEMA_VERSION = 4 -PLOT_TYPES = ("line", "scatter", "bar", "step", "barh", "barStacked", "hist", "scatterColor") -# 種類ごとに画面で隠す設定は、検証せず使わない(要件 §2.2。docs/PHASE5_DESIGN.md §6.2) -BAR_LIKE_TYPES = ("bar", "barh", "barStacked", "hist") # 点の形・塗りつぶし帯・X 方向のエラーバー・近似曲線を使わない -NO_Y2_TYPES = ("barh", "barStacked", "hist", "scatterColor") # 第2Y軸を使わない -NO_Y_ERROR_TYPES = ("barStacked", "hist") # Y 方向のエラーバーを使わない +PLOT_TYPES = ("line", "scatter", "bar", "step", "barh", "barStacked", "hist", "scatterColor", "box", "violin", "heatmap") +# 種類ごとに画面で隠す設定は、検証せず使わない(要件 §2.2。docs/PHASE5_DESIGN.md §6.2・§7.3)。js/chart-types.js と揃えること +XY_TYPES = ("line", "step", "scatter", "scatterColor") # 点の形・塗りつぶし帯・X 方向のエラーバー・近似曲線を使う(系列ごとの X と Y の組で描く) +BOX_TYPES = ("box", "violin") # 系列ごとに1つの箱・胴を描く(横軸は系列の名前) +CATEGORY_BAR_TYPES = ("bar", "barStacked", "barh") # 全系列共通の X列(plot.xColumn)を使う +SERIES_X_TYPES = XY_TYPES + ("heatmap",) # 系列ごとの X 列を使う +NO_Y2_TYPES = ("barh", "barStacked", "hist", "scatterColor") + BOX_TYPES + ("heatmap",) # 第2Y軸を使わない +NO_Y_ERROR_TYPES = ("barStacked", "hist") + BOX_TYPES + ("heatmap",) # Y 方向のエラーバーを使わない +COLOR_COLUMN_TYPES = ("scatterColor", "heatmap") # 色分けの列(ヒートマップでは値の列)を使う +HEATMAP_SERIES_MESSAGE = "ヒートマップは系列1つで描きます。系列を1つにしてください。" STEP_WHERE_CHOICES = ("pre", "mid", "post") COLORMAPS = ("viridis", "cividis", "plasma", "inferno", "magma", "coolwarm", "RdBu_r", "gray") MAX_HIST_BINS = 1000 +MAX_HEATMAP_SIZE = 500 # ヒートマップの X・Y の異なる値の上限(それぞれ) LINE_STYLES = ("solid", "dashed", "dashdot", "dotted") SCALES = ("linear", "log") SAVE_FORMATS = ("png", "jpg", "svg", "pdf") @@ -69,7 +75,7 @@ ANNOTATION_KINDS = ("text", "hline", "vline", "hspan", "vspan") ANNOTATION_COORDS = ("data", "axes") ANNOTATION_AXES = ("y", "y2") -FIT_MODELS = ("linear", "poly") +FIT_MODELS = ("linear", "poly", "custom") FIT_SHOWS = ("legend", "text", "none") MAX_ANNOTATIONS = 50 MAX_FITS = 20 @@ -108,7 +114,10 @@ "label": "", } _DEFAULT_COMPUTED = {"id": "", "source": "", "name": "", "expr": ""} -_DEFAULT_FIT = {"id": "f1", "series": "s1", "model": "linear", "degree": 2, "show": "legend", "color": "", "lineStyle": "dashed"} +_DEFAULT_FIT = { + "id": "f1", "series": "s1", "model": "linear", "degree": 2, "show": "legend", "color": "", "lineStyle": "dashed", + "expr": "", "initial": {"a": 1, "b": 1, "c": 1, "d": 1, "e": 1}, +} _DEFAULT_SERIES = { "id": "s1", @@ -175,6 +184,8 @@ def default_settings() -> dict: "hist": {"bins": None, "density": False}, "colormap": "viridis", "colorbarLabel": "", + "box": {"fliers": True, "means": False}, + "violin": {"medians": True, "means": False}, }, "axes": { "x": { @@ -277,8 +288,12 @@ class PlotSettings: step_where: str = "post" # step のときだけ使う: pre / mid / post hist_bins: int | None = None # hist のときだけ使う: None = 自動(numpy の "auto") hist_density: bool = False # hist のときだけ使う: 縦軸を確率密度にする - colormap: str = "viridis" # scatterColor のときだけ使う - colorbar_label: str = "" # scatterColor のときだけ使う("" = 系列1の色分けの列の名前) + colormap: str = "viridis" # scatterColor / heatmap のときだけ使う + colorbar_label: str = "" # scatterColor / heatmap のときだけ使う("" = 系列1の色分けの列(値の列)の名前) + box_fliers: bool = True # box のときだけ使う: 外れ値の点を描く + box_means: bool = False # box のときだけ使う: 平均の印を描く + violin_medians: bool = True # violin のときだけ使う: 中央値の線を描く + violin_means: bool = False # violin のときだけ使う: 平均の線を描く @dataclass(frozen=True) @@ -336,7 +351,7 @@ class SeriesSettings: marker: str = "auto" # auto / none / o / s / ^ / v / D / x / + / *(棒グラフでは使わない) alpha: float = 1.0 # 不透明度(1 = 透けない) fill: FillSettings = field(default_factory=FillSettings) # 棒グラフでは使わない - color_column: str = "" # "__idx__N"。scatterColor のときだけ使う(必須) + color_column: str = "" # "__idx__N"。scatterColor / heatmap(値の列)のときだけ使う(必須) def effective_marker_size(self, plot_type: str) -> float: """自動(None)は line / step=0 / それ以外=24。scatter / scatterColor で 0 以下なら 24 に補正する。""" @@ -378,6 +393,11 @@ class FitSettings: show: str = "legend" # legend / text / none color: str = "" # "" = 系列の色 line_style: str = "dashed" + # custom(任意の式)のときだけ使う。expr_node は解釈済みの式、params は使うパラメータ(a〜e の順)、initial はその初期値 + expr: str = "" + expr_node: Any = field(default=None, compare=False, repr=False) + params: tuple[str, ...] = () + initial: tuple[float, ...] = () @dataclass(frozen=True) @@ -769,12 +789,12 @@ def _parse_error_spec(raw: dict, axis: str, owner: str) -> ErrorSpec: def _parse_error_bars(raw: dict, plot_type: str, owner: str) -> ErrorBarSettings: - if plot_type in NO_Y_ERROR_TYPES: # 積み上げ棒・ヒストグラムはエラーバーを両方向とも隠すので、何も検証しない + if plot_type in NO_Y_ERROR_TYPES: # 積み上げ棒・ヒストグラム・箱ひげ・バイオリン・ヒートマップはエラーバーを両方向とも隠すので、何も検証しない return ErrorBarSettings() cap = _number(raw["capSize"], "エラーバーの端の長さ", default=3.0, minimum=0, maximum=MAX_CAP_SIZE, owner=owner) return ErrorBarSettings( y=ErrorSpec() if plot_type in NO_Y_ERROR_TYPES else _parse_error_spec(raw["y"], "Y", owner), # 積み上げ棒・ヒストグラムでは Y 方向を隠す - x=ErrorSpec() if plot_type in BAR_LIKE_TYPES else _parse_error_spec(raw["x"], "X", owner), # 棒グラフ・ヒストグラムでは X 方向を隠す + x=_parse_error_spec(raw["x"], "X", owner) if plot_type in XY_TYPES else ErrorSpec(), # X 方向は XY の種類だけ cap_size=cap, ) @@ -802,19 +822,21 @@ def _parse_fill(raw: dict, owner: str) -> FillSettings: return FillSettings(lower=lower, upper=upper, alpha=alpha) -def _parse_color_column(value: Any, owner: str) -> str: - """色分けの列(scatterColor のときだけ。必須)。""" - field_name = f"{owner}色分けの列" +def _parse_color_column(value: Any, owner: str, what: str = "色分けの列") -> str: + """色分けの列(scatterColor では「色分けの列」、heatmap では「値の列」。どちらも必須)。""" + field_name = f"{owner}{what}" if value is None or (isinstance(value, str) and not value.strip()): - raise UserError(f"{owner}色分けの列を選んでください。", field=field_name) + raise UserError(f"{owner}{what}を選んでください。", field=field_name) if not isinstance(value, str) or not _COLUMN_RE.fullmatch(value.strip()): - raise UserError(f"{owner}「色分けの列」の指定が正しくありません。列を選び直してください。", field=field_name) + raise UserError(f"{owner}「{what}」の指定が正しくありません。列を選び直してください。", field=field_name) return value.strip() 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="描画系列") + if plot_type == "heatmap" and len(raw_series) > 1: # 系列ごとの検証(値の列が未選択など)より先に知らせる + raise UserError(HEATMAP_SERIES_MESSAGE, field="系列") out = [] used_ids: set[str] = set() for i, given in enumerate(raw_series): @@ -825,21 +847,29 @@ def _parse_series(raw_series: Any, plot_type: str = "line") -> tuple[SeriesSetti while sid in used_ids: sid += "_" used_ids.add(sid) - color = _string(s["color"], "色", owner=owner).strip() or _DEFAULT_SERIES["color"] - if not is_color_like(color): - raise UserError(f"{owner}「色」が不正です。", field="色") - line_width = _number(s["lineWidth"], "線幅", default=2.0, exclusive_min=0, owner=owner) - marker = _number(s["markerSize"], "点サイズ", default=None, minimum=0, owner=owner) + heat = plot_type == "heatmap" # ヒートマップは色・線幅・線種・点サイズを隠す(カラーマップを使う)。検証せず使わない + box = plot_type in BOX_TYPES # 箱ひげ・バイオリンは点サイズ・線種を隠す + color = _DEFAULT_SERIES["color"] + line_width = 2.0 + if not heat: + color = _string(s["color"], "色", owner=owner).strip() or _DEFAULT_SERIES["color"] + if not is_color_like(color): + raise UserError(f"{owner}「色」が不正です。", field="色") + line_width = _number(s["lineWidth"], "線幅", default=2.0, exclusive_min=0, owner=owner) + marker = None if (heat or box) else _number(s["markerSize"], "点サイズ", default=None, minimum=0, owner=owner) + line_style = "solid" if (heat or box) else _choice(s["lineStyle"], "線種", LINE_STYLES, owner=owner) marker_shape = "auto" fill = FillSettings() - if plot_type not in BAR_LIKE_TYPES: # 棒グラフ・ヒストグラムでは点の形と塗りつぶし帯を隠すので、検証せず使わない + if plot_type in XY_TYPES: # 点の形と塗りつぶし帯は XY の種類だけ。ほかは隠すので、検証せず使わない marker_shape = _choice(s["marker"], "点の形", MARKERS, owner=owner, field_name=f"{owner}点の形") if plot_type in {"scatter", "scatterColor"} and marker_shape == "none": raise UserError( f"{owner}「点の形」を「なし」にすると、散布図の点が見えなくなります。点の形を選んでください。", field=f"{owner}点の形" ) fill = _parse_fill(s["fill"], owner) - color_column = _parse_color_column(s["colorColumn"], owner) if plot_type == "scatterColor" else "" + color_column = "" + if plot_type in COLOR_COLUMN_TYPES: + color_column = _parse_color_column(s["colorColumn"], owner, "値の列" if heat else "色分けの列") out.append( SeriesSettings( id=sid, @@ -847,7 +877,7 @@ def _parse_series(raw_series: Any, plot_type: str = "line") -> tuple[SeriesSetti y=_string(s["y"], "Y列", owner=owner).strip(), color=color, line_width=line_width, - line_style=_choice(s["lineStyle"], "線種", LINE_STYLES, owner=owner), + line_style=line_style, marker_size=marker, label=_string(s["label"], "凡例名", owner=owner).strip(), # 横棒・積み上げ棒・ヒストグラム・色分け散布図では第2Y軸を隠す(false として扱い、検証しない) @@ -963,6 +993,24 @@ def _parse_fits(raw: Any, series_ids: set[str]) -> tuple[FitSettings, ...]: degree = 1 if model == "poly": degree = _int_range(f["degree"], f"{owner}次数", 2, 6, default=2) + expr_text, node, params, initial = "", None, (), () + if model == "custom": + expr_text = _string(f["expr"], "式", owner=owner) + if not expr_text.strip(): + raise UserError(f"近似曲線{n}の式を入力してください。", field=f"近似曲線{n}の式") + try: + node = expr_module.parse_model(expr_text) + except expr_module.ExprError as e: + raise UserError(f"近似曲線{n}の式: {e}", field=f"近似曲線{n}の式") from None + params = expr_module.model_params(node) + given_initial = f["initial"] if isinstance(f["initial"], dict) else {} + initial = tuple( + _number( + given_initial.get(name, 1), f"初期値({name})", default=1.0, owner=owner, + field_name=f"{owner}初期値({name})", + ) + for name in params + ) color = _string(f["color"], "色", owner=owner).strip() if color and not is_color_like(color): raise UserError(f"{owner}「色」が不正です。", field=f"{owner}色") @@ -975,6 +1023,10 @@ def _parse_fits(raw: Any, series_ids: set[str]) -> tuple[FitSettings, ...]: show=_choice(f["show"], "式の表示先", FIT_SHOWS, owner=owner, field_name=f"{owner}式の表示先"), color=color, line_style=_choice(f["lineStyle"], "線種", LINE_STYLES, owner=owner, field_name=f"{owner}線種"), + expr=expr_text, + expr_node=node, + params=params, + initial=initial, ) ) return tuple(out) @@ -1056,6 +1108,7 @@ def parse_settings(raw: dict | None) -> Settings: plot_type = _choice(p["type"], "プロット種別", PLOT_TYPES) step_where, hist_bins, hist_density, colormap, colorbar_label = "post", None, False, "viridis", "" + box_fliers, box_means, violin_medians, violin_means = True, False, True, False if plot_type == "step": step = p["step"] if isinstance(p["step"], dict) else {} step_where = _choice(step.get("where", "post"), "段の付き方", STEP_WHERE_CHOICES) @@ -1063,14 +1116,22 @@ def parse_settings(raw: dict | None) -> Settings: hist = p["hist"] if isinstance(p["hist"], dict) else {} hist_bins = _int_range(hist.get("bins"), "区間の数", 1, MAX_HIST_BINS, default=None) hist_density = _boolean(hist.get("density", False), "確率密度") - elif plot_type == "scatterColor": + elif plot_type in COLOR_COLUMN_TYPES: colormap = _choice(p["colormap"], "カラーマップ", COLORMAPS) colorbar_label = _string(p["colorbarLabel"], "カラーバーのラベル").strip() + elif plot_type == "box": + box = p["box"] if isinstance(p["box"], dict) else {} + box_fliers = _boolean(box.get("fliers", True), "外れ値の点") + box_means = _boolean(box.get("means", False), "平均の印") + elif plot_type == "violin": + violin = p["violin"] if isinstance(p["violin"], dict) else {} + violin_medians = _boolean(violin.get("medians", True), "中央値の線") + violin_means = _boolean(violin.get("means", False), "平均の線") plot = PlotSettings( type=plot_type, skip_rows=_integer(p["skipRows"], "除外する先頭行数", default=0, minimum=0), - x_column="" if plot_type == "hist" else _string(p["xColumn"], "X列").strip(), # ヒストグラムは X列を隠す + x_column="" if plot_type in {"hist", "box", "violin", "heatmap"} else _string(p["xColumn"], "X列").strip(), # ヒストグラム・箱ひげ・バイオリン・ヒートマップは X列を隠す title=_string(p["title"], "タイトル").strip(), font_size=_number(p["fontSize"], "フォントサイズ", default=15.0, exclusive_min=0), figure=figure, @@ -1087,6 +1148,10 @@ def parse_settings(raw: dict | None) -> Settings: hist_density=hist_density, colormap=colormap, colorbar_label=colorbar_label, + box_fliers=box_fliers, + box_means=box_means, + violin_medians=violin_medians, + violin_means=violin_means, ) ax = merged["axes"] @@ -1097,7 +1162,7 @@ def parse_settings(raw: dict | None) -> Settings: and any(isinstance(s, dict) and s.get("secondaryAxis") is True for s in raw_series) ) axes = AxesSettings( - x=_parse_axis(ax, "x", "X"), + x=_parse_axis(ax, "x", "X", linear=plot.type in BOX_TYPES), # 箱ひげ・バイオリンの横軸はカテゴリなので、X のスケールは使わない y=_parse_axis(ax, "y", "Y", linear=plot.type == "barh"), # 横棒の縦軸はカテゴリなので、Y のスケールは使わない y2=_parse_axis(ax, "y2", "第2Y", ticks=y2_used), ) @@ -1112,8 +1177,8 @@ def parse_settings(raw: dict | None) -> Settings: check_axis_range(axes.y2, "第2Y") annotations = _parse_annotations(raw.get("annotations"), any(s.secondary_axis for s in series)) - # 棒グラフ・ヒストグラムでは近似曲線を使わない(隠れているので検証しない) - fits = () if plot.type in BAR_LIKE_TYPES else _parse_fits(raw.get("fits"), {s.id for s in series}) + # XY の種類以外では近似曲線を使わない(隠れているので検証しない) + fits = _parse_fits(raw.get("fits"), {s.id for s in series}) if plot.type in XY_TYPES else () # 計算した列は常に表示されるので、グラフの種類によらず検証する computed = _parse_computed(raw.get("computed"), file_ids) diff --git a/pyproject.toml b/pyproject.toml index 62fb3d2..c8c296c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -24,6 +24,7 @@ dev = [ "matplotlib==3.10.8", "numpy==2.4.3", "openpyxl==3.1.5", + "scipy==1.18.0", "pytest>=9.1.1", "pytest-playwright>=0.9.0", "pyyaml>=6.0.3", diff --git a/tests/e2e/helpers.py b/tests/e2e/helpers.py index c929b7b..05c5329 100644 --- a/tests/e2e/helpers.py +++ b/tests/e2e/helpers.py @@ -618,3 +618,13 @@ def option_labels(page, select_id) -> dict: return page.evaluate( "(id) => Object.fromEntries([...document.querySelectorAll(`#${id} option`)].map(o => [o.value, o.textContent.trim()]))", select_id ) + + +# ---- Phase 5d (G10) +def scipy_state(page) -> str: + """(idle / loading / ready / failed)。""" + return page.evaluate("document.documentElement.dataset.scipyState || ''") + + +def wait_scipy_state(page, state, timeout=300_000): + page.wait_for_function("(s) => document.documentElement.dataset.scipyState === s", arg=state, timeout=timeout) diff --git a/tests/e2e/test_chart_types.py b/tests/e2e/test_chart_types.py index f631f03..e549ac1 100644 --- a/tests/e2e/test_chart_types.py +++ b/tests/e2e/test_chart_types.py @@ -56,15 +56,17 @@ def test_type_options_keep_existing_labels_and_add_new(page, app_url, fixtures_d assert options[3:] == [ ["step", "step"], ["barh", "barh(横棒)"], ["barStacked", "bar(積み上げ)"], ["hist", "hist(ヒストグラム)"], ["scatterColor", "scatter(色分け)"], + ["box", "box(箱ひげ図)"], ["violin", "violin(バイオリン図)"], ["heatmap", "heatmap(ヒートマップ)"], ] labels = page.eval_on_selector_all("#colorMap option", "els => els.map(e => e.value)") assert labels == ["viridis", "cividis", "plasma", "inferno", "magma", "coolwarm", "RdBu_r", "gray"] -GROUP_IDS = ["stepGroup", "histGroup", "colorMapGroup", "yScaleGroup", "globalXGroup", "addFitBtn", "fitList", "addAnnotationBtn"] +GROUP_IDS = ["stepGroup", "histGroup", "boxGroup", "violinGroup", "xScaleGroup", "colorMapGroup", "yScaleGroup", "globalXGroup", "addFitBtn", "fitList", "addAnnotationBtn"] CARD_IDS = [ "series-s1-x", "series-s1-marker", "series-s1-marker-size", "series-s1-errorbars", "series-s1-xerr-mode", "series-s1-yerr-mode", "series-s1-fill", "series-s1-use-y2", "series-s1-color-column", "series-s1-line-width", "series-s1-alpha", + "series-s1-line-style", "series-s1-color-trigger", ] BAR_LIKE = dict(globalXGroup=False, addFitBtn=False, fitList=False, addAnnotationBtn=True) XY = dict(globalXGroup=False, addFitBtn=True, fitList=True, addAnnotationBtn=True) @@ -82,6 +84,12 @@ def test_type_options_keep_existing_labels_and_add_new(page, app_url, fixtures_d "barh": {**BAR_LIKE, "globalXGroup": True, "yScaleGroup": False, "series-s1-errorbars": 1, "series-s1-yerr-mode": 1}, "barStacked": {**BAR_LIKE, "globalXGroup": True}, "hist": {**BAR_LIKE, "histGroup": 1}, + # 箱ひげ・バイオリン: 系列の X 列・X のスケールを使わない。エラーバー・第2Y軸なし。線種は使わない + "box": {**BAR_LIKE, "boxGroup": 1, "xScaleGroup": 0, "series-s1-line-style": 0}, + "violin": {**BAR_LIKE, "violinGroup": 1, "xScaleGroup": 0, "series-s1-line-style": 0}, + # ヒートマップ: 値の列とカラーマップ。色・線幅・線種は使わない。エラーバー・第2Y軸なし + "heatmap": {**BAR_LIKE, "colorMapGroup": 1, "series-s1-x": 1, "series-s1-color-column": 1, "series-s1-line-width": 0, + "series-s1-line-style": 0, "series-s1-color-trigger": 0}, } @@ -92,18 +100,24 @@ def test_visibility_per_type(plot_type, page, app_url, fixtures_dir, console_log set_plot_type(page, plot_type) want = EXPECTED[plot_type] got = visible_ids(page, GROUP_IDS + CARD_IDS) - always = {"series-s1-line-width", "series-s1-alpha", "addAnnotationBtn", "yScaleGroup"} # 種類によらず出る(barh の Y スケールだけ隠す) + always = {"series-s1-line-width", "series-s1-alpha", "addAnnotationBtn", "yScaleGroup", "xScaleGroup", + "series-s1-line-style", "series-s1-color-trigger"} # 種類によらず出る(barh の Y スケールだけ隠す) for element_id, shown in got.items(): assert shown == bool(want.get(element_id, element_id in always)), f"{plot_type}: {element_id} shown={shown}" note_shown = not is_hidden_by_id(page, "fitBarNote") - assert note_shown == (plot_type in ("bar", "barh", "barStacked", "hist")) + assert note_shown == (plot_type in ("bar", "barh", "barStacked", "hist", "box", "violin", "heatmap")) if note_shown: assert "ヒストグラム" in page.inner_text("#fitBarNote") + assert "ヒートマップ" in page.inner_text("#fitBarNote") def test_hidden_values_are_kept_when_switching_type(page, app_url, fixtures_dir, console_log): start(page, app_url, fixtures_dir, plot_type="step") page.select_option("#stepWhere", "mid") + page.select_option("#series-s1-line-style", "dashed") + page.select_option("#series-s1-x", B) + set_plot_type(page, "box") + assert is_hidden_by_id(page, "series-s1-x") and is_hidden_by_id(page, "series-s1-line-style") set_plot_type(page, "hist") page.fill("#histBins", "7") page.check("#histDensity") @@ -117,8 +131,10 @@ def test_hidden_values_are_kept_when_switching_type(page, app_url, fixtures_dir, assert plot["step"]["where"] == "mid" and plot["hist"] == {"bins": 7, "density": True} assert plot["colormap"] == "plasma" and plot["colorbarLabel"] == "電流" assert series_state(page, "s1")["colorColumn"] == C + assert series_state(page, "s1")["lineStyle"] == "dashed" and series_state(page, "s1")["x"] == B set_plot_type(page, "step") - assert page.input_value("#stepWhere") == "mid" + assert page.input_value("#stepWhere") == "mid" and page.input_value("#series-s1-line-style") == "dashed" + assert page.input_value("#series-s1-x") == B assert axis0(page)["drawstyles"] == ["steps-mid"] set_plot_type(page, "hist") assert page.input_value("#histBins") == "7" and page.is_checked("#histDensity") @@ -291,13 +307,143 @@ def test_narrow_screen_has_no_horizontal_scroll(page, app_url, fixtures_dir, con page.set_viewport_size({"width": 375, "height": 800}) start(page, app_url, fixtures_dir, plot_type="scatterColor", x="__idx__1", y=B) page.select_option("#series-s1-color-column", C) - for plot_type in ("hist", "step", "scatterColor"): + for plot_type in ("hist", "step", "scatterColor", "box", "violin", "heatmap"): set_plot_type(page, plot_type) overflow = page.evaluate( """() => { - const wide = [...document.querySelectorAll('#stepGroup, #histGroup, #colorMapGroup, .series-item')] + const wide = [...document.querySelectorAll('#stepGroup, #histGroup, #boxGroup, #violinGroup, #colorMapGroup, .series-item')] .filter((e) => e.scrollWidth > e.clientWidth + 1).map((e) => e.id || e.className); return {page: document.documentElement.scrollWidth - window.innerWidth, wide}; }""" ) assert overflow["page"] <= 0 and overflow["wide"] == [], plot_type + + +# --- Phase 5d, G8: 箱ひげ図・バイオリン図・ヒートマップ --- +def two_series(page, y2=B): + page.click("#addSeriesBtn") + page.select_option("#series-s2-y", y2) + wait_settled(page) + + +def test_box_summary_and_toggles(page, app_url, fixtures_dir, console_log): + start(page, app_url, fixtures_dir, plot_type="box", y=A) + two_series(page) + s = axis0(page) + assert s["boxes"] == 2 and s["xlabel"] == "" and s["xscale"] == "linear" + assert is_hidden_by_id(page, "series-s1-x") and is_hidden_by_id(page, "xColumn") + assert page.is_checked("#boxFliers") and not page.is_checked("#boxMeans") + wait_code_generated(page) + before = code_text(page) + page.check("#boxMeans") + wait_settled(page) + wait_code_generated(page) + after_means = code_text(page) + assert after_means != before + page.uncheck("#boxFliers") + wait_settled(page) + wait_code_generated(page) + assert code_text(page) != after_means + assert axis0(page)["boxes"] == 2 + plot = plot_settings(page) + assert plot["box"] == {"fliers": False, "means": True} + + +def test_box_x_axis_is_category_for_ticks_and_annotations(page, app_url, fixtures_dir, console_log): + start(page, app_url, fixtures_dir, plot_type="box", y=A) + two_series(page) + open_tick_group(page, "x") + assert "何個おき" in page.inner_text("#xMajorStepHelp") + ann = add_annotation(page, "vline") + assert "何番目" in page.inner_text(f"#annotation-{ann} .ann-help") + + +def test_violin_summary_and_medians_toggle(page, app_url, fixtures_dir, console_log): + start(page, app_url, fixtures_dir, plot_type="violin", y=A) + two_series(page) + assert axis0(page)["violins"] == 2 + assert page.is_checked("#violinMedians") and not page.is_checked("#violinMeans") + assert is_hidden_by_id(page, "boxGroup") and not is_hidden_by_id(page, "violinGroup") + wait_code_generated(page) + before = code_text(page) + page.uncheck("#violinMedians") + wait_settled(page) + wait_code_generated(page) + assert code_text(page) != before + assert axis0(page)["violins"] == 2 + + +def heatmap_start(page, app_url, fixtures_dir, x="__idx__0", y="__idx__1", z="__idx__2"): + page.goto(app_url) + wait_app_ready(page) + load_fixture(page, fixtures_dir / "grid.csv") + wait_settled(page) + set_plot_type(page, "heatmap") + page.select_option("#series-s1-x", x) + page.select_option("#series-s1-y", y) + if z: + page.select_option("#series-s1-color-column", z) + wait_settled(page) + + +def test_heatmap_renders_with_value_column_label(page, app_url, fixtures_dir, console_log): + heatmap_start(page, app_url, fixtures_dir) + assert status_kind(page) != "error" + s = axis0(page) + assert s["meshes"] == 1 and s["colorbar"] is not None and s["colorbar"]["label"] == "z [2]" + assert page.inner_text("#seriesList .series-color-column-label") == "値の列" + assert not is_hidden_by_id(page, "colorMapGroup") + page.select_option("#colorMap", "plasma") + wait_settled(page) + assert axis0(page)["colorbar"]["cmap"] == "plasma" + # 色分け散布図に戻すとラベルが戻る + set_plot_type(page, "scatterColor") + assert page.inner_text("#seriesList .series-color-column-label") == "色分けの列" + + +def test_heatmap_value_column_missing_error_and_recovery(page, app_url, fixtures_dir, console_log): + heatmap_start(page, app_url, fixtures_dir, z=None) + wait_error_status(page) + assert "値の列" in status_text(page) and code_is_stale(page) + page.select_option("#series-s1-color-column", "__idx__2") + wait_settled(page) + assert status_kind(page) != "error" and not code_is_stale(page) + assert axis0(page)["meshes"] == 1 + + +def test_heatmap_two_series_error_and_recovery(page, app_url, fixtures_dir, console_log): + heatmap_start(page, app_url, fixtures_dir) + page.click("#addSeriesBtn") # 2つ目の値の列は未選択のまま: 系列の数のエラーが先に出る + wait_error_status(page) + assert "ヒートマップは系列1つ" in status_text(page) + page.click("#series-s2-remove") + wait_settled(page) + assert status_kind(page) != "error" and axis0(page)["meshes"] == 1 + + +def test_heatmap_text_axes_use_category_wording(page, app_url, fixtures_dir, console_log): + heatmap_start(page, app_url, fixtures_dir, x="__idx__3", y="__idx__4") + assert status_kind(page) != "error" + assert axis0(page)["meshes"] == 1 + # 文字列の軸はカテゴリ(スケールは使わない) + assert is_hidden_by_id(page, "xScaleGroup") and is_hidden_by_id(page, "yScaleGroup") + open_tick_group(page, "x") + assert "何個おき" in page.inner_text("#xMajorStepHelp") + open_tick_group(page, "y") + assert "何個おき" in page.inner_text("#yMajorStepHelp") + # 数値の列に戻すとスケールの欄が戻る + page.select_option("#series-s1-x", "__idx__0") + page.select_option("#series-s1-y", "__idx__1") + wait_settled(page) + assert not is_hidden_by_id(page, "xScaleGroup") and not is_hidden_by_id(page, "yScaleGroup") + + +def test_edit_mode_does_not_redraw_on_new_type_change(page, app_url, fixtures_dir, console_log): + start(page, app_url, fixtures_dir, plot_type="step", y=B) + wait_code_generated(page) + enter_edit_mode(page) + before = (image_generation(page), code_text(page)) + for plot_type in ("box", "violin", "heatmap"): + page.select_option("#plotType", plot_type) + page.wait_for_timeout(1000) + assert (image_generation(page), code_text(page)) == before diff --git a/tests/e2e/test_codegen_consistency.py b/tests/e2e/test_codegen_consistency.py index a9cb394..e19adb4 100644 --- a/tests/e2e/test_codegen_consistency.py +++ b/tests/e2e/test_codegen_consistency.py @@ -262,6 +262,12 @@ def _configure_fit_poly_text(page): add_fit(page, model="linear", show="text") +def _configure_fit_custom(page): + _band_base(page) + page.fill("#series-s1-legend-name", "温度") + add_fit(page, model="custom", expr="a*x^2 + b*x + c") + + def _configure_fit_y2(page): _band_base(page) page.click("#addSeriesBtn") @@ -319,6 +325,31 @@ def _configure_scatter_color(page): page.fill("#colorbarLabel", "電流 (A)") +def _configure_box(page): + page.select_option("#plotType", "box") + page.select_option("#series-s1-y", "__idx__1") + page.click("#addSeriesBtn") + page.select_option("#series-s2-y", "__idx__5") # 数値にできない値と空欄を含む + page.check("#boxMeans") + + +def _configure_violin(page): + page.select_option("#plotType", "violin") + page.select_option("#series-s1-y", "__idx__1") + page.click("#addSeriesBtn") + page.select_option("#series-s2-y", "__idx__2") + page.check("#violinMeans") + + +def _configure_heatmap(page): + page.select_option("#plotType", "heatmap") + page.select_option("#series-s1-x", "__idx__0") + page.select_option("#series-s1-y", "__idx__1") + page.select_option("#series-s1-color-column", "__idx__2") + page.select_option("#colorMap", "coolwarm") + page.fill("#colorbarLabel", "値") + + # --- 計算した列(Phase 5c, G6) --- def _configure_computed_one_file(page): page.fill("#skipRows", "2") # 計算は、除外した行を除いて行う(max もその行だけ) @@ -377,12 +408,16 @@ def _paste_fixture(page, fixtures_dir): "annotations_y2": ("band.csv", _configure_annotations_y2), "fit_linear_legend": ("band.csv", _configure_fit_linear_legend), "fit_poly_text": ("band.csv", _configure_fit_poly_text), + "fit_custom": ("band.csv", _configure_fit_custom), "fit_y2": ("band.csv", _configure_fit_y2), "type_step": ("chart_types.csv", _configure_step), "type_barh_err": ("chart_types.csv", _configure_barh_err), "type_bar_stacked": ("chart_types.csv", _configure_bar_stacked), "type_hist": ("chart_types.csv", _configure_hist), "type_scatter_color": ("chart_types.csv", _configure_scatter_color), + "type_box": ("chart_types.csv", _configure_box), + "type_violin": ("chart_types.csv", _configure_violin), + "type_heatmap": ("grid.csv", _configure_heatmap), "computed_one_file": ("chart_types.csv", _configure_computed_one_file), "computed_two_files": (("chart_types.csv", "band.csv"), _configure_computed_two_files), "scatter_paper1": ("utf8.csv", _configure_scatter_paper1), @@ -412,6 +447,7 @@ def l_ax_summary(summary, key): "title", "xlabel", "ylabel", "xscale", "yscale", "lines", "collections", "patches", "legend", "bands", "markers", "alphas", "annotations", "fitlines", "fittexts", # Phase 5b "drawstyles", "bars", "colorbar", # Phase 5c + "boxes", "violins", "meshes", # Phase 5d ) @@ -536,6 +572,9 @@ def test_downloaded_script_matches_browser_figure(case, page, app_url, fixtures_ assert "poly_text(" in script.read_text(encoding="utf-8") if case == "fit_poly_text": assert browser[0]["fitlines"] == 2 and browser[0]["fittexts"] == 2 + if case == "fit_custom": + assert browser[0]["fitlines"] == 1 and any("a = " in t for t in browser[0]["legend"]) + assert "from scipy.optimize import curve_fit" in script.read_text(encoding="utf-8") if case == "fit_y2": assert browser[1]["fitlines"] == 1 and browser[0]["fitlines"] == 1 if case == "line": diff --git a/tests/e2e/test_custom_fit.py b/tests/e2e/test_custom_fit.py new file mode 100644 index 0000000..9a8e3dd --- /dev/null +++ b/tests/e2e/test_custom_fit.py @@ -0,0 +1,144 @@ +"""任意の式の近似曲線(Phase 5d, G10): カードの出し分け、scipy の遅延読み込み、エラーと復帰、編集モード。""" +import pytest + +from helpers import ( + add_fit, + code_is_stale, + code_value, + enter_edit_mode, + image_summary, + is_hidden_by_id, + load_fixture, + run_edited_code, + scipy_state, + state_list, + status_text, + wait_app_ready, + wait_error_status, + wait_scipy_state, + wait_settled, +) + +pytestmark = pytest.mark.e2e + +LONG = 300_000 +X, MEAN = "__idx__0", "__idx__1" + +EDIT_CODE = """import numpy as np +import matplotlib.pyplot as plt +from scipy.optimize import curve_fit + +x = np.linspace(0, 5, 20) +y = 2 * x + 1 +p, _ = curve_fit(lambda x, a, b: a * x + b, x, y) +fig, ax = plt.subplots() +ax.plot(x, y) +plt.show() +""" + + +def start(page, app_url, fixtures_dir): + page.goto(app_url) + wait_app_ready(page) + load_fixture(page, fixtures_dir / "band.csv") + wait_settled(page) + page.select_option("#series-s1-x", X) + page.select_option("#series-s1-y", MEAN) + page.fill("#series-s1-legend-name", "温度") + wait_settled(page) + + +def test_card_fields_follow_the_model_and_expression(page, app_url, fixtures_dir, console_log): + start(page, app_url, fixtures_dir) + f = add_fit(page) + wait_settled(page) + custom_ids = [f"fit-{f}-expr", f"fit-{f}-expr-help"] + [f"fit-{f}-initial-{p}" for p in "abcde"] + assert all(is_hidden_by_id(page, i) for i in custom_ids) + # poly: 次数だけ。linear は何も増えない + page.select_option(f"#fit-{f}-model", "poly") + assert not is_hidden_by_id(page, f"fit-{f}-degree") and all(is_hidden_by_id(page, i) for i in custom_ids) + wait_settled(page) + # custom: 式と補足が出て次数は隠れる。初期値は式に出てくるパラメータだけ + page.select_option(f"#fit-{f}-model", "custom") + assert is_hidden_by_id(page, f"fit-{f}-degree") + assert not is_hidden_by_id(page, f"fit-{f}-expr") and not is_hidden_by_id(page, f"fit-{f}-expr-help") + assert page.get_attribute(f"#fit-{f}-expr", "placeholder") == "例: a*exp(-b*x) + c" + help_text = page.inner_text(f"#fit-{f}-expr-help") + assert "a〜e" in help_text and "^" in help_text and "exp" in help_text + assert all(is_hidden_by_id(page, f"fit-{f}-initial-{p}") for p in "abcde") + page.click(f"#fit-{f}-expr") + page.keyboard.type("a*exp(-b*x) + c") + shown = {p: not is_hidden_by_id(page, f"fit-{f}-initial-{p}") for p in "abcde"} + assert shown == {"a": True, "b": True, "c": True, "d": False, "e": False} + # 入力中に欄が作り直されない(フォーカスが残る)。1e3・関数名の中の文字は数えない + assert page.evaluate("document.activeElement.id") == f"fit-{f}-expr" + page.fill(f"#fit-{f}-expr", "1e3*abs(x) + d") + shown = {p: not is_hidden_by_id(page, f"fit-{f}-initial-{p}") for p in "abcde"} + assert shown == {"a": False, "b": False, "c": False, "d": True, "e": False} + page.fill(f"#fit-{f}-initial-d", "2.5") + fit = state_list(page, "fits")[0] + assert fit["model"] == "custom" and fit["expr"] == "1e3*abs(x) + d" and fit["initial"]["d"] == 2.5 + # linear に戻すとカードは元どおり + page.select_option(f"#fit-{f}-model", "linear") + assert all(is_hidden_by_id(page, i) for i in custom_ids) and is_hidden_by_id(page, f"fit-{f}-degree") + + +def test_no_scipy_request_without_custom_fit(page, app_url, fixtures_dir, console_log): + reqs = [] + page.on("request", lambda r: reqs.append(r.url)) + start(page, app_url, fixtures_dir) + add_fit(page, model="poly", degree="3") + wait_settled(page) + assert image_summary(page)[0]["fitlines"] == 1 + assert scipy_state(page) == "idle" + assert not [u for u in reqs if "scipy-" in u] + + +def test_custom_fit_with_real_scipy_error_and_recovery(page, app_url, fixtures_dir, console_log): + start(page, app_url, fixtures_dir) + reqs = [] + page.on("request", lambda r: reqs.append(r.url)) + f = add_fit(page, model="custom", expr="a*y") # y は使えない + wait_scipy_state(page, "ready", LONG) + wait_settled(page, LONG) + wait_error_status(page) + assert "近似曲線1の式" in status_text(page) + assert code_is_stale(page) + page.fill(f"#fit-{f}-expr", "a*x^2 + b*x + c") + wait_settled(page, LONG) + assert scipy_state(page) == "ready" + s = image_summary(page)[0] + assert s["fitlines"] == 1 + label = [t for t in s["legend"] if t.startswith("温度の近似")] + assert label and "a = " in label[0] and "$R^2$ = " in label[0] + code = code_value(page) + assert "from scipy.optimize import curve_fit" in code and "def fit_model_1(" in code + assert not code_is_stale(page) + assert [u for u in reqs if "scipy-" in u] + # 1次式に戻すと import は消える + page.select_option(f"#fit-{f}-model", "linear") + wait_settled(page) + assert "scipy" not in code_value(page) + assert image_summary(page)[0]["fitlines"] == 1 + + +def test_scipy_load_failure(page, app_url, fixtures_dir, console_log): + start(page, app_url, fixtures_dir) + page.route("**/scipy-*.whl", lambda r: r.abort()) + add_fit(page, model="custom", expr="a*x + b") + wait_scipy_state(page, "failed", LONG) + wait_settled(page, LONG) + wait_error_status(page) + assert "scipy を読み込めませんでした" in status_text(page) + assert code_is_stale(page) + + +def test_edit_mode_loads_scipy_on_demand(page, app_url, fixtures_dir, console_log): + start(page, app_url, fixtures_dir) + enter_edit_mode(page) + assert scipy_state(page) == "idle" + page.fill("#customPyCode", EDIT_CODE) + run_edited_code(page) + assert scipy_state(page) == "ready" + assert page.get_attribute("#codeOutput", "data-kind") == "ok" + assert image_summary(page)[0]["lines"] == 1 diff --git a/tests/e2e/test_fits.py b/tests/e2e/test_fits.py index a8d047b..5f01f7f 100644 --- a/tests/e2e/test_fits.py +++ b/tests/e2e/test_fits.py @@ -72,7 +72,7 @@ def test_linear_legend_poly_text_and_series_select(page, app_url, fixtures_dir, page.select_option("#xColumn", X) wait_settled(page) assert is_hidden_by_id(page, "fitList") and is_hidden_by_id(page, "addFitBtn") - assert page.inner_text("#fitBarNote") == "棒グラフ・ヒストグラムでは近似曲線を使えません。" + assert page.inner_text("#fitBarNote") == "棒グラフ・ヒストグラム・箱ひげ図・バイオリン図・ヒートマップでは近似曲線を使えません。" assert image_summary(page)[0]["fitlines"] == 0 page.select_option("#plotType", "line") wait_settled(page) diff --git a/tests/fixtures/README.md b/tests/fixtures/README.md index 8830b0d..035b8ac 100644 --- a/tests/fixtures/README.md +++ b/tests/fixtures/README.md @@ -25,4 +25,5 @@ | `datetime.xlsx` | Excel の日時セル(datetime 型、6時間刻みで24行)/ 値 / 温度 | | `errorbars.csv` | エラーバー用。x(0〜11)/ y / y2 / sd(4行目は空欄、7行目は `bad`、10行目は負の値 `-0.2`)/ sd_low / sd_high(上下で別の誤差)/ xsd(X 方向の誤差) | | `chart_types.csv` | グラフの種類(5c, G7)用。category(`項目1`〜`項目12`)/ a(正の値)/ b(正負が混ざる)/ c(色分け用の数値)/ err(誤差、0 以上)/ m(4行目が `n/a`、8行目が空欄) | +| `grid.csv` | ヒートマップ(5d, G8)用。縦長の格子の表。x(0〜3)/ y(0〜2)/ z(値)/ xname(文字列 A〜D)/ yname(文字列 P〜R)の 12 行 | | `band.csv` | 塗りつぶし帯・近似曲線・注釈用(5b)。x(0〜11)/ mean(ほぼ直線)/ lo・hi(帯の下端・上端。lo の7行目は `bad`)/ day(`2026-01-01` からの日付)/ other(別の系列用。右下がり) | diff --git a/tests/fixtures/grid.csv b/tests/fixtures/grid.csv new file mode 100644 index 0000000..07be191 --- /dev/null +++ b/tests/fixtures/grid.csv @@ -0,0 +1,13 @@ +x,y,z,xname,yname +0,0,0.5,A,P +1,0,2.0,B,P +2,0,3.5,C,P +3,0,5.0,D,P +0,1,2.5,A,Q +1,1,4.0,B,Q +2,1,5.5,C,Q +3,1,7.0,D,Q +0,2,4.5,A,R +1,2,6.0,B,R +2,2,7.5,C,R +3,2,9.0,D,R diff --git a/tests/fixtures/make_fixtures.py b/tests/fixtures/make_fixtures.py index 200e64c..89790dc 100644 --- a/tests/fixtures/make_fixtures.py +++ b/tests/fixtures/make_fixtures.py @@ -149,6 +149,7 @@ def main(): make_errorbar_fixture() make_band_fixture() make_chart_types_fixture() + make_grid_fixture() def make_errorbar_fixture(): @@ -193,6 +194,15 @@ def make_chart_types_fixture(): (OUT / "chart_types.csv").write_bytes(("\n".join(lines) + "\n").encode("utf-8")) +def make_grid_fixture(): + """ヒートマップ(5d, G8)。縦長の格子の表: x(0〜3)/ y(0〜2)/ z(値)/ xname(文字列 A〜D)/ yname(文字列 P〜R)。12行。""" + lines = ["x,y,z,xname,yname"] + for j in range(3): + for i in range(4): + lines.append(f"{i},{j},{round(i * 1.5 + j * 2.0 + 0.5, 2)},{'ABCD'[i]},{'PQR'[j]}") + (OUT / "grid.csv").write_bytes(("\n".join(lines) + "\n").encode("utf-8")) + + def make_datetime_fixtures(fixed): """日時の列(D5)。年をまたぐ時間刻み、ISO 8601(タイムゾーン付き)、日本語の日付、Excel の日時セル。""" # 時間刻み。値は 150 行(先頭 100 行は正しい日時。120 行目は読めない値、130 行目は空欄) diff --git a/tests/perf/bench.py b/tests/perf/bench.py index 4f5b9dd..6920ec7 100644 --- a/tests/perf/bench.py +++ b/tests/perf/bench.py @@ -616,6 +616,131 @@ def bench_computed_change(browser, url, reps, csv_path): return out +# --- Phase 5d: 箱ひげ図・バイオリン図・ヒートマップ・任意の式の近似曲線 --- +def make_heatmap_csv(path, side=100): + """縦持ちの格子 side × side 行(x, y, z の3列。z はなめらかな関数。実行時に作る合成データ)。""" + import math + with open(path, "w", newline="", encoding="utf-8") as f: + w = csv.writer(f) + w.writerow(["x", "y", "z"]) + for i in range(side): + for j in range(side): + w.writerow([i, j, round(math.sin(i / 10) * math.cos(j / 15) + 0.01 * i, 5)]) + + +def _bench_type_change(browser, url, reps, csv_path, plot_type, cond, setup=None): + """種類を plot_type にし(setup があれば続けて設定)、data-summary が cond を満たす図が出るまで待ってから、「設定変更」(タイトル入力 → 新しい画像)を測る。""" + out = [] + ctx = _warm_context(browser, url, csv_path) + for i in range(reps): + page = _prepared_page(ctx, url, csv_path) + page.select_option("#plotType", plot_type) + if setup: + setup(page) + _wait_summary(page, cond) + page.wait_for_timeout(3000) + out.append(page.evaluate(CHANGE_JS, ["#title", f"bench title {i}"])) + page.close() + ctx.close() + return out + + +def bench_box_change(browser, url, reps, csv_path): + """箱ひげ図: 5 系列(Y 列1-5)で boxes == 5 の図が出るまで待ってから、「設定変更」を測る。""" + return _bench_type_change(browser, url, reps, csv_path, "box", "s.boxes === 5") + + +def bench_violin_change(browser, url, reps, csv_path): + """バイオリン図: 5 系列(Y 列1-5)で violins == 5 の図が出るまで待ってから、「設定変更」を測る。""" + return _bench_type_change(browser, url, reps, csv_path, "violin", "s.violins === 5") + + +def bench_heatmap_change(browser, url, reps, heat_path): + """ヒートマップ: 100×100 の縦持ちデータ(10,000 行)、1 系列(X = 列0、Y = 列1、値の列 = 列2)で meshes == 1 とカラーバーが出るまで待ってから、「設定変更」を測る。 + 系列は1本だけ(_prepared_page は5系列にするので使わず、ここで読み込む)。""" + out = [] + ctx = browser.new_context() + # 温め(HTTP キャッシュ・Cache Storage の日本語フォント) + w = ctx.new_page() + w.set_default_timeout(TIMEOUT) + w.goto(url) + wait_app_ready(w, TIMEOUT) + w.close() + for i in range(reps): + page = ctx.new_page() + page.set_default_timeout(TIMEOUT) + page.goto(url) + wait_app_ready(page, TIMEOUT) + page.set_input_files("#fileInput", str(heat_path)) + wait_data_ready(page, TIMEOUT) + wait_plot_changed(page, "", TIMEOUT) + page.select_option("#plotType", "heatmap") + sid = series_ids(page)[0] + page.select_option(f"#series-{sid}-x", "__idx__0") + page.select_option(f"#series-{sid}-y", "__idx__1") + page.select_option(f"#series-{sid}-color-column", "__idx__2") + _wait_summary(page, "s.meshes === 1 && !!s.colorbar") + page.wait_for_timeout(3000) + out.append(page.evaluate(CHANGE_JS, ["#title", f"bench title {i}"])) + page.close() + ctx.close() + return out + + +def bench_custom_fit_change(browser, url, reps, csv_path): + """任意の式の近似曲線: line 5 系列に、系列ごとの近似曲線(model = custom、式 a*x + b、凡例)を 5 本付け、 + data-scipy-state が ready で fitlines == 5 の図が出るまで待ってから、「設定変更」を測る(scipy は読み込み済みの状態)。""" + out = [] + ctx = _warm_context(browser, url, csv_path) + for i in range(reps): + page = _prepared_page(ctx, url, csv_path) + for sid in series_ids(page): + add_fit(page, series=sid, model="custom", expr="a*x + b", show="legend") + page.wait_for_function("() => document.documentElement.dataset.scipyState === 'ready'", timeout=TIMEOUT) + _wait_summary(page, "s.fitlines === 5") + page.wait_for_timeout(3000) + out.append(page.evaluate(CHANGE_JS, ["#title", f"bench title {i}"])) + page.close() + ctx.close() + return out + + +def bench_scipy_first_load(browser, url, reps, csv_path): + """参考値: scipy の初回読み込み。新しいページごとに1回だけ測る(reps 個の新しいページ)。 + データ読込・1系列の描画が済んだあと、近似曲線1本を custom(a*x + b)にした時点から、fitlines == 1 の図が出るまで。 + 約 14 MB の scipy の取得と import を含むので、ネットワークに依存する。 + コンテキストは bench_custom_fit_change などと同じく温め済み(_warm_context: HTTP キャッシュ・日本語フォントの Cache Storage は温かい)。 + scipy の wheel も温め中は取得されないが、ブラウザの HTTP キャッシュが効けばネットワークは速くなる点に注意(コンテキスト内の2回目以降)。""" + out = [] + ctx = _warm_context(browser, url, csv_path) + for i in range(reps): + page = ctx.new_page() + page.set_default_timeout(TIMEOUT) + page.goto(url) + wait_app_ready(page, TIMEOUT) + page.set_input_files("#fileInput", str(csv_path)) + wait_data_ready(page, TIMEOUT) + wait_plot_changed(page, "", TIMEOUT) + page.wait_for_timeout(3000) + fit_id = add_fit(page) # 追加だけでは(1次式)scipy は不要 + page.wait_for_timeout(3000) + out.append(page.evaluate( + """([fid]) => new Promise((resolve) => { + const t0 = performance.now(); + const ok = () => { const d = document.querySelector('#plotArea img'); if (!d || !d.dataset.summary) return false; + try { return JSON.parse(d.dataset.summary)[0].fitlines === 1; } catch (e) { return false; } }; + const obs = new MutationObserver(() => { if (document.documentElement.dataset.scipyState === 'ready' && ok()) { obs.disconnect(); resolve(performance.now() - t0); } }); + obs.observe(document.getElementById('plotArea'), {childList: true, subtree: true, attributes: true}); + const m = document.getElementById(`fit-${fid}-model`); + m.value = 'custom'; m.dispatchEvent(new Event('change', {bubbles: true})); + const e = document.getElementById(`fit-${fid}-expr`); + e.value = 'a*x + b'; e.dispatchEvent(new Event('input', {bubbles: true})); + })""", [fit_id])) + page.close() + ctx.close() + return out + + def fmt(name, xs): s = stats(xs) return f"{name:<44} median {s['median']:9.0f} min {s['min']:9.0f} max {s['max']:9.0f} (ms, n={s['n']})" @@ -626,7 +751,7 @@ def main(): ap.add_argument("--reps", type=int, default=5) ap.add_argument("--headed", action="store_true") ap.add_argument("--json") - ap.add_argument("--only", choices=["old", "new", "p5a", "p5b", "p5c"], help="old: Phase 3 までの項目だけ / new: Phase 4 の項目だけ / p5a: Phase 5a の項目だけ / p5b: Phase 5b の項目だけ / p5c: Phase 5c の項目だけ(省略時は全部)") + ap.add_argument("--only", choices=["old", "new", "p5a", "p5b", "p5c", "p5d"], help="old: Phase 3 までの項目だけ / new: Phase 4 の項目だけ / p5a: Phase 5a の項目だけ / p5b: Phase 5b の項目だけ / p5c: Phase 5c の項目だけ / p5d: Phase 5d の項目だけ(省略時は全部)") a = ap.parse_args() serve = Path(os.environ.get("E2E_SERVE_DIR") or REPO) srv, url = start_server(serve) @@ -645,6 +770,8 @@ def main(): make_band_csv(band_path) color_path = tmp / "bench_color_10000x11.csv" make_color_csv(color_path) + heat_path = tmp / "bench_heatmap_10000x3.csv" + make_heatmap_csv(heat_path) big_tsv = make_tsv() small_tsv = make_tsv(rows=30, ys=2) with sync_playwright() as p: @@ -723,6 +850,25 @@ def main(): "computed_change_to_plot_ms": comp_change, "computed_change_to_plot_minus_debounce_ms": [c - DEBOUNCE_MS for c in comp_change], }) + if a.only in (None, "p5d"): + box_change = bench_box_change(browser, url, a.reps, csv_path) + violin_change = bench_violin_change(browser, url, a.reps, csv_path) + heat_change = bench_heatmap_change(browser, url, a.reps, heat_path) + cfit_change = bench_custom_fit_change(browser, url, a.reps, csv_path) + scipy_first = bench_scipy_first_load(browser, url, a.reps, csv_path) + res.update({ + # Phase 5d で追加(箱ひげ図・バイオリン図・ヒートマップ・任意の式の近似曲線。デバウンス込みと、250 ms を除いた値) + "box_change_to_plot_ms": box_change, + "box_change_to_plot_minus_debounce_ms": [c - DEBOUNCE_MS for c in box_change], + "violin_change_to_plot_ms": violin_change, + "violin_change_to_plot_minus_debounce_ms": [c - DEBOUNCE_MS for c in violin_change], + "heatmap_change_to_plot_ms": heat_change, + "heatmap_change_to_plot_minus_debounce_ms": [c - DEBOUNCE_MS for c in heat_change], + "custom_fit_change_to_plot_ms": cfit_change, + "custom_fit_change_to_plot_minus_debounce_ms": [c - DEBOUNCE_MS for c in cfit_change], + # 参考値: scipy の初回読み込み(約 14 MB の取得と import を含む。ネットワークに依存) + "scipy_first_load_to_plot_ms": scipy_first, + }) browser.close() for k, v in res.items(): print(fmt(k, v)) diff --git a/tests/unit/test_chart_types.py b/tests/unit/test_chart_types.py index f46be5b..5d62e6b 100644 --- a/tests/unit/test_chart_types.py +++ b/tests/unit/test_chart_types.py @@ -750,3 +750,589 @@ def fn(fig): assert proxies[0].get_sizes()[0] == pytest.approx((24 ** 0.5 + 1.5) ** 2) and list(proxies[0].get_linewidths()) == [0.0] bt.check(fn) + + +# ================================================================ Phase 5d: 箱ひげ図・バイオリン図・ヒートマップ(G8) + +import json # noqa: E402 +import shutil # noqa: E402 +import subprocess # noqa: E402 +from pathlib import Path # noqa: E402 + +from mplgui import settings as settings_module # noqa: E402 +from mplgui.settings import MAX_HEATMAP_SIZE # noqa: E402 + +REPO = Path(__file__).resolve().parents[2] +NEW_TYPES = ("box", "violin", "heatmap") + + +def dist_frame(n=40, seed=1): + """値の列 3 つ(a: 外れ値あり、b: 文字列を含む、c: 欠けた値だけ)と 1 行だけの列。""" + rng = np.random.default_rng(seed) + a = list(rng.normal(0, 1, n)) + a[0] = 15.0 # 外れ値 + b = [str(v) for v in rng.normal(3, 1, n)] + b[1] = "bad" + return pd.DataFrame({"a": a, "b": b, "c": [np.nan] * n, "one": [2.0] + [np.nan] * (n - 1)}) + + +def grid_frame(): + """縦長の表: x(数値)・y(数値)・z(値)・tx(文字列)・ty(文字列)。3×2 の格子で (1, 0) の組が 1 つ欠け、(0, 0) は 2 回現れる。""" + rows = [(0, 0, 1.0), (0, 0, 3.0), (0, 1, 4.0), (1, 1, 5.0), (2, 0, 6.0), (2, 1, 7.0)] + df = pd.DataFrame(rows, columns=["x", "y", "z"]) + df["tx"] = df["x"].map({0: "low", 1: "mid", 2: "high"}) + df["ty"] = df["y"].map({0: "off", 1: "on"}) + return df + + +def hm(x=0, y=1, z=2, **kw): + return series(y=y, x=x, colorColumn=f"__idx__{z}", **kw) + + +def build_new(tmp_path, plot_type, series_list, df, **plot): + return Built(tmp_path, df=df, series_list=series_list, plot_type=plot_type, mutate=mutate_plot(**plot)) + + +# ---------------------------------------------------------------- 設定(settings) + + +def test_new_types_accepted_and_plot_defaults(): + for t in NEW_TYPES: + sl = [hm()] if t == "heatmap" else [series()] + assert parse_settings(raw_settings(sl, plot_type=t)).plot.type == t + d = parse_settings(raw_settings(plot_type="line")).plot + assert (d.box_fliers, d.box_means, d.violin_medians, d.violin_means) == (True, False, True, False) + raw = settings_module.default_settings() + assert raw["plot"]["box"] == {"fliers": True, "means": False} and raw["plot"]["violin"] == {"medians": True, "means": False} + assert settings_module.SCHEMA_VERSION == 4 + + +def test_box_violin_options_validated_only_for_own_type(): + bad = {"box": {"fliers": "x", "means": 3}, "violin": {"medians": "x", "means": 3}} + for t in ("line", "bar", "hist", "heatmap", "box", "violin"): + sl = [hm()] if t == "heatmap" else [series()] + if t == "box": + bad2 = {"violin": bad["violin"]} + elif t == "violin": + bad2 = {"box": bad["box"]} + else: + bad2 = bad + parse_settings(raw_settings(sl, plot_type=t, mutate=mutate_plot(**bad2))) # 隠れているので、エラーにならない + with pytest.raises(UserError) as e: + parse_settings(raw_settings(plot_type="box", mutate=mutate_plot(box={"fliers": "x"}))) + assert e.value.field == "外れ値の点" + with pytest.raises(UserError) as e: + parse_settings(raw_settings(plot_type="violin", mutate=mutate_plot(violin={"medians": 3}))) + assert e.value.field == "中央値の線" + s = parse_settings(raw_settings(plot_type="box", mutate=mutate_plot(box={"fliers": False, "means": True}))).plot + assert (s.box_fliers, s.box_means) == (False, True) + s = parse_settings(raw_settings(plot_type="violin", mutate=mutate_plot(violin={"medians": False, "means": True}))).plot + assert (s.violin_medians, s.violin_means) == (False, True) + + +def test_heatmap_value_column_required_with_value_wording(): + with pytest.raises(UserError) as e: + parse_settings(raw_settings([series()], plot_type="heatmap")) + assert str(e.value) == "系列1の値の列を選んでください。" and e.value.field == "系列1の値の列" + with pytest.raises(UserError) as e: + parse_settings(raw_settings([series(colorColumn="abc")], plot_type="heatmap")) + assert e.value.field == "系列1の値の列" and "値の列" in str(e.value) + # 系列が2つ以上なら、系列ごとの値の列の検証より先に、系列の数のエラーを出す + with pytest.raises(UserError) as e: + parse_settings(raw_settings([hm(), series(colorColumn="abc")], plot_type="heatmap")) + assert str(e.value).startswith("ヒートマップは系列1つで描きます。") and e.value.field == "系列" + # scatterColor の文言は変えない + with pytest.raises(UserError) as e: + parse_settings(raw_settings([series()], plot_type="scatterColor")) + assert e.value.field == "系列1の色分けの列" + for t in ("box", "violin"): # 使わない種類では要らない・検証しない + assert parse_settings(raw_settings([series(colorColumn=5)], plot_type=t)).series[0].color_column == "" + + +def test_heatmap_colormap_used_and_validated_for_heatmap_only(): + with pytest.raises(UserError) as e: + parse_settings(raw_settings([hm()], plot_type="heatmap", mutate=mutate_plot(colormap="nope"))) + assert e.value.field == "カラーマップ" + s = parse_settings(raw_settings([hm()], plot_type="heatmap", mutate=mutate_plot(colormap="plasma", colorbarLabel=" 値 "))) + assert (s.plot.colormap, s.plot.colorbar_label) == ("plasma", "値") + for t in ("box", "violin"): + parse_settings(raw_settings(plot_type=t, mutate=mutate_plot(colormap="nope"))) + + +def test_new_types_hide_settings_and_keep_existing_rules(): + bad = {"marker": "zzz", "fill": {"lower": "x", "upper": ""}, "secondaryAxis": "yes", "errorBars": {"x": {"mode": "zzz"}, "y": {"mode": "zzz"}}} + fit = [{"series": "s1", "model": "zzz"}] + for t in NEW_TYPES: + extra = {"colorColumn": "__idx__2"} if t == "heatmap" else {} + s = parse_settings(raw_settings([series(**bad, **extra)], plot_type=t, fits=fit)) + sr = s.series[0] + assert s.fits == () and sr.marker == "auto" and not sr.fill.enabled and sr.secondary_axis is False + assert not sr.error_bars.y.enabled if hasattr(sr.error_bars.y, "enabled") else sr.error_bars.y.mode == "none" + assert sr.error_bars.x.mode == "none" + # 使う設定は従来どおり検証する(不透明度は3種類とも使う) + for t in NEW_TYPES: + extra = {"colorColumn": "__idx__2"} if t == "heatmap" else {} + with pytest.raises(UserError): + parse_settings(raw_settings([series(alpha=5, **extra)], plot_type=t)) + # box / violin は色・線幅を使う。線種・点サイズは使わない + with pytest.raises(UserError): + parse_settings(raw_settings([series(color="zzz")], plot_type="box")) + with pytest.raises(UserError): + parse_settings(raw_settings([series(lineWidth=0)], plot_type="violin")) + parse_settings(raw_settings([series(lineStyle="zzz", markerSize="x")], plot_type="box")) + parse_settings(raw_settings([series(lineStyle="zzz", markerSize="x")], plot_type="violin")) + # heatmap は色・線幅・線種・点サイズを使わない(検証せず、既定の値) + s = parse_settings(raw_settings([hm(color="zzz", lineWidth=-1, lineStyle="zzz", markerSize="x")], plot_type="heatmap")).series[0] + assert (s.line_width, s.line_style, s.marker_size) == (2.0, "solid", None) + # 既存の種類は従来どおり(色・線種は検証する) + for t in ("line", "bar", "hist"): + with pytest.raises(UserError): + parse_settings(raw_settings([series(color="zzz")], plot_type=t)) + with pytest.raises(UserError): + parse_settings(raw_settings([series(lineStyle="zzz")], plot_type=t)) + # X列(plot.xColumn)は新しい種類で使わない + for t in NEW_TYPES: + sl = [hm()] if t == "heatmap" else [series()] + assert parse_settings(raw_settings(sl, plot_type=t, mutate=mutate_plot(xColumn="__idx__3"))).plot.x_column == "" + assert parse_settings(raw_settings(plot_type="bar", mutate=mutate_plot(xColumn="__idx__3"))).plot.x_column == "__idx__3" + + +def test_python_rule_constants_are_consistent(): + S = settings_module + assert set(S.XY_TYPES) == {"line", "step", "scatter", "scatterColor"} + assert set(S.BOX_TYPES) == {"box", "violin"} + assert set(S.NO_Y2_TYPES) == {"barh", "barStacked", "hist", "scatterColor", "box", "violin", "heatmap"} + assert set(S.NO_Y_ERROR_TYPES) == {"barStacked", "hist", "box", "violin", "heatmap"} + assert set(S.SERIES_X_TYPES) == set(S.XY_TYPES) | {"heatmap"} + assert set(S.COLOR_COLUMN_TYPES) == {"scatterColor", "heatmap"} + assert set(S.CATEGORY_BAR_TYPES) == {"bar", "barStacked", "barh"} + + +@pytest.mark.skipif(shutil.which("node") is None, reason="node が無い") +def test_js_chart_types_match_python_rules(tmp_path): + """js/chart-types.js の述語が、settings.py の規則の定数と、全種類で一致する。""" + (tmp_path / "package.json").write_text('{"type": "module"}', encoding="utf-8") + (tmp_path / "chart-types.js").write_text((REPO / "js/chart-types.js").read_text(encoding="utf-8"), encoding="utf-8") + (tmp_path / "run.mjs").write_text( + """ + import * as m from "./chart-types.js"; + const out = {types: m.PLOT_TYPES}; + for (const t of m.PLOT_TYPES) { + out[t] = { + seriesX: m.usesSeriesX(t), globalX: m.usesGlobalX(t), marker: m.usesMarker(t), fill: m.usesFill(t), fits: m.usesFits(t), + xErr: m.usesXErrors(t), yErr: m.usesYErrors(t), y2: m.usesY2(t), color: m.usesColorColumn(t), colormap: m.usesColormap(t), + box: m.usesBox(t), violin: m.usesViolin(t), boxLike: m.isBoxLike(t), heatmap: m.isHeatmap(t), + }; + } + console.log(JSON.stringify(out)); + """, + encoding="utf-8", + ) + js = json.loads(subprocess.run(["node", "run.mjs"], cwd=tmp_path, capture_output=True, text=True, check=True, timeout=30).stdout) + S = settings_module + assert set(js["types"]) == set(S.PLOT_TYPES) + for t in S.PLOT_TYPES: + r = js[t] + assert r["seriesX"] == (t in S.SERIES_X_TYPES), t + assert r["globalX"] == (t in S.CATEGORY_BAR_TYPES), t + assert r["marker"] == r["fill"] == r["fits"] == r["xErr"] == (t in S.XY_TYPES), t + assert r["yErr"] == (t not in S.NO_Y_ERROR_TYPES), t + assert r["y2"] == (t not in S.NO_Y2_TYPES), t + assert r["color"] == r["colormap"] == (t in S.COLOR_COLUMN_TYPES), t + assert r["boxLike"] == (t in S.BOX_TYPES) and r["box"] == (t == "box") and r["violin"] == (t == "violin"), t + assert r["heatmap"] == (t == "heatmap") + + +# ---------------------------------------------------------------- 箱ひげ図 + + +def test_box_one_box_per_series_with_labels_and_positions(tmp_path): + bt = build_new(tmp_path, "box", [series(y=0), series(y=1, label="B系列"), series(y=3)], dist_frame()) + + def fn(fig): + ax = fig.axes[0] + assert [t.get_text() for t in ax.get_xticklabels()] == ["a [0]", "B系列", "one [3]"] + assert ax.get_legend() is None and ax.get_xlim() == (-0.5, 2.5) + + s = bt.check(fn) + assert s[0]["boxes"] == 3 and s[0]["violins"] == 0 and s[0]["meshes"] == 0 + assert s[0]["xlabel"] == "" and s[0]["ylabel"] == "" # 系列が複数なら縦軸の自動ラベルは空 + assert s[0]["markers"] == [] and s[0]["alphas"] == [] and s[0]["drawstyles"] == [] # 箱ひげの線は系列の線に数えない + assert s[0]["xscale"] == "linear" and s[0]["legend"] == [] + assert "tick_labels" not in bt.script.text and "vert=" not in bt.script.text + + +def test_box_values_style_fliers_means_and_numeric_cleaning(tmp_path): + df = dist_frame() + sl = [series(y=0, color="#00AA00", lineWidth=3.0, alpha=0.5), series(y=1)] + bt = build_new(tmp_path, "box", sl, df) + with bt.full() as run: + ax = run.fig.axes[0] + patches = [p for p in ax.patches if p.get_label() == "_box"] + assert len(patches) == 2 + assert patches[0].get_alpha() == 0.5 and patches[0].get_linewidth() == 3.0 + assert matplotlib_color(patches[0].get_facecolor()[:3]) == "#00aa00" and matplotlib_color(patches[0].get_edgecolor()[:3]) == "#000000" + meds = [ln for ln in ax.lines if ln.get_label() == "_box" and len(ln.get_xdata()) == 2 and ln.get_ydata()[0] == ln.get_ydata()[1] and abs(ln.get_xdata()[1] - ln.get_xdata()[0]) < 0.6 and ln.get_linewidth() == 3.0] + assert meds and all(ln.get_color() == "black" for ln in meds) + # 外れ値(15.0)が点として描かれる。NaN が混ざっても中央値は NaN にならない + fliers = [ln for ln in ax.lines if ln.get_marker() == "o" and ln.get_label() == "_box"] + assert any(15.0 in list(ln.get_ydata()) for ln in fliers) + assert not any(np.isnan(np.asarray(ln.get_ydata(), dtype=float)).any() for ln in ax.lines) + # 数値にできない値は警告(既存の形式) + assert any(w["series"] == 2 and "数値に変換できない値が1件" in w["message"] and '"bad"' in w["message"] for w in bt.plan.warnings) + assert bt.plan.warnings[0]["message"].startswith("系列2(b):") + # alpha 1 はコードに書かない + assert '"alpha"' in bt.script.text and bt.script.text.count('"alpha"') == 1 + + +def matplotlib_color(rgb): + from matplotlib.colors import to_hex + + return to_hex(rgb) + + +def test_box_fliers_and_means_toggle(tmp_path): + on = build_new(tmp_path, "box", [series(y=0)], dist_frame(), box={"fliers": True, "means": False}) + off = build_new(tmp_path, "box", [series(y=0)], dist_frame(), box={"fliers": False, "means": True}) + + def counts(bt): + with bt.full() as run: + ax = run.fig.axes[0] + fl = [ln for ln in ax.lines if ln.get_marker() == "o"] + means = [ln for ln in ax.lines if ln.get_marker() == "D"] + return sum(len(ln.get_xdata()) for ln in fl), len(means) + + assert counts(on)[0] >= 1 and counts(on)[1] == 0 and counts(off) == (0, 1) + assert "showfliers=True" in on.script.text and "showmeans=True" in off.script.text + on.check(lambda f: None) + off.check(lambda f: None) + + +def test_box_empty_series_keeps_its_position_and_warns(tmp_path): + bt = build_new(tmp_path, "box", [series(y=0), series(y=2), series(y=1)], dist_frame()) + assert any(w["series"] == 2 and "箱は描きません" in w["message"] for w in bt.plan.warnings) + assert [p.has_points for p in bt.plan.series] == [True, False, True] + assert "描ける値が無い" in bt.script.text + + def fn(fig): + ax = fig.axes[0] + assert ax.get_xlim() == (-0.5, 2.5) + assert [t.get_text() for t in ax.get_xticklabels()] == ["a [0]", "c [2]", "b [1]"] + centers = sorted(round(float((p.get_path().vertices[:, 0].min() + p.get_path().vertices[:, 0].max()) / 2), 3) for p in ax.patches if p.get_label() == "_box") + assert centers == [0.0, 2.0] # 2 つ目の位置は空いたまま + + assert bt.check(fn)[0]["boxes"] == 2 + + +def test_box_no_values_at_all_is_error(): + with pytest.raises(UserError) as e: + plan_of(df=dist_frame(), plot_type="box", series_list=[series(y=2)]) + assert "描画可能な数値データがありません" in str(e.value) + + +def test_box_datetime_y_is_error(): + df = pd.DataFrame({"d": pd.to_datetime(["2024-01-01", "2024-01-02"]), "v": [1.0, 2.0]}) + for t in ("box", "violin"): + with pytest.raises(UserError) as e: + plan_of(df=df, plot_type=t, series_list=[series(y=0)]) + assert e.value.field == "系列1のY列" and "日時の列" in str(e.value) + + +def test_box_single_series_label_and_multiple_sources(tmp_path): + bt = build_new(tmp_path, "box", [series(y=0)], dist_frame()) + s = bt.check(lambda f: None) + assert s[0]["ylabel"] == "a [0]" and s[0]["xlabel"] == "" + # データ元が違ってもよい(複数ファイル) + from mplgui.dataprep import plan_plot + + sets = raw_settings([series(y=0), series(y=0, source="d2")], plot_type="box") + sets["load"]["files"] = [{"id": "d1", "name": "a.csv", "sheet": ""}, {"id": "d2", "name": "b.csv", "sheet": ""}] + st = parse_settings(sets) + frames = {"d1": dist_frame(), "d2": dist_frame(seed=5)} + plan = plan_plot(frames, st) + assert [p.data_var for p in plan.series] == ["df1", "df2"] + from mplgui.codegen import generate_script + from mplgui.loader import load_file + from mplgui.runner import figure_summary, run_script + + infos = {} + for i, fid in enumerate(("d1", "d2")): + (tmp_path / f"f{i}.csv").write_text(frames[fid].to_csv(index=False), encoding="utf-8") + infos[fid] = load_file((tmp_path / f"f{i}.csv").read_bytes(), f"f{i}.csv", "", True).source + script = generate_script(st, infos, plan) + with run_script(script.auto_render_text(), injected={"df1": frames["d1"], "df2": frames["d2"]}) as run: + assert figure_summary(run.fig)[0]["boxes"] == 2 + + +def test_box_log_y_and_tick_step_and_annotation_index(tmp_path): + df = pd.DataFrame({f"s{i}": [1.0 + i, 5, 20, 80 + i] for i in range(5)}) + sl = [series(y=i) for i in range(5)] + + def mutate(raw): + raw["axes"]["y"]["scale"] = "log" + raw["axes"]["x"]["majorStep"] = 2 + raw["axes"]["x"]["scale"] = "log" # 横軸はカテゴリなので使わない + raw["annotations"] = [ + {"kind": "vline", "x": "1.5", "label": "境目"}, + {"kind": "text", "text": "メモ", "x": "3", "y": "30"}, + ] + + bt = Built(tmp_path, df=df, series_list=sl, plot_type="box", mutate=mutate) + s = bt.check(lambda f: None) + assert s[0]["yscale"] == "log" and s[0]["xscale"] == "linear" + assert [t for t in s[0]["xticklabels"] if t] == ["s0 [0]", "s2 [2]", "s4 [4]"] # 2 個おき + assert "tick_step = 2" in bt.script.text + assert s[0]["annotations"]["vlines"] == 1 and s[0]["annotations"]["texts"] == 1 + assert s[0]["legend"] == ["境目"] # 注釈の凡例名だけ。箱は凡例に出さない + # 注釈の X は 0 始まりの番号。文字列は解釈できない + with pytest.raises(UserError) as e: + Built(tmp_path, df=df, series_list=sl, plot_type="box", mutate=lambda r: r.update(annotations=[{"kind": "vline", "x": "abc"}])) + assert "注釈1" in str(e.value) + + +def test_box_axis_labels_override_and_title(tmp_path): + def mutate(raw): + raw["axes"]["x"]["label"] = "群" + raw["axes"]["y"]["label"] = "値" + + bt = Built(tmp_path, df=dist_frame(), series_list=[series(y=0), series(y=1)], plot_type="box", mutate=mutate) + s = bt.check(lambda f: None) + assert (s[0]["xlabel"], s[0]["ylabel"]) == ("群", "値") + + +def test_box_tick_step_too_many_is_error(): + df = pd.DataFrame({"a": [1.0, 2, 3]}) + with pytest.raises(UserError): + plan_of(df=df, plot_type="box", series_list=[series(y=0)], mutate=lambda r: r["axes"]["x"].update(majorStep=0.5)) + + +# ---------------------------------------------------------------- バイオリン図 + + +def test_violin_bodies_medians_means_and_colors(tmp_path): + sl = [series(y=0, color="#0000FF", lineWidth=2.5, alpha=0.4), series(y=1)] + bt = build_new(tmp_path, "violin", sl, dist_frame(), violin={"medians": True, "means": True}) + + def fn(fig): + ax = fig.axes[0] + bodies = [c for c in ax.collections if c.get_label() == "_violin"] + assert len(bodies) == 2 + assert bodies[0].get_alpha() == 0.4 and matplotlib_color(bodies[0].get_facecolor()[0][:3]) == "#0000ff" + assert bodies[0].get_linewidth()[0] == 2.5 + assert [t.get_text() for t in ax.get_xticklabels()] == ["a [0]", "b [1]"] + + s = bt.check(fn) + assert s[0]["violins"] == 2 and s[0]["boxes"] == 0 and s[0]["lines"] == 0 and s[0]["legend"] == [] + assert s[0]["collections"] == 2 + 2 * 5 # 胴 2 つ + (端 3 + 中央値 + 平均) × 2 + assert "vert=" not in bt.script.text + + +def test_violin_medians_off_and_means_off(tmp_path): + bt = build_new(tmp_path, "violin", [series(y=0)], dist_frame(), violin={"medians": False, "means": False}) + s = bt.check(lambda f: None) + assert s[0]["collections"] == 1 + 3 # 胴 + 端の線 3 つ + assert "showmedians=False" in bt.script.text + + +def test_violin_needs_two_values(tmp_path): + bt = build_new(tmp_path, "violin", [series(y=0), series(y=3), series(y=2)], dist_frame()) + msgs = [w["message"] for w in bt.plan.warnings] + assert any("系列2" in m and "値が1個だけ" in m for m in msgs) and any("系列3" in m and "描きません" in m for m in msgs) + s = bt.check(lambda f: None) + assert s[0]["violins"] == 1 and s[0]["xlim"] == [-0.5, 2.5] + with pytest.raises(UserError): + plan_of(df=dist_frame(), plot_type="violin", series_list=[series(y=3)]) # 描ける系列が無い + + +# ---------------------------------------------------------------- ヒートマップ + + +def test_heatmap_numeric_grid_missing_cell_duplicates_and_colorbar(tmp_path): + bt = build_new(tmp_path, "heatmap", [hm()], grid_frame(), colormap="plasma", colorbarLabel="温度 (℃)") + assert any("1件重複" in w["message"] and w["series"] == 1 for w in bt.plan.warnings) + + def fn(fig): + ax = fig.axes[0] + mesh = [c for c in ax.collections if type(c).__name__ == "QuadMesh"][0] + z = np.ma.filled(mesh.get_array().astype(float), np.nan).reshape(2, 3) + assert np.allclose(z, [[2.0, np.nan, 6.0], [4.0, 5.0, 7.0]], equal_nan=True) # (0,0) は 1 と 3 の平均。欠けたマスは NaN + assert mesh.get_cmap().name == "plasma" and ax.get_legend() is None + + s = bt.check(fn) + assert s[0]["meshes"] == 1 and s[0]["boxes"] == 0 and s[0]["violins"] == 0 + assert s[0]["colorbar"] == {"label": "温度 (℃)", "cmap": "plasma", "vmin": 2.0, "vmax": 7.0} + assert (s[0]["xlabel"], s[0]["ylabel"]) == ("x", "y [1]") and len(s) == 1 + assert s[0]["xlim"] == [-0.5, 2.5] and s[0]["ylim"] == [-0.5, 1.5] + assert 'shading="nearest"' in bt.script.text and "pivot_table" in bt.script.text and "alpha=" not in bt.script.text + + +def test_heatmap_default_colorbar_label_and_alpha(tmp_path): + bt = build_new(tmp_path, "heatmap", [hm(alpha=0.5)], grid_frame()) + s = bt.check(lambda f: None) + assert s[0]["colorbar"]["label"] == "z [2]" and s[0]["colorbar"]["cmap"] == "viridis" + assert "alpha=0.5" in bt.script.text + with bt.full() as run: + mesh = [c for c in run.fig.axes[0].collections if type(c).__name__ == "QuadMesh"][0] + assert mesh.get_alpha() == 0.5 + + +def test_heatmap_text_axes_in_order_of_appearance_and_tick_step(tmp_path): + df = grid_frame() + bt = build_new(tmp_path, "heatmap", [hm(x=3, y=4)], df) + + def fn(fig): + ax = fig.axes[0] + assert [t.get_text() for t in ax.get_xticklabels()] == ["low", "mid", "high"] # 現れた順(アルファベット順ではない) + assert [t.get_text() for t in ax.get_yticklabels()] == ["off", "on"] + + s = bt.check(fn) + assert s[0]["xlim"] == [-0.5, 2.5] and (s[0]["xlabel"], s[0]["ylabel"]) == ("tx", "ty [4]") + + wide = pd.DataFrame({"x": [f"c{i}" for i in range(10)] * 2, "y": ["r1"] * 10 + ["r2"] * 10, "z": np.arange(20.0)}) + bt = Built(tmp_path, df=wide, series_list=[hm()], plot_type="heatmap", mutate=lambda r: r["axes"]["x"].update(majorStep=3)) + s = bt.check(lambda f: None) + assert [t for t in s[0]["xticklabels"] if t] == ["c0", "c3", "c6", "c9"] and "x_tick_step = 3" in bt.script.text + + +def test_heatmap_numeric_looking_text_axis_is_converted_with_warning(tmp_path): + df = pd.DataFrame({"x": ["1", "2", "bad", "1", "2"], "y": [1.0, 1, 1, 2, 2], "z": [1.0, 2, 3, 4, 5]}) + bt = build_new(tmp_path, "heatmap", [hm()], df) + assert any("X列" in w["message"] and "数値に変換できない値が1件" in w["message"] for w in bt.plan.warnings) + s = bt.check(lambda f: None) + assert s[0]["xlim"] == [0.5, 2.5] # X は数値の軸(bad の行は除外) + + +def test_heatmap_value_column_warnings_and_errors(): + df = grid_frame() + df["zs"] = ["1", "x", "3", "4", "5", "6"] + plan = plan_of(df=df, plot_type="heatmap", series_list=[hm(z=5)]) + assert any("値の列" in w["message"] and "数値にできない値が1件" in w["message"] and "その行は使いません" in w["message"] for w in plan.warnings) + df2 = grid_frame() + df2["d"] = pd.to_datetime(["2024-01-01"] * 6) + for kw, field_name in (({"z": 5}, "系列1の値の列"), ({"x": 5}, "系列1のX列"), ({"y": 5}, "系列1のY列")): + with pytest.raises(UserError) as e: + plan_of(df=df2, plot_type="heatmap", series_list=[hm(**kw)]) + assert e.value.field == field_name and "日時の列" in str(e.value) + with pytest.raises(UserError) as e: + plan_of(df=df, plot_type="heatmap", series_list=[hm(z=9)]) + assert e.value.field == "系列1の値の列" and "列" in str(e.value) + with pytest.raises(UserError) as e: + plan_of(df=df, plot_type="heatmap", series_list=[hm(), hm()]) + assert str(e.value).startswith("ヒートマップは系列1つで描きます。") and e.value.field == "系列" + # 2つ目の系列の値の列が未選択でも、系列の数のエラーを先に出す(設定の検証の段階) + with pytest.raises(UserError) as e: + parse_settings(raw_settings([hm(), series(colorColumn="")], plot_type="heatmap")) + assert str(e.value).startswith("ヒートマップは系列1つで描きます。") and e.value.field == "系列" + nan_z = pd.DataFrame({"x": [0, 1], "y": [0, 1], "z": ["a", "b"]}) + with pytest.raises(UserError) as e: + plan_of(df=nan_z, plot_type="heatmap", series_list=[hm()]) + assert "描画可能な数値データがありません" in str(e.value) + + +def test_heatmap_size_limit(): + n = MAX_HEATMAP_SIZE + ok = pd.DataFrame({"x": np.arange(n, dtype=float), "y": np.zeros(n), "z": np.ones(n)}) + assert plan_of(df=ok, plot_type="heatmap", series_list=[hm()]).heatmap.x_count == n + big = pd.DataFrame({"x": np.arange(n + 1, dtype=float), "y": np.zeros(n + 1), "z": np.ones(n + 1)}) + with pytest.raises(UserError) as e: + plan_of(df=big, plot_type="heatmap", series_list=[hm()]) + assert e.value.field == "系列1のX列" and f"{n + 1}種類" in str(e.value) and "X" in str(e.value) + with pytest.raises(UserError) as e: + plan_of(df=big[["y", "x", "z"]], plot_type="heatmap", series_list=[hm()]) + assert e.value.field == "系列1のY列" and "Y" in str(e.value) + + +def test_heatmap_single_row_column_log_axes_and_annotation(tmp_path): + df = pd.DataFrame({"x": [1.0, 10, 100], "y": [1.0, 1, 1], "z": [1.0, 2, 3]}) # 1 行だけの格子 + + def mutate(raw): + raw["axes"]["x"]["scale"] = "log" + raw["annotations"] = [{"kind": "vline", "x": "10"}] + + bt = Built(tmp_path, df=df, series_list=[hm()], plot_type="heatmap", mutate=mutate) + s = bt.check(lambda f: None) + assert s[0]["meshes"] == 1 and s[0]["xscale"] == "log" and s[0]["annotations"]["vlines"] == 1 + one = pd.DataFrame({"x": [3.0], "y": [4.0], "z": [5.0]}) # 1 マスだけ + assert Built(tmp_path, df=one, series_list=[hm()], plot_type="heatmap").check(lambda f: None)[0]["meshes"] == 1 + + +def test_heatmap_annotation_on_text_axis_is_index(tmp_path): + def mutate(raw): + raw["annotations"] = [{"kind": "vline", "x": "1"}, {"kind": "hline", "y": "0.5"}] + + bt = Built(tmp_path, df=grid_frame(), series_list=[hm(x=3, y=4)], plot_type="heatmap", mutate=mutate) + s = bt.check(lambda f: None) + assert s[0]["annotations"]["vlines"] == 1 and s[0]["annotations"]["hlines"] == 1 + # 日時の注釈は文字列の軸では使えない + with pytest.raises(UserError): + Built(tmp_path, df=grid_frame(), series_list=[hm(x=3, y=4)], plot_type="heatmap", mutate=lambda r: r.update(annotations=[{"kind": "vline", "x": "2024-01-01"}])) + + +def test_heatmap_legend_not_emitted_without_labelled_artists(tmp_path): + bt = Built(tmp_path, df=grid_frame(), series_list=[hm(label="系列名")], plot_type="heatmap") + assert "凡例に出せるラベルが無い" in bt.script.text + assert bt.check(lambda f: None)[0]["legend"] == [] + + +# ---------------------------------------------------------------- 共通 + +@pytest.mark.parametrize("plot_type", NEW_TYPES) +def test_new_types_full_and_auto_summaries_match(tmp_path, plot_type): + if plot_type == "heatmap": + bt = build_new(tmp_path, plot_type, [hm(x=3, y=1)], grid_frame()) + else: + bt = build_new(tmp_path, plot_type, [series(y=0), series(y=1, label="B")], dist_frame()) + bt.check(lambda f: None) + + +@pytest.mark.parametrize("plot_type", NEW_TYPES) +def test_new_types_steps_and_axis_ranges(tmp_path, plot_type): + bt = build_new(tmp_path, plot_type, [hm()] if plot_type == "heatmap" else [series(y=0)], grid_frame() if plot_type == "heatmap" else dist_frame()) + steps = bt.script.steps + assert steps and all(s.message for s in steps) + if plot_type == "heatmap": + assert {"系列1の値の列", "カラーマップ"} <= {s.field for s in steps} + assert any("ヒートマップ" in s.message for s in steps) + else: + assert any(s.message.startswith("グラフを描画できませんでした") for s in steps) + + +def test_existing_types_summaries_have_zero_new_keys(tmp_path): + for t in ("line", "bar", "hist", "scatterColor"): + sl = [colored()] if t == "scatterColor" else [series(y=1, x=4)] + s = build(tmp_path, t, sl).check(lambda f: None) + assert (s[0]["boxes"], s[0]["violins"], s[0]["meshes"]) == (0, 0, 0) + + +def test_injection_new_types(tmp_path): + import ast + + evil = '"); import os; os.system("echo hi") #' + label = "'''\n" + evil + df = pd.DataFrame( + { + 'c"\'\n' + evil: ["a", "b", "a", "b", "c"], + "v" + evil: [1.0, 2, 3, 4, 5], + "z" + evil: [1.0, 2, 3, 4, 6], + "t" + evil: ["p", "q", "p", "q", "p"], + } + ) + cases = [ + ("box", [series(y=1, label=label), series(y=2, label=label)], {}), + ("violin", [series(y=1, label=label), series(y=2, label=label)], {}), + ("heatmap", [series(y=3, x=0, label=label, colorColumn="__idx__2")], {"colorbarLabel": label}), + ] + for plot_type, sl, plot in cases: + bt = build_new(tmp_path, plot_type, sl, df, **plot) + tree = ast.parse(bt.script.text) + assert not [n for n in ast.walk(tree) if isinstance(n, ast.Call) and getattr(n.func, "attr", "") == "system"] + for line in bt.script.text.splitlines(): + if line.lstrip().startswith("#"): + continue + assert "echo hi" not in line.split(" #")[0] or line.count('"') >= 2 # コードの中では文字列の内側にだけ現れる + with bt.full() as run: + assert run.fig is not None and "echo hi" not in run.output + bt.check(lambda f: None) + # 凡例名は目盛のラベルとしてリテラルに入る(柔軟な文字列でもそのまま読み戻せる) + bt = build_new(tmp_path, "box", [series(y=1, label=label)], df) + assert bt.check(lambda f: None)[0]["xticklabels"][0] == label diff --git a/tests/unit/test_expr.py b/tests/unit/test_expr.py index 6798c55..be8c12c 100644 --- a/tests/unit/test_expr.py +++ b/tests/unit/test_expr.py @@ -324,3 +324,207 @@ def test_invalid_count_aggregate(): assert count == 1 and r.isna().all() r, count = run("max([2]) + 1") assert count == 0 + + +# ---- 近似の式(モデル。G10) ------------------------------------------------- + +MODELS = [ + "a*exp(-b*x) + c", + "a*x^2 + b*x + c", + "a/(1 + exp(-b*(x - c)))", + "a*sin(b*x + c) + d", + "-a^2 * x", + "a^b^c + x", + "(a + b)*(x - e)/2", + "a*x**-b + 1e-3", + "a - (b - x)", + "a/(b*x)", + "log(abs(x) + 1)*a + sqrt(b**2)", +] + + +def merr(text): + with pytest.raises(ExprError) as e: + expr.parse_model(text) + return e.value + + +def mcode(text): + return expr.model_to_code(expr.parse_model(text), repr) + + +def mrun(text, x, **p): + ns = {"np": np, "x": x, **{k: np.float64(v) for k, v in p.items()}} + with np.errstate(all="ignore"): + return eval(mcode(text), ns) # テスト内だけで使う + + +@pytest.mark.parametrize("text", MODELS) +def test_model_accepted(text): + node = expr.parse_model(text) + assert expr.model_params(node) + + +def test_model_params_order_and_dedup(): + assert expr.model_params(expr.parse_model("c*x + a*x + c")) == ("a", "c") + assert expr.model_params(expr.parse_model("e*x + d + b")) == ("b", "d", "e") + + +def test_model_e_vs_number_vs_exp(): + n = expr.parse_model("1e-3*x + e") + assert expr.model_params(n) == ("e",) + assert expr.model_to_text(n) == "0.001*x + e" + n = expr.parse_model("2.5E3*x + a") + assert expr.model_to_text(n) == "2500*x + a" + n = expr.parse_model("exp(x) + e") + assert expr.model_params(n) == ("e",) + assert expr.model_to_code(n, repr) == "np.exp(x) + e" + + +def test_model_errors_with_positions(): + e = merr("a*[0]*x") + assert (e.message, e.position) == ( + "近似の式では列は使えません(変数は x、パラメータは a〜e です)。", + 3, + ) + e = merr("a*A + x") + assert e.position == 3 and "列は使えません" in e.message + assert merr("a*BC*x").position == 3 + for name in ("min", "max", "mean", "median", "std", "first", "last"): + e = merr(f"a*{name}(x)") + assert e.position == 3 and "近似の式では使えません" in e.message and "sqrt" in e.message + for name in ("rolling_mean", "diff", "cumsum"): + e = merr(f"{name}(x)*a") + assert e.position == 1 and "近似の式では使えません" in e.message + assert merr("a + 1").message == "式に x を含めてください。" + assert merr("a*2*3").message == "式に x を含めてください。" + assert merr("x + 1").message == "式にパラメータ(a〜e)を1つ以上含めてください。" + e = merr("a*y + x") + assert e.position == 3 and "使える名前は x と a〜e です" in e.message + assert merr("f*x").position == 1 + assert merr("a*x + k").position == 7 + e = merr("2e") + assert e.position == 2 and "演算子" in e.message + assert merr("a*x ab").position == 5 + assert merr("a(x)").position == 1 + assert merr("exp").position == 1 + assert merr("").message == "式を入力してください" + + +def test_model_normal_parse_unchanged(): + for text in ("x", "a", "x + [0]", "a*[0]"): + with pytest.raises(ExprError) as e: + parse(text) + assert "使えません" in e.value.message + assert parse("[0] + 1").kind == "series" + + +def test_model_fullwidth(): + n = expr.parse_model("a*exp(-b*x)+c") + assert expr.model_to_text(n) == "a*exp(-b*x) + c" + + +def test_model_precedence_and_assoc(): + x = np.array([0.5, 1.0, 2.0]) + assert np.allclose(mrun("-a^2 + 0*x", x, a=3), -9.0) # -(a^2) + assert np.allclose(mrun("a^b^c + 0*x", x, a=2, b=3, c=2), 2**9) + assert np.allclose(mrun("(-a)^2 + 0*x", x, a=3), 9.0) + assert np.allclose(mrun("a - (b - x)", x, a=1, b=5), 1 - (5 - x)) + assert expr.model_to_text(expr.parse_model("-a^2 + x")) == "-a^2 + x" + assert expr.model_to_text(expr.parse_model("(-a)^2 + x")) == "(-a)^2 + x" + assert expr.model_to_text(expr.parse_model("a^b^c + x")) == "a^b^c + x" + assert expr.model_to_text(expr.parse_model("(a^b)^c + x")) == "(a^b)^c + x" + assert expr.model_to_code(expr.parse_model("(a^b)^c + x"), repr) == "(a ** b) ** c + x" + + +@pytest.mark.parametrize("text", MODELS) +@pytest.mark.parametrize("kind", ["array", "series"]) +def test_model_code_matches_evaluate(text, kind): + xs = np.array([0.1, 0.5, 1.0, 2.0, 3.5]) + x = xs if kind == "array" else pd.Series(xs, index=range(5, 10)) + params = {"a": 1.3, "b": 0.7, "c": 2.0, "d": -0.4, "e": 1.1} + node = expr.parse_model(text) + got = np.asarray(mrun(text, x, **params), dtype=float) + want = expr.evaluate_model(node, xs, params) + assert np.allclose(got, want, equal_nan=True) + assert want.shape == xs.shape + + +def test_model_code_as_function_body(): + code = mcode("a*exp(-b*x) + c") + ns = {"np": np} + exec(f"def f(x, a, b, c):\n return {code}\n", ns) # テスト内だけで使う + x = np.linspace(0, 2, 5) + assert np.allclose(ns["f"](x, np.float64(2), np.float64(1), np.float64(0.5)), 2 * np.exp(-x) + 0.5) + assert expr.evaluate_model(expr.parse_model("a*x + 1"), [1, 2], {"a": 2}).tolist() == [3.0, 5.0] + + +@pytest.mark.parametrize( + "text, want", + [ + ("a*exp(-b*x)+c", "a*exp(-b*x) + c"), + ("a * x ** 2 + b * x + c", "a*x^2 + b*x + c"), + ("a/(1+exp(-b*(x-c)))", "a/(1 + exp(-b*(x - c)))"), + ("a*x^0.5", "a*x^0.5"), + ("a*x + 1e-5", "a*x + 1e-05"), + ("(a*x)^2", "(a*x)^2"), + ("a/(b*x)", "a/(b*x)"), + ("a*(b + x)", "a*(b + x)"), + ("2*3*a*x", "6*a*x"), + ], +) +def test_model_to_text(text, want): + assert expr.model_to_text(expr.parse_model(text)) == want + + +@pytest.mark.parametrize("text", MODELS) +def test_model_text_is_safe(text): + t = expr.model_to_text(expr.parse_model(text)) + assert t.isascii() and "$" not in t and "\n" not in t + assert set(t) <= set("abcdexlogsintqrpw0123456789.+-*/^() ") + + +@pytest.mark.parametrize( + "text", + [ + "a*x); import os #", + "a*x\nimport os", + "__import__('os')", + "a*x; b", + "a.real*x", + "x[0]*a", + "a*x$", + "lambda: a*x", + "a*x if b else c", + ], +) +def test_model_injection_rejected(text): + with pytest.raises(ExprError): + expr.parse_model(text) + + +def test_model_limits(): + with pytest.raises(ExprError): + expr.parse_model("a*x" + "+1" * 100) + e = merr("a*x+" + "1" * 200) + assert "200文字" in e.message + with pytest.raises(ExprError): + expr.parse_model("(" * 60 + "a*x" + ")" * 60) + with pytest.raises(ExprError): + expr.parse_model("-" * 150 + "a*x") + with pytest.raises(ExprError): + expr.parse_model("a^" * 90 + "x") + + +def test_model_nonfinite_constant(): + with pytest.raises(ExprError): + expr.parse_model("a*x + 1/0") + + +def test_no_dynamic_execution_in_module(): + import inspect + import re + + src = inspect.getsource(expr) + for word in ("eval", "exec", "compile", "ast"): + assert not re.search(rf"(? 2 個 + with pytest.raises(UserError) as e: + plan_of(df=df, fits=[custom("a * x**2 + b * x + c")]) # 3 個 <= 3 個 + assert e.value.field == "近似曲線1の系列" and "近似曲線1: " in str(e.value) and "4個以上" in str(e.value) + + +def test_custom_data_errors(): + df = decay_frame().assign(d=pd.date_range("2026-01-01", periods=30).strftime("%Y-%m-%d"), c=[f"k{i}" for i in range(30)]) + for x, word in ((2, "日時"), (3, "文字列")): + with pytest.raises(UserError) as e: + plan_of(df=df, series_list=[series(1, x=x)], fits=[custom()]) + assert e.value.field == "近似曲線1の系列" and word in str(e.value) + flat = pd.DataFrame({"t": np.arange(5.0), "v": np.full(5, 3.0)}) + with pytest.raises(UserError) as e: + plan_of(df=flat, fits=[custom("a * x + b")]) + assert "すべて同じ" in str(e.value) + + +def test_custom_injection(tmp_path): + evil = 'x"\n__import__("os").system("x") # \'\'\'' + b = Built(tmp_path, df=decay_frame(), series_list=[series(1, label=evil)], fits=[custom(), custom("a * x + b", show="text")]) + compile(b.script.text, "plot.py", "exec") + assert "\n__import__" not in b.script.text + with b.full() as run: + assert any(ln.get_label().startswith(evil + "の近似: ") for ln in run.fig.axes[0].lines) + # 式の文字列に命令を入れても、パーサが拒否する + for bad in ('a * __import__("os")', "a * x; import os", "a * x\nimport os", "a.__class__ * x", "a * x # \n"): + with pytest.raises(UserError): + parse_settings(raw_settings(fits=[custom(bad)])) + + +def test_custom_expression_only_in_comment(tmp_path): + b = Built(tmp_path, df=decay_frame(), fits=[custom("a * exp( -b*x )+c")]) + lines = [ln for ln in b.script.text.split("\n") if "a * exp( -b*x )+c" in ln] + assert len(lines) == 1 and lines[0].startswith("def fit_model_1(") and "# 近似曲線1の式: " in lines[0] + assert "\n" not in lines[0] + # 木から整えた式だけがコードとラベルに入る + assert "a*exp(-b*x) + c" in b.script.text diff --git a/uv.lock b/uv.lock index 7ac725f..1c812be 100644 --- a/uv.lock +++ b/uv.lock @@ -297,6 +297,7 @@ dev = [ { name = "pytest" }, { name = "pytest-playwright" }, { name = "pyyaml" }, + { name = "scipy" }, ] [package.metadata] @@ -310,6 +311,7 @@ dev = [ { name = "pytest", specifier = ">=9.1.1" }, { name = "pytest-playwright", specifier = ">=0.9.0" }, { name = "pyyaml", specifier = ">=6.0.3" }, + { name = "scipy", specifier = "==1.18.0" }, ] [[package]] @@ -587,6 +589,37 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/a0/f4/c67b0b3f1b9245e8d266f0f112c500d50e5b4e83cb6f3b71b6528104182a/requests-2.34.2-py3-none-any.whl", hash = "sha256:2a0d60c172f83ac6ab31e4554906c0f3b3588d37b5cb939b1c061f4907e278e0", size = 73075, upload-time = "2026-05-14T19:25:26.443Z" }, ] +[[package]] +name = "scipy" +version = "1.18.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/a7/25/c2700dfaf6442b4effaa91af24ebce5dc9d31bb4a69706313aae70d72cd0/scipy-1.18.0.tar.gz", hash = "sha256:67b2ad2ad54c72ca6d04975a9b2df8c3638c34ddd5b28738e94fc2b57929d378", size = 30774447, upload-time = "2026-06-19T15:01:43.456Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/78/b5/915a19b3de2f7430062b509653563db1633ddbb6f021b06731521115d4e2/scipy-1.18.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:4c256ee70c0d1a8a2ace807e199ccd4e3f57037433842abb3fb36bc17eaa9578", size = 31036253, upload-time = "2026-06-19T15:00:43.216Z" }, + { url = "https://files.pythonhosted.org/packages/d7/88/b72def7262e150d16be13fca37a96481138d624e700340bc3362a7588929/scipy-1.18.0-cp314-cp314-macosx_12_0_arm64.whl", hash = "sha256:2ef3abc54a4ffc53765374b0d5728532dfdd2585ed23f6b11c206a1f0b1b9af8", size = 28673758, upload-time = "2026-06-19T15:00:46.663Z" }, + { url = "https://files.pythonhosted.org/packages/91/02/2e636a61a525632c373cf6a9c24442a3ffb79e364d38e98b32042964ac32/scipy-1.18.0-cp314-cp314-macosx_14_0_arm64.whl", hash = "sha256:f2a6af57bd9e4a75d70e4117e78a1bbee84f79ae3fbb6d0111005d6ebcc4cb8d", size = 20415514, upload-time = "2026-06-19T15:00:49.399Z" }, + { url = "https://files.pythonhosted.org/packages/c9/b6/2135974442f6aba159d9d39d774a1c8cb19947016725d69fecc685df45bf/scipy-1.18.0-cp314-cp314-macosx_14_0_x86_64.whl", hash = "sha256:3f1ac564d3bf6c03d861d2cd87a1bea0da2887136f7fb1bf519c05a8971452d6", size = 23034398, upload-time = "2026-06-19T15:00:51.941Z" }, + { url = "https://files.pythonhosted.org/packages/f6/e6/ba89ec5abf6ee9257c0d1ec985573f3ae32742c24bc03e016388a40b1b15/scipy-1.18.0-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:40395a5fcd1abee49a5c7aaa98c29db393eedc835138560a588c47ec16156690", size = 33998032, upload-time = "2026-06-19T15:00:54.838Z" }, + { url = "https://files.pythonhosted.org/packages/7f/c4/bc41eb19b0fd0db868f4132920879019318d80cc522ad8f2bca4611af808/scipy-1.18.0-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8ca01e8ae69f1b18e9a58d91afead31be3cef0dd905a10249dac559ee15460a0", size = 35283333, upload-time = "2026-06-19T15:00:58.152Z" }, + { url = "https://files.pythonhosted.org/packages/53/a4/cbdeef6eb3830a8462a9d4ada814de5fc984345cc9ecf17cbec51a036f1e/scipy-1.18.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:7a7f3b01647384dbc3a711e8c6778e0aabbe93959249fef5c7393396bcac0867", size = 35610216, upload-time = "2026-06-19T15:01:01.155Z" }, + { url = "https://files.pythonhosted.org/packages/80/4d/b2b82502b65f661d1b789c1665dcdf315d5f12194e06fc0b37946294ebae/scipy-1.18.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:6aa94e78ec192a30063a5e72e561c28af769dc311190b24fe91774eff1969709", size = 37418960, upload-time = "2026-06-19T15:01:04.155Z" }, + { url = "https://files.pythonhosted.org/packages/93/3e/902d836831474b0ab5a37d16404f7bc5fafd9efba632890e271ba952635f/scipy-1.18.0-cp314-cp314-win_amd64.whl", hash = "sha256:2d8bbdc6c817f5b4006a54d799d4f5bab6f910193cbb9a1ff310833d4d270f61", size = 37288845, upload-time = "2026-06-19T15:01:07.822Z" }, + { url = "https://files.pythonhosted.org/packages/b6/43/8d73b337a3bdb14daa0314f0434210747c02d79d729ce1777574a817dcf6/scipy-1.18.0-cp314-cp314-win_arm64.whl", hash = "sha256:18e9575f1569b2c54174e6159d32942e03731177f63dce7975f0a0c88d102f5b", size = 24988971, upload-time = "2026-06-19T15:01:11.076Z" }, + { url = "https://files.pythonhosted.org/packages/b4/b4/f11918b0508a2787031a0499a03fbe3546f3bb5ca05d01038c45b278c09a/scipy-1.18.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:f351e0dd702687d12a402b867a1b4146a256923e1c38317cbc472f6372b94707", size = 31399325, upload-time = "2026-06-19T15:01:13.723Z" }, + { url = "https://files.pythonhosted.org/packages/7b/d1/1f287b57c0ff0ee5185dff3946d92c8017d39b0e431f0ae79a3ff1859512/scipy-1.18.0-cp314-cp314t-macosx_12_0_arm64.whl", hash = "sha256:7c7a51b33ce387193c97f228320cf8e87361daa1bba750638677729598b3e677", size = 29092110, upload-time = "2026-06-19T15:01:16.908Z" }, + { url = "https://files.pythonhosted.org/packages/ff/1a/7b74eb6c392fdcb27d414c0e7558a6d0231eb3b6d73571f479bb81ea8794/scipy-1.18.0-cp314-cp314t-macosx_14_0_arm64.whl", hash = "sha256:84031d7b052a54fae2f8632e0ec802073d385476eb9a63079bce6e23ef9283d4", size = 20833811, upload-time = "2026-06-19T15:01:20.488Z" }, + { url = "https://files.pythonhosted.org/packages/7c/ad/f3941716320a7b9cb4d68734a903b45fe16eff5fb7da7e16f2e619304979/scipy-1.18.0-cp314-cp314t-macosx_14_0_x86_64.whl", hash = "sha256:56abf29a7c067dde59be8b9a22d606a4ea1b2f2a4b756d9d903c62818f5dacce", size = 23396644, upload-time = "2026-06-19T15:01:23.364Z" }, + { url = "https://files.pythonhosted.org/packages/22/22/1446b62ffe07f9719b7d9b1b6a4e05a772833ae8f441fe4c22c34c9b250f/scipy-1.18.0-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1ad44305cfa24b1ba5803cbbebf033590ccbac1aa5d612d727b785325ab408b0", size = 34079318, upload-time = "2026-06-19T15:01:26.002Z" }, + { url = "https://files.pythonhosted.org/packages/56/3b/b87da667098bb470fa30c7011b0ba351ee976dd395c78798c66e941665a3/scipy-1.18.0-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:945c1761b93f38d7f99ae81ae80c63e621471608c7eeead563f6df025585cd58", size = 35324320, upload-time = "2026-06-19T15:01:28.881Z" }, + { url = "https://files.pythonhosted.org/packages/f8/a1/c7932f91909759b0267f75fdea34e91309f96b895757534b76a90b6b4344/scipy-1.18.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:1a4441f15d620578772a49e5ab48c0ee1f7a0220e387110283062729136b2553", size = 35699541, upload-time = "2026-06-19T15:01:31.968Z" }, + { url = "https://files.pythonhosted.org/packages/f7/86/5185061a1fcc41d18c5dc2463969b3a3964b31d9ac67b2fb05d4c7ff7670/scipy-1.18.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:9aac6192fac56bf2ca534389d24623f07b39ff83317d58287285e7fbd622ff76", size = 37472480, upload-time = "2026-06-19T15:01:35.136Z" }, + { url = "https://files.pythonhosted.org/packages/31/8e/f04c68e39919a010d34f2ee1367fd705b0a25a02f609d755f0bfbc0a15fc/scipy-1.18.0-cp314-cp314t-win_amd64.whl", hash = "sha256:e40baea28ae7f5475c779741e2d90b1247c78531207b49c7030e698ff81cee3f", size = 37365390, upload-time = "2026-06-19T15:01:38.091Z" }, + { url = "https://files.pythonhosted.org/packages/d5/19/969dc072906c84dd0a3b05dcf57ea750936087d7873549e408b35cfc3f97/scipy-1.18.0-cp314-cp314t-win_arm64.whl", hash = "sha256:368e0a705903c466aa5f08eefb39e6b1b6b2d659e7352a31fd9e2438365be0f8", size = 25279661, upload-time = "2026-06-19T15:01:40.817Z" }, +] + [[package]] name = "six" version = "1.17.0"