Code examples

1. Introduction

This page collects worked examples: programs that create a context, put points in it and call the kernels. The first two read a wave function from a TREXIO file, evaluate the orbitals on a regular grid and build the overlap matrix in the MO basis, once in C and once in Fortran. A third program evaluates a single atomic orbital on a grid, and the error-handling subroutine it uses is given as well.

2. Overlap matrix in the MO basis

The example computes the overlap matrix in the MO basis on a regular grid:

Sij=∫ϕi(𝐫)ϕj(𝐫)d𝐫≈∑kϕi(𝐫k)ϕj(𝐫k)δ𝐫

The program reads a wave function from a TREXIO file with qmckl_trexio_read, which fills the context with the electrons, the nuclei, the AOs and the MOs. It then takes the number of nuclei, their coordinates and the number of MOs from the context, and builds a regular mesh of 120 x 120 x 120 points around the molecule, 1728000 points in all. The mesh is handed to the context with qmckl_set_point.

The MO values at those points come from qmckl_get_mo_basis_mo_value, which the program times. They form a matrix M whose element M_ki is the value of MO i at point k, and one call to qmckl_dgemm forms the product M M^T, scaled by the volume element dr of the mesh. The program prints the resulting matrix.

2.1. C

This version adds the electron-nucleus cusp fit. The listing is split into blocks and tangled into mo_ortho.c.

The program fetches the nuclear charges, gives a cusp radius to each element, and passes the radii to qmckl_set_mo_basis_r_cusp, so the MO values come from the cusp-corrected kernels described on the MO page. The fit perturbs the orbitals: the overlap matrix is no longer exactly the identity.

C mo_ortho.c
#include <qmckl.h>
#include <stdio.h>
#include <string.h>
#include <sys/time.h>

