or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

classification.mdindex.mdmisc.mdmorphological.mdoptimizers.mdpolynomial.mdsmooth.mdspline.mdtwo-d.mdwhittaker.md

two-d.mddocs/

0

# Two-Dimensional (2D) Methods

1

2

Baseline correction algorithms designed for 2D data arrays such as images, spectroscopic maps, chromatographic surfaces, and other spatially-resolved measurements. These methods extend 1D algorithms to handle spatial correlation and provide consistent baseline correction across both dimensions while preserving important spatial features.

3

4

## Capabilities

5

6

### Baseline2D Class

7

8

The main interface for 2D baseline correction, providing access to all two-dimensional variants of baseline correction algorithms.

9

10

```python { .api }

11

class Baseline2D:

12

"""

13

Main interface for 2D baseline correction algorithms.

14

15

Provides object-oriented access to two-dimensional versions of most 1D baseline

16

correction methods, with additional capabilities for handling spatial data.

17

18

Parameters:

19

- x_data (array-like, optional): x-coordinates of the 2D grid

20

- z_data (array-like, optional): z-coordinates of the 2D grid

21

- check_finite (bool, default=True): Check for finite values in input data

22

- assume_sorted (bool, default=False): Assume coordinate arrays are sorted

23

- output_dtype (type, optional): Data type for output arrays

24

25

Attributes:

26

- x (numpy.ndarray): x-coordinates for the 2D grid

27

- x_domain (numpy.ndarray): [x_min, x_max] coordinate range

28

- z (numpy.ndarray): z-coordinates for the 2D grid

29

- z_domain (numpy.ndarray): [z_min, z_max] coordinate range

30

31

Methods:

32

- All 1D baseline correction methods adapted for 2D data

33

- _get_method(method_name): Access methods by string name for programmatic use

34

"""

35

```

36

37

### 2D Whittaker Methods

38

39

Two-dimensional versions of Whittaker-smoothing based algorithms that apply penalized least squares with 2D smoothness constraints.

40

41

```python { .api }

42

# Available 2D Whittaker methods:

43

# - asls_2d: 2D Asymmetric Least Squares

44

# - iasls_2d: 2D Improved AsLS

45

# - airpls_2d: 2D Adaptive Iteratively Reweighted PLS

46

# - arpls_2d: 2D Asymmetrically Reweighted PLS

47

# - drpls_2d: 2D Doubly Reweighted PLS

48

# - iarpls_2d: 2D Improved arPLS

49

# - aspls_2d: 2D Adaptive Smoothness PLS

50

# - psalsa_2d: 2D Peaked Signal's AsLS Algorithm

51

# - derpsalsa_2d: 2D Derivative Peak-Screening AsLS

52

53

def asls_2d(data, lam=1e6, p=1e-2, diff_order=2, max_iter=50, tol=1e-3, weights=None, x_data=None, z_data=None):

54

"""

55

2D Asymmetric Least Squares baseline correction.

56

57

Applies AsLS algorithm to 2D data with smoothness penalties in both dimensions,

58

preserving spatial correlation while correcting baseline variations.

59

60

Parameters:

61

- data (array-like): 2D input array to fit baseline (shape: [x_points, z_points])

62

- lam (float or tuple): Smoothing parameter(s). If float, same for both dimensions.

63

If tuple: (lam_x, lam_z) for dimension-specific smoothing

64

- p (float): Asymmetry parameter for peak-baseline separation

65

- diff_order (int or tuple): Order of difference penalty. Single int or (order_x, order_z)

66

- max_iter (int): Maximum iterations for convergence

67

- tol (float): Convergence tolerance for iterative fitting

68

- weights (array-like, optional): 2D weight array matching data dimensions

69

- x_data (array-like, optional): x-coordinate values

70

- z_data (array-like, optional): z-coordinate values

71

72

Returns:

73

tuple: (baseline_2d, params) with 2D baseline array and processing parameters

74

"""

75

```

76

77

### 2D Polynomial Methods

78

79

Polynomial surface fitting methods that extend 1D polynomial approaches to 2D surfaces with various robustness strategies.

80

81

```python { .api }

82

# Available 2D Polynomial methods:

83

# - poly_2d: 2D polynomial surface fitting

84

# - modpoly_2d: 2D modified polynomial with iterative masking

85

# - imodpoly_2d: 2D improved modified polynomial

86

# - penalized_poly_2d: 2D penalized polynomial with robust fitting

87

# - quant_reg_2d: 2D quantile regression polynomial

88

# - goldindec_2d: 2D Goldindec algorithm

89

90

def poly_2d(data, poly_order=(2, 2), weights=None, return_coef=False, x_data=None, z_data=None):

91

"""

92

2D polynomial surface baseline fitting.

93

94

Fits polynomial surfaces to 2D data for baseline correction, allowing

95

different polynomial orders in each dimension.

96

97

Parameters:

98

- data (array-like): 2D input array to fit baseline

99

- poly_order (int or tuple): Polynomial order. If int, same for both dimensions.

100

If tuple: (order_x, order_z) for each dimension

101

- weights (array-like, optional): 2D weight array for data points

102

- return_coef (bool): Whether to return surface coefficients

103

- x_data (array-like, optional): x-coordinate values

104

- z_data (array-like, optional): z-coordinate values

105

106

Returns:

107

tuple: (baseline_surface, params) with optional coefficient matrix

108

"""

109

```

