### Setup: Install dependencies with npm install Source: https://github.com/anselmoo/tanabesugano/blob/main/docs/README.md Run in the docs directory to install project dependencies. Requires Node.js 20 or higher and npm. ```bash cd docs npm install ``` -------------------------------- ### Install TanabeSugano from PyPI, with extras, or from GitHub Source: https://github.com/anselmoo/tanabesugano/blob/main/README.md Installation commands for the TanabeSugano package. Use the base command for standard installation, add [plotly] for interactive plotting support, [mcp] for MCP server support (Claude Desktop, Cursor, VS Code), or install from GitHub for the latest development version. Requires Python โ‰ฅ 3.12 and uses the uv_build backend. ```bash # ๐Ÿ“ฆ Install from PyPI (recommended) pip install TanabeSugano ``` ```bash # ๐Ÿ”ง Install with interactive plotting support pip install TanabeSugano[plotly] ``` ```bash # ๐Ÿค– Install with MCP server support (Claude Desktop, Cursor, VS Code, โ€ฆ) pip install TanabeSugano[mcp] ``` ```bash # ๐ŸŒ Install from GitHub (latest development version) pip install git+https://github.com/Anselmoo/TanabeSugano.git ``` -------------------------------- ### Development: Start Vite dev server with npm run dev Source: https://github.com/anselmoo/tanabesugano/blob/main/docs/README.md Starts the development server. Visit http://localhost:5173/TanabeSugano/ in your browser. ```bash npm run dev ``` -------------------------------- ### Install TanabeSugano package Source: https://github.com/anselmoo/tanabesugano/blob/main/Tanabe_Sugano.ipynb Installs the TanabeSugano package via pip. The output shows successful installation of TanabeSugano-1.4.1 and its dependencies, including prettytable-2.5.0. ```python !pip install TanabeSugano ``` ```text Output: Collecting TanabeSugano Downloading tanabesugano-1.4.1-py3-none-any.whl (16 kB) Requirement already satisfied: matplotlib<4.0.0,>=3.4.2 in /usr/local/lib/python3.10/dist-packages (from TanabeSugano) (3.7.1) Requirement already satisfied: numpy<2.0.0,>=1.20.3 in /usr/local/lib/python3.10/dist-packages (from TanabeSugano) (1.23.5) Requirement already satisfied: pandas<2.0.0,>=1.2.4 in /usr/local/lib/python3.10/dist-packages (from TanabeSugano) (1.5.3) Collecting prettytable<3.0.0,>=2.1.0 (from TanabeSugano) Downloading prettytable-2.5.0-py3-none-any.whl (24 kB) Requirement already satisfied: contourpy>=1.0.1 in /usr/local/lib/python3.10/dist-packages (from matplotlib<4.0.0,>=3.4.2->TanabeSugano) (1.1.1) Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.10/dist-packages (from matplotlib<4.0.0,>=3.4.2->TanabeSugano) (0.12.1) Requirement already satisfied: fonttools>=4.22.0 in /usr/local/lib/python3.10/dist-packages (from matplotlib<4.0.0,>=3.4.2->TanabeSugano) (4.43.1) Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.10/dist-packages (from matplotlib<4.0.0,>=3.4.2->TanabeSugano) (1.4.5) Requirement already satisfied: packaging>=20.0 in /usr/local/lib/python3.10/dist-packages (from matplotlib<4.0.0,>=3.4.2->TanabeSugano) (23.2) Requirement already satisfied: pillow>=6.2.0 in /usr/local/lib/python3.10/dist-packages (from matplotlib<4.0.0,>=3.4.2->TanabeSugano) (9.4.0) Requirement already satisfied: pyparsing>=2.3.1 in /usr/local/lib/python3.10/dist-packages (from matplotlib<4.0.0,>=3.4.2->TanabeSugano) (3.1.1) Requirement already satisfied: python-dateutil>=2.7 in /usr/local/lib/python3.10/dist-packages (from matplotlib<4.0.0,>=3.4.2->TanabeSugano) (2.8.2) Requirement already satisfied: pytz>=2020.1 in /usr/local/lib/python3.10/dist-packages (from pandas<2.0.0,>=1.2.4->TanabeSugano) (2023.3.post1) Requirement already satisfied: wcwidth in /usr/local/lib/python3.10/dist-packages (from prettytable<3.0.0,>=2.1.0->TanabeSugano) (0.2.8) Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.10/dist-packages (from python-dateutil>=2.7->matplotlib<4.0.0,>=3.4.2->TanabeSugano) (1.16.0) Installing collected packages: prettytable, TanabeSugano Attempting uninstall: prettytable Found existing installation: prettytable 3.9.0 Uninstalling prettytable-3.9.0: Successfully uninstalled prettytable-3.9.0 Successfully installed TanabeSugano-1.4.1 prettytable-2.5.0 ``` -------------------------------- ### Install TanabeSugano with MCP extra via pip or uv Source: https://github.com/anselmoo/tanabesugano/blob/main/README.md Install the package with the optional Model Context Protocol (MCP) server dependencies. Use pip or uv; the [mcp] extra is required for the MCP server. ```bash pip install "TanabeSugano[mcp]" # or with uv: uv add "TanabeSugano[mcp]" ``` -------------------------------- ### Install and run all checks with uv and poe Source: https://github.com/anselmoo/tanabesugano/blob/main/CLAUDE.md Install all dependencies including MCP and plotly extras, then run the full CI check suite. The extras are required: without [mcp] 8 tests error on missing fastmcp, and without [plotly] the artifact drift check silently skips its .html half. ```bash uv sync --all-groups --extra mcp --extra plotly uv run poe check # lint + format + types + tests + artifact drift (what CI runs) uv run poe lint # ruff over src/ AND scripts/, full ALL ruleset uv run poe format # ruff format --check uv run poe types # ty, in the project env (see below) uv run poe test # suite, no coverage, screenshot tests excluded uv run poe test-mcp # MCP-only tests uv run poe cov # suite with a coverage report uv build # wheel + sdist via the uv_build backend ``` -------------------------------- ### Development Commands Source: https://github.com/anselmoo/tanabesugano/blob/main/CONTRIBUTING.md Run the full test suite, MCP layer tests, and linting with uv. Requires Python >= 3.12. ```bash uv sync --all-groups --extra mcp # Python >= 3.12 ``` ```bash uv run pytest -vv # full suite ``` ```bash uv run pytest -vv -m mcp # MCP layer only ``` ```bash uv run pre-commit run --all-files # what CI's lint job runs ``` -------------------------------- ### ASCII data format example Source: https://github.com/anselmoo/tanabesugano/blob/main/assets/uvvis/README.md Shows the commented header and tab-separated columns of the .txt dataset files. The header lines are skipped automatically when loading with NumPy. ```text # columns: wavenumber_cm-1 wavelength_nm absorbance_au 4000.000000 2500.000000 0.015306 ... ``` -------------------------------- ### Run calculation and show plots for d_count=3 Source: https://github.com/anselmoo/tanabesugano/blob/main/Tanabe_Sugano.ipynb Creates a CMDmain instance with d_count=3, runs the calculation, generates both interactive plots, and displays the first figure. ```python cmd = CMDmain(d_count=3) cmd.calculation() fig_1, fig_2 = interactive_plot(cmd.df, cmd.B) fig_1.show() ``` ```python fig_2.show() ``` -------------------------------- ### Run calculation and show plots for d_count=2 Source: https://github.com/anselmoo/tanabesugano/blob/main/Tanabe_Sugano.ipynb Creates a CMDmain instance with d_count=2, runs the calculation, generates both interactive plots, and displays the first figure. ```python cmd = CMDmain(d_count=2) cmd.calculation() fig_1, fig_2 = interactive_plot(cmd.df, cmd.B) fig_1.show() ``` ```python fig_2.show() ``` -------------------------------- ### Import TanabeSugano modules Source: https://github.com/anselmoo/tanabesugano/blob/main/Tanabe_Sugano.ipynb Imports the CMDmain class from tanabesugano.cmd, along with plotly.express and pandas for plotting and data handling. ```python from tanabesugano.cmd import CMDmain import plotly.express as px import pandas as pd ``` -------------------------------- ### Push Release Tag Source: https://github.com/anselmoo/tanabesugano/blob/main/CONTRIBUTING.md Push a version tag to trigger the release pipeline. Replace X.Y.Z with the actual version. ```bash git tag v && git push origin v ``` -------------------------------- ### Batch.calculation() Source: https://github.com/anselmoo/tanabesugano/blob/main/README.md Performs a batch calculation sweeping parameters over specified ranges. Each parameter is specified as [start, stop, steps]. ```APIDOC ## [Python] Batch.calculation() ### Description Performs a batch calculation sweeping parameters over specified ranges. Each parameter is specified as [start, stop, steps]. ### Method Python method ### Endpoint Batch.calculation ### Parameters #### Constructor Arguments - **Dq** (list) - Required - [start, stop, steps] for Dq sweep - **B** (list) - Required - [start, stop, steps] for Racah B - **C** (list) - Required - [start, stop, steps] for Racah C - **d_count** (int) - Required - Number of d electrons ### Response #### Success Response Performs the calculation and stores results in the Batch object. #### Response Example ```python batch = Batch(Dq=[500.0, 1500.0, 20], B=[1030.0, 1030.0, 1], C=[4850.0, 4850.0, 1], d_count=8) batch.calculation() ``` ``` -------------------------------- ### Define interactive_plot function Source: https://github.com/anselmoo/tanabesugano/blob/main/Tanabe_Sugano.ipynb Defines a function that creates two interactive Plotly line charts: an Energy-Correlation-Diagram and a Tanabe-Sugano-Diagram. It requires plotly to be installed; otherwise raises an ImportError. The function returns both figures. ```python def interactive_plot(df: pd.DataFrame, B: float) -> tuple: """Interactive plot for the tanabe-sugano-diagram.""" if px is None: raise ImportError( "Plotly is not installed. Please install plotly " "with 'pip install tanabesugano[plotly]'!" ) _col = df.drop(["Energy", "delta_B", "10Dq"], axis=1).columns _font = dict(family="Avant Garde, sans-serif", size=12, color="grey") _template = "plotly_white" _size = dict( autosize=False, width=800, height=800, ) color_discrete_sequence = [ px.colors.qualitative.Light24[int(i[0]) - 1] for i in _col ] _df = df.copy() fig_1 = px.line( _df, x="10Dq", y=_col, title="Energy-Correlation-Diagram", labels={ "variable": "State", "value": "Energy (cm-1)", "10Dq": "10Dq (cm-1)", }, color_discrete_sequence=color_discrete_sequence, ) fig_1.update_layout( xaxis_title="10Dq (cm-1)", yaxis_title="dd-states (cm-1)", legend_title="State", template=_template, font=_font, **_size, ) # Apply / self.B to every column except for _col _df[_col] = _df[_col].div(B, axis=0) # Plot the tanabe-sugano-diagram fig_2 = px.line( _df, x="delta_B", y=_col, title="Tanabe-Sugano-Diagram", labels={ "variable": "State", "value": " E / B", "delta_B": "ฮ” / B", }, color_discrete_sequence=color_discrete_sequence, ) fig_2.update_layout( xaxis_title="ฮ” / B", yaxis_title="E / B", legend_title="State", template=_template, font=_font, **_size, ) return fig_1, fig_2 ``` -------------------------------- ### Sweep Dq and export figure with Batch and render_diagram Source: https://github.com/anselmoo/tanabesugano/blob/main/README.md Sweeps a range of ligand-field strengths while holding Racah parameters fixed, then exports a publication figure. Each parameter is [start, stop, steps]; hold B and C fixed with one step. render_diagram supports 'png' (default), 'pdf', or 'svg' formats. ```python from pathlib import Path from tanabesugano.batch import Batch from tanabesugano.mcp.plotting import render_diagram # Sweep Dq while holding the Racah parameters fixed. # Each parameter is [start, stop, steps]; hold B and C fixed with one step. batch = Batch(Dq=[500.0, 1500.0, 20], B=[1030.0, 1030.0, 1], C=[4850.0, 4850.0, 1], d_count=8) batch.calculation() # Publication figure: "png" (default), "pdf" or "svg". Path("d8.pdf").write_bytes( render_diagram(d_count=8, dq_max=1500.0, B=1030.0, C=4850.0, fmt="pdf"), ) ``` -------------------------------- ### Generate interactive Tanabe-Sugano plot for d5 configuration Source: https://github.com/anselmoo/tanabesugano/blob/main/Tanabe_Sugano.ipynb Creates a CMDmain instance with d_count=5, runs the calculation, and displays the first interactive plot (fig_1). The second plot (fig_2) is shown separately in the next snippet. ```python cmd = CMDmain(d_count=5) cmd.calculation() fig_1, fig_2 = interactive_plot(cmd.df, cmd.B) fig_1.show() ``` -------------------------------- ### Generate interactive Tanabe-Sugano plot for d7 configuration Source: https://github.com/anselmoo/tanabesugano/blob/main/Tanabe_Sugano.ipynb Creates a CMDmain instance with d_count=7, runs the calculation, and displays the first interactive plot (fig_1). The second plot (fig_2) is shown separately in the next snippet. ```python cmd = CMDmain(d_count=7) cmd.calculation() fig_1, fig_2 = interactive_plot(cmd.df, cmd.B) fig_1.show() ``` -------------------------------- ### Generate interactive Tanabe-Sugano plot for d6 configuration Source: https://github.com/anselmoo/tanabesugano/blob/main/Tanabe_Sugano.ipynb Creates a CMDmain instance with d_count=6, runs the calculation, and displays the first interactive plot (fig_1). The second plot (fig_2) is shown separately in the next snippet. ```python cmd = CMDmain(d_count=6) cmd.calculation() fig_1, fig_2 = interactive_plot(cmd.df, cmd.B) fig_1.show() ``` -------------------------------- ### Verify Release Notes Source: https://github.com/anselmoo/tanabesugano/blob/main/CONTRIBUTING.md Check that the release body resolves before pushing a tag. Must exit 0 with a non-empty body; a bare 'rrt release notes' exits 1 because 'changelog_workflow = "incremental"' empties '[Unreleased]' at bump time. ```bash uv run rrt release notes --version ``` -------------------------------- ### Generate interactive Tanabe-Sugano plot for d4 configuration Source: https://github.com/anselmoo/tanabesugano/blob/main/Tanabe_Sugano.ipynb Creates a CMDmain instance with d_count=4, runs the calculation, and displays the first interactive plot (fig_1). The second plot (fig_2) is shown separately in the next snippet. ```python cmd = CMDmain(d_count=4) cmd.calculation() fig_1, fig_2 = interactive_plot(cmd.df, cmd.B) fig_1.show() ``` -------------------------------- ### Generate interactive Tanabe-Sugano plot for d8 configuration Source: https://github.com/anselmoo/tanabesugano/blob/main/Tanabe_Sugano.ipynb Creates a CMDmain instance with d_count=8, runs the calculation, and displays the first interactive plot (fig_1). The second plot (fig_2) is shown separately in the next snippet. ```python cmd = CMDmain(d_count=8) cmd.calculation() fig_1, fig_2 = interactive_plot(cmd.df, cmd.B) fig_1.show() ``` -------------------------------- ### Show second interactive plot for d4 configuration Source: https://github.com/anselmoo/tanabesugano/blob/main/Tanabe_Sugano.ipynb Displays the second interactive plot (fig_2) generated for the d4 configuration. This is a separate step from showing fig_1. ```python fig_2.show() ``` -------------------------------- ### Preview: Serve production build with npm run preview Source: https://github.com/anselmoo/tanabesugano/blob/main/docs/README.md Serves the production build locally for preview. ```bash npm run preview ``` -------------------------------- ### CLI: tanabesugano --help Source: https://github.com/anselmoo/tanabesugano/blob/main/README.md Command-line interface for the Tanabe-Sugano eigensolver. Displays all available options for configuring calculations. ```APIDOC ## [CLI] tanabesugano ### Description Command-line interface for the Tanabe-Sugano eigensolver. Displays all available options for configuring calculations. ### Method CLI ### Endpoint tanabesugano ### Parameters #### Options - **-d D** (int) - Optional - Number of d electrons, 2-8 (default d5) - **-Dq DQ** (float) - Optional - 10Dq crystal field splitting (default 10Dq = 8065 cm-) - **-cut CUT** (float) - Optional - 10Dq crystal field splitting (default 10Dq = 8065 cm-) - **-B B B** (float) - Optional - Racah Parameter B and the corresponding reduction (default B = 860 cm- * 1.) - **-C C C** (float) - Optional - Racah Parameter C and the corresponding reduction (default C = 4.477*860 cm- * 1.) - **-n N** (int) - Optional - Number of roots (default nroots = 500) - **-ndisp** (flag) - Optional - Plot TS-diagram (default = on) - **-ntxt** (flag) - Optional - Save TS-diagram and dd energies (default = on) - **-slater** (flag) - Optional - Using Slater-Condon F2,F4 parameter instead Racah-Parameter B,C (default = off) - **-v, --version** (flag) - Optional - Print version number and exit - **-html** (flag) - Optional - Save the interactive Plotly diagrams as HTML (default = off) - **-html-offline** (flag) - Optional - With -html, write a shared plotly.min.js beside the diagrams so they render without a network connection (default = CDN) ### Response #### Success Response Prints help message with usage and options. #### Response Example ``` usage: tanabesugano [-h] [-d D] [-Dq DQ] [-cut CUT] [-B B B] [-C C C] [-n N] [-ndisp] [-ntxt] [-slater] [-v] [-html] [-html-offline] A python-based Eigensolver for Tanabe-Sugano- & Energy-Correlation-Diagrams based on studies by *Yukito Tanabe and Satoru Sugano* for d3-d8 transition metal ions: For further help, please use tanabe '--help' options: -h, --help show this help message and exit -d D Number of d electrons, 2-8 (default d5) -Dq DQ 10Dq crystal field splitting (default 10Dq = 8065 cm-) -cut CUT 10Dq crystal field splitting (default 10Dq = 8065 cm-) -B B B Racah Parameter B and the corresponding reduction (default B = 860 cm- * 1.) -C C C Racah Parameter C and the corresponding reduction (default C = 4.477*860 cm- * 1.) -n N Number of roots (default nroots = 500) -ndisp Plot TS-diagram (default = on) -ntxt Save TS-diagram and dd energies (default = on) -slater Using Slater-Condon F2,F4 parameter instead Racah-Parameter B,C (default = off) -v, --version Print version number and exit -html Save the interactive Plotly diagrams as HTML (default = off) -html-offline With -html, write a shared plotly.min.js beside the diagrams so they render without a network connection (default = CDN) ``` ``` -------------------------------- ### Build: Compile production build with npm run build Source: https://github.com/anselmoo/tanabesugano/blob/main/docs/README.md Builds the Vite application. Output will be in the ../docs/ directory. ```bash npm run build ``` -------------------------------- ### tanabesugano CLI help output Source: https://github.com/anselmoo/tanabesugano/blob/main/README.md Shows all command-line options for the tanabesugano tool, including defaults for d electrons, 10Dq, Racah parameters, number of roots, and output flags. Note that the MCP layer uses per-configuration Racah defaults rather than the CLI's single d5 free-ion pair. ```console $ tanabesugano --help usage: tanabesugano [-h] [-d D] [-Dq DQ] [-cut CUT] [-B B B] [-C C C] [-n N] [-ndisp] [-ntxt] [-slater] [-v] [-html] [-html-offline] A python-based Eigensolver for Tanabe-Sugano- & Energy-Correlation-Diagrams based on studies by *Yukito Tanabe and Satoru Sugano* for d3-d8 transition metal ions: For further help, please use tanabe '--help' options: -h, --help show this help message and exit -d D Number of d electrons, 2-8 (default d5) -Dq DQ 10Dq crystal field splitting (default 10Dq = 8065 cm-) -cut CUT 10Dq crystal field splitting (default 10Dq = 8065 cm-) -B B B Racah Parameter B and the corresponding reduction (default B = 860 cm- * 1.) -C C C Racah Parameter C and the corresponding reduction (default C = 4.477*860 cm- * 1.) -n N Number of roots (default nroots = 500) -ndisp Plot TS-diagram (default = on) -ntxt Save TS-diagram and dd energies (default = on) -slater Using Slater-Condon F2,F4 parameter instead Racah-Parameter B,C (default = off) -v, --version Print version number and exit -html Save the interactive Plotly diagrams as HTML (default = off) -html-offline With -html, write a shared plotly.min.js beside the diagrams so they render without a network connection (default = CDN) ``` -------------------------------- ### Claude Desktop MCP server configuration (claude_desktop_config.json) Source: https://github.com/anselmoo/tanabesugano/blob/main/README.md Add this JSON to claude_desktop_config.json to register the TanabeSugano MCP server with Claude Desktop. It uses uvx to run the tanabesugano-mcp entry point with the [mcp] extra. ```json { "mcpServers": { "tanabesugano": { "command": "uvx", "args": ["--from", "tanabesugano[mcp]", "tanabesugano-mcp"] } } } ``` -------------------------------- ### Generate Tanabe-Sugano diagram with tanabesugano CLI Source: https://github.com/anselmoo/tanabesugano/blob/main/README.md Command-line usage to generate a Tanabe-Sugano diagram. The first command creates a diagram for a d6 configuration. The second customizes parameters: -Dq sets the crystal field splitting, -B sets the Racah B parameter and ratio, and -C sets the Racah C parameter and ratio. ```bash # Generate diagram for d6 configuration tanabesugano -d 6 ``` ```bash # Customize parameters tanabesugano -d 6 -Dq 8000 -B 860 1.0 -C 3850 1.0 ``` -------------------------------- ### LevelSet.transition_unicode(level) Source: https://github.com/anselmoo/tanabesugano/blob/main/README.md Generates a Unicode string representing a transition from the ground state to the given level. ```APIDOC ## [Python] LevelSet.transition_unicode(level) ### Description Generates a Unicode string representing a transition from the ground state to the given level. ### Method Python method ### Endpoint LevelSet.transition_unicode ### Parameters #### Arguments - **level** (Level) - Required - The excited level for the transition ### Response #### Success Response Returns a string like "3A_2g -> 3T_1g(P)". #### Response Example ```python print(manifold.transition_unicode(excited)) # 3A_2g -> 3T_1g(P) ``` ``` -------------------------------- ### OptimizerFactory class for algorithm selection Source: https://github.com/anselmoo/tanabesugano/blob/main/docs/SPECTRUM_FITTING_PATTERN.md Traditional GoF factory pattern for selecting optimization algorithms. Over-engineered for a single use case; introduces indirection without benefit. ```python class OptimizerFactory: _optimizers = { 'nelder_mead': lambda obj, x0: minimize(obj, x0, method='Nelder-Mead'), 'bfgs': lambda obj, x0: minimize(obj, x0, method='BFGS'), } @staticmethod def create(method_name): return OptimizerFactory._optimizers[method_name] ``` -------------------------------- ### Project structure: docs directory layout Source: https://github.com/anselmoo/tanabesugano/blob/main/docs/README.md Shows the directory layout of the docs folder, including public CSV data, source components, and configuration files. ```text docs/ โ”œโ”€โ”€ public/ โ”‚ โ””โ”€โ”€ ts-diagrams/ # CSV data files (d2-d8) โ”œโ”€โ”€ src/ โ”‚ โ”œโ”€โ”€ components/ โ”‚ โ”‚ โ””โ”€โ”€ DiagramViewer.tsx # Main diagram component โ”‚ โ”œโ”€โ”€ utils/ โ”‚ โ”‚ โ””โ”€โ”€ dataLoader.ts # CSV loading utilities โ”‚ โ”œโ”€โ”€ App.tsx # Main app component โ”‚ โ”œโ”€โ”€ main.tsx # App entry point โ”‚ โ””โ”€โ”€ index.css # Global styles โ”œโ”€โ”€ index.html โ”œโ”€โ”€ vite.config.ts โ””โ”€โ”€ package.json ``` -------------------------------- ### Clean function-based spectrum fitting Source: https://github.com/anselmoo/tanabesugano/blob/main/docs/SPECTRUM_FITTING_PATTERN.md Shows the preferred simple function approach for spectrum fitting. Advantages include single responsibility, lazy computation, testability as a pure function, composability, and flexibility for the caller to choose initial guess, bounds, and C parameter. ```python # โœ“ Clean: Computation is a function fit = fit_spectrum(d_count, observed_peaks) # note: d_count FIRST ``` -------------------------------- ### Explicit Algorithm Selection with scipy.optimize.minimize Source: https://github.com/anselmoo/tanabesugano/blob/main/docs/SPECTRUM_FITTING_PATTERN.md Calls minimize with an explicitly chosen Nelder-Mead method and options. To swap optimizers, change the method string to BFGS, Powell, etc., without needing a factory class. ```python result = minimize( objective, initial_guess, method="Nelder-Mead", # <-- Algorithm explicitly chosen options={"maxiter": 500, "xatol": 1e-2, "fatol": 1.0}, ) ``` -------------------------------- ### Objective Function with Graded Penalties and Forward Model Source: https://github.com/anselmoo/tanabesugano/blob/main/docs/SPECTRUM_FITTING_PATTERN.md Chains bounds check, spin-regime check, forward model, and fitness metric. Uses graded finite penalties to avoid flat objective surfaces that cause Nelder-Mead to falsely converge. Handles exceptions and wrong spin regime with distinct penalties. ```python # Graded, finite penalty -- never a constant. A constant makes the objective # flat, and a flat objective makes Nelder-Mead "converge" without moving. if excess > 0 or dq <= 0 or b <= 0: return base * (2.0 + excess) try: terms = compute_point(d_count, dq, b, C) # Forward model found_ground, candidates = transition_candidates( # Ground term + spin filter terms, spin_allowed_only=not include_spin_forbidden, ) except (ValueError, KeyError, np.linalg.LinAlgError): return base * 3.0 if found_ground != reference or not candidates: return base * 2.0 # Wrong spin regime return peak_rmse(observed, np.array([e for e, _a, _s in candidates])) # Fitness ``` -------------------------------- ### Regenerate spectra with uv run Source: https://github.com/anselmoo/tanabesugano/blob/main/assets/uvvis/README.md Runs the script that regenerates the reference spectra figures and data files. ```bash uv run python scripts/plot_uvvis_fits.py ``` -------------------------------- ### Load ASCII data with NumPy Source: https://github.com/anselmoo/tanabesugano/blob/main/assets/uvvis/README.md Loads the tab-separated data from a .txt file, skipping commented header lines. Returns three arrays: wavenumber, wavelength, and absorbance. ```python import numpy as np wn, wl, ab = np.loadtxt("uvvis_fit_ni_aqua.txt", comments="#", unpack=True) ``` -------------------------------- ### render_diagram(d_count, dq_max, B, C, fmt) Source: https://github.com/anselmoo/tanabesugano/blob/main/README.md Renders a Tanabe-Sugano diagram as a publication-quality figure. Returns the figure data as bytes. ```APIDOC ## [Python] render_diagram(d_count, dq_max, B, C, fmt) ### Description Renders a Tanabe-Sugano diagram as a publication-quality figure. Returns the figure data as bytes. ### Method Python function ### Endpoint render_diagram ### Parameters #### Arguments - **d_count** (int) - Required - Number of d electrons - **dq_max** (float) - Required - Maximum Dq value for the diagram - **B** (float) - Required - Racah parameter B - **C** (float) - Required - Racah parameter C - **fmt** (str) - Optional - Output format: "png" (default), "pdf", or "svg" ### Response #### Success Response Returns bytes of the rendered figure. #### Response Example ```python Path("d8.pdf").write_bytes( render_diagram(d_count=8, dq_max=1500.0, B=1030.0, C=4850.0, fmt="pdf"), ) ``` ``` -------------------------------- ### fit_spectrum function using direct callable approach Source: https://github.com/anselmoo/tanabesugano/blob/main/docs/SPECTRUM_FITTING_PATTERN.md Python-specific variant using function-as-first-class-citizen. Defers computation until called, composes multiple sub-objectives, and returns structured results with metadata. Includes guards for ill-posed inputs, physics-based seeding, and a penalty-based objective that avoids flat plateaus and spin-regime crossing. ```python def fit_spectrum( d_count: int, observed_peaks_cm1: list[float], C: float | None = None, *, spin_state: SpinState = "high", include_spin_forbidden: bool = False, dq_bounds: tuple[float, float] | None = None, b_bounds: tuple[float, float] = (200.0, 1500.0), ) -> SpectrumFit: """Fit observed absorption peaks to find optimal Dq and B parameters.""" # 1. Refuse ill-posed inputs up front, loudly. # High-spin d5 has ZERO spin-allowed d-d transitions; d4/d6 have exactly # one (= 10Dq), so B is unidentifiable. Returning a number here would be # a confident lie. if not seed_candidates: raise ValueError("... no spin-allowed d-d transitions ...") if len(seed_candidates) < observed.size: raise ValueError("... the fit is under-determined ...") # 2. Seed from physics, not from a constant. For d3/d8 the closed form # Dq = nu1/10, B = (nu3 + nu2 - 3*nu1)/15 is exact, so the optimizer # starts on the answer. dq_seed, b_seed = closed_form_dq_b(d_count, observed.tolist()) # 3. Objective. Two rules make it honest: def objective(params: np.ndarray) -> float: dq, b = params # (a) The penalty is FINITE, scale-aware and sloped back toward the # feasible box. A constant sentinel (the old `return 1e6`) makes the # objective perfectly flat wherever nothing matches -- and # Nelder-Mead reports success on a flat plateau, so the caller gets # the untouched seed back with a sentinel RMSE and no error. if out_of_bounds: return base * (2.0 + excess) found_ground, candidates = transition_candidates( compute_point(d_count, dq, b, C), spin_allowed_only=not include_spin_forbidden, ) # (b) Pin the spin regime. Low-spin manifolds are far denser (d5: 31 # lines vs 0), and a nearest-neighbour residual is minimised by a # dense forest -- so an unconstrained search is *rewarded* for # crossing the spin crossover into a physically wrong regime. if found_ground != reference: return base * 2.0 # (c) Every observed peak contributes to BOTH numerator and denominator. # The old metric gated on a 500 cm^-1 tolerance and divided by the # matched count, so "match one peak, ignore the rest" scored 0.0. return peak_rmse(observed, np.array([e for e, _a, _s in candidates])) # 4. Multi-start, then REFUSE a result that never escaped the penalty region. # `result.success` alone is not enough -- see (a). if result.fun >= base: raise ValueError("fit never escaped the penalty region ...") ``` -------------------------------- ### Over-engineered Spectrum class approach Source: https://github.com/anselmoo/tanabesugano/blob/main/docs/SPECTRUM_FITTING_PATTERN.md Shows a class-based design for spectrum fitting that is considered over-engineered. Problems include state bloat, tight coupling to a hardcoded optimizer, unclear computation triggers, and over-abstraction. ```python # โŒ Over-engineered: Spectrum as a class class Spectrum: def __init__(self, observed_peaks, d_count): self.observed_peaks = observed_peaks self.d_count = d_count self._optimizer = self._choose_optimizer() # Premature commitment def _choose_optimizer(self): return "Nelder-Mead" # Hardcoded; no flexibility def fit(self): # ... fitting logic spectrum = Spectrum([...], 8) result = spectrum.fit() ``` -------------------------------- ### Test: Real Coordination Complex Data Source: https://github.com/anselmoo/tanabesugano/blob/main/docs/SPECTRUM_FITTING_PATTERN.md Validates the spectrum fitting pattern using literature data for [Ni(Hโ‚‚O)โ‚†]ยฒโบ. Asserts that recovered Dq and B parameters are physically sensible for an aqua nickel complex. ```python def test_nickel_aqua_complex(self) -> None: """Fit [Ni(Hโ‚‚O)โ‚†]ยฒโบ from literature absorption data. Literature: - Wavelengths: 450 nm (22,222 cmโปยน), 700 nm (14,286 cmโปยน) - Appears green: absorbs blue and red """ observed_peaks = [10**7 / 450, 10**7 / 700] fit = fit_spectrum(8, observed_peaks) # Assertion: recovered parameters are physically sensible assert 4500 < dq < 6000, f"Dq={dq:.0f} unreasonable for aqua Niยฒโบ" assert 500 < b < 800, f"B={b:.0f} unreasonable for Niยฒโบ" ``` -------------------------------- ### LevelSet.for_term(term) Source: https://github.com/anselmoo/tanabesugano/blob/main/README.md Returns a list of levels matching the given term label. Useful for selecting specific excited states. ```APIDOC ## [Python] LevelSet.for_term(term) ### Description Returns a list of levels matching the given term label. Useful for selecting specific excited states. ### Method Python method ### Endpoint LevelSet.for_term ### Parameters #### Arguments - **term** (str) - Required - Term label (e.g., "3_T_1") ### Response #### Success Response Returns a list of Level objects. #### Response Example ```python excited = manifold.for_term("3_T_1")[1] print(manifold.transition_unicode(excited)) # 3A_2g -> 3T_1g(P) ``` ``` -------------------------------- ### Objective Function Closure Captures Strategy State Source: https://github.com/anselmoo/tanabesugano/blob/main/docs/SPECTRUM_FITTING_PATTERN.md Defines the objective function for spectrum fitting, capturing observed peaks, bounds, configuration, and helper functions from the parent scope. This implements the Strategy pattern without a class, as the closure itself is the strategy. ```python def objective(params: np.ndarray) -> float: dq, b = params # Closure sees these from parent scope: # - observed (input peaks) # - dq_bounds, b_bounds (constraints) # - d_count, C (configuration) # - compute_point() (helper function) ... ``` -------------------------------- ### Solve d8 manifold with LevelSet.solve Source: https://github.com/anselmoo/tanabesugano/blob/main/README.md Solves the d8 manifold at a single ligand-field strength using the Python API. Returns a LevelSet (not a dict) with typed level objects carrying free-ion parentage; call .as_dict() for the previous shape or iterate .levels. The output shows ground label, level count, total degeneracy, and spin-allowed transition energies. ```python from tanabesugano.levels import LevelSet # Solve the d8 manifold at one ligand-field strength. manifold = LevelSet.solve(8, dq=850.0, b=1030.0, c=4850.0) print(manifold.ground.label) # 3_A_2 print(manifold.level_count) # 11 levels ... print(manifold.total_degeneracy) # ... accounting for C(10,8) = 45 microstates # Levels are typed objects, not bare arrays, and carry free-ion parentage: # 3T_1g(F) / 3T_1g(P), the notation the literature uses, rather than a # positional (a)/(b). for level in manifold.spin_allowed(): print(f"{level.parent_unicode:10} {level.energy_cm1:9.1f} cm-1") # 3T_2g 8500.0 cm-1 <- nu1 = 10Dq exactly, for d3 and d8 # 3T_1g(F) 14283.0 cm-1 # 3T_1g(P) 26667.0 cm-1 # Name a transition the way a caption would. excited = manifold.for_term("3_T_1")[1] print(manifold.transition_unicode(excited)) # 3A_2g -> 3T_1g(P) ``` -------------------------------- ### LevelSet.spin_allowed() Source: https://github.com/anselmoo/tanabesugano/blob/main/README.md Iterates over spin-allowed levels in the manifold. Each level is a typed object with parentage and energy information. ```APIDOC ## [Python] LevelSet.spin_allowed() ### Description Iterates over spin-allowed levels in the manifold. Each level is a typed object with parentage and energy information. ### Method Python method ### Endpoint LevelSet.spin_allowed ### Parameters None ### Response #### Success Response Returns an iterator of Level objects. #### Response Example ```python for level in manifold.spin_allowed(): print(f"{level.parent_unicode:10} {level.energy_cm1:9.1f} cm-1") # 3T_2g 8500.0 cm-1 <- nu1 = 10Dq exactly, for d3 and d8 # 3T_1g(F) 14283.0 cm-1 # 3T_1g(P) 26667.0 cm-1 ``` ``` -------------------------------- ### LevelSet.solve(d_count, dq, b, c) Source: https://github.com/anselmoo/tanabesugano/blob/main/README.md Solves the Tanabe-Sugano manifold for a given d-electron count and ligand-field strength. Returns a LevelSet object containing energy levels and their properties. ```APIDOC ## [Python] LevelSet.solve(d_count, dq, b, c) ### Description Solves the Tanabe-Sugano manifold for a given d-electron count and ligand-field strength. Returns a LevelSet object containing energy levels and their properties. ### Method Python method ### Endpoint LevelSet.solve ### Parameters #### Arguments - **d_count** (int) - Required - Number of d electrons (e.g., 8) - **dq** (float) - Required - 10Dq crystal field splitting in cm-1 (e.g., 850.0) - **b** (float) - Required - Racah parameter B in cm-1 (e.g., 1030.0) - **c** (float) - Required - Racah parameter C in cm-1 (e.g., 4850.0) ### Response #### Success Response Returns a LevelSet object. #### Response Example ```python manifold = LevelSet.solve(8, dq=850.0, b=1030.0, c=4850.0) print(manifold.ground.label) # 3_A_2 print(manifold.level_count) # 11 levels ... print(manifold.total_degeneracy) # ... accounting for C(10,8) = 45 microstates ``` ``` -------------------------------- ### Regenerate committed artifacts with poe tasks Source: https://github.com/anselmoo/tanabesugano/blob/main/CLAUDE.md Regenerate every committed artifact using dedicated poe tasks. The regen-diagrams-check task is the CI gate that fails on drift. ```bash uv run poe regen-all # every committed artifact uv run poe regen-diagrams # ts-diagrams CSVs, .html diagrams, manifest.json uv run poe regen-diagrams-check # fail on drift -- this is the CI gate uv run poe regen-diagrams-offline # self-contained .html with a local plotly.min.js uv run poe regen-examples # examples/ tables + the two README figures uv run poe regen-gif # re-record the README's interactive GIF (needs a browser) uv run poe regen-uvvis # assets/uvvis reference figures ```