Can we select first nonzero value of binary variable?

Dear all,

I have a binary variable taking value of 1 between specific time intervals. However, I only need first nonzero element of binary variable. For example, if binary variables take a value of 1 between time intervals of 17-20, how can I model the constraint that will only pick the first nonzero value of the binary variable. Please see the attached model.
Selecting first nonzero element of binary variable.gms (1.31 KB)
Thanks in advance and kind regards,
David

David,

In general, there is one trick. You keep storing maximum value of two consecutive y values.
let’s say y1(t) is a binary variable that stores maximum of y(t-1) and y(t).

y1(t) =g= y(t);
y1(t) =g= y(t -1);

so in your case, first nonzero value that y1 has will be at 17th position. (looks like 0, 0, 0, …, 1,1,1,1)

Here if you are can make use of y1 to achieve your goal, you can stop here. If you insist on getting a variable like (0, 0, 0…, 1, 0, 0, 0), read on.

Now you can introduce another variable y2(t) that is

0 if y1(t) and y1(t-1) are both 0 or both 1.
1 if only one of y1(t) and y1(t-1) are 1.

y2(t) =l= y1(t) + y1(t-1);
y2(t) =l= 2 - y1(t) - y1(t-1);

The above two constraints take care of the first condition

y2(t) =g= 1 - My1(t-1) - M(1- y1(t));
y2(t) =g= 1 - My1(t) - M(1- y1(t-1));

The above two constraints take care of the second condition.

The resulting y2 will have 16 zeros followed by 1 and then 3 nonzeros in your example.

This may not be the smartest way but this should work.

I would try hard to get my job done without y2(t) based on what you want to do with the first nonzero value.

  • Atharv

Dear Atharv,

Thanks for sharing codes.

Kind regards,
David