binary variable depending on a continuous variable (mixed integer programming in cplex) - constraints

I'm trying to formulate a constraint for a MIP problem that involves binary variable v and continuous variable i, such as:
if i = 0, v = 0, and
if i > 0, v = 1
I haven't been able to think of a solution to this and I'm not sure if there is a solution. Any suggestion is greatly appreciated. Thank you!

you can rely on logical constraints.
In OPL you can write
dvar boolean v;
dvar float+ i;
subject to
{
v==!(i==0);
}
And you can do the same with all CPLEX APIs

You can also model this using the 'traditional' Big-M formulation which is documented in many places on the internet and in many textbooks.
Usually this is done in a pair of constraints like this:
i <= M * v
This forces i to be zero if v is zero, and also if i is non-zero then v must be 1 which covers most of your requirement, but still allows i = 0 and v = 1. In many cases the objective is trying to minimise some expression including v and that may be sufficient to encourage v=0 when i=0. But don't fall into the silly error of using a really big value for M as that will adversely affect your linear relaxations and possibly overal performance.
Then you might also need to add a further constraint to force v to zero if i is zero such as:
v <= i
which would have the effect of directly forcing v to zero if i is zero.

Related

Sagemath: Is there a simple way to factor a polynomial over C & have the roots appear in radical instead of decimal form?

In Mathematica, if I do the following
Roots[x^3 - 2 == 0, x]
I get
x=(-1)^(2/3) 2^(1/3) || x=(-2)^(1/3) || x = 2^(1/3)
I want to do something similar in Sagemath
sage: F1.<x> = PolynomialRing(CC)
sage: f=x^3 - 2
sage: f.roots()
[(1.25992104989487, 1),
(-0.629960524947437 - 1.09112363597172*I, 1),
(-0.629960524947437 + 1.09112363597172*I, 1)]
Is there a way in sagemath to see it either as radicals or as ^(1/n) or something similar?
Is there a reason you need this computation to take place within a complex polynomial ring? I'm not an expert in computer algebra and I'm sure I'm oversimplifying or something, but I believe that is the root of this behavior; Sage treats the complex numbers as an inexact field, meaning that it stores the coefficients a and b in a+b*I as (default 53-bit) floats rather than as symbolic constants. Basically, what you are asking for is a type error, any object defined over the ComplexField (or ComplexDoubleField, or presumably any inexact field) will have floats as its coefficients. On the other hand, the corresponding behavior in the symbolic ring (where the token x lives by default) seems to be exactly what you are looking for; more specifically, evaluating var("t"); solve(t^3-2==0,t) returns [t == 1/2*I*sqrt(3)*2^(1/3) - 1/2*2^(1/3), t == -1/2*I*sqrt(3)*2^(1/3) - 1/2*2^(1/3), t == 2^(1/3)].

Pyomo constraint > 100000 OR 0

