or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

atoms.mdconstraints.mderrors.mdexpressions.mdindex.mdproblems.mdsolvers.mdtransforms.md

expressions.mddocs/

0

# Core Expressions

1

2

Fundamental building blocks for optimization problems in CVXPY. These classes represent mathematical expressions that can be combined using standard arithmetic operations to build optimization objectives and constraints.

3

4

## Capabilities

5

6

### Variables

7

8

Optimization variables represent the unknowns in an optimization problem. Variables can be scalars, vectors, or matrices with various properties like non-negativity, symmetry, or being integer-valued.

9

10

```python { .api }

11

class Variable:

12

"""

13

Optimization variable.

14

15

Parameters:

16

- shape: int or tuple, shape of the variable (default: scalar)

17

- name: str, optional name for the variable

18

- nonneg: bool, whether variable is constrained to be non-negative

19

- nonpos: bool, whether variable is constrained to be non-positive

20

- symmetric: bool, whether variable is constrained to be symmetric

21

- diag: bool, whether variable is constrained to be diagonal

22

- PSD: bool, whether variable is constrained to be positive semidefinite

23

- NSD: bool, whether variable is constrained to be negative semidefinite

24

- hermitian: bool, whether variable is constrained to be Hermitian

25

- boolean: bool, whether variable is constrained to be boolean

26

- integer: bool, whether variable is constrained to be integer

27

- pos: bool, whether variable is constrained to be positive

28

- neg: bool, whether variable is constrained to be negative

29

"""

30

def __init__(self, shape=(), name=None, **kwargs): ...

31

32

@property

33

def value(self):

34

"""Get the optimal value of the variable after solving."""

35

...

36

37

@property

38

def grad(self):

39

"""Get gradient with respect to this variable."""

40

...

41

```

42

43

Usage examples:

44

45

```python

46

import cvxpy as cp

47

48

# Scalar variable

49

x = cp.Variable()

50

51

# Vector variable

52

y = cp.Variable(5) # 5-element vector

53

54

# Matrix variable

55

Z = cp.Variable((4, 4)) # 4x4 matrix

56

57

# Non-negative vector

58

w = cp.Variable(3, nonneg=True)

59

60

# Positive semidefinite matrix

61

P = cp.Variable((3, 3), PSD=True)

62

63

# Integer variable

64

n = cp.Variable(integer=True)

65

66

# Named variable for debugging

67

alpha = cp.Variable(name="alpha")

68

```

69

70

### Parameters

71

72

Parameters represent known data in optimization problems that can be updated without rebuilding the problem structure. This enables efficient resolving with different parameter values.

73

74

```python { .api }

75

class Parameter:

76

"""

77

Problem parameter that can be updated without rebuilding.

78

79

Parameters:

80

- shape: int or tuple, shape of the parameter (default: scalar)

81

- name: str, optional name for the parameter

82

- value: array-like, initial value for the parameter

83

- nonneg: bool, whether parameter values must be non-negative

84

- nonpos: bool, whether parameter values must be non-positive

85

- symmetric: bool, whether parameter must be symmetric

86

- diag: bool, whether parameter must be diagonal

87

- PSD: bool, whether parameter must be positive semidefinite

88

- NSD: bool, whether parameter must be negative semidefinite

89

- hermitian: bool, whether parameter must be Hermitian

90

- boolean: bool, whether parameter must be boolean

91

- integer: bool, whether parameter must be integer

92

- pos: bool, whether parameter must be positive

93

- neg: bool, whether parameter must be negative

94

- imag: bool, whether parameter can have imaginary values

95

- complex: bool, whether parameter can be complex-valued

96

"""

97

def __init__(self, shape=(), name=None, value=None, **kwargs): ...

98

99

@property

100

def value(self):

101

"""Get the current value of the parameter."""

102

...

103

104

@value.setter

105

def value(self, val):

106

"""Set the value of the parameter."""

107

...

108

109

@property

110

def grad(self):

111

"""Get gradient with respect to this parameter."""

112

...

113

```

114

115

Usage examples:

116

117

```python

118

import cvxpy as cp

119

import numpy as np

120

121

# Scalar parameter with initial value

122

lam = cp.Parameter(value=1.0, nonneg=True)

123

124

# Vector parameter

125

c = cp.Parameter(5, value=np.random.randn(5))

126

127

# Matrix parameter

128

A = cp.Parameter((4, 5), value=np.random.randn(4, 5))

129

130

# Update parameter values

131

lam.value = 2.0

132

c.value = np.ones(5)

133

A.value = np.eye(4, 5)

134

135

# Parameters in optimization problems

136

x = cp.Variable(5)

137

objective = cp.Minimize(cp.quad_form(x, A.T @ A) + lam * cp.norm(x, 1))

138

problem = cp.Problem(objective)

139

140

# Solve for different parameter values

141

for lam_val in [0.1, 1.0, 10.0]:

142

lam.value = lam_val

143

problem.solve()

144

print(f"lambda={lam_val}, x={x.value}")

145

```

