@@ -1515,6 +1515,74 @@ function test_hessian_ifelse()
15151515 return
15161516end
15171517
1518+ function test_hessian_pow_variable_exponent ()
1519+ x, y = MOI. VariableIndex .(1 : 2 )
1520+ function dense_hessian (expr, p)
1521+ model = MOI. Nonlinear. Model ()
1522+ MOI. Nonlinear. set_objective (model, expr)
1523+ evaluator = MOI. Nonlinear. Evaluator (
1524+ model,
1525+ MOI. Nonlinear. SparseReverseMode (),
1526+ [x, y],
1527+ )
1528+ MOI. initialize (evaluator, [:Grad , :Hess ])
1529+ structure = MOI. hessian_lagrangian_structure (evaluator)
1530+ V = zeros (length (structure))
1531+ MOI. eval_hessian_lagrangian (evaluator, V, p, 1.0 , Float64[])
1532+ H = zeros (2 , 2 )
1533+ for ((i, j), v) in zip (structure, V)
1534+ H[i, j] += v
1535+ if i != j
1536+ H[j, i] += v
1537+ end
1538+ end
1539+ v, Hv = [1.0 , - 2.0 ], zeros (2 )
1540+ MOI. eval_hessian_lagrangian_product (evaluator, Hv, p, v, 1.0 , Float64[])
1541+ @test isapprox (Hv, H * v)
1542+ return H
1543+ end
1544+ # The Hessian of `x^g(y)` at `x > 0`, where `g`, `dg`, and `d2g` are the
1545+ # value and the first and second derivatives of `g` at `y`.
1546+ function pow_hessian (x, g, dg, d2g)
1547+ H_xy = dg * x^ (g - 1 ) * (1 + g * log (x))
1548+ H_yy = x^ g * (d2g * log (x) + (dg * log (x))^ 2 )
1549+ return [g* (g- 1 )* x^ (g- 2 ) H_xy; H_xy H_yy]
1550+ end
1551+ for y_val in (1.0 , 2.0 , 3.0 )
1552+ H = dense_hessian (:($ x^ $ y), [1.5 , y_val])
1553+ @test isapprox (H, pow_hessian (1.5 , y_val, 1.0 , 0.0 ))
1554+ end
1555+ for y_val in (1.0 , - 1.0 )
1556+ # (x^2)^(y^2) = x^(2 * y^2), and the outer exponent is 1.
1557+ H = dense_hessian (:(($ x^ 2 )^ ($ y^ 2 )), [1.5 , y_val])
1558+ @test isapprox (H, pow_hessian (1.5 , 2.0 , 4 * y_val, 4.0 ))
1559+ # (x^2)^(y^2 + 1) = x^(2 * y^2 + 2), and the outer exponent is 2.
1560+ H = dense_hessian (:(($ x^ 2 )^ ($ y^ 2 + 1 )), [1.5 , y_val])
1561+ @test isapprox (H, pow_hessian (1.5 , 4.0 , 4 * y_val, 4.0 ))
1562+ end
1563+ return
1564+ end
1565+
1566+ function test_hessian_pow_constant_exponent_nonpositive_base ()
1567+ x, y = MOI. VariableIndex .(1 : 2 )
1568+ model = MOI. Nonlinear. Model ()
1569+ MOI. Nonlinear. set_objective (model, :($ x^ 2 * $ y + $ x^ 1 * $ y^ 2 ))
1570+ evaluator = MOI. Nonlinear. Evaluator (
1571+ model,
1572+ MOI. Nonlinear. SparseReverseMode (),
1573+ [x, y],
1574+ )
1575+ MOI. initialize (evaluator, [:Grad , :Hess ])
1576+ @test MOI. hessian_lagrangian_structure (evaluator) ==
1577+ [(1 , 1 ), (2 , 2 ), (2 , 1 )]
1578+ H = zeros (3 )
1579+ for x_val in (- 1.5 , 0.0 )
1580+ MOI. eval_hessian_lagrangian (evaluator, H, [x_val, 2.0 ], 1.0 , Float64[])
1581+ @test isapprox (H, [4.0 , 2 * x_val, 2 * x_val + 4.0 ])
1582+ end
1583+ return
1584+ end
1585+
15181586end # module
15191587
15201588TestReverseAD. runtests ()
0 commit comments