# 使用优化变量的约束静电非线性优化

### 问题几何

`$\begin{array}{l}z\le -|x|-|y|\\ {x}^{2}+{y}^{2}+\left(z+1{\right)}^{2}\le 1.\end{array}$`

```[X,Y] = meshgrid(-1:.01:1); Z1 = -abs(X) - abs(Y); Z2 = -1 - sqrt(1 - X.^2 - Y.^2); Z2 = real(Z2); W1 = Z1; W2 = Z2; W1(Z1 < Z2) = nan; % Only plot points where Z1 > Z2 W2(Z1 < Z2) = nan; % Only plot points where Z1 > Z2 hand = figure; % Handle to the figure, for later use set(gcf,'Color','w') % White background surf(X,Y,W1,'LineStyle','none'); hold on surf(X,Y,W2,'LineStyle','none'); view(-44,18)```

### 定义问题变量

```N = 20; x = optimvar('x',N,'LowerBound',-1,'UpperBound',1); y = optimvar('y',N,'LowerBound',-1,'UpperBound',1); z = optimvar('z',N,'LowerBound',-2,'UpperBound',0); elecprob = optimproblem;```

### 定义约束

`elecprob.Constraints.spherec = (x.^2 + y.^2 + (z+1).^2) <= 1;`

`show(elecprob.Constraints.spherec)`
``` ((x.^2 + y.^2) + (z + 1).^2) <= arg_RHS where: arg2 = 1; arg1 = arg2(ones(1,20)); arg_RHS = arg1(:); ```

```elecprob.Constraints.plane1 = z <= -x-y; elecprob.Constraints.plane2 = z <= -x+y; elecprob.Constraints.plane3 = z <= x-y; elecprob.Constraints.plane4 = z <= x+y;```

### 定义目标函数

`$energy=\sum _{i`

```energy = optimexpr(1); for ii = 1:(N-1) jj = (ii+1):N; tempe = (x(ii) - x(jj)).^2 + (y(ii) - y(jj)).^2 + (z(ii) - z(jj)).^2; energy = energy + sum(tempe.^(-1/2)); end elecprob.Objective = energy;```

### 运行优化

```rng default % For reproducibility x0 = randn(N,3); for ii=1:N x0(ii,:) = x0(ii,:)/norm(x0(ii,:))/2; x0(ii,3) = x0(ii,3) - 1; end init.x = x0(:,1); init.y = x0(:,2); init.z = x0(:,3);```

`[sol,fval,exitflag,output] = solve(elecprob,init)`
```Solving problem using fmincon. Local minimum found that satisfies the constraints. Optimization completed because the objective function is non-decreasing in feasible directions, to within the value of the optimality tolerance, and constraints are satisfied to within the value of the constraint tolerance. ```
```sol = struct with fields: x: [20x1 double] y: [20x1 double] z: [20x1 double] ```
```fval = 163.0099 ```
```exitflag = OptimalSolution ```
```output = struct with fields: iterations: 94 funcCount: 150 constrviolation: 0 stepsize: 2.8395e-05 algorithm: 'interior-point' firstorderopt: 8.1308e-06 cgiterations: 0 message: 'Local minimum found that satisfies the constraints....' bestfeasible: [1x1 struct] objectivederivative: "reverse-AD" constraintderivative: "closed-form" solver: 'fmincon' ```

### 查看解

```figure(hand) plot3(sol.x,sol.y,sol.z,'r.','MarkerSize',25) hold off```

### 参考资料

[1] Dolan, Elizabeth D., Jorge J. Moré, and Todd S. Munson.“Benchmarking Optimization Software with COPS 3.0.”Argonne National Laboratory Technical Report ANL/MCS-TM-273, February 2004.