# How to use ConvexOptimization on a piecewise function?

I define a simple piecewise convex function, but ConvexOptimization does not take it as a valid input:

f[x_] := Piecewise[{{ -x, x < 0}, {2 x, x >= 0}}];
Plot[f[x], {x, -1, 1}]
ConvexOptimization[ f[x], {x >= -1, x <= 1}, x]

Out[]= ConvexOptimization: The function x<0 is neither convex or concave so the curvature of the objective function
... cannot be determined.


What is preventing ConvexOptimization from optimizing this function?

The issue appears to with the way the function is expressed, rather than with the function itself.

An equivalent function is

h[x_] := Max[-x, 2 x]
Plot[h[x], {x, -1, 1}]

ConvexOptimization[h[x], {x >= -1, x <= 1}, x]
(* {x -> 0.} *)

• Thank you! It's a clever solution. However, in my original application, it may not be always possible to write the function as the maximum of two functions. I am also curious why the error message says the function x<0 is neither convex or concave. Jan 16, 2022 at 1:48
• A work around for a piece-wise definition would be to optimise on each piece individually, then take the minimum Jan 16, 2022 at 7:36
• Since the maximum of convex functions is necessarily convex, it should be easier for Mathematica to check such cases. It would be interesting to see an example of a convex function with a piece-wise definition that cannot easily be written as the maximum of convex functions. Jan 16, 2022 at 12:10
• Thank you @mikado. Your solution works in many cases. But here is a convex function that cannot be written as maximum of two convex functions: f[x_] := Piecewise[{{ (-x)^(-Log[-x]), x < 0}, {x^(-Log[x]), x >= 0}}]; Plot[f[x], {x, -1/5, 1/5}]. I hope Mathematica will be able to recognize convexity for Piecewise functions in the future. Jan 16, 2022 at 15:03
• I think your expression is equivalent to f[x_]:=Exp[-(Log[x^2]/2)^2] - though the Mathematica struggles to see that this is convex at x==0. You should probably submit your problem to Wolfram support, as it does look strange. Jan 16, 2022 at 17:37