cvxrust 0.1.0

A Rust implementation of Disciplined Convex Programming
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
//! Curvature tracking for DCP (Disciplined Convex Programming).
//!
//! This module implements the curvature rules that determine whether an
//! expression is convex, concave, affine, or unknown.

use std::sync::Arc;

use crate::expr::{Array, Expr};

/// Curvature of an expression.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Curvature {
    /// Constant value (most restrictive).
    Constant,
    /// Affine function (both convex and concave).
    Affine,
    /// Convex function.
    Convex,
    /// Concave function.
    Concave,
    /// Unknown curvature (not DCP-compliant).
    Unknown,
}

impl Curvature {
    /// Check if the curvature is convex (constant, affine, or convex).
    pub fn is_convex(self) -> bool {
        matches!(
            self,
            Curvature::Constant | Curvature::Affine | Curvature::Convex
        )
    }

    /// Check if the curvature is concave (constant, affine, or concave).
    pub fn is_concave(self) -> bool {
        matches!(
            self,
            Curvature::Constant | Curvature::Affine | Curvature::Concave
        )
    }

    /// Check if the curvature is affine (constant or affine).
    pub fn is_affine(self) -> bool {
        matches!(self, Curvature::Constant | Curvature::Affine)
    }

    /// Check if this is a constant.
    pub fn is_constant(self) -> bool {
        matches!(self, Curvature::Constant)
    }

    /// Negate the curvature (convex <-> concave).
    pub fn negate(self) -> Self {
        match self {
            Curvature::Convex => Curvature::Concave,
            Curvature::Concave => Curvature::Convex,
            other => other,
        }
    }
}

/// Combine curvatures for addition: a + b.
pub fn add_curvature(a: Curvature, b: Curvature) -> Curvature {
    use Curvature::*;
    match (a, b) {
        // Constants don't affect curvature
        (Constant, x) | (x, Constant) => x,
        // Affine + Affine = Affine
        (Affine, Affine) => Affine,
        // Affine doesn't affect non-constant curvature
        (Affine, x) | (x, Affine) => x,
        // Convex + Convex = Convex
        (Convex, Convex) => Convex,
        // Concave + Concave = Concave
        (Concave, Concave) => Concave,
        // Convex + Concave = Unknown
        (Convex, Concave) | (Concave, Convex) => Unknown,
        // Unknown propagates
        (Unknown, _) | (_, Unknown) => Unknown,
    }
}

/// Combine curvatures for scalar multiplication: scalar * expr.
///
/// If scalar > 0: preserves curvature
/// If scalar < 0: negates curvature
/// If scalar == 0: constant
pub fn scalar_mul_curvature(scalar: f64, expr_curv: Curvature) -> Curvature {
    if scalar == 0.0 {
        Curvature::Constant
    } else if scalar > 0.0 {
        expr_curv
    } else {
        expr_curv.negate()
    }
}

/// Determine if a matrix is PSD, NSD, or neither.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PsdStatus {
    Psd,     // Positive semi-definite
    Nsd,     // Negative semi-definite
    Neither, // Indefinite or non-symmetric
}

impl PsdStatus {
    /// Determine PSD status of an array.
    pub fn of_array(arr: &Array) -> Self {
        match arr.is_psd() {
            Some(true) => PsdStatus::Psd,
            Some(false) => {
                // Check if negative of it is PSD
                match arr {
                    Array::Scalar(v) => {
                        if *v <= 0.0 {
                            PsdStatus::Nsd
                        } else {
                            PsdStatus::Neither
                        }
                    }
                    Array::Dense(m) => {
                        // Check if -M is PSD
                        let neg = -m.clone();
                        if neg.cholesky().is_some() {
                            PsdStatus::Nsd
                        } else {
                            PsdStatus::Neither
                        }
                    }
                    _ => PsdStatus::Neither,
                }
            }
            None => PsdStatus::Neither,
        }
    }
}

