当前位置: 首页 > Skill >

SciPy

SciPy

SciPy

使用 SciPy 教程和可直接运行的代码,解决优化、统计、信号处理和线性代数问题。

1.0.0 2026.11.15 272
获取Skill文件查看使用说明
作 者:沈辰 许可证: 更新时间:2026.11.15
本文目录展开

Setup

On first use, read setup.md for guidance on how to help the user effectively.

When to Use

User needs scientific computing in Python: optimization, curve fitting, statistical tests, signal processing, interpolation, integration, or linear algebra. Agent provides working code, not theory.

Architecture

This skill is stateless — no persistent storage needed. All code runs in user's Python environment.

See memory-template.md for optional preference tracking.

Quick Reference

Topic File
Usage guidance setup.md
Optional preferences memory-template.md

Core Rules

1. Working Code First

Every response includes runnable code. No pseudocode, no "implement this yourself".

# Always include imports
from scipy import optimize
import numpy as np

# Complete, working example
result = optimize.minimize(lambda x: x**2, x0=1.0)
print(f"Minimum at x={result.x[0]:.4f}")

2. Module Selection Guide

Problem Module Key Function
Find minimum/maximum scipy.optimize minimize, minimize_scalar
Curve fitting scipy.optimize curve_fit
Root finding scipy.optimize root, brentq, fsolve
Statistical tests scipy.stats ttest_ind, chi2_contingency
Distributions scipy.stats norm, poisson, expon
Filter signals scipy.signal butter, filtfilt, savgol_filter
FFT scipy.fft fft, ifft, fftfreq
Interpolation scipy.interpolate interp1d, UnivariateSpline
Integration scipy.integrate quad, solve_ivp
Linear algebra scipy.linalg solve, eig, svd
Sparse matrices scipy.sparse csr_matrix, linalg.spsolve
Spatial data scipy.spatial KDTree, distance
Image processing scipy.ndimage gaussian_filter, label

3. Explain Key Parameters

When code uses non-obvious parameters, explain why:

# method='L-BFGS-B' for bounded optimization
# bounds prevent physically impossible values
result = optimize.minimize(
    objective, x0, 
    method='L-BFGS-B',
    bounds=[(0, None), (0, 100)]  # x1 >= 0, 0 <= x2 <= 100
)

4. Validate Results

Always include sanity checks:

result = optimize.minimize(func, x0)
if not result.success:
    print(f"⚠️ Optimization failed: {result.message}")
else:
    print(f"✓ Converged in {result.nit} iterations")

5. NumPy Integration

SciPy builds on NumPy. Use vectorized operations:

# ✓ Vectorized (fast)
x = np.linspace(0, 10, 1000)
y = np.sin(x)

# ✗ Loop (slow)
y = [np.sin(xi) for xi in x]

Optimization Patterns

Minimize a Function

from scipy.optimize import minimize
import numpy as np

# Rosenbrock function (classic test)
def rosenbrock(x):
    return sum(100*(x[1:]-x[:-1]**2)**2 + (1-x[:-1])**2)

x0 = np.array([0, 0])
result = minimize(rosenbrock, x0, method='BFGS')

print(f"Minimum at: {result.x}")
print(f"Function value: {result.fun}")
print(f"Converged: {result.success}")

Constrained Optimization

from scipy.optimize import minimize

# Minimize f(x,y) = x² + y² subject to x + y = 1
def objective(x):
    return x[0]**2 + x[1]**2

def constraint(x):
    return x[0] + x[1] - 1  # Must equal 0

result = minimize(
    objective, 
    x0=[0.5, 0.5],
    constraints={'type': 'eq', 'fun': constraint}
)

Curve Fitting

from scipy.optimize import curve_fit
import numpy as np

# Fit exponential decay
def model(t, a, tau):
    return a * np.exp(-t / tau)

t_data = np.array([0, 1, 2, 3, 4, 5])
y_data = np.array([10, 6.1, 3.7, 2.2, 1.4, 0.8])

params, covariance = curve_fit(model, t_data, y_data)
a_fit, tau_fit = params
errors = np.sqrt(np.diag(covariance))

print(f"a = {a_fit:.2f} ± {errors[0]:.2f}")
print(f"τ = {tau_fit:.2f} ± {errors[1]:.2f}")

Statistics Patterns

Hypothesis Testing

from scipy import stats

# Compare two groups (independent t-test)
group_a = [23, 25, 28, 24, 26]
group_b = [30, 32, 29, 31, 33]

t_stat, p_value = stats.ttest_ind(group_a, group_b)
print(f"t = {t_stat:.3f}, p = {p_value:.4f}")

if p_value < 0.05:
    print("✓ Significant difference (p < 0.05)")
else:
    print("✗ No significant difference")

Distribution Fitting

from scipy import stats
import numpy as np

data = np.random.exponential(scale=2.0, size=1000)

# Fit exponential distribution
loc, scale = stats.expon.fit(data)
print(f"Fitted scale (λ⁻¹): {scale:.3f}")

