Control Flow - if condition in Julia - if-statement

I'm using Julia to solve an integer program. My variables are of the form z[i,j], i in N and j in N and N=10and z[i,j] is a binary variable.
In the first half of the program, I have a set of solutions for which z[1,2]= 1 and z[1,3]=1 and all other variables are zero. Now, I need to pass these values to another set S in such a way that S={1,2,3}. I tried to code it in Julia, but I couldn't get it in the right way. The following is the what I've tried.Here, z_value is the way that I declare my variables z[i,j]. Can someone please help me to make it correct?
for i in N
for j in N
z_value = Pair(i,j)
if z_value == 1;
push!(S, Pair(i,j))
print(S)
end
end
end

Thanks, Michael and Stefan, I got required set S by rearranging the code as
for i in N
for j in N
if getvalue(z[i,j]) == 1
push!(S, i)
push!(S, j)
end
end
end
Thanks for your effort!!

Related

ZIMPL: 2D variable declaration not recognized in constraint

I'm having a real challenge declaring a 2D variable in Zimpl. (Parameters seem to work fine.)
The following is my MWE:
set I := {1 to 10};
set J := {1 to 5};
param A[I*J] := read InputFile as "n+";
var x[I] binary;
var s[J] binary; # this works but doesn't do what I need
var s2[I*J] binary; # this does what I need but doesn't work
minimize sum<i,j> in I*J with A[i,j] < 5: (s2[i,j] - x[i]) * A[i,j];
# this constraint compiles
subto constraint1:
forall <j> in J do sum <i> in I with A[i,j] < 5: x[i] <= 1 + s[j];
# this constraint does not compile
subto constraint2:
forall <j> in J do sum <i> in I with A[i,j] < 5: x[i] <= 1 + s2[i,j];
When try to create my lp file, I get
Error 133: Unknown symbol "i"
Does anyone have any insights into how I can get the second constraint to work? As far as I can tell this is identical to the implementation of the capacitated facility problem (Section 6.3) in the Zimpl user's manual.
Thanks in advance.
You have the sum over i on the left-hand side of the constraint, but then reference i on the right-hand side as well. Which value of i do you expect there?
What would work is
forall <j> in J do sum <i> in I with A[i,j] < 5: (x[i] - s2[i,j]) <= 1;
but I am not sure this is what you want to achieve.
Adding Leon's comment to make a more complete answer:
To add to what Gerald wrote, in ZIMPL sums always only consider the next variable, so you have to put parenthesis to make it work.
To add to what Gerald wrote, in ZIMPL sums always only consider the next variable, so you have to put parenthesis to make it work.
at minimize there is the name missing.
It should be minimize obj: sum ...

One simple 'if' statement in Julia increases the run-time of my prime sieve by a factor of 15 – why?

