Skip to content

Instantly share code, notes, and snippets.

@memmett
Created January 6, 2012 16:27
Show Gist options
  • Save memmett/1571295 to your computer and use it in GitHub Desktop.
Save memmett/1571295 to your computer and use it in GitHub Desktop.
Generate an F90 module to cast complex arrays to (flat) real arrays
"""Generate an F90 module to cast various Fortran arrays to flat real
arrays."""
from itertools import product
kinds = [ '8' ]
types = [ 'real', 'complex' ]
dims = range(1,7)
module = '''\
module fcast
use iso_c_binding
interface cast
{interfaces}
end interface
contains
{procedures}
end module fcast
'''
interface = 'module procedure {name}'
procedure = '''\
subroutine {name}(s,d)
{type}({kind}), intent(in), target :: s({dims})
real({kind}), intent(out), pointer :: d(:)
{type}({kind}), pointer :: p({dims})
p => s
call c_f_pointer(c_loc(p({first})), d, (/ size(s) /))
end subroutine {name}
'''
interfaces = []
procedures = []
for k, t, j in product(kinds, types, dims):
k = str(k)
t = str(t)
d = ','.join(j*(':',))
f = ','.join(j*('1',))
name = 'cast_%s_%s_%d' % (t, k, j)
procedures.append(procedure.format(
name=name,
type=t,
kind=k,
dims=d,
first=f,
))
interfaces.append(interface.format(
name=name
))
print module.format(
interfaces='\n'.join(interfaces),
procedures='\n'.join(procedures)
)
program test
use fcast
complex(8) :: c(2,5)
real(8), pointer :: r(:)
c = 0.0d0
c(1,1) = cmplx(0.0, 1.0)
call cast(c,r)
print *, r
r(4) = 22.0
print *, c
end program test
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment