function md ( nd, np, step_num, dt )

%*****************************************************************************80
%
%% md() performs a molecular dynamics simulation.
%
%  Discussion:
%
%    MD implements a simple molecular dynamics simulation.
%
%    The velocity Verlet time integration scheme is used.
%
%    The particles interact with a central pair potential.
%
%    Based on a FORTRAN90 program by Bill Magro.
%
%  Usage:
%
%    md ( nd, np, step_num, dt )
%
%    where
%
%    * nd is the spatial dimension (2 or 3);
%    * np is the number of particles (500, for instance);
%    * step_num is the number of time steps (500, for instance).
%    * dt is the time step (0.1 for instance )
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    23 December 2020
%
%  Author:
%
%    John Burkardt
%
%  Input:
%
%    integer ND, the spatial dimension.  
%    A value of 2 or 3 is usual.
%    The default value is 3.
%
%    integer NP, the number of particles.  
%    A value of 1000 or 2000 is small but "reasonable".
%    The default value is 500.
%
%    integer STEP_NUM, the number of time steps.  
%    A value of 500 is a small but reasonable value.
%    The default value is 500.
%
%    real DT, the time step.
%    A value of 0.1 is large; the system will begin to move quickly but the
%    results will be less accurate.
%    A value of 0.0001 is small, but the results will be more accurate.
%    The default value is 0.1.
%
  mass = 1.0;
%
%  Report to the user.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'md():\n' );
  fprintf ( 1, '  MATLAB/Octave version %s\n', version ( ) );
  fprintf ( 1, '  A molecular dynamics program.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '  ND, the spatial dimension, is %d\n', nd );
  fprintf ( 1, '  NP, the number of particles in the simulation is %d.\n', np );
  fprintf ( 1, '  STEP_NUM, the number of time steps, is %d.\n', step_num );
  fprintf ( 1, '  DT, the time step size, is %g seconds.\n', dt );
%
%  This is the main time stepping loop:
%    Compute forces and energies,
%    Update positions, velocities, accelerations.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, '  At each step, we report the potential and kinetic energies.\n' );
  fprintf ( 1, '  The sum of these energies should be a constant.\n' );
  fprintf ( 1, '  As an accuracy check, we also print the relative error\n' );
  fprintf ( 1, '  in the total energy.\n' );
  fprintf ( 1, '\n' );
  fprintf ( 1, '      Step      Potential       Kinetic        (P+K-E0)/E0\n' );
  fprintf ( 1, '                Energy P        Energy K       Relative Energy Error\n' );
  fprintf ( 1, '\n' );

  step_print_index = 0;
  step_print_num = 10;
  step_print = 0;

  t = ( ( 1 : step_num + 1 ) * dt )';
  p = zeros ( step_num + 1, 1 );
  k = zeros ( step_num + 1, 1 );

  tic ( );

  for step = 0 : step_num

    if ( step == 0 )
      pos = rand ( nd, np );
      vel = 10.0 * randn ( nd, np );
      acc = zeros ( nd, np );
    else
      [ pos, vel, acc ] = update ( np, nd, pos, vel, force, acc, mass, dt );
    end

    [ force, potential, kinetic ] = compute ( np, nd, pos, vel, mass );
    p(step+1) = potential;
    k(step+1) = kinetic;

    if ( step == 0 )
      e0 = potential + kinetic;
    end

    if ( step == step_print )
      rel = ( potential + kinetic - e0 ) / e0;
      fprintf ( 1, '  %8d  %14f  %14f  %14e  %14f  %14f  %14f\n', ...
        step, potential, kinetic, rel, ...
        norm ( pos, 'fro' ), norm ( vel, 'fro' ), norm ( acc, 'fro' ) );
      step_print_index = step_print_index + 1;
      step_print = floor ( ( step_print_index * step_num ) / step_print_num );
    end

  end
%
%  Report timing.
%
  wtime = toc;
  fprintf ( 1, '\n' );
  fprintf ( 1, '  Wall clock time = %f seconds.\n', wtime );

  figure ( );
  clf ( );
  hold ( 'on' );
    plot ( t, k, 'c-', 'linewidth', 2 );
    plot ( t, p, 'b-', 'linewidth', 2 );
    plot ( t, k + p, 'g-', 'linewidth', 2 );
    plot ( [t(1),t(end)], [e0,e0], 'r--', 'linewidth', 2 );
    plot ( [t(1),t(end)], [0.0,0.0], 'k-', 'linewidth', 2 );
  hold ( 'off' );
  grid ( 'on' );
  xlabel ( '<--- T --->' );
  ylabel ( '<--- Energy --->' );
  title ( 'Energy time plot' );
  legend ( 'Kinetic', 'Potential', 'Total', 'Initial', 'Zero', ...
    'Location', 'South' );
  filename = 'md.png';
  print ( '-dpng', filename );
  fprintf ( 1, '  Graphics saved as "%s"\n', filename );