impl Expr {
    /// Get the curvature of this expression.
    pub fn curvature(&self) -> Curvature {
        match self {
            // Leaves
            Expr::Variable(_) => Curvature::Affine,
            Expr::Constant(_) => Curvature::Constant,

            // Affine operations preserve/combine curvatures
            Expr::Add(a, b) => add_curvature(a.curvature(), b.curvature()),
            Expr::Neg(a) => a.curvature().negate(),
            Expr::Mul(a, b) => mul_curvature(a, b),
            Expr::MatMul(a, b) => matmul_curvature(a, b),
            Expr::Sum(a, _) => a.curvature(),
            Expr::Reshape(a, _) => a.curvature(),
            Expr::Index(a, _) => a.curvature(),
            Expr::VStack(exprs) => combine_all_curvatures(exprs),
            Expr::HStack(exprs) => combine_all_curvatures(exprs),
            Expr::Transpose(a) => a.curvature(),
            Expr::Trace(a) => a.curvature(),

            // Nonlinear convex atoms
            Expr::Norm1(x) | Expr::Norm2(x) | Expr::NormInf(x) => {
                // Convex when argument is affine
                if x.curvature().is_affine() {
                    Curvature::Convex
                } else {
                    Curvature::Unknown
                }
            }
            Expr::Abs(x) => {
                // Convex when argument is affine
                if x.curvature().is_affine() {
                    Curvature::Convex
                } else {
                    Curvature::Unknown
                }
            }
            Expr::Pos(x) => {
                // pos(x) = max(x, 0) is convex
                // Convex when x is affine OR when x is convex
                if x.curvature().is_convex() {
                    Curvature::Convex
                } else {
                    Curvature::Unknown
                }
            }
            Expr::NegPart(x) => {
                // neg(x) = max(-x, 0) is convex
                // Convex when x is affine OR when x is concave
                if x.curvature().is_concave() {
                    Curvature::Convex
                } else {
                    Curvature::Unknown
                }
            }
            Expr::Maximum(exprs) => {
                // max(x1, ..., xn) is convex if all xi are convex
                if exprs.iter().all(|e| e.curvature().is_convex()) {
                    Curvature::Convex
                } else {
                    Curvature::Unknown
                }
            }
            Expr::Minimum(exprs) => {
                // min(x1, ..., xn) is concave if all xi are concave
                if exprs.iter().all(|e| e.curvature().is_concave()) {
                    Curvature::Concave
                } else {
                    Curvature::Unknown
                }
            }
            Expr::QuadForm(x, p) => {
                // x'Px: convex if P is PSD and x is affine
                //       concave if P is NSD and x is affine
                if !x.curvature().is_affine() {
                    return Curvature::Unknown;
                }
                if let Some(p_val) = p.constant_value() {
                    match PsdStatus::of_array(p_val) {
                        PsdStatus::Psd => Curvature::Convex,
                        PsdStatus::Nsd => Curvature::Concave,
                        PsdStatus::Neither => Curvature::Unknown,
                    }
                } else {
                    Curvature::Unknown
                }
            }
            Expr::SumSquares(x) => {
                // ||x||_2^2 is convex when x is affine
                if x.curvature().is_affine() {
                    Curvature::Convex
                } else {
                    Curvature::Unknown
                }
            }
            Expr::QuadOverLin(x, y) => {
                // ||x||_2^2 / y is convex when:
                // - x is affine
                // - y is concave and positive
                if x.curvature().is_affine() && y.curvature().is_concave() {
                    // Note: We'd need to check y > 0 at runtime
                    Curvature::Convex
                } else {
                    Curvature::Unknown
                }
            }

            // Exponential cone atoms
            Expr::Exp(x) => {
                // exp(x) is convex when x is affine
                if x.curvature().is_affine() {
                    Curvature::Convex
                } else {
                    Curvature::Unknown
                }
            }
            Expr::Log(x) => {
                // log(x) is concave when x is concave (and positive)
                if x.curvature().is_concave() {
                    Curvature::Concave
                } else {
                    Curvature::Unknown
                }
            }
            Expr::Entropy(x) => {
                // -x*log(x) is concave when x is affine (and positive)
                if x.curvature().is_affine() {
                    Curvature::Concave
                } else {
                    Curvature::Unknown
                }
            }
            Expr::Power(x, p) => {
                // x^p curvature depends on p and sign of x
                if *p == 0.0 {
                    // x^0 = 1 is constant
                    Curvature::Constant
                } else if *p == 1.0 {
                    // x^1 = x is affine
                    x.curvature()
                } else if *p == 2.0 {
                    // x^2 is convex when x is affine (same as sum_squares)
                    if x.curvature().is_affine() {
                        Curvature::Convex
                    } else {
                        Curvature::Unknown
                    }
                } else if *p > 1.0 || *p < 0.0 {
                    // x^p is convex for p > 1 or p < 0 when x is concave and nonneg
                    // For DCP we require x to be affine for simplicity
                    if x.curvature().is_affine() {
                        Curvature::Convex
                    } else {
                        Curvature::Unknown
                    }
                } else if *p > 0.0 && *p < 1.0 {
                    // x^p is concave for 0 < p < 1 when x is convex and nonneg
                    // For DCP we require x to be affine
                    if x.curvature().is_affine() {
                        Curvature::Concave
                    } else {
                        Curvature::Unknown
                    }
                } else {
                    // Other edge cases (NaN, etc.)
                    Curvature::Unknown
                }
            }

            // Additional affine atoms
            Expr::Cumsum(x, _) => x.curvature(), // Affine operation
            Expr::Diag(x) => x.curvature(),      // Affine operation
        }
    }

    /// Check if this expression is convex.
    pub fn is_convex(&self) -> bool {
        self.curvature().is_convex()
    }

