Iterating of elements in array - optimization

I am trying to write a code of CPLEX OPL on an example of (from control systems) a typical MPC (Model Predictive Control) problem. As described, here:
With optimization variables:
With following parameters:
I have tried to write it but I am stuck at iteration of the array of variable "x" (state variable) as mentioned in the constraint of the optimization problem. The code I have so far written on OPL CPLEX is given as: (The model file as .mod extension on OPL platform)
//data
{string} state = ...;
{string} input = ...;
float A[state][state] =...;
float B[state][input] =...;
float Q[state] =...;
float R[input] =...;
//variable
dvar float State[state];
dvar float Input[input];
minimize
sum( s in state, u in input )
(State[s]*Q[s]*State[s] + Input[u]*R[u]*Input[u]);
subject to {
forall( s in state, u in input )
ct1:
A[s][s]*State[s] + B[s][u]*Input[u] == State[s+1];
}
And the data file which I am using is given as: (the data file of OPL platform with .dat extension)
state = {"x","y","vx","vy"};
input = {"ux","uy"};
A = [[1, 0, 0.2, 0],
[0, 1, 0, 0.2],
[0, 0, 1, 0 ],
[0, 0, 0, 1 ]];
B = [[0, 0],
[0, 0],
[0.2, 0],
[0, 0.2]];
Q = [[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]];
R = [[1, 1],
[1, 1]];
Therefore, I need help kindly to solve this system as I am unable to solve the matter of iteration in the variable of the state variable in the constraint of the given problem.
Your kind help will be highly appreciated as I am stuck on this one for several weeks.

You can turn ct1 into
forall( s in state, u in input:s !=last( state ))
ct1:
A[s][s]*State[s] + B[s][u]*Input[u] == State[next(state,s)];
.mod
//data
{string} state = ...;
{string} input = ...;
float A[state][state] =...;
float B[state][input] =...;
float Q[state] =...;
float R[input] =...;
//variable
dvar float State[state];
dvar float Input[input];
minimize
sum( s in state, u in input )
(State[s]*Q[s]*State[s] + Input[u]*R[u]*Input[u]);
subject to {
forall( s in state, u in input:s !=last( state ))
ct1:
A[s][s]*State[s] + B[s][u]*Input[u] == State[next(state,s)];
}
.dat
state = {"x","y","vx","vy"};
input = {"ux","uy"};
A = [[1, 0, 0.2, 0],
[0, 1, 0, 0.2],
[0, 0, 1, 0 ],
[0, 0, 0, 1 ]];
B = [[0, 0],
[0, 0],
[0.2, 0],
[0, 0.2]];
Q = [1, 1, 1, 1]
;
R = [1, 1];
works

Related

Find minimum absolute difference of elements in numpy array

I have an array of arrays of shape (n, m), as well as an array b of shape (m). I want to create an array c containing distances to the closest element. I can do it with this code:
a = [[11, 2, 3, 4, 5], [4, 4, 6, 1, -2]]
b = [1, 3, 12, 0, 0]
c = []
for inner in range(len(a[0])):
min_distance = float('inf')
for outer in range(len(a)):
current_distance = abs(b[inner] - a[outer][inner])
if min_distance > current_distance:
min_distance = current_distance
c.append(min_distance)
# c=[3, 1, 6, 1, 2]
Elementwise iteration is very slow. What is the numpy way to do this?
If I understand your goal correctly, I think that this would do:
>>> c = np.min(np.abs(np.array(a) - b), axis = 0)
>>> c
array([3, 1, 6, 1, 2])

numpy: Cleanly retrieve coordinates (indices) for highest k values - along a specific axis - in ndarray