110

111

### 2D Smooth Methods

112

113

Smoothing-based 2D algorithms using morphological and statistical operations adapted for spatial data.

114

115

```python { .api }

116

# Available 2D Smooth methods:

117

# - noise_median_2d: 2D noise-median smoothing

118

# - snip_2d: 2D SNIP algorithm

119

# - swima_2d: 2D small-window moving average

120

# - ipsa_2d: 2D Iterative Polynomial Smoothing

121

# - ria_2d: 2D Range Independent Algorithm

122

123

def snip_2d(data, max_half_window=None, decreasing=False, smooth_half_window=None, filter_order=2, x_data=None, z_data=None):

124

"""

125

2D Statistical Sensitive Non-linear Iterative Peak algorithm.

126

127

Applies SNIP baseline correction to 2D data using morphological operations

128

that preserve spatial features while removing baseline variations.

129

130

Parameters:

131

- data (array-like): 2D input array to correct

132

- max_half_window (int or tuple): Maximum half-window size for operations

133

If int, same for both dimensions

134

- decreasing (bool): Whether to use decreasing window sizes

135

- smooth_half_window (int or tuple): Smoothing window size

136

- filter_order (int): Order of smoothing filter

137

- x_data (array-like, optional): x-coordinate values

138

- z_data (array-like, optional): z-coordinate values

139

140

Returns:

141

tuple: (baseline_2d, params) with spatial processing details

142

"""

143

```

144

145

### 2D Morphological Methods

146

147

Morphological operations extended to 2D for baseline correction using structural elements and spatial filtering.

148

149

```python { .api }

150

# Available 2D Morphological methods:

151

# - mpls_2d: 2D morphological penalized least squares

152

# - mor_2d: 2D morphological opening

153

# - imor_2d: 2D improved morphological baseline

154

# - mormol_2d: 2D morphological with mollification

155

# - amormol_2d: 2D averaging morphological with mollification

156

# - rolling_ball_2d: 2D rolling ball baseline

157

# - mwmv_2d: 2D moving window minimum value

158

# - tophat_2d: 2D top-hat morphological baseline

159

160

def rolling_ball_2d(data, half_window=None, x_data=None, z_data=None):

161

"""

162

2D rolling ball baseline correction.

163

164

Applies morphological rolling ball operation in 2D to estimate baseline

165

by simulating a ball rolling under the data surface.

166

167

Parameters:

168

- data (array-like): 2D input array to correct

169

- half_window (int or tuple): Half-size of rolling ball structuring element

170

If int, creates circular ball. If tuple: (radius_x, radius_z)

171

- x_data (array-like, optional): x-coordinate values

172

- z_data (array-like, optional): z-coordinate values

173

174

Returns:

175

tuple: (baseline_2d, params) with morphological operation details

176

"""

177

```

178

179

### 2D Spline Methods

180

181

Spline-based methods extended to 2D using tensor product B-splines for flexible surface modeling.

182

183

```python { .api }

184

# Available 2D Spline methods:

185

# - mixture_model_2d: 2D mixture model splines

186

# - irsqr_2d: 2D iterative reweighted spline quantile regression

187

# - pspline_asls_2d: 2D penalized spline AsLS

188

# - pspline_iasls_2d: 2D penalized spline IAsLS

189

# - pspline_airpls_2d: 2D penalized spline airPLS

190

191

def mixture_model_2d(data, lam=1e5, p=1e-2, num_knots=(10, 10), spline_degree=(3, 3), diff_order=(3, 3), max_iter=50, tol=1e-3, weights=None):

192

"""

193

2D mixture model baseline using tensor product splines.

194

195

Estimates 2D baseline using spline surfaces with mixture model approach

196

for optimal baseline-peak separation across spatial dimensions.

197

198

Parameters:

199

- data (array-like): 2D input array to fit baseline

200

- lam (float or tuple): Smoothing parameter(s) for spline regularization

201

- p (float): Asymmetry parameter for mixture model

202

- num_knots (int or tuple): Number of knots in each dimension

203

- spline_degree (int or tuple): Degree of spline basis in each dimension

204

- diff_order (int or tuple): Order of difference penalty in each dimension

205

- max_iter (int): Maximum iterations for convergence

206

- tol (float): Convergence tolerance

207

- weights (array-like, optional): 2D weight array

208

209

Returns:

210

tuple: (baseline_surface, params) with spline fitting details

211

"""

212

```