# Test goodness of fit
ks_stat, ks_p = stats.kstest(data, 'expon', args=(loc, scale))
print(f"KS test: p = {ks_p:.4f}")

Confidence Intervals

from scipy import stats
import numpy as np

data = [2.3, 2.5, 2.1, 2.8, 2.4, 2.6, 2.2]
confidence = 0.95

mean = np.mean(data)
sem = stats.sem(data)
ci = stats.t.interval(confidence, len(data)-1, loc=mean, scale=sem)

print(f"Mean: {mean:.2f}")
print(f"95% CI: [{ci[0]:.2f}, {ci[1]:.2f}]")

Signal Processing Patterns

Low-Pass Filter

from scipy import signal
import numpy as np

# Create noisy signal
fs = 1000  # Sample rate
t = np.linspace(0, 1, fs)
clean = np.sin(2 * np.pi * 10 * t)  # 10 Hz
noisy = clean + 0.5 * np.random.randn(len(t))

# Design and apply Butterworth filter
cutoff = 20  # Hz
order = 4
b, a = signal.butter(order, cutoff / (fs/2), btype='low')
filtered = signal.filtfilt(b, a, noisy)  # Zero-phase filtering

FFT Analysis

from scipy.fft import fft, fftfreq
import numpy as np

# Sample signal
fs = 1000
t = np.linspace(0, 1, fs)
signal_data = np.sin(2*np.pi*50*t) + 0.5*np.sin(2*np.pi*120*t)

# Compute FFT
yf = fft(signal_data)
xf = fftfreq(len(t), 1/fs)

# Get magnitude spectrum (positive frequencies only)
n = len(t) // 2
freqs = xf[:n]
magnitudes = 2/n * np.abs(yf[:n])

# Find dominant frequency
peak_idx = np.argmax(magnitudes)
print(f"Dominant frequency: {freqs[peak_idx]:.1f} Hz")

Interpolation Patterns

1D Interpolation

from scipy.interpolate import interp1d, UnivariateSpline
import numpy as np

x = np.array([0, 1, 2, 3, 4, 5])
y = np.array([0, 0.8, 0.9, 0.1, -0.8, -1])

# Linear interpolation
f_linear = interp1d(x, y, kind='linear')

# Cubic interpolation (smoother)
f_cubic = interp1d(x, y, kind='cubic')

# Smoothing spline (handles noise)
spline = UnivariateSpline(x, y, s=0.5)

x_new = np.linspace(0, 5, 100)
y_cubic = f_cubic(x_new)

Integration Patterns

Numerical Integration

from scipy.integrate import quad
import numpy as np

# Integrate sin(x) from 0 to π
result, error = quad(np.sin, 0, np.pi)
print(f"∫sin(x)dx from 0 to π = {result:.6f} ± {error:.2e}")
# Expected: 2.0

Solve ODE

from scipy.integrate import solve_ivp
import numpy as np

# dy/dt = -2y, y(0) = 1 (exponential decay)
def dydt(t, y):
    return -2 * y

sol = solve_ivp(dydt, [0, 5], [1], t_eval=np.linspace(0, 5, 100))

# sol.t contains time points
# sol.y[0] contains y values

Linear Algebra Patterns

Solve Linear System

from scipy import linalg
import numpy as np

# Solve Ax = b
A = np.array([[3, 1], [1, 2]])
b = np.array([9, 8])

x = linalg.solve(A, b)
print(f"Solution: x = {x}")

# Verify
print(f"Check A @ x = {A @ x}")

Eigendecomposition

from scipy import linalg
import numpy as np

A = np.array([[1, 2], [2, 1]])
eigenvalues, eigenvectors = linalg.eig(A)

print(f"Eigenvalues: {eigenvalues}")
print(f"Eigenvectors:n{eigenvectors}")

Common Traps

  • Wrong bounds format in minimize → bounds must be list of (min, max) tuples, one per variable
  • Forgetting to check result.success → optimization can fail silently, always check
  • Using interp1d outside data range → raises error by default, use fill_value='extrapolate' or bounds_error=False
  • filtfilt vs lfilter → use filtfilt for zero-phase filtering, lfilter introduces phase shift
  • curve_fit with bad initial guess → can converge to wrong solution, always provide reasonable p0
  • Integer division in Python 3 → use x / 2 not x // 2 for float division in formulas

Security & Privacy

Data that stays local:

  • All computations run in user's Python environment
  • No data leaves the machine

This skill does NOT:

  • Send data externally
  • Create persistent files
  • Access network resources

Related Skills

Install with clawhub install <slug> if user confirms:

  • math — mathematical concepts
  • data-analysis — data exploration
  • data — data handling patterns

Feedback

  • If useful: clawhub star scipy
  • Stay updated: clawhub sync

推荐文章

更多
PHP时间戳与日期字符串相互转换方法详解

