Adding quadratic constraints in docplex - quadratic-programming

I have problem by writing quadratic constraints by docplex in python
This is my constraint:
A[i,j,k]=Z[i,j,k] *h[i,j,k]+Q[i,j,k]*d[i,j,k] ∀i,j,k
I wrote the constraint as below:
mdl.add_quadratic_constraints(z_qsd[i,j,k]*h_qsd[i,j,k]+Q_qsd[i,j,k]*d_qsd[i,j,k]==A_qsd[i,j,k] for i in q_ualification for j in s_hift for k in d_ay)
when I solve the model, I get this message:
Model is non-convex

The multiplication operator '*' has been overloaded in DOcplex to write quadratic expression. In other terms, you can multiply two variables.
Forgetting about indices, and assuming you have only four variables A,z,h,Q
the constraint can be written as:
mdl.add(A == Z *h + Q *d)
Now, for three-dimensional variables, you should use a variation of Model.continuous_var_cube (change the type), for example:
As = mdl.continous_var_cube(3,5,7, "A")
which builds a Python dictionary of variables, indexed by tuples of indices in the cartesian product of the
three ranges (1..3)x(1..5)x(1..7), that is 3x5x7 = 85 variables.
Each variable can be accessed by a collection of indices,
as in
a123 = As[1,2,3]