int main(int argc, char** argv)
{
  const char* trexio_filename = "..//share/qmckl/test_data/h2o_5z.h5";
  qmckl_exit_code rc = QMCKL_SUCCESS;

The program creates a context and reads into it a TREXIO file for the water molecule. The file name is hard-coded, ..//share/qmckl/test_data/h2o_5z.h5, and the file does not ship with QMCkl; the Fortran version below takes the name on the command line instead.

C mo_ortho.c
qmckl_context context = qmckl_context_create();

rc = qmckl_trexio_read(context, trexio_filename, strlen(trexio_filename));

if (rc != QMCKL_SUCCESS) {
  fprintf(stderr, "Error reading TREXIO file:\n%s\n", qmckl_string_of_error(rc));
  exit(1);
}

We impose the electron-nucleus cusp fitting to occur when the electrons are close to the nuclei. The critical distance is 0.5 atomic units for hydrogens and 0.1 for the oxygen. To identify which atom is an oxygen and which are hydrogens, we fetch the nuclear charges from the context.

C mo_ortho.c
int64_t nucl_num;

rc = qmckl_get_nucleus_num(context, &nucl_num);

if (rc != QMCKL_SUCCESS) {
  fprintf(stderr, "Error getting nucl_num:\n%s\n", qmckl_string_of_error(rc));
  exit(1);
}


double nucl_charge[nucl_num];

rc = qmckl_get_nucleus_charge(context, &(nucl_charge[0]), nucl_num);

if (rc != QMCKL_SUCCESS) {
  fprintf(stderr, "Error getting nucl_charge:\n%s\n", qmckl_string_of_error(rc));
  exit(1);
}


double r_cusp[nucl_num];

for (size_t i=0 ; i<nucl_num ; ++i) {

  switch ((int) nucl_charge[i]) {

  case 1:
    r_cusp[i] = 0.5;
    break;

  case 8:
    r_cusp[i] = 0.1;
    break;
  }

}


rc = qmckl_set_mo_basis_r_cusp(context, &(r_cusp[0]), nucl_num);

if (rc != QMCKL_SUCCESS) {
  fprintf(stderr, "Error setting r_cusp:\n%s\n", qmckl_string_of_error(rc));
  exit(1);
}

The grid points r_k form a regular mesh around the molecule. It is built from the nuclear coordinates, which come from the context:

C mo_ortho.c
double nucl_coord[nucl_num][3];

rc = qmckl_get_nucleus_coord(context, 'N', &(nucl_coord[0][0]), nucl_num*3);

if (rc != QMCKL_SUCCESS) {
  fprintf(stderr, "Error getting nucl_coord:\n%s\n", qmckl_string_of_error(rc));
  exit(1);
}

for (size_t i=0 ; i<nucl_num ; ++i) {
  printf("%d  %+f %+f %+f\n",
         (int32_t) nucl_charge[i],
         nucl_coord[i][0],
         nucl_coord[i][1],
         nucl_coord[i][2]);
}

The coordinates of the grid points are computed next, from the extent of the molecule:

C mo_ortho.c
size_t nx[3] = { 120, 120, 120 };
double shift[3] = {5.,5.,5.};
int64_t point_num = nx[0] * nx[1] * nx[2];

double rmin[3] = { nucl_coord[0][0], nucl_coord[0][1], nucl_coord[0][2] } ;
double rmax[3] = { nucl_coord[0][0], nucl_coord[0][1], nucl_coord[0][2] } ;

for (size_t i=0 ; i<nucl_num ; ++i) {
  for (int j=0 ; j<3 ; ++j) {
    rmin[j] = nucl_coord[i][j] < rmin[j] ? nucl_coord[i][j] : rmin[j];
    rmax[j] = nucl_coord[i][j] > rmax[j] ? nucl_coord[i][j] : rmax[j];
  }
}

rmin[0] -= shift[0]; rmin[1] -= shift[1]; rmin[2] -= shift[2];
rmax[0] += shift[0]; rmax[1] += shift[1]; rmax[2] += shift[2];

double step[3];

double* linspace[3];
for (int i=0 ; i<3 ; ++i) {

  linspace[i] = (double*) calloc( sizeof(double), nx[i] );

  if (linspace[i] == NULL) {
    fprintf(stderr, "Allocation failed (linspace)\n");
    exit(1);
  }

  step[i] = (rmax[i] - rmin[i]) / ((double) (nx[i]-1));

  for (size_t j=0 ; j<nx[i] ; ++j) {
    linspace[i][j] = rmin[i] + j*step[i];
  }

}

double dr = step[0] * step[1] * step[2];

The list of grid points on which the MOs are evaluated follows the mesh and is handed to the QMCkl context:

C mo_ortho.c
double* point = (double*) calloc(sizeof(double), 3*point_num);

if (point == NULL) {
  fprintf(stderr, "Allocation failed (point)\n");
  exit(1);
}

size_t m = 0;
for (size_t i=0 ; i<nx[0] ; ++i) {
  for (size_t j=0 ; j<nx[1] ; ++j) {
    for (size_t k=0 ; k<nx[2] ; ++k) {

      point[m] = linspace[0][i];
      m++;

      point[m] = linspace[1][j];
      m++;

      point[m] = linspace[2][k];
      m++;

    }
  }
}

rc = qmckl_set_point(context, 'N', point_num, point, (point_num*3));

if (rc != QMCKL_SUCCESS) {
  fprintf(stderr, "Error setting points:\n%s\n", qmckl_string_of_error(rc));
  exit(1);
}

The MOs are evaluated at every grid point and the call is timed. The values are stored as a flat array of point_num*mo_num doubles, with the MO index running fastest: its element k*mo_num+i is the value of MO i at point k.

C mo_ortho.c
int64_t mo_num;
rc = qmckl_get_mo_basis_mo_num(context, &mo_num);

long before, after;
struct timeval timecheck;

double* mo_value = (double*) calloc(sizeof(double), point_num*mo_num);
if (mo_value == NULL) {
  fprintf(stderr, "Allocation failed (mo_value)\n");
  exit(1);
}

gettimeofday(&timecheck, NULL);
before = (long)timecheck.tv_sec * 1000 + (long)timecheck.tv_usec / 1000;

rc = qmckl_get_mo_basis_mo_value(context, mo_value, point_num*mo_num);
if (rc != QMCKL_SUCCESS) {
  fprintf(stderr, "Error getting mo_value)\n");
  exit(1);
}

gettimeofday(&timecheck, NULL);
after = (long)timecheck.tv_sec * 1000 + (long)timecheck.tv_usec / 1000;

printf("Number of MOs: %ld\n", (long) mo_num);
printf("Number of grid points: %ld\n", (long) point_num);
printf("Execution time : %f seconds\n", (after - before)*1.e-3);

The overlap matrix follows from one matrix product, M M^T, with the volume element dr as prefactor:

C mo_ortho.c
  double* overlap = (double*) malloc (mo_num*mo_num*sizeof(double));

  rc = qmckl_dgemm(context, 'N', 'T', mo_num, mo_num, point_num, dr,
                   mo_value, mo_num, mo_value, mo_num, 0.0,
                   overlap, mo_num);

  for (size_t i=0 ; i<mo_num ; ++i) {
    printf("%4ld", i);
    for (size_t j=0 ; j<mo_num ; ++j) {
      printf(" %f", overlap[i*mo_num+j]);
    }
    printf("\n");
  }

  // Clean-up and exit
  free(mo_value);
  free(overlap);

  rc = qmckl_context_destroy(context);
  if (rc != QMCKL_SUCCESS) {
    fprintf(stderr, "Error destroying context)\n");
    exit(1);
  }

  return 0;
}