本文介绍PHP中时间数值(Unix时间戳)与日期字符串之间的相互转换方法。通过strtotime和date函数,实现将当前时间、指定日期转换为时间戳,以及将时间戳格式化为可读的日期时间字符串,并提供相关在线计算工具推荐。

2025.11.30 1,035
PHP日期转时间戳时区偏差怎么解决

在 PHP 中将日期字符串转换为时间戳时,若未显式指定时区,默认使用脚本配置的 date.timezone 或系统时区。当服务器时区与业务逻辑预期(如 UTC )不一致时,会产生偏差。解决核心是确保输入字符串携带明确时区信息,或在转换前统一设置时区上下文。

2026.10.24 1,031
PHP跨域配置:怎么安全地允许指定域名而非使用通配符

在 PHP 中安全地允许指定域名跨域,核心是解析请求头中的 Origin ,验证其是否在白名单内,然后动态设置 Access-Control-Allow-Origin 响应头。不要使用通配符 * ,也不要硬编码单一域名。

2025.03.29 1,019
JavaScript中利用replace结合正则实现replaceAll效果

JavaScript原生仅支持replace()进行单次或全局替换,缺乏类似Java的replaceAll()便捷方法。本文总结四种在JS中实现全量替换的方案:使用带g标志的正则、带gm标志的正则、扩展String原型以及split后join。通过对比代码示例,展示各方法的实现细节与适用场景,帮助开发者根据需求选择最优解。

2025.04.29 1,017
OpenAI的Jalapeno芯片未落地,教你分辨300兆瓦算力消息

OpenAI计划在SB Energy租赁的数据中心部署约300兆瓦自研Jalapeno推理芯片,但目前双方仍处于洽谈阶段,交易细节与上线时间表均未公布。本文带你按报道原文核实项目所处阶段,厘清芯片发布、电力功率与实际推理算力的边界,并将融资意向与签约、开工、投运节点分开追踪,避免误将规划容量计入现有算力。

2026.12.02 1,014
PHP实现基础文件上传:HTML表单与$_FILES处理流程

在 HTML 表单中设置 enctype="multipart/form-data" ,并在 PHP 后端通过 $_FILES 数组接收文件,调用 move_uploaded_file() 将临时文件移动到目标目录即可完成上传。

2026.09.07 1,014
Skill 文件
  • SKILL.md
    • Setup
    • When to Use
    • Architecture
    • Quick Reference
    • Core Rules
      • 1. Working Code First
      • 2. Module Selection Guide
      • 3. Explain Key Parameters
      • 4. Validate Results
      • 5. NumPy Integration
    • Optimization Patterns
      • Minimize a Function
      • Constrained Optimization
      • Curve Fitting
    • Statistics Patterns
      • Hypothesis Testing
      • Distribution Fitting
      • Confidence Intervals
    • Signal Processing Patterns
      • Low-Pass Filter
      • FFT Analysis
    • Interpolation Patterns
      • 1D Interpolation
    • Integration Patterns
      • Numerical Integration
      • Solve ODE
    • Linear Algebra Patterns
      • Solve Linear System
      • Eigendecomposition
    • Common Traps
    • Security & Privacy
    • Related Skills
    • Feedback
  • 项目或源文件

相关 Skill

更多
service-qa-coach service-qa-coach Review support quality for chat, email, phone, social DM, or marketplace service teams. Use when a team needs a QA scorecard, failure-mode analysis, coaching plan, calibration checklist, or service-improvement brief without live ticketing, CRM, or contact-center system access.
高中数学作业批改助手 高中数学作业批改助手 >图片识别 直接读取学生手写作答照片,识别公式、符号、步骤 🧮 自动推导 根据题目自动生成参考答案和评分细则,无需教师预设 📊 逐步给分 每个关键步骤独立评分,体现过程分 📝 结构化报告 输出含识别内容、参考答案、逐步评分、改进建议的完整报告 🗂 批量批改 支持一次性批改多道题,最终汇总得分表
Vibration Analysis Vibration Analysis 分析来自CMS趋势、RMS/峰值、频谱及SCADA报警的风机传动链(主轴、齿轮箱、发电机)振动数据。
Traditional Bone Tool Making Basics Traditional Bone Tool Making Basics Use when you need custom, durable, repairable tools like awls, needles, scrapers, harpoons, or fishing hooks made from local animal bones or antlers and comm...
音频混音工具 音频混音工具 名称:Sound Mixing Tool(标识 sound-mixing-tool) 短简介(≤60字):音乐/音效响度精确对齐 + 融合混音工作流:用 ffmpeg 两段式 loudnorm 把多组素材 LUFS 偏差压到 <0.10,再最小干预融合、导出可进引擎的独立分轨。 标签/关键词:音频混音 响度匹配 LUFS ffmpeg 游戏音频 音效设计 Wwise FMOD 分轨导出 后期处理 触发词:混音 · 响度匹配 · LUFS 对齐 · MIX 版本 · 音乐音效分轨 · 融合 · 不打架 · 不能盖住 适用场景 :游戏音频集成、影视短视频配乐、播客后期