I would like to be able to:
select k highest values along (or across?) the first dimension
find indices for those k values
assign those values to a new ndarray of equal shape at their respective positions.
I'm wondering if there is a quicker way to achieve the result exemplified below. In particular, I would like to avoid making the batch indices "manually".
Here's my solution:
# Create unordered array (instrumental to the example)
arr = np.arange(24).reshape(2, 3, 4)
arr_1 = arr[0,::2].copy()
arr_2 = arr[1,1::].copy()
arr[0,::2] = arr_2[:,::-1]
arr[1,1:] = arr_1[:,::-1]
# reshape array to: (batch_size, H*W)
arr_batched = arr.reshape(arr.shape[0], -1)
# find indices for k greatest values along all but the 1st dimension.
gr_ind = np.argpartition(arr_batched, -k)[:, -k]
# flatten and unravel indices.
maxk_ind_flat = gr_ind.flatten()
maxk_ind_shape = np.unravel_index(maxk_ind_flat, arr.shape)
# maxk_ind_shape prints: (array([0, 0, 0, 0]), array([2, 2, 0, 0]), array([1, 0, 2, 3]))
# note: unraveling indices obtained by partitioning an array of shape (2, n) will not keep into account the first dimension (here [0,0,0,0])
# Craft batch indices...
batch_indices = np.repeat(np.arange(arr.shape[0], k)
# ...and join
maxk_indices = tuple([batch_indices]+[ind for ind in maxk_ind_shape[1:]])
# The result is used to re-assign k-highest values for each batch element to a destination matrix:
arr2 = np.zeros_like(arr)
arr2[maxk_indices] = arr[maxk_indices]
# arr2 prints:
# array([[[ 0, 0, 0, 0],
# [ 0, 0, 0, 0],
# [23,22, 0, 0]],
#
# [[ 0, 0, 14, 15],
# [ 0, 0, 0, 0],
# [ 0, 0, 0, 0]]])
Any help would be appreciated.
One way would be to use np.[put/take]_along_axis:
gr_ind = np.argpartition(arr_batched,-k,axis=-1)[:,-k:]
arr_2 = np.zeros_like(arr)
np.put_along_axis(arr_2.reshape(arr_batched.shape),gr_ind,np.take_along_axis(arr_batched,gr_ind,-1),-1)

Distance between non-negative elements of two vectors

I have two vectors:
v1 = [1, 3, 2, 0, 0, 0, 6]
v2 = [2, 0, 1, 0, 4, 2, 1]
I need to compute a distance that is the absolute value of the positive elements on that respective position. For example, the above is:
D(v1, v2) = D(v2, v1) = Abs(1-2) + Abs(2-1) + Abs(6-1) = 7
How can I implement this in numpy?
Here is a solution I found with numpy:
v1 = np.array(v1)
v2 = np.array(v2)
sum(abs(v1[(v1>0)&(v2>0)] - v2[(v1>0)&(v2>0)]))
Hope this helps

how to implement the variable array with one and zero in tensorflow

I'm totally new on tensorflow, and I just want to implement a kind of selection function by using matrices multiplication.
example below:
#input:
I = [[9.6, 4.1, 3.2]]
#selection:(single "1" value , and the other are "0s")
s = tf.transpose(tf.Variable([[a, b, c]]))
e.g. s could be [[0, 1, 0]] or [[0, 0, 1]] or [[1, 0, 0]]
#result:(multiplication)
o = tf.matul(I, s)
sorry for the poor expression,
I intend to find the 'solution' in distribution functions with different means and sigmas. (value range from 0 to 1).
so now, i have three variable i, j, index.
value1 = np.exp(-((index - m1[i]) ** 2.) / s1[i]** 2.)
value2 = np.exp(-((index - m2[j]) ** 2.) / s2[j]** 2.)
m1 = [1, 3, 5] s = [0.2, 0.4, 0.5]. #first graph
m2 = [3, 5, 7]. s = [0.5, 0.5, 1.0]. #second graph
I want to get the max or optimization of total value
e.g. value1 + value2 = 1+1 = 2 and one of the solutions: i = 2, j=1, index=5
or I could do this in the other module?

Delete rows from a ndarray in python

I have a 2D - array A, which contains the x and y coordinates of points
array([[ 0, 0],
[ 0, 0],
[ 0, 0],
[ 3, 4],
[ 4, 1],
[ 5, 10],
[ 9, 7]])
as you can see the point ( 0 , 0 ) appears more often.
I want to delete this point so that the array looks like this:
array([[ 3, 4],
[ 4, 1],
[ 5, 10],
[ 9, 7]])
Since the array in real is very huge, it is very important to do this without for loops, otherwise it takes very long.
I'm new to python but i'm used to matlab, where I can solve it very easily with:
A (A(:,1) == 0 & A(:,2) == 0, :) = []
I thought it is almost the same or very similar in python, but I can't figure it out - am totally stuck. Errors like "use a.any()/all()" or "ufunc "bitwise_and" not supported for the input types" appear and I don't know what I should change.
Technically what you are doing in MATLAB is not deleting elements from A. What you are actually doing is creating a new array that lacks the elements of A. It is equivalent to:
>> A = A (A(:,1) ~= 0 | A(:,2) ~= 0, :);
You can do exactly the same thing in numpy:
>>> a = a[(a[:,0] != 0) | (a[:,1] != 0), :]
However, thanks to numpy's automatic broadcasting, you can make this simpler:
>>> a = a[(a != [0, 0]).any(1)]
This will work for any target array so long as it has the same number of columns as a.