or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

aggregation-methods.mdgallery.mdhigh-level-interface.mdindex.mdkrylov-methods.mdmultilevel-solver.mdrelaxation-methods.mdsolver-constructors.mdstrength-of-connection.mdutilities.md

gallery.mddocs/

0

# Test Problem Gallery

1

2

Comprehensive collection of test matrices and problems for AMG development and evaluation. The gallery includes PDE discretizations, finite element problems, and various test matrices commonly used in multigrid research.

3

4

## Capabilities

5

6

### Poisson Problems

7

8

Discrete Poisson operators on regular grids, fundamental test problems for multigrid methods.

9

10

```python { .api }

11

def poisson(grid, format='csr', dtype=float):

12

"""

13

Generate discrete Poisson operator on regular grid.

14

15

Creates finite difference discretization of -∇²u using

16

standard 5-point (2D) or 7-point (3D) stencils.

17

18

Parameters:

19

- grid: tuple, grid dimensions:

20

* (n,): 1D grid with n points

21

* (nx, ny): 2D grid with nx×ny points

22

* (nx, ny, nz): 3D grid with nx×ny×nz points

23

- format: str, sparse matrix format:

24

* 'csr': compressed sparse row (default)

25

* 'csc': compressed sparse column

26

* 'coo': coordinate format

27

* 'lil': list of lists format

28

- dtype: data type, float or complex

29

30

Returns:

31

sparse matrix: Poisson operator matrix

32

33

Raises:

34

ValueError: if grid dimensions are invalid

35

"""

36

37

def gauge_laplacian(grid, beta=0.1, format='csr', dtype=float):

38

"""

39

Generate gauge Laplacian operator.

40

41

Creates Laplacian with gauge transformation, resulting in

42

singular matrix with non-trivial nullspace.

43

44

Parameters:

45

- grid: tuple, grid dimensions

46

- beta: float, gauge parameter

47

- format: str, sparse matrix format

48

- dtype: data type

49

50

Returns:

51

sparse matrix: gauge Laplacian operator

52

"""

53

```

54

55

**Usage Examples:**

56

57

```python

58

import pyamg

59

import numpy as np

60

61

# 1D Poisson problem

62

A1d = pyamg.gallery.poisson((100,))

63

print(f"1D Poisson: {A1d.shape}, {A1d.nnz} nonzeros")

64

65

# 2D Poisson problem

66

A2d = pyamg.gallery.poisson((50, 50))

67

print(f"2D Poisson: {A2d.shape}, {A2d.nnz} nonzeros")

68

69

# 3D Poisson problem

70

A3d = pyamg.gallery.poisson((20, 20, 20))

71

print(f"3D Poisson: {A3d.shape}, {A3d.nnz} nonzeros")

72

73

# Different matrix format

74

A_coo = pyamg.gallery.poisson((40, 40), format='coo')

75

76

# Gauge Laplacian (singular)

77

A_gauge = pyamg.gallery.gauge_laplacian((30, 30))

78

```

79

80

### Linear Elasticity Problems

81

82

Discrete linear elasticity operators for solid mechanics problems, challenging for AMG due to near-nullspace.

83

84

```python { .api }

85

def linear_elasticity(grid, format='csr', dtype=float):

86

"""

87

Generate linear elasticity operator for displacement formulation.

88

89

Creates finite element discretization of linear elasticity

90

equations using Q1 elements. Results in block system with

91

rigid body modes in nullspace.

92

93

Parameters:

94

- grid: tuple, grid dimensions (nx, ny) for 2D problems

95

- format: str, sparse matrix format

96

- dtype: data type

97

98

Returns:

99

sparse matrix: elasticity operator (2*nx*ny × 2*nx*ny for 2D)

100

101

Notes:

102

- Nullspace contains rigid body modes (translation + rotation)

103

- Requires special treatment in AMG (near-nullspace)

104

- Best solved with Smoothed Aggregation using rigid body modes

105

"""

106

107

def linear_elasticity_p1(vertices, elements, format='csr'):

108

"""

109

Generate P1 linear elasticity operator on triangular mesh.

110

111

Creates finite element discretization using P1 (linear)

112

elements on unstructured triangular mesh.

113

114

Parameters:

115

- vertices: array, vertex coordinates (n_vertices × 2)

116

- elements: array, element connectivity (n_elements × 3)

117

- format: str, sparse matrix format

118

119

Returns:

120

sparse matrix: P1 elasticity operator

121

"""

122

```