    /// Check if this expression is concave.
    pub fn is_concave(&self) -> bool {
        self.curvature().is_concave()
    }

    /// Check if this expression is affine.
    pub fn is_affine(&self) -> bool {
        self.curvature().is_affine()
    }
}

/// Handle multiplication curvature.
fn mul_curvature(a: &Expr, b: &Expr) -> Curvature {
    let ac = a.curvature();
    let bc = b.curvature();

    // If both are constant, result is constant
    if ac.is_constant() && bc.is_constant() {
        return Curvature::Constant;
    }

    // If one is constant, the other determines curvature (scaled)
    if ac.is_constant() {
        if let Some(arr) = a.constant_value() {
            if let Some(scalar) = arr.as_scalar() {
                return scalar_mul_curvature(scalar, bc);
            }
        }
        // Non-scalar constant * expression: only affine if expression is affine
        if bc.is_affine() {
            return Curvature::Affine;
        }
        return Curvature::Unknown;
    }

    if bc.is_constant() {
        if let Some(arr) = b.constant_value() {
            if let Some(scalar) = arr.as_scalar() {
                return scalar_mul_curvature(scalar, ac);
            }
        }
        // Expression * non-scalar constant: only affine if expression is affine
        if ac.is_affine() {
            return Curvature::Affine;
        }
        return Curvature::Unknown;
    }

    // Both non-constant: only affine * affine gives meaningful result
    // But affine * affine is quadratic (not affine unless one is scalar constant)
    Curvature::Unknown
}

/// Handle matrix multiplication curvature.
fn matmul_curvature(a: &Expr, b: &Expr) -> Curvature {
    let ac = a.curvature();
    let bc = b.curvature();

    // Constant @ anything = preserves curvature
    if ac.is_constant() {
        return bc;
    }
    // Anything @ constant = preserves curvature
    if bc.is_constant() {
        return ac;
    }

    // affine @ affine = quadratic (not DCP unless one side is constant)
    Curvature::Unknown
}

/// Combine curvatures for stacking operations.
fn combine_all_curvatures(exprs: &[Arc<Expr>]) -> Curvature {
    if exprs.is_empty() {
        return Curvature::Constant;
    }

    let mut result = Curvature::Constant;
    for e in exprs {
        result = add_curvature(result, e.curvature());
    }
    result
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::expr::{constant, variable};

    #[test]
    fn test_curvature_basics() {
        assert!(Curvature::Constant.is_convex());
        assert!(Curvature::Constant.is_concave());
        assert!(Curvature::Constant.is_affine());

        assert!(Curvature::Affine.is_convex());
        assert!(Curvature::Affine.is_concave());
        assert!(Curvature::Affine.is_affine());

        assert!(Curvature::Convex.is_convex());
        assert!(!Curvature::Convex.is_concave());
        assert!(!Curvature::Convex.is_affine());

        assert!(!Curvature::Concave.is_convex());
        assert!(Curvature::Concave.is_concave());
        assert!(!Curvature::Concave.is_affine());
    }

    #[test]
    fn test_negate_curvature() {
        assert_eq!(Curvature::Convex.negate(), Curvature::Concave);
        assert_eq!(Curvature::Concave.negate(), Curvature::Convex);
        assert_eq!(Curvature::Affine.negate(), Curvature::Affine);
        assert_eq!(Curvature::Constant.negate(), Curvature::Constant);
    }

    #[test]
    fn test_add_curvature() {
        use Curvature::*;
        assert_eq!(add_curvature(Convex, Convex), Convex);
        assert_eq!(add_curvature(Concave, Concave), Concave);
        assert_eq!(add_curvature(Affine, Affine), Affine);
        assert_eq!(add_curvature(Convex, Affine), Convex);
        assert_eq!(add_curvature(Concave, Affine), Concave);
        assert_eq!(add_curvature(Convex, Concave), Unknown);
    }

    #[test]
    fn test_variable_is_affine() {
        let x = variable(5);
        assert!(x.is_affine());
        assert!(x.is_convex());
        assert!(x.is_concave());
    }

    #[test]
    fn test_constant_is_constant() {
        let c = constant(5.0);
        assert_eq!(c.curvature(), Curvature::Constant);
    }

    #[test]
    fn test_norm_is_convex() {
        let x = variable(5);
        let n = Expr::Norm2(Arc::new(x));
        assert_eq!(n.curvature(), Curvature::Convex);
        assert!(n.is_convex());
        assert!(!n.is_concave());
    }

    #[test]
    fn test_neg_flips_curvature() {
        let x = variable(5);
        let n = Expr::Norm2(Arc::new(x));
        let neg_n = Expr::Neg(Arc::new(n));
        assert_eq!(neg_n.curvature(), Curvature::Concave);
    }
}