Fortran where & do concurrent
Two constructs express array computations at a higher level than ordinary loops: where applies an assignment only to selected elements, and do concurrent declares that the iterations of a loop are independent, so the compiler may run them in any order, vectorise them or spread them across threads.
where: masked array assignment
where (mask) performs the enclosed array assignments only where the logical mask is true; elsewhere handles the other elements:
program where_demo
implicit none
real :: readings(8) = [3.2, -1.0, 4.8, 0.0, -2.5, 7.1, 2.2, -0.4]
real :: cleaned(8), log_values(8)
where (readings < 0.0)
cleaned = 0.0 ! negative sensor values are invalid
elsewhere
cleaned = readings
end where
print '(8f6.2)', cleaned
! avoid log(0) and log of negatives: compute only where it is safe
log_values = -99.0
where (readings > 0.0) log_values = log(readings) ! one-line form
print '(8f6.2)', log_values
end program where_demo 3.20 0.00 4.80 0.00 0.00 7.10 2.20 0.00
1.16-99.00 1.57-99.00-99.00 1.96 0.79-99.00
The second line shows what happens when a value needs exactly the full field width: -99.00 takes all 6 characters of f6.2, so it touches the previous number. Use a wider field (f7.2) or add 1x separators for readable output.
All arrays in a where must have the same shape as the mask. elsewhere (other_mask) can test a second condition, like else if:
program classify
implicit none
integer :: i
real :: temps(6) = [-5.0, 3.0, 12.0, 21.0, 28.0, 35.0]
character(len=4) :: label(6)
where (temps < 0.0)
label = 'ice'
elsewhere (temps < 15.0)
label = 'cold'
elsewhere (temps < 25.0)
label = 'mild'
elsewhere
label = 'hot'
end where
print '(6(f6.1, 1x, a4, 2x))', (temps(i), label(i), i = 1, 6)
end program classify -5.0 ice 3.0 cold 12.0 cold 21.0 mild 28.0 hot 35.0 hot
merge: the expression form
When you need a value rather than an assignment statement, merge(true_value, false_value, mask) does the same element-wise choice inside an expression:
program merge_demo
implicit none
integer :: i
integer :: n(8) = [(i, i = 1, 8)]
print '(8i4)', merge(n / 2, 3 * n + 1, mod(n, 2) == 0) ! one Collatz step
end program merge_demo 4 1 10 2 16 3 22 4
Note: Unlike a
wherestatement,mergeevaluates both value arrays for every element, so it can't protect you fromlog(0)or division by zero.
do concurrent
do concurrent (index = start:end) tells the compiler that the iterations can run in any order, including at the same time. In return you promise that no iteration depends on another one: no iteration may read a value that another iteration writes. Procedures called inside must be pure.
program concurrent_demo
use iso_fortran_env, only: real64
implicit none
integer, parameter :: n = 8
real(real64) :: x(n), y(n)
integer :: i
do concurrent (i = 1:n)
x(i) = (i - 1) * 0.25_real64
y(i) = exp(-x(i)) * cos(2 * x(i))
end do
print '(8f7.3)', x
print '(8f7.3)', y
end program concurrent_demo 0.000 0.250 0.500 0.750 1.000 1.250 1.500 1.750
1.000 0.683 0.328 0.033 -0.153 -0.230 -0.221 -0.163
Several indices and a mask can be combined in one header. The mask restricts which index combinations run:
program concurrent_2d
implicit none
integer, parameter :: n = 5
integer :: a(n, n), i, j
a = 0
do concurrent (i = 1:n, j = 1:n, i >= j) ! lower triangle only
a(i, j) = i * 10 + j
end do
do i = 1, n
print '(5i4)', a(i, :)
end do
end program concurrent_2d 11 0 0 0 0
21 22 0 0 0
31 32 33 0 0
41 42 43 44 0
51 52 53 54 55
What is not allowed in do concurrent
A loop whose iterations depend on each other is not concurrent. A running sum, for example, reads the result of the previous iteration:
! WRONG: s(i) needs s(i-1), so iterations are not independent
do concurrent (i = 2:n)
s(i) = s(i - 1) + x(i)
end doThe compiler usually can't detect this mistake, and the result may be wrong only when the loop is actually parallelised. Also not allowed inside: exit, return, stop, I/O on units that other iterations use (gfortran accepts print, but the order would not be defined), and calls to impure procedures.
Fortran 2018 added locality specifiers to make the intent explicit: local(tmp) gives each iteration its own copy of tmp, shared(a) marks shared data, and default(none) forces you to declare everything. Fortran 2023 adds reduce(+: total) for sums.
do concurrent (i = 1:n) local(t) shared(a, b)
t = a(i) * 2.0
b(i) = t + 1.0
end doforall: legacy
Older code uses forall (i = 1:n) a(i) = …. It is an array assignment, not a loop, and was declared obsolescent in Fortran 2018. Use do concurrent or plain array syntax instead.
Test yourself
What does where (x > 0) y = sqrt(x) do?
- Assigns sqrt(x) to all of y
- Assigns sqrt(x(i)) to y(i) only where x(i) > 0
- Stops if any x is negative
- Returns the index of the first positive x
What do you promise when writing do concurrent?
- The loop runs on a GPU
- The iterations are independent and may execute in any order
- The loop runs exactly once
- The loop body has no arrays
Why can't merge protect against division by zero?
- It can, always
- Both value arguments are evaluated for every element before choosing
- It only works on integers
- It ignores the mask