Adding an OR constraint in JuMP/Gurobi - julia

I'm trying to add a constraint to a model that constrains a variable to be one of the values in a set, i.e. constrains X to be 0 OR 3 OR 4.
Current code is as follows:
#addConstraint(m, x==4)
But I would like to do something like:
#addConstraint(m, x==0 or x==3 or x==4)
Is this possible in julia? Using JuMP as the solver.

Define helper variables h3, h4 to be binary and then set constraints: x = 3*h3 + 4*h4 and h3 + h4 <= 1.

Related

Constrained Optimization in R using constOptim

I am trying to find the maximum values of this objective function:
f(x1,x2,x3) = 1300x1 + 600x2 + 500x3
subject to the following constraints
300x1 + 150x2 + 100x3 <= 4,000
90x1 + 30x2 + 40x3 <= 1,000
x1 <= 5
x1, x2, x3 >= 0
Below is the code I am using, which is not returning the values I'm looking for. The outputs for the variables are 9.453022e-12 3.272252e-12 5.548419e-14 and the total value is -1.428002e-08.
I'm new to R. What am I doing wrong? Thank you.
f=function(x) -(1300*x[1]+600*x[2]+500*x[3]) # minimize -f(x,y,z)
inequalities=function(x){ #define the ineqaulities function
h=0
h[1]=-(300*x[1]+150*x[2]+100*x[3]-4000)
h[2]=-(90*x[1]+30*x[2]+40*x[3]-1000)
h[3]=-(1*x[1]+0*x[2]+0*x[3]-5)
return(h)}
g=function(x){ #x,y,z > 0
h=0
h[1]=x[1]
h[2]=x[2]
h[3]=x[3]
return(h)}
p0=c(0,0,0) #give the starting point
y=constrOptim.nl(p0,f,hin=inequalities,heq=g);
print(y$par)
print(y$value)
The documentation says:
heq: a vector function specifying equality constraints such that heq[j] = 0 for all j
So the lower bounds x[1],x[2],x[3] >= 0 you are trying to specify, are actually interpreted as x[1],x[2],x[3] = 0. Hence the solution: 9.453022e-12, 3.272252e-12 5.548419e-14. Your lower bounds need to be incorporated in hin.
Note that there are better, linear solvers for linear problems. Passing on a linear problem to a non-linear solver is not optimal.

OpenMDAO 1.2.0 implicit component

I new to OpenMDAO and I'm still learning how to formulate the problems.
For a simple example, let's say I have 3 input variables with the given bounds:
1 <= x <= 10
0 <= y <= 10
1 <= z <= 10
and I have 4 outputs, defined as:
f1 = x * y
f2 = 2 * z
g1 = x + y - 1
g2 = z
my goal is to minimize f1 * g1, but enforce the constraint f1 = f2 and g1 = g2. For example, one solution is x=3, y=4, z=6 (no idea if this is optimal).
For this simple problem, you can probably just feed the output equality constraints to the driver. However, for my actual problem it's hard to find an initial starting point that satisfy all the constraints, and as the result the optimizer failed to do anything. I figure maybe I could define y and z as states in an implicit component and have a nonlinear solver figure out the right values of y and z given x, then feed x to the optimization driver.
Is this a possible approach? If so, how will the implicit component look like in this case? I looked at the Sellar problem tutorial but I wasn't able to translate it to this case.
You could create an implicit component if you want. In that case, you would define an apply_linear method in your component. That is done with the sellar problem here.
In your case since you have a 2 equation set of residuals which are both dependent on the state variables, I suggest you create a single array state variable of length 2, call it foo (I used a new variable to avoid any confusion, but name it whatever you want!). Then you will define two residuals, one for each element of the residual array of the new state variable.
Something like:
resids['foo'][0] = params['x'] * unknowns['foo'][0] - 2 * unknowns['foo'][1]
resids['foo'][1] = params['x'] + unknowns['foo'][0] - 1 - unknowns['foo'][1]
If you wanted to keep the state variable names separate you could, and it will still work. You'll just have to arbitrarily assign one residual equation to one variable and one to the other.
Then the only thing left is to add a non linear solver to the group containing your implicit component and it should work. If you choose to use a newton solver, you'll either need to set fd_options['force_fd'] = True or define derivatives of your residuals wrt all params and state variables.

