GAMS: Why is the value of the parameter pp(ss,ii) coming out as zero? - gams-math

I have written the following code below in GAMS and it may not be the best in the world but I don't see why it keeps returning the value of the parameter pp(ss,ii) as all zeros when it should be a matrix of exactly 2 ones in each row.
Could you please help me?
set
ii set of bays /1*10/
ss set of solutions /1*45/
Parameters
H Number of bays /10/
C Number of cranes /2/
r Safety Margin /1/
p(ii)
pp(ss,ii)
;
p(ii) = 0;
Scalar i; i=1;
Scalar j; j=i;
Scalar k; k=C;
Scalar qq;
Scalar q;
Scalar kk;
Scalar m;
Scalar n;
Scalar stop /0/;
Scalar stop1 /0/;
Scalar stop2 /0/;
Scalar F /1/;
Scalar k1 /0/;
Scalar k2 /0/;
while ((i <= H-(C-1)*r-1*(C-1)),
while((j<=H and stop=0),
if (sum(ii, p(ii)) = C,
stop = 1;
);
loop(ii$(ord(ii)=j),
p(ii) = 1;
);
j = j+r+1;
);
if (sum(ii, p(ii)) = C,
loop((ss,ii)$(ord(ss)=F),
pp(ss,ii) = p(ii);
);
);
F = F+1;
qq=0;
for (q = 1 to H-(C-1)*r-1*(C-1)-1,
loop (ii$((ord(ii) = q) and (stop1 = 0)),
if ((p(ii) = 1) ,
qq=1;
stop1 = 1;
);
);
);
* if (qq=0,
* if (p(ii)$(ord(ii)= H-(C-1)*r-1*(C-1))=1 and p(ii)$(ord(ii)=H) = 1,
* abort "finished";
* );
*
* );
k1 = 0;
k2 = 0;
if(qq=0,
loop(ii$(ord(ii)= H-(C-1)*r-1*(C-1)),
if (p(ii) = 1,
k1 = 1;
);
);
loop(ii$(ord(ii)=H),
if (p(ii) = 1,
k2 = 1;
);
);
abort$(k1 + k2 = 2) "Finished";
);
if (j-r-1 = H,
loop(ii$(ord(ii)=H-(C-k)*r-(C-k)) ,
if(k = C,
k = k-1;
elseif (p(ii)= 1),
k = k-1;
);
);
if(k=1,
loop(ii,
p(ii)=0;
);
i = i+1;
j = i;
k = C;
else
loop(ii$(ord(ii)=H),
p(ii) = 0;
);
m=1;
n=0;
while((n<k),
loop(ii$(ord(ii)=m),
if(p(ii) = 1,
n = n+1;
);
m = m+1;
);
);
loop(ii$(ord(ii) = m-1),
p(ii) = 0;
);
loop(ii$(ord(ii) = m),
p(ii) = 1;
);
j = m+r+1;
);
else
loop(ii$(ord(ii) = j-r-1),
p(ii)=0;
);
loop(ii$(ord(ii) = j-r),
p(ii)= 1;
);
j=j+1;
);
);
Display pp;