I've been experimenting with various prime sieves in Julia with a view to finding the fastest. This is my simplest, if not my fastest, and it runs in around 5-6 ms on my 1.80 GHz processor for n = 1 million. However, when I add a simple 'if' statement to take care of the cases where n <= 1 or s (the start number) > n, the run-time increases by a factor of 15 to around 80-90 ms.
using BenchmarkTools
function get_primes_1(n::Int64, s::Int64=2)::Vector{Int64}
#=if n <= 1 || s > n
return []
end=#
sieve = fill(true, n)
for i = 3:2:isqrt(n) + 1
if sieve[i]
for j = i ^ 2:i:n
sieve[j]= false
end
end
end
pl = [i for i in s - s % 2 + 1:2:n if sieve[i]]
return s == 2 ? unshift!(pl, 2) : pl
end
#btime get_primes_1(1_000_000)
Output with the 'if' statement commented out, as above, is:
5.752 ms (25 allocations: 2.95 MiB)
Output with the 'if' statement included is:
86.496 ms (2121646 allocations: 35.55 MiB)
I'm probably embarrassingly ignorant or being terminally stupid, but if someone could point out what I'm doing wrong it would be very much appreciated.
The problem of this function is with Julia compiler having problems with type inference when closures appear in your function. In this case the closure is a comprehension and the problem is that if statement makes sieve to be only conditionally defined.
You can see this by moving sieve up:
function get_primes_1(n::Int64, s::Int64=2)::Vector{Int64}
sieve = fill(true, n)
if n <= 1 || s > n
return Int[]
end
for i = 3:2:isqrt(n) + 1
if sieve[i]
for j = i ^ 2:i:n
sieve[j]= false
end
end
end
pl = [i for i in s - s % 2 + 1:2:n if sieve[i]]
return s == 2 ? unshift!(pl, 2) : pl
end
However, this makes sieve to be created also when n<1 which you want to avoid I guess :).
You can solve this problem by wrapping sieve in let block like this:
function get_primes_1(n::Int64, s::Int64=2)::Vector{Int64}
if n <= 1 || s > n
return Int[]
end
sieve = fill(true, n)
for i = 3:2:isqrt(n) + 1
if sieve[i]
for j = i ^ 2:i:n
sieve[j]= false
end
end
end
let sieve = sieve
pl = [i for i in s - s % 2 + 1:2:n if sieve[i]]
return s == 2 ? unshift!(pl, 2) : pl
end
end
or avoiding an inner closure for example like this:
function get_primes_1(n::Int64, s::Int64=2)::Vector{Int64}
if n <= 1 || s > n
return Int[]
end
sieve = fill(true, n)
for i = 3:2:isqrt(n) + 1
if sieve[i]
for j = i ^ 2:i:n
sieve[j]= false
end
end
end
pl = Int[]
for i in s - s %2 +1:2:n
sieve[i] && push!(pl, i)
end
s == 2 ? unshift!(pl, 2) : pl
end
Now you might ask how can you detect such problems and make sure that some solution solves them? The answer is to use #code_warntype on a function. In your original function you will notice that sieve is Core.Box which is an indication of the problem.
See https://github.com/JuliaLang/julia/issues/15276 for details. In general this is in my perception the most important issue with performance of Julia code which is easy to miss. Hopefully in the future the compiler will be smarter with this.
Edit: My suggestion actually doesn't seem to help. I missed your output annotation, so the return type appears to be correctly inferred after all. I am stumped, for the moment.
Original answer:
The problem isn't that there is an if statement, but that you introduce a type instability inside that if statement. You can read about type instabilities in the performance section of the Julia manual here.
An empty array defined like this: [], has a different type than a vector of integers:
> typeof([1,2,3])
Array{Int64,1}
> typeof([])
Array{Any,1}
The compiler cannot predict what the output type of the function will be, and therefore produces defensive, slow code.
Try to change
return []
to
return Int[]

Range checking for my remove function in c++