2.2. Fortran

The same calculation in Fortran. This version takes the TREXIO file name on the command line, uses the qmckl module of the generated interface qmckl_f.F90, and leaves the cusp fit out.

Fortran mo_ortho_f.f90
#include <qmckl_f.F90>

program main
  use iso_c_binding
  use qmckl
  implicit none

  ! Declare variables
  integer :: argc
  character(128) :: trexio_filename, err_msg
  integer(qmckl_exit_code) :: rc
  integer(qmckl_context) :: context
  integer*8 :: nucl_num, mo_num, point_num
  double precision, allocatable :: nucl_coord(:,:)
  integer*8  :: nx(3)
  double precision, dimension(3) :: shift, step, rmin, rmax
  double precision, allocatable :: mo_value(:,:), overlap(:,:), point(:), linspace(:,:)
  double precision :: before, after, dr
  integer*8 :: i,j,k,m

  ! Initialize variables
  err_msg = ' ' 
  argc = command_argument_count()
  if (argc /= 1) then
    print *, "Usage: ./program <TREXIO filename>"
    stop -1
  end if
  call get_command_argument(1, trexio_filename)
  rc = QMCKL_SUCCESS

  ! Create a QMCkl context
  context = qmckl_context_create()

  ! Read the TREXIO file into the context
  rc = qmckl_trexio_read(context, trim(trexio_filename), len(trexio_filename)*1_8)
  if (rc /= QMCKL_SUCCESS) then
    call qmckl_string_of_error(rc, err_msg)
    write(*,*) "Error reading TREXIO file:", err_msg
    stop -1
  end if

  ! Retrieve the number of nuclei
  rc = qmckl_get_nucleus_num(context, nucl_num)
  if (rc /= QMCKL_SUCCESS) then
    call qmckl_string_of_error(rc, err_msg)
    write(*,*) "Error getting nucl_num:", err_msg
    stop -1
  end if

  ! Retrieve the nuclear coordinates
  allocate(nucl_coord(3, nucl_num))
  rc = qmckl_get_nucleus_coord(context, 'N', nucl_coord, nucl_num * 3_8)
  if (rc /= QMCKL_SUCCESS) then
    call qmckl_string_of_error(rc, err_msg)
    write(*,*) "Error getting nucl_coord:", err_msg
    stop -1
  end if

  ! Retrieve the number of MOs
  rc = qmckl_get_mo_basis_mo_num(context, mo_num)
  if (rc /= QMCKL_SUCCESS) then
    call qmckl_string_of_error(rc, err_msg)
    write(*,*) "Error getting mo_num:", err_msg
    stop -1
  end if

  ! Initialize grid points for the calculation
  nx = (/ 120, 120, 120 /)
  shift = (/ 5.d0, 5.d0, 5.d0 /)
  point_num = nx(1) * nx(2) * nx(3)

  ! Initialize rmin and rmax
  rmin = nucl_coord(:,1)
  rmax = nucl_coord(:,1)

  ! Update rmin and rmax based on nucl_coord
  do i = 1, 3
    do j = 1, nucl_num
      rmin(i) = min(nucl_coord(i,j), rmin(i))
      rmax(i) = max(nucl_coord(i,j), rmax(i))
    end do
  end do

  ! Apply shift
  rmin = rmin - shift
  rmax = rmax + shift

  ! Initialize linspace and step
  allocate(linspace(3, maxval(nx)))

  do i = 1, 3
    step(i) = (rmax(i) - rmin(i)) / real(nx(i) - 1, 8)
    do j = 1, nx(i)
      linspace(i, j) = rmin(i) + (j - 1) * step(i)
    end do
  end do

  ! Initialize point array
  allocate(point(3 * point_num))
  m = 1
  do i = 1, nx(1)
    do j = 1, nx(2)
      do k = 1, nx(3)
        point(m) = linspace(1, i); m = m + 1
        point(m) = linspace(2, j); m = m + 1
        point(m) = linspace(3, k); m = m + 1
      end do
    end do
  end do

  deallocate(linspace)


  ! Set points in QMCKL context
  rc = qmckl_set_point(context, 'N', point_num, point, point_num * 3)
  if (rc /= QMCKL_SUCCESS) then
    call qmckl_string_of_error(rc, err_msg)
    write(*,*) "Error setting point:", err_msg
    stop -1
  end if




  ! Perform the actual calculation and measure the time taken
  call cpu_time(before)
  allocate(mo_value(point_num, mo_num))
  rc = qmckl_get_mo_basis_mo_value(context, mo_value, point_num * mo_num)
  if (rc /= QMCKL_SUCCESS) then
    call qmckl_string_of_error(rc, err_msg)
    write(*,*) "Error getting mo_value:", err_msg
    stop
  end if
  call cpu_time(after)

  write(*,*) "Number of MOs:", mo_num
  write(*,*) "Number of grid points:", point_num
  write(*,*) "Execution time:", (after - before), "seconds"

  ! Compute the overlap matrix
  dr = step(1) * step(2) * step(3)

  allocate(overlap(mo_num, mo_num))
  rc = qmckl_dgemm(context, 'N', 'T', mo_num, mo_num, point_num, dr, &
                   mo_value, mo_num, mo_value, mo_num, 0.d0, overlap, mo_num)

  ! Print the overlap matrix
  do i = 1, mo_num
    write(*,'(i4)', advance='no') i
    do j = 1, mo_num
      write(*,'(f8.4)', advance='no') overlap(i, j)
    end do
    write(*,*)
  end do

  ! Clean-up and exit
  deallocate(mo_value, overlap)
  rc = qmckl_context_destroy(context)
  if (rc /= QMCKL_SUCCESS) then
    call qmckl_string_of_error(rc, err_msg)
    write(*,*) "Error destroying context:", err_msg
    stop -1
  end if