On how to hunt errors in rather complex code:
first look up where you assigne values to your variable. You set pp = p; one time.
look up if p is right. Display says p is zero too.
during the pre solve process you can add aditional "display" statements in the middle of you code - to get the values at this points.
This gives you the hint that there are some values in p - but when you put the display statement after if (sum(ii, p(ii)) = C, you wont get any display calls -> sum(p) <> C ?
A closer Look into the p before the if and you'll see that there are three values inside which are more than two.
At the last step its simple to see the error in you code. It's the position of you stop = 1; criteria. Its placed at the beginning of the while loop. The loop will still continue in the current iteration and create a third value.
Solution:
Change the criteria to if (sum(ii, p(ii)) = C-1, or put the criteria at the end of the while loop.

Related

How to fix "submatrix incorrectly defined" in Scilab?

I am trying to find three parameters (a, b, c) to fit my experimental data using ODE solver and optimization by least squares using Scilab in-built functions.
However, I keep having the message "submatrix incorrectly defined" at line "y_exp(:,1) = [0.135 ..."
When I try another series of data (t, yexp) such as the one used in the original template I get no error messages. The template I use was found here: https://wiki.scilab.org/Non%20linear%20optimization%20for%20parameter%20fitting%20example
function dy = myModel ( t , y , a , b, c )
// The right-hand side of the Ordinary Differential Equation.
dy(1) = -a*y(1) - b*y(1)*y(2)
dy(2) = a*y(1) - b*y(1)*y(2) - c*y(2)
endfunction
function f = myDifferences ( k )
// Returns the difference between the simulated differential
// equation and the experimental data.
global MYDATA
t = MYDATA.t
y_exp = MYDATA.y_exp
a = k(1)
b = k(2)
c = k(3)
y0 = y_exp(1,:)
t0 = 0
y_calc=ode(y0',t0,t,list(myModel,a,b,c))
diffmat = y_calc' - y_exp
// Make a column vector
f = diffmat(:)
MYDATA.funeval = MYDATA.funeval+ 1
endfunction
// Experimental data
t = [0,20,30,45,75,105,135,180,240]';
y_exp(:,1) =
[0.135,0.0924,0.067,0.0527,0.0363,0.02445,0.01668,0.012,0.009]';
y_exp(:,2) =
[0,0.00918,0.0132,0.01835,0.0261,0.03215,0.0366,0.0393,0.0401]';
// Store data for future use
global MYDATA;
MYDATA.t = t;
MYDATA.y_exp = y_exp;
MYDATA.funeval = 0;
function val = L_Squares ( k )
// Computes the sum of squares of the differences.
f = myDifferences ( k )
val = sum(f.^2)
endfunction
// Initial guess
a = 0;
b = 0;
c = 0;
x0 = [a;b;c];
[fopt ,xopt]=leastsq(myDifferences, x0)
Does anyone know how to approach this problem?
Just rewrite lines 28,29 as
y_exp = [0.135,0.0924,0.067,0.0527,0.0363,0.02445,0.01668,0.012,0.009
0,0.00918,0.0132,0.01835,0.0261,0.03215,0.0366,0.0393,0.0401]';
or insert a clear at line 1 (you may have defined y_exp before with a different size).

How to pass a pointer argument to a function without knowing the size to be allocated for that pointer

I know this question is very noob. I am trying to understand how the pointer thing works. I studied basics of C but still did not understand this.
Given this piece of function:
+ (void)nv21ToRgbWithWidth:(unsigned int)width height:(unsigned int)height yuyv:(unsigned char *)yuyv rgb:(unsigned char *)rgb
{
const int nv_start = width * height ;
UInt32 i, j, index = 0, rgb_index = 0;
UInt8 y, u, v;
int r, g, b, nv_index = 0;
for(i = 0; i < height ; i++)
{
for(j = 0; j < width; j ++){
//nv_index = (rgb_index / 2 - width / 2 * ((i + 1) / 2)) * 2;
nv_index = i / 2 * width + j - j % 2;
y = yuyv[rgb_index];
u = yuyv[nv_start + nv_index ];
v = yuyv[nv_start + nv_index + 1];
r = y + (140 * (v-128))/100; //r
g = y - (34 * (u-128))/100 - (71 * (v-128))/100; //g
b = y + (177 * (u-128))/100; //b
if(r > 255) r = 255;
if(g > 255) g = 255;
if(b > 255) b = 255;
if(r < 0) r = 0;
if(g < 0) g = 0;
if(b < 0) b = 0;
index = rgb_index % width + (height - i - 1) * width;
rgb[index * 3+0] = b;
rgb[index * 3+1] = g;
rgb[index * 3+2] = r;
rgb_index++;
}
}
}
How am I suppose to know how the unsigned char * for rgb should be initialized before passing in to the function?
I tried calling the function like this:
unsigned char *rgb = NULL;
[MyClass nv21ToRgbWithWidth:imageWidth height:imageHeight yuyv:yuyvValues rgb:rgb];
But the the program crashes on this line:
rgb[index * 3+0] = b;
I see rgb was initialized with NULL, so you can't assign values. So, I thought of initializing an array and pass it to pointer rgb like this:
unsigned char rgbArr[10000];
unsigned char *rgb = rgbArr;
but the function still crashes. I really don't know how should I pass the rgb parameter in this function. Please help me understand this.
The expected size in bytes seems to be at least height*width*3; it might be that allocating such an array as a local variable (as you do with unsigned char rgbArr[10000]) exceeds a stack limit; The program likely crashes in such a case. I'd try to use the heap instead:
unsigned char* rgb = malloc(imageHeight*imageWidth*3);
[MyClass nv21ToRgbWithWidth:imageWidth height:imageHeight yuyv:yuyvValues rgb:rgb];
...
free(rgb);
That is what the malloc(), calloc(), realloc() and free() functions are for. Don't forget to use the free() function to prevent memory leaks... I hope that helps.

OpenCV Mat image data structure

I have an image that has been processed throw:
//UIImage to Mat
cv::Mat originalMat = [self cvMatFromUIImage:inputImage];
//Grayscale
cv::Mat grayMat;
cv::cvtColor(originalMat, grayMat, CV_RGB2GRAY);
//Blur
cv::Mat gaussMat;
cv::GaussianBlur( grayMat , gaussMat, cv::Size(9, 9), 2, 2 );
//Threshold
cv::threshold(grayMat,tMat,100,255,cv::THRESH_BINARY);
than I want to analyze (calculate qty of white and black points) that belows to line. For instance: I have an image 100x120px and I want to check lines where x = 5 and y = from 0 to 119; and vice versa x = 0..99; y = 5;
so I expect that Mat will contains x - Mat.cols and y - Mat.rows but looks it saves data in another way. for example I've tried to change pixels color that belows to lines but didn't get 2 lines:
for( int x = 0; x < tMat.cols; x++ ){
tMat.at<cv::Vec4b>(5,x)[0] = 100;
}
for( int y = 0; y < tMat.rows; y++ ){
tMat.at<cv::Vec4b>(y,5)[0] = 100;
}
return [self UIImageFromCVMat:tMat];
result for white image:
why I did't get 2 lines? Is it possible to draw\check lines in Mat directly? what if I going to check line that calculates via y = kx + b?
You are accessing the pixel values in the wrong way. You are working with image that only has one channel, that's why you should access pixel values like this:
for (int x = 0; x < tMat.cols; x++){
tMat.at<unsigned char>(5, x) = 100;
}
for (int y = 0; y < tMat.rows; y++){
tMat.at<unsigned char>(y, 5) = 100;
}
The Mat element's type is defined by two properties - the number of channels and the underlying type of data. If you do not know the meaning of those terms, I strongly suggest that you read the documentation for methods cv::Mat::type(), cv::Mat::channels() and cv::Mat::depth().
Two more examples:
mat.at<float>(x, y) = 1.0f; // if mat type is CV_32FC1
mat.at<cv::Vec3b>(x, y) = Vec3b(1, 2, 3); // if mat type is CV_8UC3
Probably an issue with your Mat data types. The output of threshold is a single channel image that is 8-bit or 32-bit (http://docs.opencv.org/2.4/modules/imgproc/doc/miscellaneous_transformations.html?highlight=threshold#threshold), so you probably should not be setting values with Mat.at<Vec4b>[0].
Here's a function to return the type of your matrix. Usage is in the commented out part. Copied from How to find out what type of a Mat object is with Mat::type() in OpenCV.
std::string type2str(int type){
//string ty = type2str( comparisonResult.type() );
//printf("Matrix: %s %dx%d \n", ty.c_str(), comparisonResult.cols, comparisonResult.rows );
string r;
uchar depth = type & CV_MAT_DEPTH_MASK;
uchar chans = 1 + (type >> CV_CN_SHIFT);
switch ( depth ) {
case CV_8U: r = "8U"; break;
case CV_8S: r = "8S"; break;
case CV_16U: r = "16U"; break;
case CV_16S: r = "16S"; break;
case CV_32S: r = "32S"; break;
case CV_32F: r = "32F"; break;
case CV_64F: r = "64F"; break;
default: r = "User"; break;
}
r += "C";
r += (chans+'0');
return r;}

Unable to calculate the sum of prime numbers below 2 million

I'm doing the Euler's Method project to find the sum of prime numbers below 2 million and I'm struggling. Here is the code I'm using. When I calculate the sum below 10 and the sum below 50 I'm getting the right value, but where I'm calculating the sum below 2 million project Euler is saying my solution is incorrect. Any ideas?
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
#autoreleasepool {
int p = 2, d, total;
BOOL isPrime;
total = 0;
NSLog(#"%i ", p);
for ( p = 3; p < 2e6; p += 2){
isPrime = YES;
for ( d = 3; isPrime == YES && d < p; d += 2)
if ( p % d == 0)
isPrime = NO;
if (isPrime == YES){
NSLog(#"%i ", p);
total += p ;}
}
NSLog(#"total = %i", total + 2);
}
return 0;
}
This function sums the primes less than n using the Sieve of Eratosthenes:
function sumPrimes(n)
sum := 0
sieve := makeArray(2..n, True)
for p from 2 to n step 1
if sieve[p]
sum := sum + p
for i from p * p to n step p
sieve[i] := False
return sum
I'll leave it to you to translate to Objective-C with a suitable data type. For n = 2000000, this should run in one or two seconds.
There are a couple of mistakes. The first being that you're overflowing. Use a long instead of an int. The second thing is just a performance boost. Change your for loop from p < 2e6, to p*p <= 2e6. This way you rule out all numbers above the square root of 2e6. Fix those problems and you'll be good to go. Good luck!

Divide integer by 16 without using division or cast

OKAY... let me rephrase this question...
How can I obtain x 16ths of an integer without using division or casting to double....
int res = (ref * frac) >> 4
(but worry a a bit about overflow. How big can ref and frac get? If it could overflow, cast to a longer integer type first)
In any operation of such kind it makes sense to multiply first, then divide. Now, if your operands are integers and you are using a compileable language (eg. C), use shr 4 instead of /16 - this will save some processor cycles.
Assuming everything here are ints, any optimizing compiler worth its salt will notice 16 is a power of two, and shift frac accordingly -- so long as optimizations are turned on. Worry more about major optimizations the compiler can't do for you.
If anything, you should bracket ref * frac and then have the divide, as any value of frac less than 16 will result in 0, whether by shift or divide.
You can use left shift or right shift:
public static final long divisionUsingMultiplication(int a, int b) {
int temp = b;
int counter = 0;
while (temp <= a) {
temp = temp<<1;
counter++;
}
a -= b<<(counter-1);
long result = (long)Math.pow(2, counter-1);
if (b <= a) result += divisionUsingMultiplication(a,b);
return result;
}
public static final long divisionUsingShift(int a, int b) {
int absA = Math.abs(a);
int absB = Math.abs(b);
int x, y, counter;
long result = 0L;
while (absA >= absB) {
x = absA >> 1;
y = absB;
counter = 1;
while (x >= y) {
y <<= 1;
counter <<= 1;
}
absA -= y;
result += counter;
}
return (a>0&&b>0 || a<0&&b<0)?result:-result;
}
I don't understand the constraint, but this pseudo code rounds up (?):
res = 0
ref= 10
frac = 2
denominator = 16
temp = frac * ref
while temp > 0
temp -= denominator
res += 1
repeat
echo res