Unexpected data declaration statement - fortran

I'm writing a code for LU decomposition and I don't know how to fix the "unexpected data declaration statement" pointed at line 8 (where I'm declaring an array. See the code fragment). Why is it unexpected?
!Decomposição LU
!-----------------------------------------------------------
PROGRAM LUdecomp
IMPLICIT INTEGER (I-K,N), REAL (A-H, L-M,O-Z)
INTEGER, PARAMETER :: N=3
REAL, DIMENSION (N,N) :: A,L,U
A = reshape((/3.,1.,4.,4.,2.,0.,3.,2.,3./),(/3,3/)) !exemplo do Bortoli*******
REAL, DIMENSION(3) :: B=(/9.,3.,-2./),Z,X
OPEN(1,file = 'LUFACTOR.out')
!
! FORALL (I = 1:N, J = 1:N) A(I,J) = 1.0/REAL(I+J-1)
!-------Fazendo a fatoração A = LU-----------------------------
CALL LU(N, A, L, U)
DO I=1,N
WRITE(*,10)(L(I,J), J=1,N), (U(I,J), J=1,N)
END DO
10 FORMAT(3(F8.4), 7x, 3(F8.4))
!

This statement
REAL, DIMENSION(3) :: B=(/9.,3.,-2./),Z,X
is in the wrong place. In a Fortran program-unit (program, subroutine, function) -- certainly one without the new ASSOCIATE and BLOCK constructs -- all declarations have to precede all executable statements.
Move the misplaced statement ahead of the first executable statement.

Related

How do I define integer array for given variable nBoxes [duplicate]

I'm writing a code for LU decomposition and I don't know how to fix the "unexpected data declaration statement" pointed at line 8 (where I'm declaring an array. See the code fragment). Why is it unexpected?
!Decomposição LU
!-----------------------------------------------------------
PROGRAM LUdecomp
IMPLICIT INTEGER (I-K,N), REAL (A-H, L-M,O-Z)
INTEGER, PARAMETER :: N=3
REAL, DIMENSION (N,N) :: A,L,U
A = reshape((/3.,1.,4.,4.,2.,0.,3.,2.,3./),(/3,3/)) !exemplo do Bortoli*******
REAL, DIMENSION(3) :: B=(/9.,3.,-2./),Z,X
OPEN(1,file = 'LUFACTOR.out')
!
! FORALL (I = 1:N, J = 1:N) A(I,J) = 1.0/REAL(I+J-1)
!-------Fazendo a fatoração A = LU-----------------------------
CALL LU(N, A, L, U)
DO I=1,N
WRITE(*,10)(L(I,J), J=1,N), (U(I,J), J=1,N)
END DO
10 FORMAT(3(F8.4), 7x, 3(F8.4))
!
This statement
REAL, DIMENSION(3) :: B=(/9.,3.,-2./),Z,X
is in the wrong place. In a Fortran program-unit (program, subroutine, function) -- certainly one without the new ASSOCIATE and BLOCK constructs -- all declarations have to precede all executable statements.
Move the misplaced statement ahead of the first executable statement.

Do loop inside a where block in Fortran

Even though I do not exactly know why, it seems that Fortran (90) does not allow do loops inside where blocks. A code structured as follows does not compile with gfortran (Unexpected DO statement in WHERE block at (1)):
real :: a(30), b(30,10,5)
integer :: i, j
do i=1,10
where(a(:) > 0.)
! do lots of calculations
! modify a
do j=1,5
b(:,i,j)=...
enddo
endwhere
enddo
The only workaround that I can think of would be
real :: a2(30)
do i=1,10
a2(:)=a(:)
where(a(:) > 0.)
! do lots of calculations
! modify a
endwhere
do j=1,5
where(a2(:) > 0.)
b(:,i,j)=...
endwhere
enddo
enddo
I suppose that there are more elegant solutions? Especially if the where condition is less straightforward, this will look messy pretty soon... Thanks!
If your arrays are all 1-indexed, you can replace where constructs by explicitly storing and using array masks, for example
program test
implicit none
real :: a(30), b(30,10,5)
integer :: i, j
integer, allocatable :: mask(:)
do i=1,10
mask = filter(a(:)>0.)
! do lots of calculations
! modify a
do j=1,5
b(mask,i,j)=...
enddo
enddo
contains
! Returns the array of indices `i` for which `input(i)` is `true`.
function filter(input) result(output)
logical, intent(in) :: input(:)
integer, allocatable :: output(:)
integer :: i
output = pack([(i,i=1,size(input))], mask=input)
end function
end program

Fortran character format string as subroutine argument

I am struggling with reading a text string in. Am using gfortran 4.9.2.
Below I have written a little subroutine in which I would like to submit the write format as argument.
Ideally I'd like to be able to call it with
call printarray(mat1, "F8.3")
to print out a matrix mat1 in that format for example. The numbers of columns should be determined automatically inside the subroutine.
subroutine printarray(x, udf_temp)
implicit none
real, dimension(:,:), intent(in) :: x ! array to be printed
integer, dimension(2) :: dims ! array for shape of x
integer :: i, j
character(len=10) :: udf_temp ! user defined format, eg "F8.3, ...
character(len = :), allocatable :: udf ! trimmed udf_temp
character(len = 10) :: udf2
character(len = 10) :: txt1, txt2
integer :: ncols ! no. of columns of array
integer :: udf_temp_length
udf_temp_length = len_trim(udf_temp)
allocate(character(len=udf_temp_length) :: udf)
dims = shape(x)
ncols = dims(2)
write (txt1, '(I5)') ncols
udf2 = trim(txt1)//adjustl(udf)
txt2 = "("//trim(udf2)//")"
do i = 1, dims(1)
write (*, txt2) (x(i, j), j = 1, dims(2)) ! this is line 38
end do
end suroutine printarray
when I set len = 10:
character(len=10) :: udf_temp
I get compile error:
call printarray(mat1, "F8.3")
1
Warning: Character length of actual argument shorter than of dummy argument 'udf_temp' (4/10) at (1)
When I set len = *
character(len=*) :: udf_temp
it compiles but at runtime:
At line 38 of file where2.f95 (unit = 6, file = 'stdout')
Fortran runtime error: Unexpected element '( 8
What am I doing wrong?
Is there a neater way to do this?
Here's a summary of your question that I will try to address: You want to have a subroutine that will print a specified two-dimensional array with a specified format, such that each row is printed on a single line. For example, assume we have the real array:
real, dimension(2,8) :: x
x = reshape([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16], shape=[2,8], order=[2,1])
! Then the array is:
! 1.000 2.000 3.000 4.000 5.000 6.000 7.000 8.000
! 9.000 10.000 11.000 12.000 13.000 14.000 15.000 16.000
We want to use the format "F8.3", which prints floating point values (reals) with a field width of 8 and 3 decimal places.
Now, you are making a couple of mistakes when creating the format within your subroutine. First, you try to use udf to create the udf2 string. This is a problem because although you have allocated the size of udf, nothing has been assigned to it (pointed out in a comment by #francescalus). Thus, you see the error message you reported: Fortran runtime error: Unexpected element '( 8.
In the following, I make a couple of simplifying changes and demonstrate a few (slightly) different techniques. As shown, I suggest the use of * to indicate that the format can be applied an unlimited number of times, until all elements of the output list have been visited. Of course, explicitly stating the number of times to apply the format (ie, "(8F8.3)" instead of "(*(F8.3))") is fine, but the latter is slightly less work.
program main
implicit none
real, dimension(2,8) :: x
character(len=:), allocatable :: udf_in
x = reshape([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16], shape=[2,8], order=[2,1])
udf_in = "F8.3"
call printarray(x, udf_in)
contains
subroutine printarray(x, udf_in)
implicit none
real, dimension(:,:), intent(in) :: x
character(len=*), intent(in) :: udf_in
integer :: ncols ! size(x,dim=2)
character(len=10) :: ncols_str ! ncols, stringified
integer, dimension(2) :: dims ! shape of x
character(len=:), allocatable :: udf0, udf1 ! format codes
integer :: i, j ! index counters
dims = shape(x) ! or just use: ncols = size(x, dim=2)
ncols = dims(2)
write (ncols_str, '(i0)') ncols ! use 'i0' for min. size
udf0 = "(" // ncols_str // udf_in // ")" ! create string: "(8F8.3)"
udf1 = "(*(" // udf_in // "))" ! create string: "(*(F8.3))"
print *, "Version 1:"
do i = 1, dims(1)
write (*, udf0) (x(i, j), j = 1,ncols) ! implied do-loop over j.
end do
print *, "Version 2:"
do i = 1, dims(1)
! udf1: "(*(F8.3))"
write (*, udf1) (x(i, j), j = 1,ncols) ! implied do-loop over j
end do
print *, "Version 3:"
do i = 1, size(x,dim=1) ! no need to create nrows/ncols vars.
write(*, udf1) x(i,:) ! let the compiler handle the extents.
enddo
end subroutine printarray
end program main
Observe: the final do-loop ("Version 3") is very simple. It does not need an explicit count of ncols because the * takes care of it automatically. Due to its simplicity, there is really no need for a subroutine at all.
besides the actual error (not using the input argument), this whole thing can be done much more simply:
subroutine printarray(m,f)
implicit none
character(len=*)f
real m(:,:)
character*10 n
write(n,'(i0)')size(m(1,:))
write(*,'('//n//f//')')transpose(m)
end subroutine
end
note no need for the loop constructs as fortran will automatically write the whole array , line wrapping as you reach the length of data specified by your format.
alternately you can use a loop construct, then you can use a '*' repeat count in the format and obviate the need for the internal write to construct the format string.
subroutine printarray(m,f)
implicit none
character(len=*)f
real m(:,:)
integer :: i
do i=1,size(m(:,1))
write(*,'(*('//f//'))')m(i,:)
enddo
end subroutine
end

Functions Passing Arrays In/Out Program Fortran 90

I'm working on trying to pass an array into a function to be able to calculate new values that will replace the original values in that array. However, I keep getting zeroes to be returned and I'm not sure why. My code is below:
program HW10
implicit none
integer :: i
integer, parameter :: &
p=38 !lines to read
real, parameter :: &
g=9.81 !Value of gravity acceleration
integer , dimension(p) :: direction, speed, rh, speedconv
real, dimension (p) :: pressure, height, temp, dewpt, mixr
real :: average, knots
open(1,file='HW10input.txt', status='old', action='read')
10 format (F6.1, T9, F6.1, T16, F5.1, T23, F5.1, T33, I2, T38, F4.2, T46, I3, T53, I3)
do i=1,p
read(1,10)pressure(i), height(i), temp(i), dewpt(i), rh(i), mixr(i), direction(i), speed(i)
end do
close (1)
open(2, file='outputfilehw10.txt', status='new', action='write')
do i=1,p
write (*, 20) pressure(i), height(i), temp(i), dewpt(i), rh(i), mixr(i), direction(i), speed(i)
20 format (F6.1, T9, F6.1, T16, F5.1, T23, F5.1, T33, I2, T38, F4.2, T46, I3, T53, I3)
end do
write (*,*) 'Average= ', average(temp, p)
do i=1,p
write (*,*) 'Wind Speeds: ', knots(speed, p)
end do
end program HW10
The issue comes when I get to the function "knots" at the bottom. This is what the function looks like:
real function knots (x, n)
integer, intent(in) :: n
real, dimension(n), intent(inout) :: x
integer :: i
do i = 1, n
x(i) = (x(i) * 0.514444 )
end do
return x
end function knots
The code will read in the data fine, as I have the code displaying it properly. However when I want to see the changed data within the wind speed array, all of the data points are zeroes. I'm new to Fortran so I'm not quite sure what to do. Thanks in advance!
If I try to compile the code given in the question (put all in the same file) with gfortran 4.8.3 I get the following two errors:
First error:
return x
1
Error: Alternate RETURN statement at (1) is only allowed within a SUBROUTINE
Second error:
write (*,*) 'Wind Speeds: ', knots(speed, p)
1
Warning: Type mismatch in argument 'x' at (1); passed INTEGER(4) to REAL(4)
Let's deal with the first of these - unlike many other programming languages it is not used to set the return value.
So, why did the compiler just complain that you've done this in a function rather than a subroutine instead of the compiler complaining that you've put a value here? There's a historic feature known as alternate return that is a bit like using a goto -- these are only allowed in subroutines.
So let's replace return x with just return -- this avoids the compiler error, but how does the code know what value to return? When defining functions in fortran you can explicitly specify a name for the result, but if you don't do this then it assumes your result is a variable with the same name as the function, so in your case knots. So in your code the variable to be returned is called knots but it never gets set to anything. By "coincidence" it looks like the bit of memory being used to store the result, which is never explicitly set to anything, is either being initialised to zero by the compiler or you're just accessing uninitialised memory that happens to be full of zeros.
So how do we fix this? Let's define the result explicitly
function knots (x, n) result(y)
implicit none
integer, intent(in) :: n
real, dimension(n), intent(inout) :: x
real, dimension(n) :: y
integer :: i
do i = 1, n
y(i) = (x(i) * 0.514444 )
end do
return
end function knots
If we try to compile we now get a new error!
write (*,*) 'Wind Speeds: ', knots(speed, p)
1
Error: The reference to function 'knots' at (1) either needs an explicit INTERFACE or the rank is incorrect
Functions/subroutines with arguments/return values typically need to have an interface defined . There are many ways to achieve this, I'm going to do it by putting the function in a module:
module myknots
implicit none
public :: knots
contains
function knots (x, n) result(y)
implicit none
integer, intent(in) :: n
real, dimension(n), intent(inout) :: x
real, dimension(n) :: y
integer :: i
do i = 1, n
y(i) = (x(i) * 0.514444 )
end do
return
end function knots
end module myknots
We then need to add use myknots, only: knots to the top of the main program. This now leaves us with just the second error.
What this is telling us is that you've passed an integer array to a function that expects a real value. This is because speed is declared as integer but x in knots is declared as real. To fix this let us create a new knots function in which x is declared as integer. I'll also use an explicit interface to allow us to refer to either version of knots using the name knots. Doing this the myknots module looks like
module myknots
implicit none
private
public :: knots
interface knots
module procedure knots_r
module procedure knots_i
end interface knots
contains
function knots_r (x, n) result(y)
implicit none
integer, intent(in) :: n
real, dimension(n), intent(inout) :: x
real, dimension(n) :: y
integer :: i
do i = 1, n
y(i) = (x(i) * 0.514444 )
end do
return
end function knots_r
function knots_i (x, n) result(y)
implicit none
integer, intent(in) :: n
integer, dimension(n), intent(inout) :: x
real, dimension(n) :: y
integer :: i
do i = 1, n
y(i) = (x(i) * 0.514444 )
end do
return
end function knots_i
end module myknots
The main program looks like
Program HW10
use myknots, only: knots
implicit none
integer :: i
integer, parameter :: &
p=38 !lines to read
real, parameter :: &
g=9.81 !Value of gravity acceleration
integer , dimension(p) :: direction, speed, rh, speedconv
real, dimension (p) :: pressure, height, temp, dewpt, mixr
real :: average
open(1,file='HW10input.txt', status='old', action='read')
10 format (F6.1, T9, F6.1, T16, F5.1, T23, F5.1, T33, I2, T38, F4.2, T46, I3, T53, I3)
do i=1,p
read(1,10)pressure(i), height(i), temp(i), dewpt(i), rh(i), mixr(i), direction(i), speed(i)
end do
close (1)
open(2, file='outputfilehw10.txt', status='new', action='write')
do i=1,p
write (*, 20) pressure(i), height(i), temp(i), dewpt(i), rh(i), mixr(i), direction(i), speed(i)
20 format (F6.1, T9, F6.1, T16, F5.1, T23, F5.1, T33, I2, T38, F4.2, T46, I3, T53, I3)
end do
write (*,*) 'Average= ', average(temp, p)
do i=1,p
write (*,*) 'Wind Speeds: ', knots(speed, p)
end do
end program HW10
This has fixed all the immediate issues, but you still won't be able to produce an executable as you haven't yet defined the average function. Hopefully the steps above should be enough to allow you to implement this yourself.
You have a function knots which has a real result. Look at the line
write (*,*) 'Wind Speeds: ', knots(speed, p)
The function reference knots(speed, p) is evaluated to return that real result, and that result is then printed.
There are two problems, based on the same misunderstanding: in the function knots the result of the function has the name knots. This isn't the same thing as the intent(inout) dummy argument x.
Problem 1: you don't defined the value of knots in the function.
Problem 2: the value of knots isn't the value you want. You want the value (on return) of speed.
You could either define the result knots to be the output array, or you can use a subroutine instead. I won't go into the details of those two approaches (as there are plenty of resources available there), but I will clearly note: if knots becomes a function with result array there will need to be an explicit interface available when it is referenced.

Prevent changing variables with intent(in)

so reading the following question (Correct use of FORTRAN INTENT() for large arrays) I learned that defining a variable with intent(in) isn't enough, since when the variable is passed to another subroutine/function, it can be changed again. So how can I avoid this? In the original thread they talked about putting the subroutine into a module, but that doesn't help for me. For example I want to calculate the determinant of a matrix with a LU-factorization. Therefore I use the Lapack function zgetrf, but however this function alters my input matrix and the compiler don't displays any warnings. So what can I do?
module matHelper
implicit none
contains
subroutine initMat(AA)
real*8 :: u
double complex, dimension(:,:), intent(inout) :: AA
integer :: row, col, counter
counter = 1
do row=1,size(AA,1)
do col=1,size(AA,2)
AA(row,col)=cmplx(counter ,0)
counter=counter+1
end do
end do
end subroutine initMat
!subroutine to write a Matrix to file
!Input: AA - double complex matrix
! fid - integer file id
! fname - file name
! stat - integer status =replace[0] or old[1]
subroutine writeMat(AA,fid, fname, stat)
integer :: fid, stat
character(len=*) :: fname
double complex, dimension(:,:), intent(in) :: AA
integer :: row, col
character (len=64) :: fmtString
!opening file with given options
if(fid /= 0) then
if(stat == 0) then
open(unit=fid, file=fname, status='replace', &
action='write')
else if(stat ==1) then
open(unit=fid, file=fname, status='old', &
action='write')
else
print*, 'Error while trying to open file with Id', fid
return
end if
end if
!initializing matrix print format
write(fmtString,'(I0)') size(aa,2)
fmtString = '('// trim(fmtString) //'("{",ES10.3, ",", 1X, ES10.3,"}",:,1X))'
!write(*,*) fmtString
!writing matrix to file by iterating through each row
do row=1,size(aa,1)
write(fid,fmt = fmtString) AA(row,:)
enddo
write(fid,*) ''
end subroutine writeMat
!function to calculate the determinant of the input
!Input: AA - double complex matrix
!Output determinantMat - double complex,
! 0 if AA not a square matrix
function determinantMat(AA)
double complex, dimension(:,:), intent(in) :: AA
double complex :: determinantMat
integer, dimension(min(size(AA,1),size(AA,2)))&
:: ipiv
integer :: ii, info
!check if not square matrix, then set determinant to 0
if(size(AA,1)/= size(AA,2)) then
determinantMat = 0
return
end if
!compute LU facotirzation with LAPACK function
call zgetrf(size(AA,1),size(AA,2), AA,size(AA,1), ipiv,info)
if(info /= 0) then
determinantMat = cmplx(0.D0, 0.D0)
return
end if
determinantMat = cmplx(1.D0, 0.D0)
!determinant of triangular matrix is product of diagonal elements
do ii=1,size(AA,1)
if(ipiv(ii) /= ii) then
!a permutation was done, so a factor of -1
determinantMat = -determinantMat *AA(ii,ii)
else
!no permutation, so no -1
determinantMat = determinantMat*AA(ii,ii)
end if
end do
end function determinantMat
end module matHelper
!***********************************************************************
!module which stores matrix elements, dimension, trace, determinant
program test
use matHelper
implicit none
double complex, dimension(:,:), allocatable :: AA, BB
integer :: n, fid
fid = 0;
allocate(AA(3,3))
call initMat(AA)
call writeMat(AA,0,' ', 0)
print*, 'Determinante: ',determinantMat(AA) !changes AA
call writeMat(AA,0, ' ', 0)
end program test
PS: I am using the ifort compiler v15.0.3 20150407
I do not have ifort at home, but you may want to try compiling with '-check interfaces' and maybe with '-ipo'. You may need the path to 'zgetrf' for the '-check interfaces' to work, and if that is not source then it may not help.
If you declare 'function determinantMat' as 'PURE FUNCTION determinantMat' then I am pretty sure it would complain because 'zgetrf' is not known to be PURE nor ELEMENTAL. Try ^this stuff^ first.
If LAPACK has a module, then zgetrf could be known to be, or not be, PURE/ELEMENTAL. https://software.intel.com/en-us/articles/blas-and-lapack-fortran95-mod-files
I would suggest you add to your compile line:
-check interfaces -ipo
During initial build I like (Take it out for speed once it works):
-check all -warn all
Making a temporary array is one way around it. (I have not compiled this, so it is only a conceptual exemplar.)
PURE FUNCTION determinantMat(AA)
USE LAPACK95 !--New Line--!
IMPLICIT NONE !--New Line--!
double complex, dimension(:,:) , intent(IN ) :: AA
double complex :: determinantMat !<- output
!--internals--
integer, dimension(min(size(AA,1),size(AA,2))) :: ipiv
!!--Next line is new--
double complex, dimension(size(AA,1),size(AA,2)) :: AA_Temp !!<- I have no idea if this will work, you may need an allocatable??
integer :: ii, info
!check if not square matrix, then set determinant to 0
if(size(AA,1)/= size(AA,2)) then
determinantMat = 0
return
end if
!compute LU factorization with LAPACK function
!!--Next line is new--
AA_Temp = AA !--Initialise AA_Temp to be the same as AA--!
call zgetrf(size(AA_temp,1),size(AA_Temp,2), AA_Temp,size(AA_Temp,1), ipiv,info)
if(info /= 0) then
determinantMat = cmplx(0.D0, 0.D0)
return
end if
determinantMat = cmplx(1.D0, 0.D0)
!determinant of triangular matrix is product of diagonal elements
do ii=1,size(AA_Temp,1)
if(ipiv(ii) /= ii) then
!a permutation was done, so a factor of -1
determinantMat = -determinantMat *AA_Temp(ii,ii)
else
!no permutation, so no -1
determinantMat = determinantMat*AA_Temp(ii,ii)
end if
end do
end function determinantMat
With the 'USE LAPACK95' you probably do not need PURE, but if you wanted it to be PURE then you want to explicitly say so.