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

high-level-interface.mddocs/

0

# High-Level Solving Interface

1

2

The PyAMG high-level interface provides simple functions for solving linear systems without requiring detailed knowledge of AMG algorithms. These functions automatically select appropriate solver methods and parameters based on problem characteristics.

3

4

## Capabilities

5

6

### Solve Function

7

8

The primary high-level interface for solving linear systems using AMG methods.

9

10

```python { .api }

11

def solve(A, b, x0=None, tol=1e-5, maxiter=400, return_solver=False,

12

existing_solver=None, verb=True, residuals=None):

13

"""

14

Solve the linear system Ax = b using AMG.

15

16

Automatically selects optimal solver method and parameters for the given

17

matrix. Uses robust smoothed aggregation settings by default.

18

19

Parameters:

20

- A: sparse matrix, coefficient matrix (scipy.sparse format)

21

- b: array-like, right-hand side vector

22

- x0: array-like, initial guess (default: random vector)

23

- tol: float, convergence tolerance (default 1e-5)

24

- maxiter: int, maximum iterations (default 400)

25

- return_solver: bool, if True return solver along with solution

26

- existing_solver: MultilevelSolver, reuse existing solver to save setup cost

27

- verb: bool, print verbose output during solve

28

- residuals: list, stores residual norms if provided

29

30

Returns:

31

array or tuple: solution vector x, or (x, ml) if return_solver=True

32

33

Raises:

34

ValueError: if A and b have incompatible dimensions

35

RuntimeError: if solver fails to converge

36

"""

37

```

38

39

**Usage Examples:**

40

41

```python

42

import pyamg

43

import numpy as np

44

from scipy.sparse import csr_matrix

45

46

# Simple usage with automatic method selection

47

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

48

b = np.random.rand(A.shape[0])

49

x = pyamg.solve(A, b)

50

51

# Control convergence and verbosity

52

x = pyamg.solve(A, b, tol=1e-8, maxiter=100, verb=False)

53

54

# Return solver for reuse

55

x, ml = pyamg.solve(A, b, return_solver=True)

56

57

# Reuse existing solver (efficient for multiple solves)

58

b2 = np.random.rand(A.shape[0])

59

x2 = pyamg.solve(A, b2, existing_solver=ml)

60

61

# Monitor convergence with residuals

62

residuals = []

63

x = pyamg.solve(A, b, residuals=residuals)

64

print(f"Converged in {len(residuals)} iterations")

65

66

# Provide initial guess

67

x0 = np.ones(A.shape[0])

68

x = pyamg.solve(A, b, x0=x0)

69

```

70

71

### Solver Factory

72

73

Creates AMG solver objects from automatic configuration analysis.

74

75

```python { .api }

76

def solver(A, config):

77

"""

78

Create AMG solver for matrix A using provided configuration.

79

80

Creates smoothed aggregation solver using the provided configuration

81

dictionary. Configuration should be generated using solver_configuration().

82

83

Parameters:

84

- A: sparse matrix, coefficient matrix

85

- config: dict, solver configuration parameters

86

87

Returns:

88

MultilevelSolver: configured smoothed aggregation solver

89

90

Raises:

91

TypeError: if solver creation fails

92

ValueError: if matrix is not square or has invalid properties

93

"""

94

```

95

96

**Usage Examples:**

97

98

```python

99

# Create solver with automatic configuration

100

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

101

config = pyamg.solver_configuration(A)

102

ml = pyamg.solver(A, config)

103

104

# Solve multiple systems with same solver

105

b1 = np.random.rand(A.shape[0])

106

b2 = np.random.rand(A.shape[0])

107

x1 = ml.solve(b1)

108

x2 = ml.solve(b2)

109

110

# Generate configuration with verbose output disabled

111

config = pyamg.solver_configuration(A, verb=False)

112

ml = pyamg.solver(A, config)

113

114

# Provide near null-space for elasticity problems

115

A = pyamg.gallery.linear_elasticity((10, 10))

116

B = np.ones((A.shape[0], 1)) # Constant vector

117

config = pyamg.solver_configuration(A, B=B)

118

ml = pyamg.solver(A, config)

119

```