213

214

## Usage Examples

215

216

### Basic 2D baseline correction:

217

218

```python

219

import numpy as np

220

from pybaselines.two_d import Baseline2D

221

222

# Create sample 2D spectroscopic map data

223

x = np.linspace(0, 100, 50)

224

z = np.linspace(0, 100, 50)

225

X, Z = np.meshgrid(x, z, indexing='ij')

226

227

# Create 2D baseline surface with spatial variation

228

baseline_2d = 10 + 0.1*X + 0.05*Z + 0.001*X*Z

229

230

# Add 2D peaks (e.g., spatial features in spectroscopic map)

231

peak1 = 50 * np.exp(-((X-25)**2 + (Z-25)**2) / 200)

232

peak2 = 40 * np.exp(-((X-75)**2 + (Z-75)**2) / 150)

233

data_2d = baseline_2d + peak1 + peak2 + np.random.normal(0, 1, X.shape)

234

235

# Initialize 2D baseline correction

236

baseline_2d_corrector = Baseline2D(x_data=x, z_data=z)

237

238

# Apply 2D AsLS baseline correction

239

baseline_est, params = baseline_2d_corrector.asls(data_2d, lam=1e5, p=0.01)

240

corrected_2d = data_2d - baseline_est

241

242

print(f"2D baseline shape: {baseline_est.shape}")

243

print(f"Spatial correlation preserved: {params.get('spatial_consistency', True)}")

244

```

245

246

### 2D morphological baseline correction:

247

248

```python

249

# Rolling ball method for 2D chromatographic data

250

baseline_morph, params_morph = baseline_2d_corrector.rolling_ball(data_2d, half_window=5)

251

corrected_morph = data_2d - baseline_morph

252

253

# 2D SNIP for spectroscopic imaging

254

baseline_snip, params_snip = baseline_2d_corrector.snip(data_2d, max_half_window=8)

255

corrected_snip = data_2d - baseline_snip

256

```

257

258

### Dimension-specific parameter control:

259

260

```python

261

# Different smoothing in x and z directions

262

baseline_aniso, params_aniso = baseline_2d_corrector.asls(

263

data_2d,

264

lam=(1e5, 1e6), # Stronger smoothing in z-direction

265

diff_order=(2, 3) # Different penalty orders

266

)

267

corrected_aniso = data_2d - baseline_aniso

268

269

print("Applied anisotropic smoothing with dimension-specific parameters")

270

```

271

272

### 2D spline surface fitting:

273

274

```python

275

# Flexible spline surface baseline

276

baseline_spline, params_spline = baseline_2d_corrector.mixture_model(

277

data_2d,

278

num_knots=(8, 8), # 8x8 knot grid

279

spline_degree=(3, 3), # Cubic splines in both directions

280

lam=1e4

281

)

282

corrected_spline = data_2d - baseline_spline

283

284

print(f"Used {params_spline.get('total_knots', 64)} knots for 2D spline surface")

285

```

286

287

### Processing large 2D datasets efficiently:

288

289

```python

290

# For large spectroscopic imaging datasets

291

large_data = np.random.randn(200, 200) + np.sin(np.linspace(0, 10, 200))[:, None]

292

293

# Use efficient 2D polynomial for large data

294

baseline_large, params_large = baseline_2d_corrector.poly(

295

large_data,

296

poly_order=(3, 3) # Moderate polynomial order for efficiency

297

)

298

299

# Alternative: downsample for initial correction, then refine

300

downsampled = large_data[::4, ::4] # Downsample by factor of 4

301

baseline_down, _ = baseline_2d_corrector.asls(downsampled, lam=1e5)

302

303

# Upsample baseline back to full resolution

304

from scipy.interpolate import interp2d

305

f = interp2d(np.arange(0, 200, 4), np.arange(0, 200, 4), baseline_down.T, kind='cubic')

306

baseline_upsampled = f(np.arange(200), np.arange(200)).T

307

308

print("Efficient processing of large 2D datasets using downsampling approach")

309

```

310

311

### Region-specific 2D correction:

312

313

```python

314

# Apply different methods to different spatial regions

315

region1_data = data_2d[:25, :25] # Top-left quadrant

316

region2_data = data_2d[25:, 25:] # Bottom-right quadrant

317

318

# Different methods for different regions

319

baseline_r1, _ = baseline_2d_corrector.asls(region1_data, lam=1e5)

320

baseline_r2, _ = baseline_2d_corrector.rolling_ball(region2_data, half_window=3)

321

322

# Combine regional corrections

323

baseline_combined = np.zeros_like(data_2d)

324

baseline_combined[:25, :25] = baseline_r1

325

baseline_combined[25:, 25:] = baseline_r2

326

327

# Smooth transitions between regions using interpolation

328

print("Applied region-specific 2D baseline correction methods")

329

```