scipy-curve-fit

0
0
Source

Use scipy.optimize.curve_fit for nonlinear least squares parameter estimation from experimental data.

Install

mkdir -p .claude/skills/scipy-curve-fit && curl -L -o skill.zip "https://mcp.directory/api/skills/download/5775" && unzip -o skill.zip -d .claude/skills/scipy-curve-fit && rm skill.zip

Installs to .claude/skills/scipy-curve-fit

About this skill

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

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

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:

# 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:

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

Calculating Fit Quality

R-squared (Coefficient of Determination)

# 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)

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

Complete Example

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

latex-writing

benchflow-ai

Guide LaTeX document authoring following best practices and proper semantic markup. Use proactively when: (1) writing or editing .tex files, (2) writing or editing .nw literate programming files, (3) literate-programming skill is active and working with .nw files, (4) user mentions LaTeX, BibTeX, or document formatting, (5) reviewing LaTeX code quality. Ensures proper use of semantic environments (description vs itemize), csquotes (\enquote{} not ``...''), and cleveref (\cref{} not \S\ref{}).

4935

geospatial-analysis

benchflow-ai

Analyze geospatial data using geopandas with proper coordinate projections. Use when calculating distances between geographic features, performing spatial filtering, or working with plate boundaries and earthquake data.

287

pytorch

benchflow-ai

Building and training neural networks with PyTorch. Use when implementing deep learning models, training loops, data pipelines, model optimization with torch.compile, distributed training, or deploying PyTorch models.

305

search-flights

benchflow-ai

Search flights by origin, destination, and departure date using the bundled flights dataset. Use this skill when proposing flight options or checking whether a route/date combination exists.

214

d3js-visualization

benchflow-ai

Build deterministic, verifiable data visualizations with D3.js (v6). Generate standalone HTML/SVG (and optional PNG) from local data files without external network dependencies. Use when tasks require charts, plots, axes/scales, legends, tooltips, or data-driven SVG output.

174

deep-learning

benchflow-ai

PyTorch, TensorFlow, neural networks, CNNs, transformers, and deep learning for production

83

You might also like

flutter-development

aj-geddes

Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.

643969

drawio-diagrams-enhanced

jgtolentino

Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.

591705

ui-ux-pro-max

nextlevelbuilder

"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."

318398

godot

bfollington

This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.

339397

nano-banana-pro

garg-aayush

Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.

451339

fastapi-templates

wshobson

Create production-ready FastAPI projects with async patterns, dependency injection, and comprehensive error handling. Use when building new FastAPI applications or setting up backend API projects.

304231

Stay ahead of the MCP ecosystem

Get weekly updates on new skills and servers.