Cplex c++ multidimensional decision variable - c++

I'm new using cplex and I try to find some information on internet but didn't find clear stuff to help me in my problem.
I have P[k] k will be equal to 1 to 4
and I have a decision variable x[i][k] must be equal to 0 or 1 (also p[k])
the i is between 1 to 5
For now I do like this
IloEnv env;
IloModel model(env);
IloNumVarArray p(env);
p.add(IloNumVar(env, 0, 1));
p.add(IloNumVar(env, 0, 1));
p.add(IloNumVar(env, 0, 1));
IloIntVar x(env, 0, 1);
model.add(IloMaximize(env, 1000 * p[1] + 2000 * p[2] + 500 * p[3] + 1500 * p[4]));
for(int k = 1; k <= 4; k++){
for(int i = 1; i <= 5; i++){
model.add(x[i][k] + x[i][k] + x[i][k] + x[i][k] + x[i][k] => 2 * p[k]; );
}}
The loop should do something like this:
x[1][1] + x[2][1] + x[3][1] + x[4][1] + x[5][1] => 2 * p[1];
x[1][2] + x[2][2] + x[3][2] + x[4][2] + x[5][2] => 2 * p[2];
x[1][3] + x[2][3] + x[3][3] + x[4][3] + x[5][3] => 2 * p[3];
x[1][4] + x[2][4] + x[3][4] + x[4][4] + x[5][4] => 3 * p[4];
but I'm far away from this result.
Does anyone have an idea?
Thanks

You probably want to use an IloNumExpr
for(int k = 0; k < 4; k++){
IloNumExpr sum_over_i(env);
for(int i = 0; i < 5; i++){
sum_over_i += x[i][k];
}
model.add(sum_over_i >= 2 * p[k]; );
}
You also need to declare x as a 2-dimensional array.
IloArray x(env, 4);
for (int k = 0; k < 4; ++k)
x[k] = IloIntVarArray(env, 5, 0, 1);
Also, in c++, array indices are from 0 to size-1, not 1 to size. Your objective should be written
model.add(IloMaximize(env, 1000 * p[0] + 2000 * p[1] + 500 * p[2] + 1500 * p[3]));

Usertfwr already gave a good answer, but I would like to give another version of solution which might help you to code CPLEX applications in a more generic way. First, I would suggest you to use a text file to hold all the data (objective function coefficients) which will be fed into the program. In your case, you only have to copy literally the following matrix like data to notepad and name it as “coef.dat”:
[1000, 2000, 500, 1500]
Now comes the full code, let me know if have difficulties understanding any statement:
#include <ilcplex/ilocplex.h>
#include <fstream>
#include <iostream>
ILOSTLBEGIN
int main(int argc, char **argv) {
IloEnv env;
try {
const char* inputData = "coef.dat";
ifstream inFile(inputData); // put your data in the same directory as your executable
if(!inFile) {
cerr << "Cannot open the file " << inputData << " successfully! " <<endl;
throw(-1);
}
// Define parameters (coef of objective function)
IloNumArray a(env);
// Read in data
inFile >> a;
// Define variables
IloBoolVarArray p(env, a.getSize()); // note that a.getSize() = 4
IloArray<IloBoolVarArray> X(env, 5); // note that you need a 5x4 X variables, not 4x5
for(int i = 0; i < 5; i++) {
X[i] = IloBoolVarArray(env,4);
}
// Build model
IloModel model(env);
// Add objective function
IloExpr objFun (env);
for(int i = 0; i < a.getSize(); i++){
objFun += a[i]*p[i];
}
model.add(IloMaximize(env, objFun));
objFun.end();
// Add constraints -- similar to usertfwr’s answer
for(int i = 0; i < 4; k++){
IloExpr sumConst (env);
for(int j = 0; j < 5; i++){
sumConst += x[j][i];
}
// before clearing sumConst expr, add it to model
model.add(sumConst >= 2*p[i]);
sumConst.end(); // very important to end after having been added to the model
}
// Extract the model to CPLEX
IloCplex cplex(mod);
// Export the LP model to a txt file to check correctness
//cplex.exportModel("model.lp");
// Solve model
cplex.solve();
}
catch (IloException& e) {
cerr << "Concert exception caught: " << e << endl;
}
catch (...) {
cerr << "Unknown exception caught" << endl;
}
env.end();
}