123

124

**Usage Examples:**

125

126

```python

127

# 2D linear elasticity

128

A_elastic = pyamg.gallery.linear_elasticity((40, 40))

129

print(f"Elasticity: {A_elastic.shape}, {A_elastic.nnz} nonzeros")

130

131

# Solve with rigid body modes

132

B = np.ones((A_elastic.shape[0], 3)) # Translation + rotation modes

133

ml = pyamg.smoothed_aggregation_solver(A_elastic, B=B)

134

135

# P1 elasticity on triangle mesh

136

vertices = np.array([[0,0], [1,0], [1,1], [0,1]])

137

elements = np.array([[0,1,2], [0,2,3]])

138

A_p1 = pyamg.gallery.linear_elasticity_p1(vertices, elements)

139

```

140

141

### Stencil-Based Problems

142

143

General stencil discretizations for various PDEs and difference operators.

144

145

```python { .api }

146

def stencil_grid(stencil, grid, format='csr', dtype=float):

147

"""

148

Generate matrix from stencil on regular grid.

149

150

Creates sparse matrix by applying given stencil to all

151

interior points of regular grid with appropriate boundary conditions.

152

153

Parameters:

154

- stencil: array, stencil weights:

155

* 1D: shape (2*r+1,) for radius r stencil

156

* 2D: shape (2*r+1, 2*s+1) for radius (r,s) stencil

157

* 3D: shape (2*r+1, 2*s+1, 2*t+1) stencil

158

- grid: tuple, grid dimensions

159

- format: str, sparse matrix format

160

- dtype: data type

161

162

Returns:

163

sparse matrix: stencil-generated operator

164

165

Raises:

166

ValueError: if stencil and grid dimensions are incompatible

167

"""

168

169

def diffusion_stencil_2d(epsilon=1.0, theta=0.0, type='FE'):

170

"""

171

Generate 2D diffusion stencil with anisotropy.

172

173

Creates stencil for anisotropic diffusion operator with

174

specified anisotropy ratio and orientation.

175

176

Parameters:

177

- epsilon: float, anisotropy ratio (>1 for strong anisotropy)

178

- theta: float, rotation angle in radians

179

- type: str, discretization type:

180

* 'FE': finite element

181

* 'FD': finite difference

182

183

Returns:

184

array: 3×3 stencil for 2D diffusion operator

185

"""

186

```

187

188

**Usage Examples:**

189

190

```python

191

# Custom 1D stencil (second derivative)

192

stencil_1d = np.array([1, -2, 1])

193

A_custom = pyamg.gallery.stencil_grid(stencil_1d, (100,))

194

195

# 2D Laplacian stencil

196

stencil_2d = np.array([[0, 1, 0],

197

[1, -4, 1],

198

[0, 1, 0]])

199

A_laplace = pyamg.gallery.stencil_grid(stencil_2d, (50, 50))

200

201

# Anisotropic diffusion

202

stencil_aniso = pyamg.gallery.diffusion_stencil_2d(epsilon=100, theta=np.pi/4)

203

A_aniso = pyamg.gallery.stencil_grid(stencil_aniso, (40, 40))

204

```

205

206

### Random and Example Matrices

207

208

Utilities for generating random sparse matrices and loading example problems.

209

210

```python { .api }

211

def sprand(m, n, density, format='csr', dtype=float,

212

distribution='uniform', **kwargs):

213

"""

214

Generate random sparse matrix.

215

216

Creates sparse matrix with specified density and random

217

value distribution, useful for testing and benchmarking.

218

219

Parameters:

220

- m: int, number of rows

221

- n: int, number of columns

222

- density: float, fraction of nonzero entries (0 < density ≤ 1)

223

- format: str, sparse matrix format

224

- dtype: data type

225

- distribution: str, random distribution:

226

* 'uniform': uniform distribution [0,1]

227

* 'normal': normal distribution N(0,1)

228

- **kwargs: distribution-specific parameters

229

230

Returns:

231

sparse matrix: random sparse matrix

232

"""

233

234

def load_example(name):

235

"""

236

Load example matrix from PyAMG collection.

237

238

Loads predefined test matrices commonly used in

239

multigrid research and benchmarking.

240

241

Parameters:

242

- name: str, example name:

243

* 'airfoil': unstructured airfoil mesh

244

* 'bar': structural mechanics bar

245

* 'fem_2d': 2D finite element matrix

246

* Additional examples available

247

248

Returns:

249

sparse matrix: loaded example matrix

250

251

Raises:

252

ValueError: if example name is not recognized

253

"""

254

```