%
%  Terminate.
%
  fprintf ( 1, '\n' );
  fprintf ( 1, 'md():\n' );
  fprintf ( 1, '  Normal end of execution.\n' );

  return
end
function [ f, pot, kin ] = compute ( np, nd, pos, vel, mass )

%*****************************************************************************80
%
%% compute() computes the forces and energies.
%
%  Discussion:
%
%    The potential function V(X) is a harmonic well which smoothly
%    saturates to a maximum value at PI/2:
%
%      v(x) = ( sin ( min ( x, PI/2 ) ) )^2
%
%    The derivative of the potential is:
%
%      dv(x) = 2.0 * sin ( min ( x, PI/2 ) ) * cos ( min ( x, PI/2 ) )
%            = sin ( 2.0 * min ( x, PI/2 ) )
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    30 July 2009
%
%  Author:
%
%    John Burkardt and Gene Cliff.
%
%  Input:
%
%    integer NP, the number of particles.
%
%    integer ND, the number of spatial dimensions.
%
%    real POS(ND,NP), the positions.
%
%    real VEL(ND,NP), the velocities.
%
%    real MASS, the mass of each particle.
%
%  Output:
%
%    real F(ND,NP), the forces.
%
%    real POT, the total potential energy.
%
%    real KIN, the total kinetic energy.
%
  f = zeros ( nd, np );
  rij = zeros ( nd, 1 );

  pot = 0.0;

  for i = 1 : np
%
%  Compute the potential energy and forces.
%
    for j = 1 : np

      if ( i ~= j )
%
%  DO NOT replace this loop with a "vectorized" version.
%  It will run much more slowly.
%
        for k = 1 : nd
          rij(k) = pos(k,i) - pos(k,j);
        end

        d = norm ( rij );
%
%  Truncate the distance.
%
        d2 = min ( d, pi / 2.0 );
%
%  Attribute half of the total potential energy to particle J.
%
        pot = pot + 0.5 * sin ( d2 ) * sin ( d2 );
%
%  Add particle J's contribution to the force on particle I.
%
%  DO NOT replace this loop with a "vectorized" version.
%  It will run much more slowly.
%
        for k = 1 : nd
          f(k,i) = f(k,i) - rij(k) * sin ( 2.0 * d2 ) / d;
        end

      end

    end

  end
%
%  Compute the total kinetic energy.
%
  kin = 0.5 * mass * sum ( sum ( vel(1:nd,1:np).^2 ) );

  return
end
function timestamp ( )

%*****************************************************************************80
%
%% timestamp() prints the current YMDHMS date as a timestamp.
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    14 February 2003
%
%  Author:
%
%    John Burkardt
%
  t = now;
  c = datevec ( t );
  s = datestr ( c, 0 );
  fprintf ( 1, '%s\n', s );

  return
end
function [ pos, vel, acc ] = update ( np, nd, pos, vel, force, acc, mass, dt )

%*****************************************************************************80
%
%% update() updates positions, velocities and accelerations.
%
%  Discussion:
%
%    The time integration is fully parallel.
%
%    A velocity Verlet algorithm is used for the updating.
%
%    x(t+dt) = x(t) + v(t) * dt + 0.5 * a(t) * dt * dt
%    v(t+dt) = v(t) + 0.5 * ( a(t) + a(t+dt) ) * dt
%    a(t+dt) = force(t) / m
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    15 July 2008
%
%  Author:
%
%    John Burkardt
%
%  Input:
%
%    integer NP, the number of particles.
%
%    integer ND, the number of spatial dimensions.
%
%    real POS(ND,NP), the positions.
%
%    real VEL(ND,NP), the velocities.
%
%    real FORCE(ND,NP), the forces.
%
%    real ACC(ND,NP), the accelerations.
%
%    real MASS, the mass of each particle.
%
%    real DT, the time step.
%
%  Output:
%
%    real POS(ND,NP), the updated positions.
%
%    real VEL(ND,NP), the updated velocities.
%
%    real ACC(ND,NP), the updated accelerations.
%
  pos(1:nd,1:np) = pos(1:nd,1:np) + vel(1:nd,1:np) * dt ...
    + 0.5 * acc(1:nd,1:np) * dt * dt;

  vel(1:nd,1:np) = vel(1:nd,1:np) ...
    + 0.5 * dt * ( force(1:nd,1:np) / mass + acc(1:nd,1:np) );

  acc(1:nd,1:np) = force(1:nd,1:np) / mass;

  return
end
 