All,
I am working on some code where there is a requirement to buy/sell a minimum of 100,000 packets. If not possible then this should be zeroed.
I have tried a number of things for things for this including:
def objective_rule(model):
return sum(model.Prices[ProductCount]*model.Amount[ProductCount]*(model.Amount[ProductCount]>100000) for ProductCount in model.Products)
But this is slower than expected.
I would like to put an explicit constraint in place. Something akin to:
def minTradesize_Constraint(model):
return ((model.Amount[ProductCount]>=100000)| \
(model.Amount[ProductCount]==0.00) for ProductCount in model.Products)
I have looked at indicator functions but the Pyomo continuous approximations don't help.
Any help/guidance appreciated.
Basically, what you are trying to achieve is make the model.Amount[ProductCount] terms take discontinuous values (zero or larger or equal to 100,000). To achieve that, first, you will basically need to define a binary variable: model.y = pyomo.Var(model.Products, within=pyomo.Binary).
Then you will need to add the following constraints:
def minTradesize_Constraint1(model):
return (model.Amount[ProductCount] >= 100000 * y[ProductCount] for ProductCount in model.Products)
def minTradesize_Constraint2(model):
return (model.Amount[ProductCount] <= M * y[ProductCount] for ProductCount in model.Products)
where M is a sufficiently large number (can be a realistic upper bound for your model.Amount[ProductCount] variable).
As a result of this formulation, if y[ProductCount] is zero, then the model.Amount[ProductCount] term will also be zero. If the model wants now to make model.Amount[ProductCount] variable take positive values, it will have to set the binary y[ProductCount] to 1, hence, forcing model.Amount[ProductCount] to become larger or equal to 100,000.
Note: I have formulated the constraints in the same style that you did in your answer. However, if I understand your model correctly, I would say that the first constraint, for instance, should be:
def minTradesize_Constraint1(model, ProductCount):
return (model.Amount[ProductCount] >= 100000 * y[ProductCount]
and the for ProductCount in model.Products part should be added when you create the Pyomo constraint.
to simplify the solution even further. I added a variable called route_selected
model.route_selected = pe.Var(<a set, for me its routes == r>, domain=pe.Binary, initialize=0, within=pe.Binary)
model.route_selected = pe.Var(model.R, domain=pe.Binary, initialize=0, within=pe.Binary)
thats my dependent variable looks
# Variable to solve, this is the variable that will be changed by solver to find a solution
# for each route, port, cust, year combination what should be supplied amount
model.x_rpcy = pe.Var(self.model.R, self.model.P, self.model.C, self.model.Y, domain=pe.NonNegativeIntegers, initialize=0)
and then added this constraint
for y in self.model.Y:
for r in self.model.R:
lhs = sum(self.model.x_rpcy[r, p, c, y] for p in self.model.P for c in self.model.C)
vessel_size = 1000
self.model.const_route.add(lhs == vessel_size * self.model.route_selected[r])
model.const_route.add(lhs == vessel_size * model.route_selected[r])

How to add if(A and B) then C constraints in Gurobi

Now I have three 5 by 3 matrix, X, Y, Z. All elements in them are binary variables. I want to add the following constraints:
I know I should introduce an auxiliary binary variable here. But I really stuck in how to write these simple conditional equalities as linear constraints. Any advice, tricks, suggestions?
Many thanks in advance!
Actually you don't need extra binary variables for this.
x(i,j)=1 and x(i+1,j)=0 => z(i+1,j)=1
can be interpreted as:
z(i+1,j) >= x(i,j)*(1-x(i+1,j))
This can be written as a linear inequality:
z(i+1,j) >= x(i,j) - x(i+1,j)
Similarly,
x(i,j)=0 and x(i+1,j)=1 => y(i+1,j)=1
can be formulated as:
y(i+1,j) >= x(i+1,j) - x(i,j)

Efficient Multiplication of Varying-Length #s [Conceptual]

EDIT
So it seems I "underestimated" what varying length numbers meant. I didn't even think about situations where the operands are 100 digits long. In that case, my proposed algorithm is definitely not efficient. I'd probably need an implementation who's complexity depends on the # of digits in each operands as opposed to its numerical value, right?
As suggested below, I will look into the Karatsuba algorithm...
Write the pseudocode of an algorithm that takes in two arbitrary length numbers (provided as strings), and computes the product of these numbers. Use an efficient procedure for multiplication of large numbers of arbitrary length. Analyze the efficiency of your algorithm.
I decided to take the (semi) easy way out and use the Russian Peasant Algorithm. It works like this:
a * b = a/2 * 2b if a is even
a * b = (a-1)/2 * 2b + a if a is odd
My pseudocode is:
rpa(x, y){
if x is 1
return y
if x is even
return rpa(x/2, 2y)
if x is odd
return rpa((x-1)/2, 2y) + y
}
I have 3 questions:
Is this efficient for arbitrary length numbers? I implemented it in C and tried varying length numbers. The run-time in was near-instant in all cases so it's hard to tell empirically...
Can I apply the Master's Theorem to understand the complexity...?
a = # subproblems in recursion = 1 (max 1 recursive call across all states)
n / b = size of each subproblem = n / 1 -> b = 1 (problem doesn't change size...?)
f(n^d) = work done outside recursive calls = 1 -> d = 0 (the addition when a is odd)
a = 1, b^d = 1, a = b^d -> complexity is in n^d*log(n) = log(n)
this makes sense logically since we are halving the problem at each step, right?
What might my professor mean by providing arbitrary length numbers "as strings". Why do that?
Many thanks in advance
What might my professor mean by providing arbitrary length numbers "as strings". Why do that?
This actually change everything about the problem (and make your algorithm incorrect).
It means than 1234 is provided as 1,2,3,4 and you cannot operate directly on the whole number. You need to analyze your algorithm in terms of #additions, #multiplications, #divisions.
You should expect a division to be a bit more expensive than a multiplication, and a multiplication to be lot more expensive than an addition. So a good algorithm try to reduce the number of divisions and multiplications.
Check out the Karatsuba algorithm, (ps don't copy it that's not what your teacher want) is one of the fastest for this specification.
Add 3): Native integers are limited in how large (or small) numbers they can represent (32- or 64-bit integers for example). To represent arbitrary length numbers you can choose strings, because then you are not really limited by this. The problem is then, of course, that your arithmetic units are not really made to add strings ;-)

