Skip to main content
skill CX Codex

scipy-curve-fit — Claude Code skill: what it does, how to install

scipy-curve-fit guides coding agents to estimate nonlinear model parameters from experimental data with scipy.optimize.curve_fit.

Apache-2.0 2 installs ★ 1,933 updated 2026-10-24

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add benchflow-ai/skillsbench --skill scipy-curve-fit -a claude-code
Open on GitHub

What scipy-curve-fit does

The skill provides reference implementations for nonlinear least squares parameter estimation in Python. It details how to set up scipy.optimize.curve_fit, configure parameter bounds, and choose initial guesses p0 to speed up convergence.

It focuses on fitting first-order step response models. The agent learns how to extract gain K and time constant tau, while evaluating fit quality through R-squared and root mean square error calculations.

Without scipy and numpy in the environment, the generated scripts fail immediately. If input measurements contain NaN values or poor initial guesses, the solver terminates with a RuntimeError.

What it helps with

  • Estimate parameters for nonlinear models using experimental test data
  • Define parameter bounds and initial guesses for curve_fit
  • Fit first-order step response models to identify gain K and time constant tau
  • Evaluate fitting accuracy using R-squared and RMSE metrics

Example prompts for the agent

  • Fit a first-order step response to experimental time and output arrays using scipy.optimize.curve_fit
  • Set initial guesses p0 and parameter bounds to prevent unrealistic values in curve_fit
  • Calculate R-squared and RMSE metrics for my fitted model predictions

How to install scipy-curve-fit

1Skills CLI (Vercel)

npx skills add benchflow-ai/skillsbench --skill scipy-curve-fit -a claude-code

2Manually: put the files in place

~/.claude/skills/scipy-curve-fit/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/scipy-curve-fit/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about scipy-curve-fit

How do I install scipy-curve-fit in Claude Code?

Run npx skills add benchflow-ai/skillsbench --skill scipy-curve-fit -a claude-code in your terminal. This creates the skill file at ~/.claude/skills/scipy-curve-fit/SKILL.md.

What does scipy-curve-fit do?

It teaches coding agents how to perform nonlinear least squares optimization using scipy.optimize.curve_fit. It includes templates for step response identification, constraints, and error metrics.

Why does curve_fit raise a RuntimeError?

This indicates that the optimization algorithm failed to converge. Supply closer initial values p0 and ensure your dataset has no missing or NaN entries.

Source text

SKILL.md · Apache-2.0
---
name: scipy-curve-fit
description: Use scipy.optimize.curve_fit for nonlinear least squares parameter estimation from experimental data.
---

# Using scipy.optimize.curve_fit for Parameter Estimation

## Overview

`scipy.optimize.curve_fit` is a tool for fitting models to experimental data using nonlinear least squares optimization.

## Basic Usage

```python
from scipy.optimize import curve_fit
import numpy as np

# Define your model function
def model(x, param1, param2):
    return param1 * (1 - np.exp(-x / param2))

# Fit to data
popt, pcov = curve_fit(model, x_data, y_data)

# popt contains the optimal parameters [param1, param2]
# pcov contains the covariance matrix
```

## Fitting a First-Order Step Response

```python
import numpy as np
from scipy.optimize import curve_fit

# Known values from experiment
y_initial = ...  # Initial output value
u = ...          # Input magnitude during step test

# Define the step response model
def step_response(t, K, tau):
    """First-order step response with fixed initial value and input."""
    return y_initial + K * u * (1 - np.exp(-t / tau))

# Your experimental data
t_data = np.array([...])  # Time points
y_data = np.array([...])  # Output readings

# Perform the fit
popt, pcov = curve_fit(
    step_response,
    t_data,
    y_data,
    p0=[K_guess, tau_guess],      # Initial guesses
    bounds=([K_min, tau_min], [K_max, tau_max])  # Parameter bounds
)

K_estimated, tau_estimated = popt
```

## Setting Initial Guesses (p0)

Good initial guesses speed up convergence:

```python
# Estimate K from steady-state data
K_guess = (y_data[-1] - y_initial) / u

# Estimate tau from 63.2% rise time
y_63 = y_initial + 0.632 * (y_data[-1] - y_initial)
idx_63 = np.argmin(np.abs(y_data - y_63))
tau_guess = t_data[idx_63]

p0 = [K_guess, tau_guess]
```

