[lammps-users] allocation/deallocation of scratch buffers

I am developing a modification to PairEAM::compute() in C++ to calculate a new forcefield with a different approach to potential functions. My new code requires intermediate variables:

double **rhop; // derivative of rho wrt r, segregated by site and type
double **rhot; // density values for each atom and each type
double *hc; // coefficients of polynomial target function h(x); typically about 5 coefficients

Where and how is it appropriate to declare, allocate, deallocate, initialize these variables? Should I do something like the following?

pair_eam.h:
   private:
     double **rhop;
     double **rhot;
     double *hc;

pair_eam.cpp:
PairEAM::PairEAM()
{
   ...
   hc = NULL;
}

PairEAM::~PairEAM()
{
   ...
   if (hc) {
     memory->sfree(hc);
     memory->destroy_2d_double_array(rhop);
     memory->destroy_2d_double_array(rhot);
   }
}

PairEAM::compute()
{
   ...
   if (hc) {
     memory->sfree(hc);
     memory->destroy_2d_double_array(rhop);
     memory->destroy_2d_double_array(rhot);
   }
   hc = (double *)
     memory->srealloc(hc,(hd+1),"pair:hc");
   rhop = (double **)
     memory->create_2d_double_array(num_atoms,ntypes,"pair:rhop");
   rhot = (double **)
     memory->create_2d_double_array(num_atoms,ntypes,"pair:rhot");
   for ( int ai = 0; ai < num_atoms; ai++ ) {
     for ( int ti = 0; ti < ntypes; ti++ ) {
       rhop[ai][ti] = 0.0;
       rhot[ai][ti] = 0.0;
     }
   }
   ...
}

Yes, you can add any variables as private in pair_eam_new.h
and allocate/delete them in pair_eam_new.cpp. If hc is
constant, I would allocate and initialize it only once - not in
compute() but in one of the init or settings or allocate() routines.

Also, rather than free/reallocate the 2d arrays every timestep
in compute(), I typically store a value like “maxlocal” and only
reallocate when the atoms on a processor (nlocal) exceed it.
See the logic at the top of pppm::compute() for example. That
way, once your simulation equilibrates, you aren’t doing much
memory (re)allocation.

If your modified EAM routine is of general interest, send it along
when you’re done …

Steve