255

256

**Usage Examples:**

257

258

```python

259

# Random sparse matrix

260

A_rand = pyamg.gallery.sprand(1000, 1000, density=0.01)

261

262

# Random with normal distribution

263

A_normal = pyamg.gallery.sprand(500, 500, density=0.02,

264

distribution='normal')

265

266

# Load example problem

267

try:

268

A_example = pyamg.gallery.load_example('airfoil')

269

print(f"Airfoil: {A_example.shape}, {A_example.nnz} nonzeros")

270

except ValueError:

271

print("Example not available")

272

```

273

274

### Finite Element Methods

275

276

Advanced finite element problem generation and mesh utilities.

277

278

```python { .api }

279

class Mesh:

280

"""

281

Mesh representation for finite element problems.

282

283

Manages vertices, elements, and connectivity for

284

unstructured mesh-based discretizations.

285

286

Attributes:

287

- vertices: array of vertex coordinates

288

- elements: array of element connectivity

289

- boundary: boundary node information

290

"""

291

292

def __init__(self, vertices, elements):

293

"""

294

Initialize mesh from vertices and elements.

295

296

Parameters:

297

- vertices: array, vertex coordinates (n_vertices × dim)

298

- elements: array, element connectivity (n_elements × nodes_per_element)

299

"""

300

301

def regular_triangle_mesh(nx, ny):

302

"""

303

Generate regular triangular mesh.

304

305

Creates structured triangular mesh on unit square

306

with specified resolution.

307

308

Parameters:

309

- nx: int, number of divisions in x direction

310

- ny: int, number of divisions in y direction

311

312

Returns:

313

tuple: (vertices, elements) arrays for triangle mesh

314

"""

315

316

def stokes(mesh, format='csr'):

317

"""

318

Generate Stokes problem operator.

319

320

Creates mixed finite element discretization of

321

Stokes equations (incompressible flow).

322

323

Parameters:

324

- mesh: Mesh object or tuple (vertices, elements)

325

- format: str, sparse matrix format

326

327

Returns:

328

sparse matrix: Stokes operator (saddle point system)

329

"""

330

```

331

332

**Usage Examples:**

333

334

```python

335

# Create triangular mesh

336

vertices, elements = pyamg.gallery.regular_triangle_mesh(20, 20)

337

mesh = pyamg.gallery.Mesh(vertices, elements)

338

339

# Generate Stokes problem

340

A_stokes = pyamg.gallery.stokes(mesh)

341

print(f"Stokes: {A_stokes.shape}, {A_stokes.nnz} nonzeros")

342

```

343

344

### Demo Function

345

346

Interactive demonstration of PyAMG capabilities.

347

348

```python { .api }

349

def demo(**kwargs):

350

"""

351

Run PyAMG demonstration showing solver capabilities.

352

353

Interactive demo that creates test problems, constructs

354

AMG solvers, and displays convergence behavior and

355

hierarchy information.

356

357

Parameters:

358

- **kwargs: demo configuration options

359

360

Returns:

361

None (prints demo output)

362

"""

363

```

364

365

**Usage Examples:**

366

367

```python

368

# Run basic demo

369

pyamg.gallery.demo()

370

371

# Demo with custom parameters

372

pyamg.gallery.demo(grid_size=(100, 100), solver='smoothed_aggregation')

373

```

374

375

## Usage Guidelines

376

377

### Problem Selection

378

379

- **Poisson**: Basic testing, algorithm development

380

- **Linear Elasticity**: Near-nullspace testing, realistic applications

381

- **Stencil**: Custom PDE discretizations

382

- **Random**: Stress testing, pathological cases

383

384

### Performance Considerations

385

386

- Large 3D problems can consume significant memory

387

- Anisotropic problems may require specialized solvers

388

- Elasticity problems need appropriate near-nullspace treatment

389

- Random matrices may not represent realistic AMG performance

390

391

### Best Practices

392

393

- Start with small problem sizes for algorithm testing

394

- Use appropriate matrix format for target application

395

- Consider boundary conditions for realistic problems

396

- Validate results against known solutions when possible