Here is a small quadratic-objective
problem example, inspired by the famous "zoo" examples from Alex Fleischer
(see https://www.linkedin.com/pulse/making-optimization-simple-python-alex-fleischer/ for more)
mdl = Model(name='buses')
nbbus40 = mdl.integer_var(name='nbBus40')
nbbus30 = mdl.integer_var(name='nbBus30')
mdl.add_constraint(nbbus40*40 + nbbus30*30 >= 300, 'kids')
# X**2 is the square of variable X
mdl.minimize(500 * nbbus40**2 + 400 * nbbus30**2)
mdl.solve()
for v in mdl.iter_integer_vars():
print(v," = ",v.solution_value)

Related

Z3 - how to count matches?

I have a finite set of pairs of type (int a, int b). The exact values of the pairs are explicitly present in the knowledge base. For example it could be represented by a function (int a, int b) -> (bool exists) which is fully defined on a finite domain.
I would like to write a function f with signature (int b) -> (int count), representing the number of pairs containing the specified b value as its second member. I would like to do this in z3 python, though it would also be useful to know how to do this in the z3 language
For example, my pairs could be:
(0, 0)
(0, 1)
(1, 1)
(1, 2)
(2, 1)
then f(0) = 1, f(1) = 3, f(2) = 1
This is a bit of an odd thing to do in z3: If the exact values of the pairs are in your knowledge base, then why do you need an SMT solver? You can just search and count using your regular programming techniques, whichever language you are in.
But perhaps you have some other constraints that come into play, and want a generic answer. Here's how one would code this problem in z3py:
from z3 import *
pairs = [(0, 0), (0, 1), (1, 1), (1, 2), (2, 1)]
def count(snd):
return sum([If(snd == p[1], 1, 0) for p in pairs])
s = Solver()
searchFor = Int('searchFor')
result = Int('result')
s.add(Or(*[searchFor == d[0] for d in pairs]))
s.add(result == count(searchFor))
while s.check() == sat:
m = s.model()
print("f(" + str(m[searchFor]) + ") = " + str(m[result]))
s.add(searchFor != m[searchFor])
When run, this prints:
f(0) = 1
f(1) = 3
f(2) = 1
as you predicted.
Again; if your pairs are exactly known (i.e., they are concrete numbers), don't use z3 for this problem: Simply write a program to count as needed. If the database values, however, are not necessarily concrete but have other constraints, then above would be the way to go.
To find out how this is coded in SMTLib (the native language z3 speaks), you can insert print(s.sexpr()) in the program before the while loop starts. That's one way. Of course, if you were writing this by hand, you might want to code it differently in SMTLib; but I'd strongly recommend sticking to higher-level languages instead of SMTLib as it tends to be hard to read/write for anyone except machines.

Need a vectorized solution in pytorch

I'm doing an experiment using face images in PyTorch framework. The input x is the given face image of size 5 * 5 (height * width) and there are 192 channels.
Objective: To obtain patches of x of patch_size(given as argument).
I have obtained the required result with the help of two for loops. But I want a better-vectorized solution so that the computation cost will be very less than using two for loops.
Used: PyTorch 0.4.1, (12 GB) Nvidia TitanX GPU.
The following is my implementation using two for loops
def extractpatches( x, patch_size): # x is bsx192x5x5
patches = x.unfold( 2, patch_size , 1).unfold(3,patch_size,1)
bs,c,pi,pj, _, _ = patches.size() #bs,192,
cnt = 0
p = torch.empty((bs,pi*pj,c,patch_size,patch_size)).to(device)
s = torch.empty((bs,pi*pj, c*patch_size*patch_size)).to(device)
//Want a vectorized method instead of two for loops below
for i in range(pi):
for j in range(pj):
p[:,cnt,:,:,:] = patches[:,:,i,j,:,:]
s[:,cnt,:] = p[:,cnt,:,:,:].view(-1,c*patch_size*patch_size)
cnt = cnt+1
return s
Thanks for your help in advance.
I think you can try this as following. I used some parts of your code for my experiment and it worked for me. Here l and f are the lists of tensor patches
l = [patches[:,:,int(i/pi),i%pi,:,:] for i in range(pi * pi)]
f = [l[i].contiguous().view(-1,c*patch_size*patch_size) for i in range(pi * pi)]
You can verify the above code using toy input values.
Thanks.

syntax: unexpected "=" in Julia

I have written this segment of Julia code which filters keypoints in an image by an interpolation of the fields in of the extremum from a difference in gaussian scale space.
mutable struct discrete_extremum
o
s
m
n
intensity
end
mutable struct candidateKeypoint
oE
s
m
n
σ
x
y
ω
end
LB = Array{candidateKeypoint}(0)
for extremum in LA′
for i = 1:5
H̄ = Hessian(extremum.o, extremum.s, extremum.m, extremum.n)
ḡ = ThreeDgradient(extremum.o, extremum.s, extremum.m, extremum.n)
α⋆ = alphaStar(H̄, ḡ)
ω = omega(H̄, ḡ, extremum.o, extremum.s, extremum.m, extremum.n)
δOE = δMin * 2^(extremum.o - 1)
α1⋆ = α⋆[1]
α2⋆ = α⋆[2]
α3⋆ = α⋆[3]
σ = (δOE/δMin) * σMin * 2^((α1⋆ + extremum.s)/nSpo)
x = δOE * (α2⋆ + extremum.m)
y = δOE * (α2⋆ + extremum.n)
extremum.s, extremum.m, extremum.n = round(Int64, extremum.s + α1⋆), round(Int64, extremum.m + α2⋆), round(Int64, extremum.n + α3⋆)
if max(abs(α1⋆), abs(α2⋆), abs(α3⋆)) < 0.6
break
end
end
if max(abs(α1⋆), abs(α2⋆), abs(α3⋆)) < 0.6
push!(LB, candidateKeypoint(extremum, σ, x, y, ω))
end
end
I am getting this error:
syntax: unexpected "="
There is no line number mentioned. Can you guys suggest what I am doing wrong?
P.S. I have posted the question here as well.
I guess the problem is your α⋆, α1⋆, α2⋆, α3⋆ variables, because the symbol ⋆ is a Julia operator. In general, using unicode characters is fine but try to avoid using operator symbols that already have a meaning in the language.
You could replace your α⋆ by α′ (\alpha followed by \prime) or ̂α (\hat followed by \alpha) for example. However, don't go overboard with non-ASCII characters. They are there to make code more readable, not less.
UPDATE: Incorporated comments by #DNF and #phg.

Assign value to specific bit of BitVecExpr in Z3

Here is my verilog statement:
reg[2:0] a; // Create register 'a' which is 3 bit.
assign a[1] = 1'b1; // Assigning value to 1st bit of register 'a'.
I have to implement the statement above in Z3.
For the 1st line of the verilog statement using BitVecExpr:
BitVecExpr a = ctx.mkBVConst("a",3);
I am a facing problem while implementing 2nd line of verilog statement.
Does anyone know how to implement this in Z3?
With Z3 you can't modify variables. In fact Z3 doesn't call this a variable, it's a constant.
You need to make a new constant that is related to the old constant. For example if you want to say y = x + 1 this would be
var y = ctx.MkBVAdd(x, 1);
If you want to say x = x + 1 you need to introduce a new name for the old and for the new x:
var x2 = ctx.MkBVAdd(x1, 1);

How to calculate the summation of pairwise minima of two ranges with standard formulas?

Problem statement
I'd like to calculate the following formula in a Google Spreadsheet, where x and y are both ranges of n rows and 1 column and t is a variable, using only standard formulas:
Current situation
Right now I'm feeding x (say, A1:A10), y (say, B1:B10) and t (say, D1) to a custom function (myFunction(t, x, y), see below), but executing scripts is rather performance intensive, so I'd like to know if there is a way to make this calculation without using a custom function.
function myFunction(t, x, y)
{
var sum = 0;
for (var i = 0; i < x.length; i++)
{
var xi = parseInt(x[i]);
var yi = parseInt(y[i]);
sum += Math.min(t * xi, yi);
}
return sum;
}
In this example, E1 would become: =myFunction(D1, A1:A10, B1:B10)
Desired situation
I am looking for something like =SUM(MIN(D1 * A1:A10, B1:B10)), but a confirmation or an educated guess that this is not possible is of course also welcome.
I have not been able to test, but I think that the following formula can do what you need.
=SUM(ARRAYFORMULA(IF(ARRAYFORMULA(D1 * A1:A10) < B1:B10; ARRAYFORMULA(D1 * A1:A10); B1:B10)))
UPDATE
Indeed, a better approach is commented by Jelle Fresen, eliminating unnecessary redundancy.
=SUM(ARRAYFORMULA(IF(D1 * A1:A10 < B1:B10; D1 * A1:A10; B1:B10)))

Resources