How to create a bool variable to indicate if another integer variable is between two specific values - or-tools

In ortools cp-sat, how could we link an boolean decision variable to whether an integer variable value is between two given values.
from ortools.sat.python import cp_model
def get(x):
return solver.Value(x)
model = cp_model.CpModel()
x_is_between_5_and_10 = model.NewBoolVar('x_is_between_5_and_10')
x = model.NewIntVar(0, 100, 'x')
model.Add(x == 7)
model.Add(x_is_between_5_and_10 == 1).OnlyEnforceIf(5 <= x).OnlyEnforceIf(x <= 10)
solver = cp_model.CpSolver()
status = solver.Solve(model=model)
print('x', get(x))
print('x_is_between_5_and_10', get(x_is_between_5_and_10))

Use:
model.AddLinearConstraint(x, 5, 10).OnlyEnforceIf(x_is_between_5_and_10).
model.AddLinearExpressionInDomain(x, cp_model.Domain.FromIntervals([[0, 4], [11, 100]])).OnlyEnforceIf(x_is_between_5_and_10.Not())
Note you can also write
model.AddLinearExpressionInDomain(x, cp_model.Domain.FromIntervals([[5, 10]])).OnlyEnforceIf(x_is_between_5_and_10)
for the first equation. But it that case, AddLinearConstraint() is smaller.
See the doc.

Related

Why I am getting different P values if using different packages

I am trying to compare categorical data from 2 groups.
Yes No
GrpA: [152, 220]
GrpB: [187, 350]
However, I am getting different P value results when using different methods:
count = [152, 220]
nobs = [187, 350]
import statsmodels
import scipy.stats
# USING STATSMODELS PACKAGE:
res = statsmodels.stats.proportion.proportions_chisquare(count, nobs)
print("P value =", res[1])
res = statsmodels.stats.proportion.proportions_ztest(count, nobs)
print("P value =", res[1])
# USING SCIPY.STATS PACKAGE:
res = scipy.stats.chi2_contingency([count, nobs], correction=True)
print("P value =", res[1])
res = scipy.stats.chi2_contingency([count, nobs], correction=False)
print("P value =", res[1])
Output is:
P value using proportions_chisquare = 1.037221289479458e-05
P value using proportions_ztest= 1.0372212894794536e-05
P value using chi2_contingency with correction= 0.0749218380702875
P value using chi2_contingency without correction= 0.06421435896354544
First 2 are identical (and highly significant), but they are different from last 2 (non-signficant).
Why are the results different? Which is the correct method to do this analysis?

How do constraint optimization in OrTools with coefficents?

