SciPy is a collection of mathematical algorithms and convenience functions built on NumPy. It provides essential tools for scientific and technical computing, particularly for signal processing, optimization, and statistics.
Why SciPy?
- Comprehensive: Covers most scientific computing needs
- Efficient: Optimized implementations of algorithms
- Well-Tested: Reliable, production-ready code
- Integration: Works seamlessly with NumPy
- Modular: Import only what you need
Key Modules
Signal Processing (scipy.signal)
Essential for neural data analysis:
from scipy import signal
import numpy as np
# Filter a neural signal
b, a = signal.butter(4, [1, 100], 'bandpass', fs=1000)
filtered = signal.filtfilt(b, a, neural_data)
# Compute power spectral density
freqs, psd = signal.welch(lfp_signal, fs=1000)
# Find peaks in data
peaks, _ = signal.find_peaks(trace, height=threshold)
Fourier Transforms (scipy.fft)
from scipy.fft import fft, fftfreq
# Frequency analysis
spectrum = fft(signal)
frequencies = fftfreq(len(signal), 1/sampling_rate)
Optimization (scipy.optimize)
from scipy.optimize import minimize, curve_fit
# Fit function to data
def model(x, a, b):
return a * np.exp(-b * x)
params, _ = curve_fit(model, x_data, y_data)
Statistics (scipy.stats)
from scipy.stats import ttest_ind, pearsonr
# Statistical tests
t_stat, p_value = ttest_ind(group1, group2)
# Correlation
r, p = pearsonr(neural_activity, behavior)
Interpolation (scipy.interpolate)
from scipy.interpolate import interp1d
# Resample data
f = interp1d(old_times, values, kind='cubic')
new_values = f(new_times)
Common Use Cases in Neuroscience
LFP Analysis
- Bandpass filtering for specific frequency bands
- Hilbert transform for phase and amplitude
- Spectrogram for time-frequency analysis
- Coherence between signals
Spike Analysis
- Convolve with kernels for firing rate estimation
- Detect spike times from continuous recordings
- Cross-correlation for spike-field coupling
Calcium Imaging
- Deconvolve calcium traces to infer spikes
- Baseline correction and normalization
- Detect transient events
Getting Started
Install SciPy:
conda install scipy
# or
pip install scipy
Basic example:
from scipy import signal
import numpy as np
import matplotlib.pyplot as plt
# Generate noisy signal
t = np.linspace(0, 1, 1000)
clean = np.sin(2 * np.pi * 5 * t)
noisy = clean + 0.5 * np.random.randn(len(t))
# Filter signal
sos = signal.butter(4, 10, 'low', fs=1000, output='sos')
filtered = signal.sosfilt(sos, noisy)
# Plot
plt.plot(t, noisy, alpha=0.3, label='Noisy')
plt.plot(t, filtered, label='Filtered')
plt.legend()
plt.show()
Tips
- Use
signal.butterwithfiltfiltfor zero-phase filtering - Check Nyquist frequency before filtering (fs/2)
- Use
signal.welchinstead of raw FFT for power spectra - Choose appropriate window functions for spectral analysis
- Use
scipy.statsfor statistical tests before Pingouin - Consider
scipy.ndimagefor image processing tasks