Related

OpenCV - Accessing Mat data using for loop

I'm trying to create a convolution function but I'm having trouble during the access to the kernel data (cv::Mat).
I create the 3x3 kernel:
cv::Mat krn(3, 3, CV_32FC1);
krn.setTo(1);
krn = krn/9;
And I try to loop over it. Next the image Mat will be the image to which I want to apply the convolution operator and output will be the result of convolution:
for (int r = 0; r < image.rows - krn.rows; ++r) {
for (int c = 0; c < image.cols - krn.cols; ++c) {
int sum = 0;
for (int rs = 0; rs < krn.rows; ++rs) {
for (int cs = 0; cs < krn.cols; ++cs) {
sum += krn.data[rs * krn.cols + cs] * image.data[(r + rs) * image.cols + c + cs];
}
}
output.data[(r+1)*src.cols + c + 1]=sum; // assuming 3x3 kernel
}
}
However the output is not as desired (only randomic black and white pixel).
However, if I change my code this way:
for (int r = 0; r < image.rows - krn.rows; ++r) {
for (int c = 0; c < image.cols - krn.cols; ++c) {
int sum = 0;
for (int rs = 0; rs < krn.rows; ++rs) {
for (int cs = 0; cs < krn.cols; ++cs) {
sum += 0.11 * image.data[(r + rs) * image.cols + c + cs]; // CHANGE HERE
}
}
output.data[(r+1)*src.cols + c + 1]=sum; // assuming 3x3 kernel
}
}
Using 0.11 instead of the kernel values seems to give the correct output.
For this reason I think I'm doing something wrong accessing the kernel's data.
P.S: I cannot use krn.at<float>(rs,cs).
Thanks!
Instead of needlessly using memcpy, you can just cast the pointer. I'll use a C-style cast because why not.
cv::Mat krn = 1 / (cv::Mat_<float>(3,3) <<
1, 2, 3,
4, 5, 6,
7, 8, 9);
for (int i = 0; i < krn.rows; i += 1)
{
for (int j = 0; j < krn.cols; j += 1)
{
// to see clearly what's happening
uint8_t *byteptr = krn.data + krn.step[0] * i + krn.step[1] * j;
float *floatptr = (float*) byteptr;
// or in one step:
float *floatptr = (float*) (krn.data + krn.step[0] * i + krn.step[1] * j);
cout << "krn.at<float>(" << i << "," << j << ") = " << (*floatptr) << endl;
endl;
}
}
krn.at<float>(0,0) = 1
krn.at<float>(0,1) = 0.5
krn.at<float>(0,2) = 0.333333
krn.at<float>(1,0) = 0.25
krn.at<float>(1,1) = 0.2
krn.at<float>(1,2) = 0.166667
krn.at<float>(2,0) = 0.142857
krn.at<float>(2,1) = 0.125
krn.at<float>(2,2) = 0.111111
Note that pointer arithmetic may not be obvious. if you have a uint8_t*, adding 1 moves it by one uint8_t, and if you have a float*, adding 1 moves it by one float which is four bytes. The step[] contains offsets expressed in bytes.
Consult the documentation for details, which include information on the step[] array that contains the strides/steps to calculate the offset given a tuple of indices into the matrix.
cv::Mat::data is pointer of type uchar.
By data[y * cols + x] you access some byte of stored float values in krn. To get full float values use at method template:
krn.at<float>(rs,cs)
Consider changing type of sum variable to be real. Without this, you may lose partial results when calculating convolution .
So, if you cannot use at, just read 4 bytes from data pointer:
float v = 0.0;
memcpy(&v, krn.data + (rs * krn.step + cs * sizeof(float)), 4);
step - means total bytes occupied by one line in mat.

DTW Algorithm OCT-file