end program main

3. Checking errors

Every QMCkl function returns an exit code, QMCKL_SUCCESS when the call worked. qmckl_check_error stops the program on any other code: it prints the message it is given, prints the text of the code with qmckl_string_of_error, whose buffer holds 128 characters, and exits with the code. The program below calls it after each QMCkl call.

Fortran qmckl_check_error.f90
subroutine qmckl_check_error(rc, message)
  use qmckl
  implicit none
  integer(qmckl_exit_code), intent(in) :: rc
  character(len=*)        , intent(in) :: message
  character(len=128)                   :: str_buffer
  if (rc /= QMCKL_SUCCESS) then
     print *, message
     call qmckl_string_of_error(rc, str_buffer)
     print *, str_buffer
     call exit(rc)
  end if
end subroutine qmckl_check_error

4. Computing an atomic orbital on a grid

The Fortran program ao_grid evaluates one atomic orbital on a regular grid. The grid has point_num_x points along each direction, so it holds point_num points in all, and its box extends five atomic units beyond the molecule. The points are stored as (point_num,3), whose Fortran layout already has all the x coordinates first, so they reach qmckl_set_point with transp='T'.

The program uses the qmckl_check_error subroutine defined above. Run it with

Shell ao_grid.f90
$ ao_grid <trexio_file> <AO_id> <point_num>
Fortran ao_grid.f90
subroutine qmckl_check_error(rc, message)
  use qmckl
  implicit none
  integer(qmckl_exit_code), intent(in) :: rc
  character(len=*)        , intent(in) :: message
  character(len=128)                   :: str_buffer
  if (rc /= QMCKL_SUCCESS) then
     print *, message
     call qmckl_string_of_error(rc, str_buffer)
     print *, str_buffer
     call exit(rc)
  end if
end subroutine qmckl_check_error

program ao_grid
  use qmckl
  implicit none

  integer(qmckl_context)    :: qmckl_ctx  ! QMCkl context
  integer(qmckl_exit_code)  :: rc         ! Exit code of QMCkl functions

  character(len=128)            :: trexio_filename
  character(len=128)            :: str_buffer
  integer                       :: ao_id
  integer                       :: point_num_x

  integer(c_int64_t)            :: nucl_num
  double precision, allocatable :: nucl_coord(:,:)

  integer(c_int64_t)            :: point_num
  integer(c_int64_t)            :: ao_num
  integer(c_int64_t)            :: ipoint, i, j, k
  double precision              :: x, y, z, dr(3)
  double precision              :: rmin(3), rmax(3)
  double precision, allocatable :: points(:,:)
  double precision, allocatable :: ao_vgl(:,:,:)