Find out if a solution exists for multiple equations (in N) [duplicate]

This question already has answers here:
Algorithm for solving systems of linear inequalities
(5 answers)
Closed 8 years ago.
Consider the following equations:
X > Y
X + Y > 7
Y <= 10
X >= 0
Y >= 0
I want to find out if there exists a solution that fulfills all of them (natural numbers).
I don't care about the exact solution, I just want to know if there is a solution at all
I have read about Microsoft Solver Foundation or other linear programming libraries, but I'm not sure if they can solve problems like this.
Especially I'm not sure if the can solve equations with variables on each side, like
X > Y, or X + Y > Z
most examples are of the form:
X * 10 + Y * 30 > constant
I need it to be able to solve systems with maximum of 4-8 variables, all in range of 0-100
Another important constraint I have, the library needs to be fast. I need to be able to solve systems of like 7 equations in like 0,00001 seconds
Interesting question. Feels a lot like the integer-knapsack problem.
First of all, whether variables are on each side is irrelevant, since an equation like
X + Y > Z
can be rewritten to
X + Y - Z > 0
So let's assume that all constraints are of the format
(const1 * var1) + ... + (const8 * var8) > const
To support less variables, just use the value 0 for one of the constants.
The way to visualize this is to see the case of 2 variables as determining the convex hull of the 'lines' corresponding to the constraints. So each constraint can be drawn as a 2D line, and only values on one side of the line are allowed.
To visualize this for 3 variables, it's the same as whether the convex hull of 'planes' determined by the constraint have any grid points ('natural numbers') in them.
The trouble in this case is the fact that the solution should have only natural numbers: this makes normal linear algebra impossible, since a grid is imposed. I would not know of any library supporting such restrictions.
But it would not be too difficult to write a solution yourself: the idea is to find a solution by trying every number by pruning aggressively.
So in your example: test all X in the range 0 to 100. Now go to the next variable, and determine the valid range for the free variable based on the constraints. Worked out for x == 8: then the range for y would be:
0 .. 7 because of constraint x > y
0 .. 100 because of constraint x + y > 7 (since x is already 8)
0 .. 9 because of constraint y < 10
...and we repeat this for all constraints. The final constraint for y is then 0 .. 7, because that is the most tight constraint. Now repeat this process for the left-over unbound variables, and you're done if you find at least one solution.
I expect this code to be about 100 lines with dynamic programming; computation time very much depends on the input and vary wildly.
For example, a set of equations which would take a long time:
A + B + C + D + E + F + G + H > 400.5
A + B + C + D + E + F + G + H < 400.6
As a human we can deduce that since we're requiring natural numbers, there is no solution to these equations. However, this solution is not prunable using the method described above, all combinations of A .. G will have to be tested before it will be concluded that there is no fitting H. Therefore it will look at about all possibilities. Not really pleasant, but unavoidable.

error in embedded conditional expression