## Setting Parameter Bounds

Bounds prevent physically impossible solutions:

```python
bounds = (
    [lower_K, lower_tau],    # Lower bounds
    [upper_K, upper_tau]     # Upper bounds
)
```

## Calculating Fit Quality

### R-squared (Coefficient of Determination)

```python
# Predicted values from fitted model
y_predicted = step_response(t_data, K_estimated, tau_estimated)

# Calculate R-squared
ss_residuals = np.sum((y_data - y_predicted) ** 2)
ss_total = np.sum((y_data - np.mean(y_data)) ** 2)
r_squared = 1 - (ss_residuals / ss_total)
```

### Root Mean Square Error (RMSE)

```python
residuals = y_data - y_predicted
rmse = np.sqrt(np.mean(residuals ** 2))
```

## Complete Example

```python
import numpy as np
from scipy.optimize import curve_fit

def fit_first_order_model(data, y_initial, input_value):
    """
    Fit first-order model to step response data.

    Returns dict with K, tau, r_squared, fitting_error
    """
    t_data = np.array([d["time"] for d in data])
    y_data = np.array([d["output"] for d in data])

    def model(t, K, tau):
        return y_initial + K * input_value * (1 - np.exp(-t / tau))

    # Initial guesses
    K_guess = (y_data[-1] - y_initial) / input_value
    tau_guess = t_data[len(t_data)//3]  # Rough guess

    # Fit with bounds
    popt, _ = curve_fit(
        model, t_data, y_data,
        p0=[K_guess, tau_guess],
        bounds=([0, 0], [np.inf, np.inf])
    )

    K, tau = popt

    # Calculate quality metrics
    y_pred = model(t_data, K, tau)
    ss_res = np.sum((y_data - y_pred) ** 2)
    ss_tot = np.sum((y_data - np.mean(y_data)) ** 2)
    r_squared = 1 - (ss_res / ss_tot)
    fitting_error = np.sqrt(np.mean((y_data - y_pred) ** 2))

    return {
        "K": float(K),
        "tau": float(tau),
        "r_squared": float(r_squared),
        "fitting_error": float(fitting_error)
    }
```

## Common Issues

1. **RuntimeError**: Optimal parameters not found
   - Try better initial guesses
   - Check that data is valid (no NaN, reasonable range)

2. **Poor fit (low R^2)**:
   - Data might not be from step response phase
   - System might not be first-order
   - Too much noise in measurements

3. **Unrealistic parameters**:
   - Add bounds to constrain solution
   - Check units are consistent

© benchflow-ai · Apache-2.0 · benchflow-ai/skillsbench

Similar skills

All skills for Science and research →

From the same set22

The whole set →
reflow-machine-maintenance-guidance reflow-machine-maintenance-guidance handles reflow oven upkeep questions by computing ramp rates, time above liquidus and conveyor limits from thermocouple logs, MES data and the handbook. CX Codex +1 5installs text-to-speech The text-to-speech skill guides TTS cleanup, loudness matching, and segment timing for video audio exports. CX Codex +1 4installs civ6lib civ6lib validates Civilization 6 district placement and computes adjacency bonuses. Use it when an agent needs to reason about city layouts and game rules. CX Codex +1 2installs meteorology-driver-classification meteorology-driver-classification sorts the columns of an environmental dataset into heat, flow, wind and human drivers, so an attribution run can treat each group as one factor. CX Codex +1 2installs python-scala-idioms python-scala-idioms guides AI agents to translate Python into idiomatic Scala. Enforces immutability, pattern matching, sealed domain traits, and type-safe error handling. CX Codex +1 1installs first-order-model-fitting The first-order-model-fitting skill fits first-order models to experimental step responses and returns K and tau. Use it when you need a compact model of thermal, electrical, or mechanical behavior. CX Codex +1 1installs hex-grid-spatial hex-grid-spatial is a Claude Code skill that calculates neighbours, hex distance, and radius cells on odd-r offset maps for movement or area-of-effect logic. CX Codex +1 1installs python-scala-syntax-mapping python-scala-syntax-mapping is a Claude Code skill that maps Python syntax to Scala for coding assistants translating variables, comprehensions, and control structures. CX Codex +1 1installs

Project sponsors

Companies that keep this analytics open