Why is 0 divided by 0 an error?

I have come across this problem in a calculation I do in my code, where the divisor is 0 if the divident is 0 too. In my code I return 0 for that case. I am wondering, while division by zero is generally undefined, why not make an exception for this case? My understanding why division by zero is undefined is basically that it cannot be reversed. However, I do not see this problem in the case 0/0.
EDIT OK, so this question spawned a lot of discussion. I made the mistake of over-eagerly accepting an answer based on the fact that it received a lot of votes. I now accepted AakashM's answer, because it provides an idea on how to analyze the problem.
Let's say:
0/0 = x
Now, rearranging the equation (multiplying both sides by 0) gives:
x * 0 = 0
Now do you see the problem? There are an infinite number of values for x as anything multiplied by 0 is 0.
This is maths rather than programming, but briefly:
It's in some sense justifiable to assign a 'value' of positive-infinity to some-strictly-positive-quantity / 0, because the limit is well-defined
However, the limit of x / y as x and y both tend to zero depends on the path they take. For example, lim (x -> 0) 2x / x is clearly 2, whereas lim (x -> 0) x / 5x is clearly 1/5. The mathematical definition of a limit requires that it is the same whatever path is followed to the limit.
(Was inspired by Tony Breyal's rather good answer to post one of my own)
Zero is a tricky and subtle beast - it does not conform to the usual laws of algebra as we know them.
Zero divided by any number (except zero itself) is zero. Put more mathematically:
0/n = 0 for all non-zero numbers n.
You get into the tricky realms when you try to divide by zero itself. It's not true that a number divided by 0 is always undefined. It depends on the problem. I'm going to give you an example from calculus where the number 0/0 is defined.
Say we have two functions, f(x) and g(x). If you take their quotient, f(x)/g(x), you get another function. Let's call this h(x).
You can also take limits of functions. For example, the limit of a function f(x) as x goes to 2 is the value that the function gets closest to as it takes on x's that approach 2. We would write this limit as:
lim{x->2} f(x)
This is a pretty intuitive notion. Just draw a graph of your function, and move your pencil along it. As the x values approach 2, see where the function goes.
Now for our example. Let:
f(x) = 2x - 2
g(x) = x - 1
and consider their quotient:
h(x) = f(x)/g(x)
What if we want the lim{x->1} h(x)? There are theorems that say that
lim{x->1} h(x) = lim{x->1} f(x) / g(x)
= (lim{x->1} f(x)) / (lim{x->1} g(x))
= (lim{x->1} 2x-2) / (lim{x->1} x-1)
=~ [2*(1) - 2] / [(1) - 1] # informally speaking...
= 0 / 0
(!!!)
So we now have:
lim{x->1} h(x) = 0/0
But I can employ another theorem, called l'Hopital's rule, that tells me that this limit is also equal to 2. So in this case, 0/0 = 2 (didn't I tell you it was a strange beast?)
Here's another bit of weirdness with 0. Let's say that 0/0 followed that old algebraic rule that anything divided by itself is 1. Then you can do the following proof:
We're given that:
0/0 = 1
Now multiply both sides by any number n.
n * (0/0) = n * 1
Simplify both sides:
(n*0)/0 = n
(0/0) = n
Again, use the assumption that 0/0 = 1:
1 = n
So we just proved that all other numbers n are equal to 1! So 0/0 can't be equal to 1.
walks on back to her home over at mathoverflow.com
Here's a full explanation:
http://en.wikipedia.org/wiki/Division_by_zero
( Including the proof that 1 = 2 :-) )
You normally deal with this in programming by using an if statement to get the desired behaviour for your application.
The problem is with the denominator. The numerator is effectively irrelevant.
10 / n
10 / 1 = 10
10 / 0.1 = 100
10 / 0.001 = 1,000
10 / 0.0001 = 10,000
Therefore: 10 / 0 = infinity (in the limit as n reaches 0)
The Pattern is that as n gets smaller, the results gets bigger. At n = 0, the result is infinity, which is a unstable or non-fixed point. You can't write infinity down as a number, because it isn't, it's a concept of an ever increasing number.
Otherwise, you could think of it mathematically using the laws on logarithms and thus take division out of the equation altogther:
log(0/0) = log(0) - log(0)
BUT
log(0) = -infinity
Again, the problem is the the result is undefined because it's a concept and not a numerical number you can input.
Having said all this, if you're interested in how to turn an indeterminate form into a determinate form, look up l'Hopital's rule, which effectively says:
f(x) / g(x) = f'(x) / g'(x)
assuming the limit exists, and therefore you can get a result which is a fixed point instead of a unstable point.
Hope that helps a little,
Tony Breyal
P.S. using the rules of logs is often a good computational way to get around the problems of performing operations which result in numbers which are so infinitesimal small that given the precision of a machine’s floating point values, is indistinguishable from zero. Practical programming example is 'maximum likelihood' which generally has to make use of logs in order to keep solutions stable
Look at division in reverse: if a/b = c then c*b = a. Now, if you substitute a=b=0, you end up with c*0 = 0. But ANYTHING multiplied by zero equals zero, so the result can be anything at all. You would like 0/0 to be 0, someone else might like it to be 1 (for example, the limiting value of sin(x)/x is 1 when x approaches 0). So the best solution is to leave it undefined and report an error.
You may want to look at Dr. James Anderson's work on Transarithmetic. It isn't widely accepted.
Transarithmetic introduces the term/number 'Nullity' to take the value of 0/0, which James likens to the introduction 'i' and 'j'.
The structure of modern math is set by mathematicians who think in terms of axioms.
Having additional axioms that aren't productive and don't really allow one to do more stuff is against the ideal of having clear math.
How many times does 0 go into 0? 5. Yes - 5 * 0 = 0, 11. Yes - 11 * 0 = 0, 43. Yes - 43 * 0 = 0. Perhaps you can see why it's undefined now? :)
Since x/y=z should be equivalent to x=yz, and any z would satisfy 0=0z, how useful would such an 'exception' be?
Another explanation of why 0/0 is undefined is that you could write:
0/0 = (4 - 4)/0 = 4/0 - 4/0
And 4/0 is undefined.
If a/b = c, then a = b * c.
In the case of a=0 and b=0, c can be anything because 0 * c = 0 will be true for all possible values of c. Therefore, 0/0 is undefined.
This is only a Logical answer not a mathamatical one,
imagine Zero as empty how can you Divide an empty by an empty this is the case in division by zero also how can you divide by something which is empty.
0 means nothing, so if you have nothing, it does not imply towards anything to distribute to anything. Some Transit Facilities when they list out the number of trips of a particular line, trip number 0 is usually the special route that is routed in a different way. Typically, a good example would be in the Torrance Transit Systems where Line 2 has a trip before the first trip known as trip number 0 that operates on weekdays only, that trip in particular is trip number 0 because it is a specialized route that is routed differently from all the other routes.
See the following web pages for details:
http://transit.torrnet.com/PDF/Line-2_MAP.pdf
http://transit.torrnet.com/PDF/Line-2_Time_PDF.pdf
On the map, trip number 0 is the trip that is mapped in dotted line, the solid line maps the regular routing.
Sometimes 0 can be used on numbering the trips a route takes where it is considered the "Express Service" route.
why not make an exception for this
case?
Because:
as others said, it's not that easy;)
there's no application for defining 0/0 - adding exception would complicate mathematics for no gains.
This is what I'd do:
function div(a, b) {
if(b === 0 && a !== 0) {
return undefined;
}
if(b === 0 && a === 0) {
return Math.random;
}
return a/b;
}
When you type in zero divided by zero, there's an error because whatever you multiply zero from will be zero so it could be any number.
As Andrzej Doyle said:
Anything dived by zero is infinity. 0/0 is also infinity. You can't get 0/0 = 1. That's the basic principle of maths. That's how the whole world goes round. But you can sure edit a program to say "0/0 is not possible" or "Cannot divide by zero" as they say in cell phones.

Resources