146

147

### Callback Parameters

148

149

Special parameters that use callback functions to compute their values dynamically during problem solving.

150

151

```python { .api }

152

class CallbackParam:

153

"""

154

Parameter with a callback function for dynamic value computation.

155

156

Parameters:

157

- callback: callable, function that returns the parameter value

158

- shape: int or tuple, shape of the parameter

159

- name: str, optional name for the parameter

160

"""

161

def __init__(self, callback, shape=(), name=None): ...

162

163

@property

164

def value(self):

165

"""Get value by calling the callback function."""

166

...

167

```

168

169

### Constants

170

171

Constants represent fixed numerical values in optimization problems. CVXPY automatically converts Python numbers and NumPy arrays to Constants.

172

173

```python { .api }

174

class Constant:

175

"""

176

Constant value in an optimization problem.

177

178

Parameters:

179

- value: scalar, array-like, or sparse matrix

180

"""

181

def __init__(self, value): ...

182

183

@property

184

def value(self):

185

"""Get the constant value."""

186

...

187

188

@property

189

def grad(self):

190

"""Constants have zero gradient."""

191

...

192

```

193

194

Usage examples:

195

196

```python

197

import cvxpy as cp

198

import numpy as np

199

200

# Scalar constant (usually automatic)

201

c1 = cp.Constant(3.14)

202

# Equivalent to just using: 3.14

203

204

# Vector constant

205

c2 = cp.Constant([1, 2, 3])

206

# Equivalent to: np.array([1, 2, 3])

207

208

# Matrix constant

209

c3 = cp.Constant(np.eye(3))

210

211

# Constants are created automatically

212

x = cp.Variable()

213

expr = 2 * x + 5 # 2 and 5 become Constants automatically

214

```

215

216

### Expression Base Class

217

218

The base class for all mathematical expressions in CVXPY, providing arithmetic operations and properties.

219

220

```python { .api }

221

class Expression:

222

"""

223

Base class for all mathematical expressions.

224

"""

225

226

# Arithmetic operations

227

def __add__(self, other): ...

228

def __radd__(self, other): ...

229

def __sub__(self, other): ...

230

def __rsub__(self, other): ...

231

def __mul__(self, other): ...

232

def __rmul__(self, other): ...

233

def __truediv__(self, other): ...

234

def __rtruediv__(self, other): ...

235

def __pow__(self, other): ...

236

def __neg__(self): ...

237

def __pos__(self): ...

238

239

# Comparison operations

240

def __eq__(self, other): ...

241

def __le__(self, other): ...

242

def __lt__(self, other): ...

243

def __ge__(self, other): ...

244

def __gt__(self, other): ...

245

246

# Matrix operations

247

def __matmul__(self, other): ...

248

def __rmatmul__(self, other): ...

249

250

# Indexing

251

def __getitem__(self, key): ...

252

253

@property

254

def value(self):

255

"""Numeric value of the expression (None if not evaluated)."""

256

...

257

258

@property

259

def grad(self):

260

"""Gradient of the expression."""

261

...

262

263

@property

264

def shape(self):

265

"""Shape of the expression as a tuple."""

266

...

267

268

@property

269

def size(self):

270

"""Total number of elements in the expression."""

271

...

272

273

@property

274

def ndim(self):

275

"""Number of dimensions."""

276

...

277

278

@property

279

def T(self):

280

"""Transpose of the expression."""

281

...

282

283

def flatten(self):

284

"""Flatten the expression to a vector."""

285

...

286

287

def reshape(self, shape):

288

"""Reshape the expression."""

289

...

290

```

291

292

Usage examples:

293

294

```python

295

import cvxpy as cp

296

297

# Create variables

298

x = cp.Variable(3)

299

y = cp.Variable(3)

300

301

# Arithmetic operations

302

expr1 = x + y

303

expr2 = 2 * x - 3 * y

304

expr3 = x @ y # dot product

305

expr4 = x[0] + x[1] # indexing

306

307

# Properties

308

print(f"Shape: {expr1.shape}")

309

print(f"Size: {expr1.size}")

310

311

# After solving a problem

312

problem = cp.Problem(cp.Minimize(cp.sum_squares(x)), [x >= 0, cp.sum(x) == 1])

313

problem.solve()

314

print(f"Optimal x: {x.value}")

315

print(f"Objective value: {expr1.value}")

316

```