I want to use ortools to generate all the possible combinations of a simple problem as in the following program. In this case I want x and y to be multiplications of 5 and additionally if start is 7, then the values of the x should be 7, 10, 15, 20, 25 and so on. How can I change following code for this?
model = cp_model.CpModel()
start = 7
end = 20
x = model.NewIntVar(start , end - 1, "x")
y = model.NewIntVar(start , end - 1, "y")
# Create the constraints.
model.Add(x != y)
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from ortools.sat.python import cp_model
class VarArraySolutionPrinter(cp_model.CpSolverSolutionCallback):
"""Print intermediate solutions."""
def __init__(self, variables):
self.__variables = variables
self.__solution_count = 0
def NewSolution(self):
self.__solution_count += 1
for v in self.__variables:
print('%s=%i' % (v, self.Value(v)), end=' ')
print()
def SolutionCount(self):
return self.__solution_count
def mod_or_start():
model = cp_model.CpModel()
start = 7
end = 20
x = model.NewIntVar(start, end - 1, 'x') # 8..19
y = model.NewIntVar(start, end - 1, 'y') # 8..19
x_is_start = model.NewBoolVar('x_is_start')
y_is_start = model.NewBoolVar('y_is_start')
x_is_modulo_5 = model.NewBoolVar('x_is_modulo_5')
y_is_modulo_5 = model.NewBoolVar('y_is_modulo_5')
model.Add(x == start).OnlyEnforceIf(x_is_start)
model.Add(y == start).OnlyEnforceIf(y_is_start)
# Buggy.
# model.AddModuloEquality(0, x, 5).OnlyEnforceIf(x_is_modulo_5)
# model.AddModuloEquality(0, y, 5).OnlyEnforceIf(y_is_modulo_5)
# Workaround until the modulo code is fixed.
sub_x = model.NewIntVar(start // 5, end // 5, 'sub_x')
sub_y = model.NewIntVar(start // 5, end // 5, 'sub_y')
model.Add(x == 5 * sub_x).OnlyEnforceIf(x_is_modulo_5)
model.Add(y == 5 * sub_y).OnlyEnforceIf(y_is_modulo_5)
# Remove duplicate solutions
model.Add(sub_x == start // 5).OnlyEnforceIf(x_is_modulo_5.Not())
model.Add(sub_y == start // 5).OnlyEnforceIf(y_is_modulo_5.Not())
# At least one option is true.
model.AddBoolOr([x_is_start, x_is_modulo_5])
model.AddBoolOr([y_is_start, y_is_modulo_5])
# Create a solver and solve.
solver = cp_model.CpSolver()
solution_printer = VarArraySolutionPrinter([x, y])
status = solver.SearchForAllSolutions(model, solution_printer)
print('Status = %s' % solver.StatusName(status))
print('Number of solutions found: %i' % solution_printer.SolutionCount())
mod_or_start()
Outputs:
x=15 y=15
x=15 y=7
x=10 y=7
x=7 y=7
x=7 y=15
x=7 y=10
x=10 y=15
x=10 y=10
x=15 y=10
Status = FEASIBLE
Number of solutions found: 9

How does this recursion work? Can you explain how they got the output?

function fnum = fib(n)
if (n == 1) || (n == 2)
fnum = 1;
else
fnum = fib(n-1) + fib(n-2);
end
Can you explain how does each step outputs for the given input. For example inputting 7 gives me 13, 5 gives me 5, but I am not able to track how. I would highly appreciate your reply.
Recursion basically means that the function calls itself.
If we follow your function for fib(3), you will see that what it does is call fib(2)+fib(1). The values of these are defined, and are 1, so it will return 2.
If you call it with fib(4), it will go and compute fib(3)+fib(2). You already know what fib(3) does (see previous paragraph), and we already mentioned that fib(2) returns 1.
If you call it with fib(5) it will go and compute fib(4)+fib(3). See previous paragraph.
This is a very useful way of programming as it is a very simple function to compute something that is arguably more complicated. The most important thing is that you make sure that any recursive function has strong stopping criteria, else it can go forever!
Do you know how Fibonacci series is defined? This function implements that recursively.
Longer answer
Fibonacci series is defined as
n(1) = 1
n(2) = 1
n(k+1) = n(k) + n(k-1)
So when you put 5 as argument, the expansion becomes
n(4+1) = n(4)+n(3)
= n(3)+n(2)+n(2)+n(1)
= n(2)+n(1)+1+1+1
= 1+1+1+1+1
= 5
A much easier back of envelop method is to start from first index and add last two terms to arrive at the next.
1, 1, 2 <- (1+1), 3 <- (2+1), 5 <- (3+2), ...
The Fibonnacci series is defined as f(1) = 1, f(2) = 1 and for all n > 2, f(n) = f(n-1) + f(n-2)
So when you call fib(1) it returns 1 same for fib(2). But when you call fib(3) it returns fib(3-1) + fib(3-2) which is fib(2) + fib(1) = 2. And then when you call fib(4)it returns fib(3) + fib(2) = (fib(2) + fib(1)) + fib(1) = 3. And recursively the fibonnaci series is equal to 1, 1, 3, 5, 8, 13, 21, ...
For the code when n is different than 1 or 2 it call the function fib recursively. And when is equals to 1 or 2 it returns 1.

Merging two sorted lists, one with additional 0s

Consider the following problem:
We are given two arrays A and B such that A and B are sorted
except A has B.length additional 0s appended to its end. For instance, A and B could be the following:
A = [2, 4, 6, 7, 0, 0, 0]
B = [1, 7, 9]
Our goal is to create one sorted list by inserting each entry of B
into A in place. For instance, running the algorithm on the above
example would leave
A = [1, 2, 4, 6, 7, 7, 9]
Is there a clever way to do this in better than O(n^2) time? The only way I could think of is to insert each element of B into A by scanning linearly and performing the appropriate number of shifts, but this leads to the O(n^2) solution.
Some pseudo-code (sorta C-ish), assuming array indexing is 0-based:
pA = A + len(A) - 1;
pC = pA; // last element in A
while (! *pA) --pA; // find the last non-zero entry in A
pB = B + len(B) - 1;
while (pA >= A) && (pB >= B)
if *pA > *pB
*pC = *pA; --pA;
else
*pC = *pB; --pB;
--pC
while (pB >= B) // still some bits in B to copy over
*pC = *pB; --pB; --pC;
Not really tested, and just written off the top of my head, but it should give you the idea... May not have the termination and boundary conditions exactly right.
You can do it in O(n).
Work from the end, moving the largest element towards the end of A. This way you avoid a lot of trouble to do with where to keep the elements while iterating. This is pretty easy to implement:
int indexA = A.Length - B.Length - 1;
int indexB = B.Length - 1;
int insertAt = A.Length;
while (indexA > 0 || indexB > 0)
{
insertAt--;
A[insertAt] = max(B[indexB], A[indexA]);
if (A[indexA] <= B[indexB])
indexB--;
else
indexA--;
}

Three boolean values saved in one tinyint

probably a simple question but I seem to be suffering from programmer's block. :)
I have three boolean values: A, B, and C. I would like to save the state combination as an unsigned tinyint (max 255) into a database and be able to derive the states from the saved integer.
Even though there are only a limited number of combinations, I would like to avoid hard-coding each state combination to a specific value (something like if A=true and B=true has the value 1).
I tried to assign values to the variables so (A=1, B=2, C=3) and then adding, but I can't differentiate between A and B being true from i.e. only C being true.
I am stumped but pretty sure that it is possible.
Thanks
Binary maths I think. Choose a location that's a power of 2 (1, 2, 4, 8 etch) then you can use the 'bitwise and' operator & to determine the value.
Say A = 1, B = 2 , C= 4
00000111 => A B and C => 7
00000101 => A and C => 5
00000100 => C => 4
then to determine them :
if( val & 4 ) // same as if (C)
if( val & 2 ) // same as if (B)
if( val & 1 ) // same as if (A)
if((val & 4) && (val & 2) ) // same as if (C and B)
No need for a state table.
Edit: to reflect comment
If the tinyint has a maximum value of 255 => you have 8 bits to play with and can store 8 boolean values in there
binary math as others have said
encoding:
myTinyInt = A*1 + B*2 + C*4 (assuming you convert A,B,C to 0 or 1 beforehand)
decoding
bool A = myTinyInt & 1 != 0 (& is the bitwise and operator in many languages)
bool B = myTinyInt & 2 != 0
bool C = myTinyInt & 4 != 0
I'll add that you should find a way to not use magic numbers. You can build masks into constants using the Left Logical/Bit Shift with a constant bit position that is the position of the flag of interest in the bit field. (Wow... that makes almost no sense.) An example in C++ would be:
enum Flags {
kBitMask_A = (1 << 0),
kBitMask_B = (1 << 1),
kBitMask_C = (1 << 2),
};
uint8_t byte = 0; // byte = 0b00000000
byte |= kBitMask_A; // Set A, byte = 0b00000001
byte |= kBitMask_C; // Set C, byte = 0b00000101
if (byte & kBitMask_A) { // Test A, (0b00000101 & 0b00000001) = T
byte &= ~kBitMask_A; // Clear A, byte = 0b00000100
}
In any case, I would recommend looking for Bitset support in your favorite programming language. Many languages will abstract the logical operations away behind normal arithmetic or "test/set" operations.
Need to use binary...
A = 1,
B = 2,
C = 4,
D = 8,
E = 16,
F = 32,
G = 64,
H = 128
This means A + B = 3 but C = 4. You'll never have two conflicting values. I've listed the maximum you can have for a single byte, 8 values or (bits).