120

121

### Solver Configuration

122

123

Generates configuration dictionaries for creating solvers with specific parameters.

124

125

```python { .api }

126

def solver_configuration(A, B=None, verb=True):

127

"""

128

Generate solver configuration dictionary based on matrix analysis.

129

130

Analyzes matrix properties and returns dictionary of recommended

131

smoothed aggregation solver parameters.

132

133

Parameters:

134

- A: sparse matrix, coefficient matrix to analyze

135

- B: array, near null-space modes (default None for constant vector)

136

- verb: bool, verbose output during analysis (default True)

137

138

Returns:

139

dict: configuration dictionary with keys:

140

* 'symmetry': detected matrix symmetry

141

* 'strength': strength of connection parameters

142

* 'aggregate': aggregation parameters

143

* 'smooth': prolongation smoothing parameters

144

* 'presmoother': pre-smoothing configuration

145

* 'postsmoother': post-smoothing configuration

146

* 'max_levels': maximum number of levels

147

* 'max_coarse': maximum coarse grid size

148

* 'coarse_solver': coarse grid solver method

149

* 'B': near null-space modes

150

* 'BH': hermitian transpose of B

151

* 'keep': flag to keep operators

152

153

Raises:

154

ValueError: if matrix analysis fails

155

"""

156

```

157

158

**Usage Examples:**

159

160

```python

161

# Get automatic configuration

162

A = pyamg.gallery.linear_elasticity((20, 20))

163

config = pyamg.solver_configuration(A)

164

print(config)

165

166

# Silent analysis

167

config = pyamg.solver_configuration(A, verb=False)

168

169

# Create solver from configuration

170

ml = pyamg.solver(A, config)

171

172

# Provide near null-space modes

173

B = np.ones((A.shape[0], 3)) # Multiple modes for elasticity

174

config = pyamg.solver_configuration(A, B=B, verb=False)

175

ml = pyamg.solver(A, config)

176

```

177

178

### Matrix Format Utilities

179

180

Helper functions for ensuring proper matrix formats for AMG solvers.

181

182

```python { .api }

183

def make_csr(A):

184

"""

185

Convert matrix to CSR format required by PyAMG solvers.

186

187

Parameters:

188

- A: array-like or sparse matrix, input matrix

189

190

Returns:

191

scipy.sparse.csr_matrix: matrix in CSR format

192

193

Raises:

194

ValueError: if conversion fails or matrix is not 2D

195

"""

196

```

197

198

**Usage Examples:**

199

200

```python

201

import numpy as np

202

from scipy.sparse import coo_matrix

203

204

# Convert dense matrix

205

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

206

A_csr = pyamg.make_csr(A_dense)

207

208

# Convert other sparse formats

209

A_coo = coo_matrix(A_dense)

210

A_csr = pyamg.make_csr(A_coo)

211

212

# Use in solver

213

ml = pyamg.solver(A_csr)

214

```

215

216

## Configuration Guidelines

217

218

### Method Selection

219

220

- **Classical AMG**: Best for M-matrices and problems with strong diagonal dominance

221

- **Smoothed Aggregation**: Best for symmetric positive definite problems, especially those arising from finite elements

222

- **AIR**: Experimental method for challenging problems

223

224

### Performance Tips

225

226

- Use `solver()` to create MultilevelSolver once, then call `solve()` multiple times for different right-hand sides

227

- For large problems, consider reducing `max_levels` to control memory usage

228

- CSR format is most efficient for PyAMG operations

229

- Initial guess can significantly improve convergence for iterative acceleration

230

231

### Common Issues

232

233

- **Memory errors**: Reduce `max_levels` or increase `max_coarse`

234

- **Slow convergence**: Try different solver methods or Krylov acceleration

235

- **Poor scaling**: Check matrix conditioning and consider preconditioning strategies