I am trying to create a Dynamic Time Warping(DTW) function, which will calculate the minimum distance between the two signals provided to it. It is based on the following algorithm,
DTW Algorithm:-
int DTWDistance(s: array [1..n], t: array [1..m]) {
DTW := array [0..n, 0..m]
w := abs(n-m)// adapt window size (*)
for i := 0 to n
for j:= 0 to m
DTW[i, j] := infinity
DTW[0, 0] := 0
for i := 1 to n
for j := max(1, i-w) to min(m, i+w)
cost := d(s[i], t[j])
DTW[i, j] := cost + minimum(DTW[i-1, j ], // insertion
DTW[i, j-1], // deletion
DTW[i-1, j-1]) // match
return DTW[n, m]
more info DTW Algorithm
Now I was able to create an Octave function of this Algorithm and its working properly.
Octave Function:-
function dtw_distance = dtw2(a,b)
length_a = length(a);
length_b = length(b);
an=zeros(length_a+1,length_b+1);
an(:,:)=9999;
an(1,1)=0;
cost=0;
#Here we have also implemented the window size.
w=abs(length_a-length_b);
for i=1:length_a
for j=max(1,i-w):min(length_b,i+w)
cost=abs(a(i)-b(j));
an(i+1,j+1)=cost+min([an(i,j+1),an(i+1,j),an(i,j)]);
end
end
an;
dtw_distance=an(length_a+1,length_b+1);
Now the computation time of this code increases as the size of argument increases. Hence I am trying to create OCT file which is written in C++ for faster execution.
C++ OCT File:-
#include <octave/oct.h>
octave_idx_type getMax(octave_idx_type a, octave_idx_type b){
return (a>b)?a:b;
}
octave_idx_type getMin(octave_idx_type a, octave_idx_type b){
return (a<b)?a:b;
}
DEFUN_DLD (dtw3, args, , "Find DTW of two Signals With Window")
{
int nargin = args.length();
if (nargin != 2)
print_usage();
else
{
NDArray A = args(0).array_value();
NDArray B = args(1).array_value();
octave_stdout << "Size of A is" << A.length();
octave_stdout << "Size of B is" << B.length();
if (! error_state)
{
octave_idx_type row = A.length()+1;
octave_idx_type col = B.length()+1;
Matrix results (row,col);
for(octave_idx_type i = 0; i <= row ; i++)
{
for(octave_idx_type j=0; j<= col ; j++)
{
results(i,j)=9999;
}
}
octave_stdout << "row col" << results.dim1() << results.dim2() ;
octave_stdout << "row end" << results(row,0) ;
octave_stdout << "col end" << results(0,col) ;
results(0,0)=0;
octave_idx_type win = (row>col)?(row-col):(col-row);
octave_idx_type cost = 0;
for(octave_idx_type i = 1 ; i <= row ; i++)
{
for(octave_idx_type j = getMax(1,i-win) ; j <= getMin(col,i+win) ; j++)
{
cost=(A(i)>B(j))?(A(i)-B(j)):(B(j)-A(i));
results(i,j)= cost + getMin(getMin(results(i-1,j),results(i,j-1)),results(i-1,j-1));
}
}
octave_stdout << "Ans is: " << results(row,col);
return octave_value(results(row,col));
}
}
}
Sample Input/Output
Input - Arg1: [1 2 3 4 5] , Arg2: [1 2 3 4 5 6 7]
Output:
For Octave Function: Ans is 3
For OCT FIle:
* Error in /usr/lib/x86_64-linux-gnu/octave/4.0.0/exec/x86_64-pc-linux-gnu/octave-gui': double free or corruption (!prev): 0x00007f24e81eb0a0 ***
panic: Aborted -- stopping myself...
*** Error in/usr/lib/x86_64-linux-gnu/octave/4.0.0/exec/x86_64-pc-linux-gnu/octave-gui': malloc(): memory corruption: 0x00007f24e81eb230 *
Input : Arg1 : A=rand(1,221), Args2: B=rand(1,299)
Output:
For Octave Function: Ans is 72.63
For OCT File:
* Error in `/usr/lib/x86_64-linux-gnu/octave/4.0.0/exec/x86_64-pc-linux-gnu/octave-gui': double free or corruption (!prev): 0x00007f57a06ad940 *
panic: Aborted -- stopping myself...
Size of A is221Size of B is299row col222300row end9999col end9999Ans is:1 attempting to save variables to 'octave-workspace'...
save to 'octave-workspace' complete
Aborted (core dumped)
My Problem:
First of all what is this double free corruption error I am getting when using OCT files?
The answer for Octave file and OCT file is different, whats the error in OCT file which is causing this?
Thank you.
First, you should read how to debug oct files (http://wiki.octave.org/Debugging_Octave#Debugging_oct-files)
Then you'll find this part:
Matrix results (row,col);
for(octave_idx_type i = 0; i <= row ; i++)
{
for(octave_idx_type j=0; j<= col ; j++)
{
results(i,j)=9999;
}
}
The Matrix result has dimension row, col but you are writing until i<=row and j<=col which is 1 beyond bounds. Try i<row and j<col
There were so many problems in your code which was too much to describe, here my changes. I've replaces some functions which buildt-in functions:
#include <octave/oct.h>
DEFUN_DLD (dtw3, args, , "Find DTW of two signals with window")
{
int nargin = args.length();
if (nargin != 2)
print_usage();
Matrix A = args(0).array_value();
Matrix B = args(1).array_value();
octave_stdout << "Size of A is " << A.length() << std::endl;;
octave_stdout << "Size of B is " << B.length() << std::endl;
if (! error_state)
{
octave_idx_type n = A.length();
octave_idx_type m = B.length();
Matrix results (n + 1, m + 1);
for(octave_idx_type i = 0; i <= n ; i++)
for(octave_idx_type j = 0; j <= m ; j++)
results(i, j) = octave_Inf;
results(0, 0) = 0;
octave_idx_type win = abs (n-m);
double cost = 0;
for(octave_idx_type i = 1 ; i <= n ; i++)
for(octave_idx_type j = std::max(1, i-win) ; j <= std::min(m, i+win) ; j++)
{
cost = abs(A(i-1) - B(j-1));
results(i, j) = cost + std::min(std::min(results(i-1,j),results(i,j-1)),results(i-1,j-1));
}
//octave_stdout << results << std::endl;
return ovl(results(n, m));
}
}

What is wrong with this code to retrieve bgr values of an image using the step method

Here is the code I got from a reputable source but its not working:
Mat img = imread("/home/w/d1",CV_LOAD_IMAGE_COLOR);
unsigned char *input = (unsigned char*)(img.data);
int i,j,r,g,b;
for(int i = 0;i < img.rows ;i++){
for(int j = 0;j < img.cols ;j++){
b = input[img.step * j + i ] ;
g = input[img.step * j + i + 1];
r = input[img.step * j + i + 2];
cout << b << g <<r;
}
}
When I run it the output isn't the same as when I do a cout << img;
I think it might be something to do with the new C++ interface. If that is so and I'm supposed to use the step1 method, can some one show me how to update my code to access BGR values with the step1 method. I couldn't find online doc. on how to use step1. Thanks in advance for any help.
your code looks basically right, but as far as I see, your ordering is wrong.
You must access
value = data[img.step*ROW + COL] but you have row and col switched.
edit: in addition you need to multiply the COL with the number of channels:
value = data[img.step*ROW + #channels*COL + currentChannel]
try:
Mat img = imread("/home/w/d1",CV_LOAD_IMAGE_COLOR);
unsigned char *input = (unsigned char*)(img.data);
int i,j,r,g,b;
for(int i = 0;i < img.rows ;i++){
for(int j = 0;j < img.cols ;j++){
b = input[img.step * i + 3*j ] ; // 3 == img.channels()
g = input[img.step * i + 3*j + 1];
r = input[img.step * i + 3*j + 2];
cout << b << g <<r;
}
}
maybe you want to avoid the 'raw data' approach:
for(int i=0; i<img.rows; i++) {
for(int j=0; j<img.cols; j++) {
Vec3b pix = img.at<Vec3b>(i,j);
cout << int(pix[0]) << int(pix[1]) << int(pix[2]) << endl;
}
}

class variable access within recursive function

for an intro program, we were asked to build a program that could find every single possible working magic square of a given size. I am having trouble modifying a class variable from within a recursive function. I am trying to increment the number of magic squares found every time the combination of numbers I am trying yields a magic square.
More specifically, I am trying to modify numSquares within the function recursiveMagic(). After setting a breakpoint at that specific line, the variable, numSquares does not change, even though I am incrementing it. I think it has something to do with the recursion, however, I am not sure. If you want to lend some advice, I appreciate it.
//============================================================================
// Name : magicSquare.cpp
// Author :
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
using namespace std;
/**
* MagicSquare
*/
class MagicSquare {
private:
int magicSquare[9];
int usedNumbers[9];
int numSquares;
int N;
int magicInt;
public:
MagicSquare() {
numSquares = 0;
for (int i = 0; i < 9; i++)
usedNumbers[i] = 0;
N = 3; //default is 3
magicInt = N * (N * N + 1) / 2;
}
MagicSquare(int n) {
numSquares = 0;
for (int i = 0; i < 9; i++)
usedNumbers[i] = 0;
N = n;
magicInt = N * (N * N + 1) / 2;
}
void recursiveMagic(int n) {
for (int i = 1; i <= N * N + 1; i++) {
if (usedNumbers[i - 1] == 0) {
usedNumbers[i - 1] = 1;
magicSquare[n] = i;
if (n < N * N)
recursiveMagic(n + 1);
else {
if (isMagicSquare()) {
numSquares++; //this is the line that is not working correctly
printSquare();
}
}
usedNumbers[i - 1] = 0;
}
}
}
//To efficiently check all rows and collumns, we must convert the one dimensional array into a 2d array
//since the sudo 2d array looks like this:
// 0 1 2
// 3 4 5
// 6 7 8
//the following for-if loops convert the i to the appropriate location.
bool isMagicSquare() {
for (int i = 0; i < 3; i++) {
if ((magicSquare[i * 3] + magicSquare[i * 3 + 1] + magicSquare[i * 3 + 2]) != magicInt) //check horizontal
return false;
else if ((magicSquare[i] + magicSquare[i + 3] + magicSquare[i + 6]) != magicInt) // check vertical
return false;
}
if ((magicSquare[0] + magicSquare[4] + magicSquare[8]) != magicInt)
return false;
if ((magicSquare[6] + magicSquare[4] + magicSquare[2]) != magicInt)
return false;
return true;
}
/**
* printSquare: prints the current magic square combination
*/
void printSquare() {
for (int i = 0; i < 3; i++)
cout << magicSquare[i * 3] << " " << magicSquare[i * 3 + 1]
<< " " << magicSquare[i * 3 + 2] << endl;
cout << "------------------" << endl;
}
/**
* checkRow: checks to see if the current row will complete the magic square
* #param i - used to determine what row is being analyzed
* #return true if it is a working row, and false if it is not
*/
bool checkRow(int i) {
i = (i + 1) % 3 - 1;
return (magicSquare[i * 3] + magicSquare[i * 3 + 1] + magicSquare[i * 3 + 2]) == magicInt;
}
int getnumSquares() {
return numSquares;
}
}; //------End of MagicSquare Class-----
int main() {
MagicSquare square;
cout << "Begin Magic Square recursion:" << endl << "------------------"
<< endl;
square.recursiveMagic(0);
cout << "Done with routine, returned combinations: " << square.getnumSquares() << endl;
return 0;
}
The array is being overwritten leading to overwriting the numSquares field.
class MagicSquare {
private:
int magicSquare[9];
int usedNumbers[9];
Changes to
class MagicSquare {
private:
int magicSquare[10];
int usedNumbers[10];
Also in your initializer the loop says < 9 but what you want to say is < 10. Or just use memset is better for that purpose.

Laguerre interpolation algorithm, something's wrong with my implementation

This is a problem I have been struggling for a week, coming back just to give up after wasted hours...
I am supposed to find coefficents for the following Laguerre polynomial:
P0(x) = 1
P1(x) = 1 - x
Pn(x) = ((2n - 1 - x) / n) * P(n-1) - ((n - 1) / n) * P(n-2)
I believe there is an error in my implementation, because for some reason the coefficents I get seem way too big. This is the output this program generates:
a1 = -190.234
a2 = -295.833
a3 = 378.283
a4 = -939.537
a5 = 774.861
a6 = -400.612
Description of code (given below):
If you scroll the code down a little to the part where I declare array, you'll find given x's and y's.
The function polynomial just fills an array with values of said polynomial for certain x. It's a recursive function. I believe it works well, because I have checked the output values.
The gauss function finds coefficents by performing Gaussian elimination on output array. I think this is where the problems begin. I am wondering, if there's a mistake in this code or perhaps my method of veryfying results is bad? I am trying to verify them like that:
-190.234 * 1.5 ^ 5 - 295.833 * 1.5 ^ 4 ... - 400.612 = -3017,817625 =/= 2
Code:
#include "stdafx.h"
#include <conio.h>
#include <iostream>
#include <iomanip>
#include <math.h>
using namespace std;
double polynomial(int i, int j, double **tab)
{
double n = i;
double **array = tab;
double x = array[j][0];
if (i == 0) {
return 1;
} else if (i == 1) {
return 1 - x;
} else {
double minusone = polynomial(i - 1, j, array);
double minustwo = polynomial(i - 2, j, array);
double result = (((2.0 * n) - 1 - x) / n) * minusone - ((n - 1.0) / n) * minustwo;
return result;
}
}
int gauss(int n, double tab[6][7], double results[7])
{
double multiplier, divider;
for (int m = 0; m <= n; m++)
{
for (int i = m + 1; i <= n; i++)
{
multiplier = tab[i][m];
divider = tab[m][m];
if (divider == 0) {
return 1;
}
for (int j = m; j <= n; j++)
{
if (i == n) {
break;
}
tab[i][j] = (tab[m][j] * multiplier / divider) - tab[i][j];
}
for (int j = m; j <= n; j++) {
tab[i - 1][j] = tab[i - 1][j] / divider;
}
}
}
double s = 0;
results[n - 1] = tab[n - 1][n];
int y = 0;
for (int i = n-2; i >= 0; i--)
{
s = 0;
y++;
for (int x = 0; x < n; x++)
{
s = s + (tab[i][n - 1 - x] * results[n-(x + 1)]);
if (y == x + 1) {
break;
}
}
results[i] = tab[i][n] - s;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int num;
double **array;
array = new double*[5];
for (int i = 0; i <= 5; i++)
{
array[i] = new double[2];
}
//i 0 1 2 3 4 5
array[0][0] = 1.5; //xi 1.5 2 2.5 3.5 3.8 4.1
array[0][1] = 2; //yi 2 5 -1 0.5 3 7
array[1][0] = 2;
array[1][1] = 5;
array[2][0] = 2.5;
array[2][1] = -1;
array[3][0] = 3.5;
array[3][1] = 0.5;
array[4][0] = 3.8;
array[4][1] = 3;
array[5][0] = 4.1;
array[5][1] = 7;
double W[6][7]; //n + 1
for (int i = 0; i <= 5; i++)
{
for (int j = 0; j <= 5; j++)
{
W[i][j] = polynomial(j, i, array);
}
W[i][6] = array[i][1];
}
for (int i = 0; i <= 5; i++)
{
for (int j = 0; j <= 6; j++)
{
cout << W[i][j] << "\t";
}
cout << endl;
}
double results[6];
gauss(6, W, results);
for (int i = 0; i < 6; i++) {
cout << "a" << i + 1 << " = " << results[i] << endl;
}
_getch();
return 0;
}
I believe your interpretation of the recursive polynomial generation either needs revising or is a bit too clever for me.
given P[0][5] = {1,0,0,0,0,...}; P[1][5]={1,-1,0,0,0,...};
then P[2] is a*P[0] + convolution(P[1], { c, d });
where a = -((n - 1) / n)
c = (2n - 1)/n and d= - 1/n
This can be generalized: P[n] == a*P[n-2] + conv(P[n-1], { c,d });
In every step there is involved a polynomial multiplication with (c + d*x), which increases the degree by one (just by one...) and adding to P[n-1] multiplied with a scalar a.
Then most likely the interpolation factor x is in range [0..1].
(convolution means, that you should implement polynomial multiplication, which luckily is easy...)
[a,b,c,d]
* [e,f]
------------------
af,bf,cf,df +
ae,be,ce,de, 0 +
--------------------------
(= coefficients of the final polynomial)
The definition of P1(x) = x - 1 is not implemented as stated. You have 1 - x in the computation.
I did not look any further.