I have a conditional expression that when it is satisfied (==7) by the result of a function (VitPath$states) implies the summation of other embedded conditional expressions when their conditions (<0.1) are also satisfied resulting in G
G<-if(tail(VitPath$states,1)==7)
{if(summary(ResFit)$coef[370]<0.1) summary(ResFit)$coef[64]*summary(ResFit)$coef[91]
else 0 +
if(summary(ResFit)$coef[371]<0.1) summary(ResFit)$coef[65]*summary(ResFit)$coef[93]
else 0 +
if(summary(ResFit)$coef[372]<0.1) summary(ResFit)$coef[66]*summary(ResFit)$coef[95]
else 0 +
if(summary(ResFit)$coef[373]<0.1) summary(ResFit)$coef[67]*summary(ResFit)$coef[97]
else 0 +
if(summary(ResFit)$coef[374]<0.1) summary(ResFit)$coef[68]*summary(ResFit)$coef[99]
else 0 +
if(summary(ResFit)$coef[375]<0.1) summary(ResFit)$coef[69]*summary(ResFit)$coef[101]
else 0 +
if(summary(ResFit)$coef[376]<0.1) summary(ResFit)$coef[70]*summary(ResFit)$coef[103]
else 0 +
if(summary(ResFit)$coef[377]<0.1) summary(ResFit)$coef[71]*summary(ResFit)$coef[105]
else 0 +
if(summary(ResFit)$coef[378]<0.1) summary(ResFit)$coef[72]*summary(ResFit)$coef[107]
else 0} else 0
It seems that the embedded conditional expressions are not properly expresed as it produces an error in the first embedded expression as it seem not to understand the multiplication.
Computing the asymptotic covariance matrix of estimates
Error en if (summary(ResFit)$coef[370] < 0.1) summary(ResFit)$coef[64] * :
valor ausente donde TRUE/FALSE es necesario
Is there a way to do this without changing the present format. When I place a parenthesis or brakets (summary(ResFit)$coef[71]*summary(ResFit)$coef[105]) it also does not work.
Many thanks
EDITED
ResFit is produced by the following expression X beeing a vector of numeric values
ResFit = HMMFit(X, nStates=9, control=list(init="KMEANS"))
Try this. It's a Boolean algebra version; When the test fails, the result will be 0 but when it success it will be the product. I assume you only want the first column of the summary coef matrix since multiplying teh standard errors would not make much sense:
G<-if(tail(VitPath$states,1)==7) { summary(ResFit)$coef[370:378,1]<0.1 )*
( summary(ResFit)$coef[64:72,1])*(summary(ResFit)$coef[91:107,1]) }
This should be much faster, as well as being clearer and easier to maintain. If you are using a modeling function different than lm, you should post further details. I was assuming the structure returned from the $coef-call would be like:
coefficients
a p x 4 matrix with columns for the estimated coefficient, its standard error, t-statistic and corresponding (two-sided) p-value. Aliased coefficients are omitted.

Calculate the length of a segment of a quadratic bezier

I use this algorithm to calculate the length of a quadratic bezier:
http://www.malczak.linuxpl.com/blog/quadratic-bezier-curve-length/
However, what I wish to do is calculate the length of the bezier from 0 to t where 0 < t < 1
Is there any way to modify the formula used in the link above to get the length of the first segment of a bezier curve?
Just to clarify, I'm not looking for the distance between q(0) and q(t) but the length of the arc that goes between these points.
(I don't wish to use adaptive subdivision to aproximate the length)
Since I was sure a similar form solution would exist for that variable t case - I extended the solution given in the link.
Starting from the equation in the link:
Which we can write as
Where b = B/(2A) and c = C/A.
Then transforming u = t + b we get
Where k = c - b^2
Now we can use the integral identity from the link to obtain:
So, in summary, the required steps are:
Calculate A,B,C as in the original equation.
Calculate b = B/(2A) and c = C/A
Calculate u = t + b and k = c -b^2
Plug these values into the equation above.
[Edit by Spektre] I just managed to implement this in C++ so here the code (and working correctly matching naively obtained arc lengths):
float x0,x1,x2,y0,y1,y2; // control points of Bezier curve
float get_l_analytic(float t) // get arclength from parameter t=<0,1>
{
float ax,ay,bx,by,A,B,C,b,c,u,k,L;
ax=x0-x1-x1+x2;
ay=y0-y1-y1+y2;
bx=x1+x1-x0-x0;
by=y1+y1-y0-y0;
A=4.0*((ax*ax)+(ay*ay));
B=4.0*((ax*bx)+(ay*by));
C= (bx*bx)+(by*by);
b=B/(2.0*A);
c=C/A;
u=t+b;
k=c-(b*b);
L=0.5*sqrt(A)*
(
(u*sqrt((u*u)+k))
-(b*sqrt((b*b)+k))
+(k*log(fabs((u+sqrt((u*u)+k))/(b+sqrt((b*b)+k)))))
);
return L;
}
There is still room for improvement as some therms are computed more than once ...
While there may be a closed form expression, this is what I'd do:
Use De-Casteljau's algorithm to split the bezier into the 0 to t part and use the algorithm from the link to calculate its length.
You just have to evaluate the integral not between 0 and 1 but between 0 and t. You can use the symbolic toolbox of your choice to do that if you're not into the math. For instance:
http://integrals.wolfram.com/index.jsp?expr=Sqrt\[a*x*x%2Bb*x%2Bc\]&random=false
Evaluate the result for x = t and x = 0 and subtract them.

Resources