So I have a method in c++ that takes an array and removes a certain number of values in the array. The method removes the range of values from the starting value all the way up to but not including the end value. void dynamic_array::remove(int start, int end) {
The only problem I'm having is with the range checking. So I've set up a way to check to make sure the start and end values are not in the incorrect places however whenever I test the code, it appears that it doesn't catch the range exception. Here's the code that's supposed to check the exception:
if (not (0 <= ((start <= (end < size))))){
throw exception(SUBSCRIPT_RANGE_EXCEPTION);
}
you cannot use the notation 1 < x < 2 in c++ (or most languages). So you have to do each comparison separately. ie. (1<x) && (x<2) (brackets not really necessary here).
If you are interested, you actually can use the notation, but it means something different than you might think. It means that you first compare 1<x which gives either true (1) or zero(0) and then you compare this 1 or 0 with two.
It should be written
if(!(0 <= start && start <= end && end < size)){
throw exception
}
As i know, C++ can't understand the way you write it.
C++ does not work this way. The result of a single logical comparison is a boolean value. For example, the first comparison:
end < size
If this comparison is true, the result becomes a true value, which is for all practical purposes is 1. So, your expression now becomes, for all practical purposes:
if (not (0 <= ((start <= 1)))){
Which is already pretty much nonsensical, not to mention that there isn't a not operator in C++. Things pretty much roll downhill, from that point on.
You just need to make two logical comparisons: start < end, and end <= size. If you spend a few moments to think about it, you would realize this is all you need:
if (!(start < end && end <= size))

How to exit "repeat until loop" in fortran?

I have defined two 2D arrays h and hh.I want to assign hh with new values. For a specific k', I want hh(k',j)=1, if the condition
h(k',j)>0
is true; and once the condition is false, i.e., h(k',j')<0, then for any j>j', hh(k',j)=0. I used the following DO WHILE loop:
do k=1, npair
do j =1, movie
hh(k,j)=0.0
enddo
enddo
do k=1, npair
do j =1, nmovie
do while (h(k,j)>0)
hh(k,j)=h(k,j)
enddo
enddo
But if the condition (h(k,j)>0) is always true, there will be a infinite loop! Could you please suggest how can implement it?
It seems to me that you can set each value of hh given the value of h. I'm also assuming hh and h are the same size. So you should do something for each element in hh. I recommend the following:
do k=1,N1 ! N1 and N2 are the limits of the hh and h array.
do j=1,N2
if ( h(k,j) > 0) then ! Check the condition for a specific element in h
hh(k,j) = 1
else
! -- We need to set *all* values in the desired range
hh(k,j:N2) = 0
! -- And we need to stop loop from overwriting values hh(k,j+1), for example
! -- So we break out of the j loop
exit
endif
enddo
enddo
You should check to make sure this does what you think it will. Note that I'm using colon notation to assign a range of values in the hh array.
Also, you're unclear on what happens if h(k,j) is 0 exactly.

Why doesn't this fortran code work?

Hey, I wrote this (fortran) with the aim of finding the minimum spanning tree of a bunch of points (syscount of them). I know for a fact that this approach works, since i wrote it in javascript earlier today. js is slow though, and i wanted to see how much faster fortran would be!!
only problem is it's not working, i'm getting an annoying error;
prims.f95:72.43:
if((check == 1) .and. (path(nodesin(j))(k) < minpath)) then
1
Error: Expected a right parenthesis in expression at (1)
What the hell is that about?! the 43rd character on the line is the "h" of "path"
nodesin(1) = 1
do i = 1,syscount-1
pathstart = -1
pathend = -1
minpath = 2000
do j = 1,i
do k = 1, syscount
check = 1
do l = 1, i
if(nodesin(l) == k) then
check = 0
end if
end do
if((check == 1) .and. (path(nodesin(j))(k) < minpath)) then
minpath = path(nodesin(j))(k)
pathstart = nodesin(j)
pathend = k
end if
end do
end do
nodesin(i+1) = pathend
minpaths(i)(1) = pathstart
minpaths(i)(2) = pathend
end do
Also, i'm fairly new to fortran, so i have a few other questions;
can i use && instead of .and. ?
is there a versions of the for(object in list){} loop found in many other languages?
is there a verion of the php function in_array ? i.e. bool in_array(needle,haystack), and if there is, is there a better way of doing it than:
check = false
Asize = size(array)
do i = 1, Asize
if(array(i) == needle) then
check = true
end if
end do
then to using the check variable to see if it's there?
(I haven't posted anything on stackoverflow before. please don't get angry if i've broken loads of etiquette things!)
It looks like you have defined path and minpaths as two-dimensional arrays. Multi-dimensional arrays are accessed differently in Fortran when compared to C-like languages. In Fortran you separate the indices by commas within one set of parentheses.
I'm guessing by the use of these variables they are integer arrays. Here is how you access elements of those arrays (since you didn't share your variable declarations I am making up the shape of these arrays):
integer :: path(n1, n2)
integer :: minpaths(n3, 2)
your if statement should be:
if((check == 1) .and. (path(nodesin(j), k) < minpath)) then
your access to minpaths should be:
minpaths(i, 1) = pathstart
minpaths(i, 2) = pathend
Also, if you are not using IMPLICIT NONE I recommend you consider it. Not using it is dangerous, and you are using variable names that are close to each other (minpath and minpaths). You could save hours of hair pulling debugging by using IMPLICIT NONE.
While .EQ. can be replaced with ==, there is still only .AND.
For your code block to check whether a "variable is there", you can use "where" and have much shorter code!
In Fortran >= 90 statements and functions can operate on arrays so that explicit loops don't have to be used as frequently.
There is no for (object in list), but using the where statement can do something very similar.
Many of the intrinsic functions that act on arrays also take masks as optional arguments to selectively operate.
I suggest reading a book to learn about these features. I like the one by Metcalf, Reid and Cohen. In the meantime, the second Wikipedia article may help: http://en.wikipedia.org/wiki/Fortran_95_language_features