Start by fetching the command-line arguments:

Fortran ao_grid.f90
if (iargc() /= 3) then
   print *, 'Syntax: ao_grid <trexio_file> <AO_id> <point_num>'
   call exit(-1)
end if
call getarg(1, trexio_filename)
call getarg(2, str_buffer)
read(str_buffer, *) ao_id
call getarg(3, str_buffer)
read(str_buffer, *) point_num_x

if (point_num_x < 0 .or. point_num_x > 300) then
   print *, 'Error: 0 < point_num < 300'
   call exit(-1)
end if

Create the QMCkl context and initialize it with the wave function present in the TREXIO file:

Fortran ao_grid.f90
qmckl_ctx = qmckl_context_create()
rc  = qmckl_trexio_read(qmckl_ctx, trexio_filename, 1_8*len(trim(trexio_filename)))
call qmckl_check_error(rc, 'Read TREXIO')

The number of AOs comes from the context, and is used to check ao_id. It indexes the Fortran array of AO values, so it runs from 1 to ao_num:

Fortran ao_grid.f90
rc = qmckl_get_ao_basis_ao_num(qmckl_ctx, ao_num)
call qmckl_check_error(rc, 'Getting ao_num')

if (ao_id < 1 .or. ao_id > ao_num) then
   print *, 'Error: 1 <= ao_id <= ', ao_num
   call exit(-1)
end if

The limits of the box need the nuclear coordinates, which are in the context:

Fortran ao_grid.f90
rc = qmckl_get_nucleus_num(qmckl_ctx, nucl_num)
call qmckl_check_error(rc, 'Get nucleus num')

allocate( nucl_coord(3, nucl_num) )
rc = qmckl_get_nucleus_coord(qmckl_ctx, 'N', nucl_coord, 3_8*nucl_num)
call qmckl_check_error(rc, 'Get nucleus coord')

The corners of the box and the step along each direction:

Fortran ao_grid.f90
rmin(1) = minval( nucl_coord(1,:) ) - 5.d0
rmin(2) = minval( nucl_coord(2,:) ) - 5.d0
rmin(3) = minval( nucl_coord(3,:) ) - 5.d0

rmax(1) = maxval( nucl_coord(1,:) ) + 5.d0
rmax(2) = maxval( nucl_coord(2,:) ) + 5.d0
rmax(3) = maxval( nucl_coord(3,:) ) + 5.d0

dr(1:3) = (rmax(1:3) - rmin(1:3)) / dble(point_num_x-1)

The list of points follows the mesh, with x varying fastest:

Fortran ao_grid.f90
point_num = point_num_x**3
allocate( points(point_num, 3) )
ipoint=0
z = rmin(3)
do k=1,point_num_x
   y = rmin(2)
   do j=1,point_num_x
      x = rmin(1)
      do i=1,point_num_x
         ipoint = ipoint+1
         points(ipoint,1) = x
         points(ipoint,2) = y
         points(ipoint,3) = z
         x = x + dr(1)
      end do
      y = y + dr(2)
   end do
   z = z + dr(3)
end do

We give the points to QMCkl:

Fortran ao_grid.f90
rc = qmckl_set_point(qmckl_ctx, 'T', point_num, points, size(points)*1_8 )
call qmckl_check_error(rc, 'Setting points')

The values, gradients and Laplacians of all the AOs are retrieved in one array of shape (ao_num,5,point_num):

Fortran ao_grid.f90
allocate( ao_vgl(ao_num, 5, point_num) )
rc = qmckl_get_ao_basis_ao_vgl(qmckl_ctx, ao_vgl, ao_num*5_8*point_num)
call qmckl_check_error(rc, 'Getting ao_vgl')

The value (component 1) and the Laplacian (component 5) of the chosen AO are printed for every point:

Fortran ao_grid.f90
do ipoint=1, point_num
   print '(3(F10.6,X),2(E20.10,X))', points(ipoint, 1:3), ao_vgl(ao_id,1,ipoint), ao_vgl(ao_id,5,ipoint)
end do
Fortran ao_grid.f90
  deallocate( nucl_coord, points, ao_vgl )
end program ao_grid