Silverfrost Forums

Welcome to our forums

FTN95 and netCDF

18 Feb 2025 11:21 #31939

Hello,

Just wondering if anyone has managed to build the netcdf Fortran module to work with FTN95 or if there are other ways to deal with netCDF in Fortran?

The code is rather involved! https://docs.unidata.ucar.edu/netcdf-fortran/current/

I have used a workaround that requires GMT (Generic Mapping Tools) installed to allow reading and writing netCDF grid files. Not perfect but works.

A simple read/write test:

! Test driver program for working with netCDF files
! Prerequisite - full install of Generic Mapping Tools (GMT)
! Binaries must be in the PATH (default under Windows)

program read_netcdf
  
  implicit none
  
  character(len=30) :: filename
  character(len=100) :: range_str, command
  integer :: ierror, ios, n
  real(kind=2) :: x, y, z
  real(kind=2) :: xmin, xmax, ymin, ymax, zmin, zmax
  character(len=200) :: line
  logical :: first = .true.
  
  filename = 'Bathy_crop1_scaled.grd'

  ! Prompt user for the NetCDF file name
  !write(*,*) 'Enter the NetCDF filename: '
  !read(*, '(a)') filename

  ! Use GMT to get x, y  and z from a netCDF file for processing
  ! Use gmt command grd2xyz with redirection
  call system(trim('grd2xyz ' // trim(filename) // ' > gmt_xyz.txt'))

! XYZ file generated by grd2xyz (netCDF to xyz)
open(10, file='gmt_xyz.txt', status='old', action='read', iostat=ierror)
open(20, file='xyz_output.txt')

n = 0
do
     read(10, '(a)', IOSTAT=ios) line
     if (ios /= 0) exit  ! exit loop if end of file

     ! read x, y, z values from the line
     read(line, *, iostat=ios) x, y, z
     if (ios /= 0) cycle  ! skip invalid lines
     n = n + 1 ! Line count

     ! initialize min/max with the first valid values
     if (first) then
        xmin = x; ymin = y; zmin = z
        xmax = x; ymax = y; zmax = z
        first = .false.
     else
        xmin = min(xmin, x)
        ymin = min(ymin, y)
        zmin = min(zmin, z)
        xmax = max(xmax, x)
        ymax = max(ymax, y)
        zmax = max(zmax, z)
     end if

      ! Match the data precision of the GMT text data from xyz2grd
      write(20,'(f12.5,1x,f15.5,1x,f15.8)') x, y, z
end do

close(10)
close(20)

! Convert each real number to a string and trim spaces
write(range_str, '(F0.2,'/',F0.2,'/',F0.2,'/',F0.2)') xmin, xmax, ymin, ymax

write(*,*) 'Data read complete. Number of points: ', n
write(*,'(A,F12.5,A,F12.5)') 'X range: ', xmin, ' to ', xmax
write(*,'(A,F15.5,A,F15.5)') 'Y range: ', ymin, ' to ', ymax
write(*,'(A,F10.5,A,F10.5)') 'Z range: ', zmin, ' to ', zmax

! GMT command to build a netCDF grid file
command = 'xyz2grd xyz_output.txt -Gxyzoutput2.grd -R' // trim(range_str) // ' -I0.25 -V'

! Check the string results
print *, trim(range_str)
print *, trim(command)

call system(command)

end program read_netcdf

Lester

Please login to reply.