complex to real+imag part
Given a complex array we can assign pointers to its real and imaginary part following the answer in https://stackoverflow.com/a/54819542
program main
use iso_c_binding
implicit none
complex, target :: z(2) = [(1,2), (3,4)]
real, pointer :: re(:), im(:), buf(:)
call c_f_pointer(c_loc(z), buf, shape=[size(z)*2])
re(1:2) => buf(1::2)
im(1:2) => buf(2::2)
print *, 'z', z
print *, 're', re
print *, 'im', im
end program
real+imag part to complex
My question is how to do it the other way around?
Given two real arrays re,im. How can one assign a complex pointer z where the real part is given by re and imaginary part by im? Something similar to
program main
implicit none
real, target :: re(2)=[1,3], im(2)=[2,4]
complex, pointer :: z(:)
z => cmplx(re, im) ! doesnt work as cmplx doesnt return a pointer result
end program
Is it even possible as re,im are not always contiguous in memory?
This question already has answers here:
changing array dimensions in fortran
(6 answers)
Providing an argument that has not the TARGET attribute to a procedure with a dummy argument that has the TARGET attribute
(1 answer)
Closed 2 years ago.
To avoid an XY-problem I will first summarize my overall goal.
We have a large legacy codebase of fortran77 code, that implemented their own memory allocation.
It consists of a 1D Work Array that is equivalenced to be used with different types.
It looks roughly like this:
Real*8 Work(1:IWORKLEN)
Real*4 sWork(1:IWORKLEN)
Integer iWork(1:IWORKLEN)
Character*1 cWork(1:2*ICWORKLEN)
Equivalence (Work,sWork)
Equivalence (Work,iWork)
Equivalence (Work,cWork)
The custom allocator will then return indices in this work array.
We have nicer allocations for new code, but a large part still uses this legacy code.
One of the obvious drawbacks is that everything is a 1D array and the programmer has to do the manual pointer arithmetic to index multidimensional arrays.
For this reason it would be great to reinterpret parts of this array as n-dimensional arrays using pointers.
Unfortunately one cannot add the target attribute to equivalenced variables.
While playing around I created this minimal example, which solves our problems without the need for target:
program test_dummy_target
implicit none(type, external)
integer, allocatable :: work(:)
integer, pointer :: M(:, :) => null()
work = [1, 2, 3, 4]
M => recast(work, 2, 2)
write(*, *) M(1, :)
write(*, *) M(2, :)
contains
function recast(vec, n, m) result(mat)
integer, target, intent(in) :: vec(:)
integer, intent(in) :: n, m
integer, pointer :: mat(:, :)
mat(1 : n, 1 : m) => vec(:)
end function
end program
On the other hand
program test_dummy_target
implicit none
integer, allocatable :: vec(:)
integer, pointer :: M(:, :) => null()
vec = [1, 2, 3, 4]
M(1 : 2, 1 : 2) => vec
write(*, *) M(1, :)
write(*, *) M(2, :)
end program
does not compile, because target is required for vec.
So now my question:
Is there undefined behaviour lurking in my minimal example? I don't get why the first example should work properly, if the second one does not.
How do I properly recast the 1D Work array without a copy?
There are basically two ways to pass arrays to a subroutine in Fortran 90/95:
PROGRAM ARRAY
INTEGER, ALLOCATABLE :: A(:,:)
INTEGER :: N
ALLOCATE(A(N,N))
CALL ARRAY_EXPLICIT(A,N)
! or
CALL ARRAY_ASSUMED(A)
END PROGRAM ARRAY
SUBROUTINE ARRAY_EXPLICIT(A,N)
INTEGER :: N
INTEGER :: A(N,N)
! bla bla
END SUBROUTINE ARRAY_EXPLICIT
SUBROUTINE ARRAY_ASSUMED(A)
INTEGER, ALLOCATABLE :: A(:,:)
N=SIZE(A,1)
! bla bla
END SUBROUTINE ARRAY_ASSUMED
where you need an explicit interface for the second, usually through the use of a module.
From FORTRAN77, I'm used to the first alternative, and I read this is also the most efficient if you pass the whole array.
The nice thing with the explicit shape is that I can also call a subroutine and treat the array as a vector instead of a matrix:
SUBROUTINE ARRAY_EXPLICIT(A,N)
INTEGER :: N
INTEGER :: A(N**2)
! bla bla
END SUBROUTINE ARRAY_EXPLICIT
I wondered if there is a nice way to do that kind of thing using the second, assumed shape interface, without copying it.
See the RESHAPE intrinsic, e.g.
http://gcc.gnu.org/onlinedocs/gfortran/RESHAPE.html
Alternatively, if you want to avoid the copy (in some cases an optimizing compiler might be able to do a reshape without copying, e.g. if the RHS array is not used afterwards, but I wouldn't count on it), as of Fortran 2003 you can assign pointers to targets of different rank, using bounds remapping. E.g. something like
program ptrtest
real, pointer :: a(:)
real, pointer :: b(:,:)
integer :: n = 10
allocate(a(n**2))
a = 42
b (1:n, 1:n) => a
end program ptrtest
I was looking to do the same thing and came across this discussion. None of the solutions suited my purposes, but I found that there is a way to reshape an array without copying the data using iso_c_binding if you are using the fortran 2003 standard which current fortran 90/95 compilers tend to support. I know the discussion is old, but I figured I would add what I came up with for the benefit of others with this question.
The key is to use the function C_LOC to convert an array to an array pointer, and then use C_F_POINTER to convert this back into a fortran array pointer with the desired shape. One challenge with using C_LOC is that C_LOC only works for array that have a directly specified shape. This is because arrays in fortran with an incomplete size specification (i.e., that use a : for some dimension) include an array descriptor along with the array data. C_LOC does not give you the memory location of the array data, but the location of the descriptor. So an allocatable array or a pointer array don't work with C_LOC (unless you want the location of the compiler specific array descriptor data structure). The solution is to create a subroutine or function that receives the array as an array of fixed size (the size really doesn't matter). This causes the array variable in the function (or subroutine) to point to the location of the array data rather than the location of the array descriptor. You then use C_LOC to get a pointer to the array data location and C_F_POINTER to convert this pointer back into an array with the desired shape. The desired shape must be passed into this function to be used with C_F_POINTER. Below is an example:
program arrayresize
implicit none
integer, allocatable :: array1(:)
integer, pointer :: array2(:,:)
! allocate and initialize array1
allocate(array1(6))
array1 = (/1,2,3,4,5,6/)
! This starts out initialized to 2
print *, 'array1(2) = ', array1(2)
! Point array2 to same data as array1. The shape of array2
! is passed in as an array of intergers because C_F_POINTER
! uses and array of intergers as a SIZE parameter.
array2 => getArray(array1, (/2,3/))
! Change the value at array2(2,1) (same as array1(2))
array2(2,1) = 5
! Show that data in array1(2) was modified by changing
! array2(2,1)
print *, 'array(2,1) = array1(2) = ', array1(2)
contains
function getArray(array, shape_) result(aptr)
use iso_c_binding, only: C_LOC, C_F_POINTER
! Pass in the array as an array of fixed size so that there
! is no array descriptor associated with it. This means we
! can get a pointer to the location of the data using C_LOC
integer, target :: array(1)
integer :: shape_(:)
integer, pointer :: aptr(:,:)
! Use C_LOC to get the start location of the array data, and
! use C_F_POINTER to turn this into a fortran pointer (aptr).
! Note that we need to specify the shape of the pointer using an
! integer array.
call C_F_POINTER(C_LOC(array), aptr, shape_)
end function
end program
#janneb has already answered re RESHAPE. RESHAPE is a function -- usually used in an assignment statement so there will be a copy operation. Perhaps it can be done without copying using pointers. Unless the array is huge, it is probably better to use RESHAPE.
I'm skeptical that the explicit shape array is more efficient than the assumed shape, in terms of runtime. My inclination is to use the features of the Fortran >=90 language and use assumed shape declarations ... that way you don't have to bother passing the dimensions.
EDIT:
I tested the sample program of #janneb with ifort 11, gfortran 4.5 and gfortran 4.6. Of these three, it only works in gfortran 4.6. Interestingly, to go the other direction and connect a 1-D array to an existing 2-D array requires another new feature of Fortran 2008, the "contiguous" attribute -- at least according to gfortran 4.6.0 20110318. Without this attribute in the declaration, there is a compile time error.
program test_ptrs
implicit none
integer :: i, j
real, dimension (:,:), pointer, contiguous :: array_twod
real, dimension (:), pointer :: array_oned
allocate ( array_twod (2,2) )
do i=1,2
do j=1,2
array_twod (i,j) = i*j
end do
end do
array_oned (1:4) => array_twod
write (*, *) array_oned
stop
end program test_ptrs
You can use assumed-size arrays, but it can mean multiple layers of wrapper
routines:
program test
implicit none
integer :: test_array(10,2)
test_array(:,1) = (/1, 2, 3, 4, 5, 6, 7, 8, 9, 10/)
test_array(:,2) = (/11, 12, 13, 14, 15, 16, 17, 18, 19, 20/)
write(*,*) "Original array:"
call print_a(test_array)
write(*,*) "Reshaped array:"
call print_reshaped(test_array, size(test_array))
contains
subroutine print_reshaped(a, n)
integer, intent(in) :: a(*)
integer, intent(in) :: n
call print_two_dim(a, 2, n/2)
end subroutine
subroutine print_two_dim(a, n1, n2)
integer, intent(in) :: a(1:n1,1:*)
integer, intent(in) :: n1, n2
call print_a(a(1:n1,1:n2))
end subroutine
subroutine print_a(a)
integer, intent(in) :: a(:,:)
integer :: i
write(*,*) "shape:", shape(a)
do i = 1, size(a(1,:))
write(*,*) a(:,i)
end do
end subroutine
end program test
I am using ifort 14.0.3 and 2D to 1D conversion, I could use an allocatable array for 2D array and a pointer array for 1D:
integer,allocatable,target :: A(:,:)
integer,pointer :: AP(:)
allocate(A(3,N))
AP(1:3*N) => A
As #M.S.B mentioned, in case both A and AP have the pointer attribute, I had to use contiguous attribute for A to guarantee the consistency of the conversion.
Gfortran is a bit paranoid with interfaces. It not only wants to know the type, kind, rank and number of arguments, but also the shape, the target attribute and the intent (although I agree with the intent part). I encountered a similar problem.
With gfortran, there are three different dimension definition:
1. Fixed
2. Variable
3. Assumed-size
With ifort, categories 1 and 2 are considered the same, so you can do just define any dimension size as 0 in the interface and it works.
program test
implicit none
integer, dimension(:), allocatable :: ownlist
interface
subroutine blueprint(sz,arr)
integer, intent(in) :: sz
integer, dimension(0), intent(in) :: arr
! This zero means that the size does not matter,
! as long as it is a one-dimensional integer array.
end subroutine blueprint
end interface
procedure(blueprint), pointer :: ptr
allocate(ownlist(3))
ownlist = (/3,4,5/)
ptr => rout1
call ptr(3,ownlist)
deallocate(ownlist)
allocate(ownlist(0:10))
ownlist = (/3,4,5,6,7,8,9,0,1,2,3/)
ptr => rout2
call ptr(3,ownlist)
deallocate(ownlist)
contains
! This one has a dimension size as input.
subroutine rout1(sz,arr)
implicit none
integer, intent(in) :: sz
integer, dimension(sz), intent(in) :: arr
write(*,*) arr
write(*,*) arr(1)
end subroutine rout1
! This one has a fixed dimension size.
subroutine rout2(sz,arr)
implicit none
integer, intent(in) :: sz
integer, dimension(0:10), intent(in) :: arr
write(*,*) "Ignored integer: ",sz
write(*,*) arr
write(*,*) arr(1)
end subroutine rout2
end program test
Gfortran complains about the interface. Changing the 0 into 'sz' solves the problem four 'rout1', but not for 'rout2'.
However, you can fool gfortran around and say dimension(0:10+0*sz) instead of dimension(0:10) and gfortran compiles and gives the same
result as ifort.
This is a stupid trick and it relies on the existence of the integer 'sz' that may not be there. Another program:
program difficult_test
implicit none
integer, dimension(:), allocatable :: ownlist
interface
subroutine blueprint(arr)
integer, dimension(0), intent(in) :: arr
end subroutine blueprint
end interface
procedure(blueprint), pointer :: ptr
allocate(ownlist(3))
ownlist = (/3,4,5/)
ptr => rout1
call ptr(ownlist)
deallocate(ownlist)
allocate(ownlist(0:10))
ownlist = (/3,4,5,6,7,8,9,0,1,2,3/)
ptr => rout2
call ptr(ownlist)
deallocate(ownlist)
contains
subroutine rout1(arr)
implicit none
integer, dimension(3), intent(in) :: arr
write(*,*) arr
write(*,*) arr(1)
end subroutine rout1
subroutine rout2(arr)
implicit none
integer, dimension(0:10), intent(in) :: arr
write(*,*) arr
write(*,*) arr(1)
end subroutine rout2
end program difficult_test
This works under ifort for the same reasons as the previous example, but gfortran complains about the interface. I do not know how I can fix it.
The only thing I want to tell gfortran is 'I do not know the dimension size yet, but we will fix it.'. But this needs a spare integer arguemnt (or something else that we can turn into an integer) to fool gfortran around.
As I understand, a user-derived type's definition can't contain target attributes. E.g., this isn't allowed:
type TestType
integer, target :: t
end type
However, it's fine for them to be a pointer:
type TestType2
integer, pointer :: p
end type
My question is, then, how can one use a pointer to point at an object's type variable? For example, if I wanted an object of type(TestType2) to have its p variable point to an object of type(TestType)'s t variable, how would I go about this? For example:
type(TestType) :: tt
type(TestType2) :: tt2
tt%t = 1
tt%p => tt%t
Thanks!
There would be very little sense in
type TestType
integer, target :: t
end type
because values of type(TestType) may easily come up in contexts where
they cannot be a target of a pointer.
As #roygvib comments, you have to give the target attribute to the whole object variable:
type(TestType), target :: tt
then you can make pointers to any of its components.
I could imagine that one could allow giving the target attribute to allocatable structure components in the type declaration, but it is not allowed. Certainly that would not make good sense for regular components.
Thanks #roygvib and #Vladimir F, I hadn't realised that giving the whole object variable the target attribute would allow me to point to any of its components. That worked perfectly.
For posterity, as my use case was a little more complex than the example above, I thought I'd post a more representative example of what I was trying to achieve. I was creating a grid system containing GridCells and Rivers, each GridCell having an array of Rivers, and each River also having an array of Rivers that flow into in (inflows) - these inflows would be Rivers that have been previously created and stored in the GridCell's array of rivers. I wanted to use pointers so that the inflows could just point to the corresponding river in a particular GridCell's rivers array.
The added complication is that River itself is an abstract type, extended by different SubRivers (SubRiver1 and SubRiver2 in the example below). I wanted the arrays of rivers and inflows to be of class(River) (i.e., polymorphic) and the only way to achieve that without Fortran complaining about polymorphic arrays was to create another user-derived type RiverElement with a polymorphic class(River), allocatable :: item property to store the river (see here).
Finally, because I couldn't set the inflows array such that each item was a pointer (setting inflows(:) as a pointer makes a pointer array, not an array of pointer), I had to create another user-derived type specifically for storing pointers to Rivers.
Here's the module with all the type definitions:
module TestModule
implicit none
type :: RiverPointer
class(River), pointer :: item => null()
end type
type, abstract :: River
type(RiverPointer), allocatable :: inflows(:)
integer :: id
end type
type :: RiverElement
class(River), allocatable :: item
end type
type :: GridCell
type(RiverElement), allocatable :: rivers(:)
end type
type, extends(River) :: SubRiver1
end type
type, extends(River) :: SubRiver2
end type
end module
And here's a test program showing that it works:
program main
use TestModule
implicit none
type(GridCell), target :: gc
type(SubRiver1) :: sr1
type(SubRiver2) :: sr2
type(SubRiver1) :: sr3
sr1%id = 1
sr2%id = 2
sr3%id = 3
allocate(gc%rivers(3))
allocate(gc%rivers(1)%item, source=sr1)
allocate(gc%rivers(2)%item, source=sr2)
allocate(gc%rivers(3)%item, source=sr3)
allocate(sr3%inflows(2))
sr3%inflows(1)%item => gc%rivers(1)%item
sr3%inflows(2)%item => gc%rivers(2)%item
write(*,*) sr3%inflows(1)%item%id ! 1
write(*,*) sr3%inflows(2)%item%id ! 2
gc%rivers(1)%item%id = 100
write(*,*) sr3%inflows(1)%item%id ! 100
end program
Thanks all!
I am trying to create an array of arrays in Fortran.
Something like the following
TYPE :: array_of_arrays
REAL, DIMENSION(:), POINTER :: p => NULL()
END TYPE
TYPE(array_of_arrays), DIMENSION(2) :: some_array
So that I can do:
REAL, DIMENSION(3), TARGET :: some_vector1 = (/1.0, 2.1, 4.3/)
REAL, DIMENSION(3), TARGET :: some_vector2 = (/3.0, 1.2, 9.6/)
some_array(1)%p => some_vector1
some_array(2)%p => some_vector2
WRITE(*,*) some_array(1)%p ! I see some_vector1
WRITE(*,*) some_array(2)%p ! I see some_vector2
Now it's cumbersome for me to actually declare each of these some_vector arrays to correspond to each element in my array of arrays.
What I'd like to do is have in a separate subroutine where a temporary vector is set as a target, and that subroutine sets up my array of arrays to point to that temporary vector.
This way I can have anonymous arrays.
However, this doesn't seem to be working and I wonder if first if I am doing something that Fortran doesn't support.
So does Fortran support anonymous arrays, that is (in case I have the terms wrong), an array who can only be accessed through a reference?
Sure; as IanH suggests, you can just have the pointer refer to allocated memory directly, rather than refer to a variable; this is one of the few cases where the allocated memory doesn't automatically get deallocated once it goes out of scope.
eg,
module arrays
TYPE :: array_of_arrays
REAL, DIMENSION(:), POINTER :: p => NULL()
END TYPE
contains
subroutine alloc(aa)
type(array_of_arrays), intent(inout) :: aa(:)
integer :: i
allocate( aa(1)%p(1) )
aa(1) % p = [1.]
allocate( aa(2)%p(5) )
aa(2) % p = [ (i, i=1,5) ]
end subroutine alloc
end module arrays
program usearrays
use arrays
TYPE(array_of_arrays), DIMENSION(2) :: some_array
call alloc(some_array)
WRITE(*,*) some_array(1)%p ! I see some_vector1
WRITE(*,*) some_array(2)%p ! I see some_vector2
deallocate( some_array(1) )
deallocate( some_array(2) )
end program usearrays
and running it gives
$ gfortran -o arrays arrays.f90
$ ./arrays
1.0000000
1.0000000 2.0000000 3.0000000 4.0000000 5.0000000