SlaterDet.C 58 KB
Newer Older
Francois Gygi committed
1 2
////////////////////////////////////////////////////////////////////////////////
//
Francois Gygi committed
3 4 5 6
// Copyright (c) 2008 The Regents of the University of California
//
// This file is part of Qbox
//
Francois Gygi committed
7 8
// Qbox is distributed under the terms of the GNU General Public License
// as published by the Free Software Foundation, either version 2 of
Francois Gygi committed
9 10 11 12 13 14
// the License, or (at your option) any later version.
// See the file COPYING in the root directory of this distribution
// or <http://www.gnu.org/licenses/>.
//
////////////////////////////////////////////////////////////////////////////////
//
Francois Gygi committed
15 16 17 18 19 20 21 22
// SlaterDet.C
//
////////////////////////////////////////////////////////////////////////////////

#include "SlaterDet.h"
#include "FourierTransform.h"
#include "Context.h"
#include "blas.h" // daxpy
Francois Gygi committed
23
#include "Base64Transcoder.h"
24
#include "SharedFilePtr.h"
Francois Gygi committed
25
#include "Timer.h"
Francois Gygi committed
26 27

#include <cstdlib>
28
#include <cstring> // memcpy
Francois Gygi committed
29 30 31
#include <iostream>
#include <iomanip>
#include <sstream>
Francois Gygi committed
32
#include <limits>
Francois Gygi committed
33 34 35
using namespace std;

////////////////////////////////////////////////////////////////////////////////
36
SlaterDet::SlaterDet(const Context& ctxt, D3vector kpoint) : ctxt_(ctxt),
37
 c_(ctxt)
Francois Gygi committed
38
{
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
  // create cartesian communicator mapped on ctxt
  int ndims=2;
  // Note: MPI_Cart_comm uses row-major ordering. Need to give
  // transposed dimensions as input arguments
  int dims[2] = {ctxt.npcol(), ctxt.nprow()};
  int periods[2] = { 0, 0};
  int reorder = 0;
  MPI_Comm comm;
  MPI_Cart_create(ctxt.comm(),ndims,dims,periods,reorder,&comm);

  int size, myrank;
  MPI_Comm_size(comm,&size);
  MPI_Comm_rank(comm,&myrank);
  int coords[2];
  MPI_Cart_coords(comm,myrank,2,coords);

#ifdef DEBUG
  for ( int i = 0; i < size; i++ )
57
  {
58 59 60 61
    MPI_Barrier(comm);
    if ( myrank == i )
      cout << myrank << ": myrow=" << ctxt.myrow() << " mycol=" << ctxt.mycol()
           << " coords= " << coords[0] << ", " << coords[1] << endl;
62
  }
63 64 65 66 67 68 69 70 71 72 73 74 75
#endif

  // Split the cartesian communicator comm to define my_col_comm_
  // MPI_Cart_create uses row-major ordering. Need to keep the second
  // dimension to get a communicator corresponding to a column of ctxt
  int remain_dims[2] = { 0, 1 };
  MPI_Cart_sub(comm, remain_dims, &my_col_comm_);

  // Free the cartesian communicator
  MPI_Comm_free(&comm);

  // define basis on the column subcommunicator
  basis_ = new Basis(my_col_comm_,kpoint);
Francois Gygi committed
76
}
Francois Gygi committed
77 78 79

////////////////////////////////////////////////////////////////////////////////
SlaterDet::SlaterDet(const SlaterDet& rhs) : ctxt_(rhs.context()),
80 81 82 83
  basis_(new Basis(*(rhs.basis_))), c_(rhs.c_)
  {
    MPI_Comm_dup(rhs.my_col_comm_,&my_col_comm_);
  }
84

Francois Gygi committed
85
////////////////////////////////////////////////////////////////////////////////
86
SlaterDet::~SlaterDet()
87 88
{
  delete basis_;
Francois Gygi committed
89
  // cout << ctxt_.mype() << ": SlaterDet::dtor: ctxt=" << ctxt_;
90 91 92 93 94 95 96 97 98 99
#ifdef TIMING
  for ( TimerMap::iterator i = tmap.begin(); i != tmap.end(); i++ )
  {
    double time = (*i).second.real();
    double tmin = time;
    double tmax = time;
    ctxt_.dmin(1,1,&tmin,1);
    ctxt_.dmax(1,1,&tmax,1);
    if ( ctxt_.myproc()==0 )
    {
100 101
      string s = "name=\"" + (*i).first + "\"";
      cout << "<timing " << left << setw(22) << s
102 103
           << " min=\"" << setprecision(3) << tmin << "\""
           << " max=\"" << setprecision(3) << tmax << "\"/>"
104 105 106 107
           << endl;
    }
  }
#endif
108
  MPI_Comm_free(&my_col_comm_);
Francois Gygi committed
109 110 111
}

////////////////////////////////////////////////////////////////////////////////
112
void SlaterDet::resize(const UnitCell& cell, const UnitCell& refcell,
Francois Gygi committed
113 114
  double ecut, int nst)
{
115 116
  // Test in next line should be replaced by test on basis min/max indices
  // to signal change in basis vectors
117
  //if ( basis_->refcell().volume() != 0.0 && !refcell.encloses(cell) )
118 119
  //{
    //cout << " SlaterDet::resize: cell=" << cell;
120
    //cout << " SlaterDet::resize: refcell=" << basis_->refcell();
121
    //throw SlaterDetException("could not resize: cell not in refcell");
122
  //}
123

Francois Gygi committed
124 125
  try
  {
126
    // create a temporary copy of the basis
127 128 129
    Basis btmp(*basis_);

    // perform normal resize operations, possibly resetting contents of c_
130
    basis_->resize(cell,refcell,ecut);
Francois Gygi committed
131 132
    occ_.resize(nst);
    eig_.resize(nst);
133

134
    const int mb = basis_->maxlocalsize();
135 136
    const int m = ctxt_.nprow() * mb;
    const int nb = nst/ctxt_.npcol() + (nst%ctxt_.npcol() > 0 ? 1 : 0);
137

138 139 140 141 142 143
    // check if the dimensions of c_ must change
    if ( m!=c_.m() || nst!=c_.n() || mb!=c_.mb() || nb!=c_.nb() )
    {
      // make a copy of c_ before resize
      ComplexMatrix ctmp(c_);
      c_.resize(m,nst,mb,nb);
Francois Gygi committed
144
      init();
145

146 147 148
      // check if data can be copied from temporary copy
      // It is assumed that nst and ecut are not changing at the same time
      // Only the cases where one change at a time occurs is covered
149

150 151
      // consider only cases where the dimensions are finite
      if ( c_.m() > 0 && c_.n() > 0 )
152
      {
153 154
        // first case: only nst has changed
        if ( c_.m() == ctmp.m() && c_.n() != ctmp.n() )
155
        {
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
          //cout << "SlaterDet::resize: c_m/n=   "
          //     << c_.m() << "/" << c_.n() << endl;
          //cout << "SlaterDet::resize: ctmp_m/n=" << ctmp.m()
          //     << "/" << ctmp.n() << endl;
          // nst has changed, basis is unchanged
          // copy coefficients up to min(n_old, n_new)
          if ( c_.n() < ctmp.n() )
          {
            c_.getsub(ctmp,ctmp.m(),c_.n(),0,0);
          }
          else
          {
            c_.getsub(ctmp,ctmp.m(),ctmp.n(),0,0);
          }
          gram();
171
        }
172 173 174
        // second case: basis was resized, nst unchanged
        if ( btmp.ecut() > 0.0 && basis_->ecut() > 0.0 &&
             c_.m() != ctmp.m() && c_.n() == ctmp.n() )
175
        {
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
          // transform all states to real space and interpolate
          int np0 = max(basis_->np(0),btmp.np(0));
          int np1 = max(basis_->np(1),btmp.np(1));
          int np2 = max(basis_->np(2),btmp.np(2));
          //cout << " SlaterDet::resize: grid: np0/1/2: "
          //     << np0 << " " << np1 << " " << np2 << endl;
          // FourierTransform tf1(oldbasis, new basis grid)
          // FourierTransform tf2(newbasis, new basis grid)
          FourierTransform ft1(btmp,np0,np1,np2);
          FourierTransform ft2(*basis_,np0,np1,np2);
          // allocate real-space grid
          valarray<complex<double> > tmpr(ft1.np012loc());
          // transform each state from old basis to grid to new basis
          for ( int n = 0; n < nstloc(); n++ )
          {
            for ( int i = 0; i < tmpr.size(); i++ )
              tmpr[i] = 0.0;
            ft1.backward(ctmp.cvalptr(n*ctmp.mloc()),&tmpr[0]);
            ft2.forward(&tmpr[0], c_.valptr(n*c_.mloc()));
          }
196 197 198
        }
      }
    }
Francois Gygi committed
199 200 201 202 203 204
  }
  catch ( bad_alloc )
  {
    cout << " bad_alloc exception caught in SlaterDet::resize" << endl;
    throw;
  }
Francois Gygi committed
205
#if 0
206 207 208 209 210 211 212 213 214
  // print error in imaginary part of c(G=0)
  double imag_err = g0_imag_error();
  if ( ctxt_.onpe0() )
  {
    cout.setf(ios::scientific,ios::floatfield);
    cout << " SlaterDet::resize: imag error on exit: " << imag_err << endl;
  }
#endif
  cleanup();
Francois Gygi committed
215
}
216
////////////////////////////////////////////////////////////////////////////////
Francois Gygi committed
217
void SlaterDet::init(void)
218 219
{
  // initialize coefficients with lowest plane waves
220
  if ( c_.n() <= basis_->size() )
221 222 223 224
  {
    // initialize c_
    c_.clear();
    const double s2i = 1.0 / sqrt(2.0);
225

226 227 228 229 230 231 232 233 234
    // for each n, find the smallest g vector and initialize
    int ismallest = 0;
    // on each process, basis.isort(ismallest) is the index of the smallest
    // local g vector
    for ( int n = 0; n < c_.n(); n++ )
    {
      double value = 1.0;
      if ( basis().real() && n != 0 )
        value = s2i;
235

236
      // find process row holding the smallest g vector
237 238 239
      // kpg2: size^2 of smallest vector on this task
      // set kpg2 to largest double value if localsize == 0
      double kpg2 = numeric_limits<double>::max();
240
      if ( ismallest < basis_->localsize() )
241 242 243
      {
        kpg2 = basis_->kpg2(basis_->isort(ismallest));
      }
Francois Gygi committed
244
      // cout << "smallest vector on proc " << ctxt_.mype()
245
      //      << " has norm " << kpg2 << endl;
246
      int minrow, mincol;
247 248
      ctxt_.dmin('c',' ',1,1,&kpg2,1,&minrow,&mincol,1,-1,-1);

249 250 251 252 253
      // find column hosting state n
      int pc = c_.pc(n);
      int pr = minrow;
      if ( pr == ctxt_.myrow() )
      {
254
        int iii = basis_->isort(ismallest);
255 256 257 258 259
        ismallest++; // increment on entire process row
        if ( pc == ctxt_.mycol() )
        {
          // cout << " n=" << n << " on process "
          //      << pr << "," << pc
260 261 262
          //      << " vector " << basis_->idx(3*iii) << " "
          //      << basis_->idx(3*iii+1) << " "
          //      << basis_->idx(3*iii+2) << " norm="
Francois Gygi committed
263
          //      << basis_->g2(iii) << " "
264 265 266 267 268 269 270 271 272
          //      << value << endl;
          int jjj = c_.m(n) * c_.nb() + c_.y(n);
          int index = iii+c_.mloc()*jjj;
          c_[index] = complex<double> (value,0.0);
        }
      }
    }
  }
}
Francois Gygi committed
273 274

////////////////////////////////////////////////////////////////////////////////
275
void SlaterDet::compute_density(FourierTransform& ft,
Francois Gygi committed
276 277
  double weight, double* rho) const
{
Francois Gygi committed
278
  //Timer tm_ft, tm_rhosum;
Francois Gygi committed
279 280 281
  // compute density of the states residing on my column of ctxt_
  assert(occ_.size() == c_.n());
  vector<complex<double> > tmp(ft.np012loc());
282

283 284
  assert(basis_->cell().volume() > 0.0);
  const double omega_inv = 1.0 / basis_->cell().volume();
Francois Gygi committed
285
  const int np012loc = ft.np012loc();
286

287
  if ( basis_->real() )
Francois Gygi committed
288 289 290 291 292 293
  {
    // transform two states at a time
    for ( int n = 0; n < nstloc()-1; n++, n++ )
    {
      // global n index
      const int nn = ctxt_.mycol() * c_.nb() + n;
Francois Gygi committed
294 295
      const double fac1 = weight * omega_inv * occ_[nn];
      const double fac2 = weight * omega_inv * occ_[nn+1];
296

Francois Gygi committed
297 298
      if ( fac1 + fac2 > 0.0 )
      {
Francois Gygi committed
299
        //tm_ft.start();
Francois Gygi committed
300
        ft.backward(c_.cvalptr(n*c_.mloc()),
Francois Gygi committed
301 302
                    c_.cvalptr((n+1)*c_.mloc()),&tmp[0]);
        //tm_ft.stop();
Francois Gygi committed
303 304
        const double* psi = (double*) &tmp[0];
        int ii = 0;
Francois Gygi committed
305
        //tm_rhosum.start();
Francois Gygi committed
306 307 308 309 310 311 312
        for ( int i = 0; i < np012loc; i++ )
        {
          const double psi1 = psi[ii];
          const double psi2 = psi[ii+1];
          rho[i] += fac1 * psi1 * psi1 + fac2 * psi2 * psi2;
          ii++; ii++;
        }
Francois Gygi committed
313
        //tm_rhosum.start();
Francois Gygi committed
314 315 316 317 318 319 320
      }
    }
    if ( nstloc() % 2 != 0 )
    {
      const int n = nstloc()-1;
      // global n index
      const int nn = ctxt_.mycol() * c_.nb() + n;
Francois Gygi committed
321
      const double fac1 = weight * omega_inv * occ_[nn];
322

Francois Gygi committed
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
      if ( fac1 > 0.0 )
      {
        ft.backward(c_.cvalptr(n*c_.mloc()),&tmp[0]);
        const double* psi = (double*) &tmp[0];
        int ii = 0;
        for ( int i = 0; i < np012loc; i++ )
        {
          const double psi1 = psi[ii];
          rho[i] += fac1 * psi1 * psi1;
          ii++; ii++;
        }
      }
    }
  }
  else
  {
    // only one transform at a time
    for ( int n = 0; n < nstloc(); n++ )
    {
      // global n index
      const int nn = ctxt_.mycol() * c_.nb() + n;
Francois Gygi committed
344
      const double fac = weight * omega_inv * occ_[nn];
345

Francois Gygi committed
346 347 348 349 350 351 352 353
      if ( fac > 0.0 )
      {
        ft.backward(c_.cvalptr(n*c_.mloc()),&tmp[0]);
        for ( int i = 0; i < np012loc; i++ )
          rho[i] += fac * norm(tmp[i]);
      }
    }
  }
354
  // cout << "SlaterDet: compute_density: ft_bwd time: "
Francois Gygi committed
355
  //      << tm_ft.real() << endl;
356
  // cout << "SlaterDet: compute_density: rhosum time: "
Francois Gygi committed
357
  //      << tm_rhosum.real() << endl;
Francois Gygi committed
358 359
}

Francois Gygi committed
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
////////////////////////////////////////////////////////////////////////////////
void SlaterDet::compute_tau(FourierTransform& ft,
  double weight, double* taur) const
{
  // compute tau of the states residing on my column of ctxt_
  assert(occ_.size() == c_.n());
  vector<complex<double> > tmp(ft.np012loc());
  const int ngwloc = basis_->localsize();

  const int mloc = c_.mloc();
  assert(basis_->cell().volume() > 0.0);
  const double omega_inv = 1.0 / basis_->cell().volume();
  const int np012loc = ft.np012loc();

  if ( basis_->real() )
  {
    vector<complex<double> > taug0(ngwloc), taug1(ngwloc);
    // transform two states at a time
    for ( int n = 0; n < nstloc()-1; n++, n++ )
    {
      const int nn = ctxt_.mycol() * c_.nb() + n;
      // next line: factor 0.5 from definition of tau
      const double fac1 = 0.5 * weight * omega_inv * occ_[nn];
      const double fac2 = 0.5 * weight * omega_inv * occ_[nn+1];
      const complex<double>* p = c_.cvalptr();
      if ( fac1 + fac2 > 0.0 )
      {
        for ( int j = 0; j < 3; j++ )
        {
          const double *const gxj = basis_->gx_ptr(j);
          for ( int ig = 0; ig < ngwloc; ig++ )
          {
            // i*G_j*c(G)
            taug0[ig] = complex<double>(0.0,gxj[ig]) * p[ig+n*mloc];
            taug1[ig] = complex<double>(0.0,gxj[ig]) * p[ig+(n+1)*mloc];
          }
          ft.backward(&taug0[0],&taug1[0],&tmp[0]);
          const double* gpsi = (double*) &tmp[0];
          int ii = 0;
          for ( int i = 0; i < np012loc; i++ )
          {
            const double gpsi1 = gpsi[ii];
            const double gpsi2 = gpsi[ii+1];
            taur[i] += fac1 * gpsi1 * gpsi1 + fac2 * gpsi2 * gpsi2;
            ii++; ii++;
          }
        }
      }
    }
    if ( nstloc() % 2 != 0 )
    {
      const int n = nstloc()-1;
      // global n index
      const int nn = ctxt_.mycol() * c_.nb() + n;
      const double fac1 = 0.5 * weight * omega_inv * occ_[nn];
      const complex<double>* p = c_.cvalptr();
      if ( fac1 > 0.0 )
      {
        for ( int j = 0; j < 3; j++ )
        {
          const double *const gxj = basis_->gx_ptr(j);
          for ( int ig = 0; ig < ngwloc; ig++ )
          {
            // i*G_j*c(G)
            taug1[ig] = complex<double>(0.0,gxj[ig]) * p[ig+n*mloc];
          }
          ft.backward(&taug1[0],&tmp[0]);
          const double* gpsi = (double*) &tmp[0];
          int ii = 0;
          for ( int i = 0; i < np012loc; i++ )
          {
            const double gpsi1 = gpsi[ii];
            taur[i] += fac1 * gpsi1 * gpsi1;
            ii++; ii++;
          }
        }
      }
    }
  }
  else
  {
    vector<complex<double> > taug(ngwloc);
    for ( int n = 0; n < nstloc(); n++ )
    {
      const int nn = ctxt_.mycol() * c_.nb() + n;
      // next line: factor 0.5 from definition of tau
      const double fac1 = 0.5 * weight * omega_inv * occ_[nn];
      const complex<double>* p = c_.cvalptr();
      if ( fac1 > 0.0 )
      {
        for ( int j = 0; j < 3; j++ )
        {
          const double *const kpgxj = basis_->kpgx_ptr(j);
          for ( int ig = 0; ig < ngwloc; ig++ )
          {
            // i*(k+G)_j*c(G)
            taug[ig] = complex<double>(0.0,kpgxj[ig]) * p[ig+n*mloc];
          }
          ft.backward(&taug[0],&tmp[0]);
          for ( int i = 0; i < np012loc; i++ )
          {
            taur[i] += fac1 * norm(tmp[i]);
          }
        }
      }
    }
  }
}

Francois Gygi committed
469
////////////////////////////////////////////////////////////////////////////////
470
void SlaterDet::rs_mul_add(FourierTransform& ft,
Francois Gygi committed
471
  const double* v, SlaterDet& sdp) const
Francois Gygi committed
472 473 474 475
{
  // transform states to real space, multiply states by v[r] in real space
  // transform back to reciprocal space and add to sdp
  // sdp[n] += v * sd[n]
476

Francois Gygi committed
477 478
  vector<complex<double> > tmp(ft.np012loc());
  vector<complex<double> > ctmp(2*c_.mloc());
479

Francois Gygi committed
480 481 482 483
  const int np012loc = ft.np012loc();
  const int mloc = c_.mloc();
  double* dcp = (double*) sdp.c().valptr();

484
  if ( basis_->real() )
Francois Gygi committed
485 486 487 488 489 490
  {
    // transform two states at a time
    for ( int n = 0; n < nstloc()-1; n++, n++ )
    {
      ft.backward(c_.cvalptr(n*mloc),
                 c_.cvalptr((n+1)*mloc),&tmp[0]);
Francois Gygi committed
491 492

      #pragma omp parallel for
Francois Gygi committed
493
      for ( int i = 0; i < np012loc; i++ )
Francois Gygi committed
494 495
        tmp[i] *= v[i];

Francois Gygi committed
496 497 498 499
      ft.forward(&tmp[0], &ctmp[0], &ctmp[mloc]);
      int len = 4 * mloc;
      int inc1 = 1;
      double alpha = 1.0;
Francois Gygi committed
500
      daxpy(&len,&alpha,(double*)&ctmp[0],&inc1,&dcp[2*n*mloc],&inc1);
Francois Gygi committed
501 502 503 504 505
    }
    if ( nstloc() % 2 != 0 )
    {
      const int n = nstloc()-1;
      ft.backward(c_.cvalptr(n*mloc),&tmp[0]);
Francois Gygi committed
506 507

      #pragma omp parallel for
Francois Gygi committed
508
      for ( int i = 0; i < np012loc; i++ )
Francois Gygi committed
509 510
        tmp[i] *= v[i];

Francois Gygi committed
511 512 513 514
      ft.forward(&tmp[0], &ctmp[0]);
      int len = 2 * mloc;
      int inc1 = 1;
      double alpha = 1.0;
Francois Gygi committed
515
      daxpy(&len,&alpha,(double*)&ctmp[0],&inc1,&dcp[2*n*mloc],&inc1);
Francois Gygi committed
516 517 518 519 520 521 522 523
    }
  }
  else
  {
    // only one transform at a time
    for ( int n = 0; n < nstloc(); n++ )
    {
      ft.backward(c_.cvalptr(n*mloc),&tmp[0]);
Francois Gygi committed
524 525

      #pragma omp parallel for
Francois Gygi committed
526 527
      for ( int i = 0; i < np012loc; i++ )
        tmp[i] *= v[i];
Francois Gygi committed
528

Francois Gygi committed
529 530 531 532
      ft.forward(&tmp[0], &ctmp[0]);
      int len = 2 * mloc;
      int inc1 = 1;
      double alpha = 1.0;
Francois Gygi committed
533
      daxpy(&len,&alpha,(double*)&ctmp[0],&inc1,&dcp[2*n*mloc],&inc1);
Francois Gygi committed
534 535
    }
  }
536

Francois Gygi committed
537 538 539 540 541
}

////////////////////////////////////////////////////////////////////////////////
void SlaterDet::gram(void)
{
542
  cleanup();
543
  if ( basis_->real() )
Francois Gygi committed
544 545 546 547 548
  {
    // k = 0 case
    // create a DoubleMatrix proxy for c_
    DoubleMatrix c_proxy(c_);
    DoubleMatrix s(ctxt_,c_.n(),c_.n(),c_.nb(),c_.nb());
549 550 551
#if TIMING
    tmap["syrk"].start();
#endif
552
    s.syrk('l','t',2.0,c_proxy,0.0);
553 554 555 556
#if TIMING
    tmap["syrk"].stop();
    tmap["syr"].start();
#endif
Francois Gygi committed
557
    s.syr('l',-1.0,c_proxy,0,'r');
558 559 560 561 562
#if TIMING
    tmap["syr"].stop();
    tmap["potrf"].start();
#endif

563 564
#ifdef CHOLESKY_REMAP
    // create a square context for the Cholesky decomposition
565 566
    // int nsq = (int) sqrt((double) ctxt_.size());
    int nsq = CHOLESKY_REMAP;
567 568 569 570 571
    Context csq(nsq,nsq);
    DoubleMatrix ssq(csq,c_.n(),c_.n(),c_.nb(),c_.nb());
    ssq.getsub(s,s.m(),s.n(),0,0);
    ssq.potrf('l'); // Cholesky decomposition: S = L * L^T
    s.getsub(ssq,s.m(),s.n(),0,0);
572 573
#else
    s.potrf('l'); // Cholesky decomposition: S = L * L^T
574
#endif
Francois Gygi committed
575
    // solve triangular system X * L^T = C
576 577 578 579
#if TIMING
    tmap["potrf"].stop();
    tmap["trsm"].start();
#endif
Francois Gygi committed
580
    c_proxy.trsm('r','l','t','n',1.0,s);
581 582 583
#if TIMING
    tmap["trsm"].stop();
#endif
Francois Gygi committed
584 585 586 587 588
  }
  else
  {
    // k != 0 case
    ComplexMatrix s(ctxt_,c_.n(),c_.n(),c_.nb(),c_.nb());
589
    s.herk('l','c',1.0,c_,0.0);
590 591
    s.potrf('l'); // Cholesky decomposition: S = L * L^H
    // solve triangular system X * L^H = C
Francois Gygi committed
592 593 594 595 596
    c_.trsm('r','l','c','n',1.0,s);
  }
}

////////////////////////////////////////////////////////////////////////////////
Francois Gygi committed
597
void SlaterDet::riccati(const SlaterDet& sd)
Francois Gygi committed
598
{
599
  cleanup();
600
  if ( basis_->real() )
Francois Gygi committed
601 602 603 604 605 606
  {
    // k = 0 case
    DoubleMatrix s(ctxt_,c_.n(),c_.n(),c_.nb(),c_.nb());
    DoubleMatrix r(ctxt_,c_.n(),c_.n(),c_.nb(),c_.nb());
    s.identity();
    r.identity();
607

Francois Gygi committed
608 609 610
    DoubleMatrix x(ctxt_,c_.n(),c_.n(),c_.nb(),c_.nb());
    DoubleMatrix xm(ctxt_,c_.n(),c_.n(),c_.nb(),c_.nb());
    DoubleMatrix t(ctxt_,c_.n(),c_.n(),c_.nb(),c_.nb());
611

Francois Gygi committed
612 613 614
    // DoubleMatrix proxy for c_ and sd.c()
    DoubleMatrix c_proxy(c_);
    DoubleMatrix sdc_proxy(sd.c());
615

Francois Gygi committed
616 617 618
#if TIMING
    tmap["riccati_syrk"].start();
#endif
Francois Gygi committed
619 620 621 622
    // Factor -1.0 in next line: -0.5 from definition of s, 2.0 for G and -G
    s.syrk('l','t',-1.0,c_proxy,0.5); // s = 0.5 * ( I - A )
    // symmetric rank-1 update using first row of c_proxy
    s.syr('l',0.5,c_proxy,0,'r');
Francois Gygi committed
623 624 625 626
#if TIMING
    tmap["riccati_syrk"].stop();
    tmap["riccati_gemm"].start();
#endif
Francois Gygi committed
627 628 629 630
    // factor -2.0 in next line: G and -G
    r.gemm('t','n',-2.0,sdc_proxy,c_proxy,1.0); // r = ( I - B )
    // rank-1 update using first row of sdc_proxy() and c_proxy
    r.ger(1.0,sdc_proxy,0,c_proxy,0);
Francois Gygi committed
631 632 633
#if TIMING
    tmap["riccati_gemm"].stop();
#endif
634

Francois Gygi committed
635 636
    xm = s;
    xm.symmetrize('l');
637

Francois Gygi committed
638 639 640
#if TIMING
    tmap["riccati_while"].start();
#endif
Francois Gygi committed
641 642
    s.syrk('l','t',0.5,r,1.0); // s = s + 0.5 * r^T * r
    s.symmetrize('l');
643

Francois Gygi committed
644 645
    double diff = 1.0;
    const double epsilon = 1.e-10;
Francois Gygi committed
646
    const int maxiter = 5;
Francois Gygi committed
647
    int iter = 0;
648

Francois Gygi committed
649 650 651 652 653 654 655
    while ( iter < maxiter && diff > epsilon )
    {
      // x = s - 0.5 * ( r - xm )^T * ( r - xm )
      // Note: t and r are not symmetric, x, xm, and s are symmetric

      for ( int i = 0; i < t.size(); i++ )
        t[i] = r[i] - xm[i];
656

Francois Gygi committed
657 658
      x = s;
      x.syrk('l','t',-0.5,t,1.0);
659

Francois Gygi committed
660 661
      // get full matrix x
      x.symmetrize('l');
662

Francois Gygi committed
663 664
      for ( int i = 0; i < t.size(); i++ )
        t[i] = x[i] - xm[i];
665

Francois Gygi committed
666
      diff = t.nrm2();
667

Francois Gygi committed
668 669 670
      xm = x;
      iter++;
    }
Francois Gygi committed
671 672 673 674
#if TIMING
    tmap["riccati_while"].stop();
    tmap["riccati_symm"].start();
#endif
Francois Gygi committed
675
    c_proxy.symm('r','l',1.0,x,sdc_proxy,1.0);
Francois Gygi committed
676 677 678
#if TIMING
    tmap["riccati_symm"].stop();
#endif
Francois Gygi committed
679 680 681 682 683 684 685 686
  }
  else
  {
    // k != 0 case
    ComplexMatrix s(ctxt_,c_.n(),c_.n(),c_.nb(),c_.nb());
    ComplexMatrix r(ctxt_,c_.n(),c_.n(),c_.nb(),c_.nb());
    s.identity();
    r.identity();
687

Francois Gygi committed
688 689 690
    ComplexMatrix x(ctxt_,c_.n(),c_.n(),c_.nb(),c_.nb());
    ComplexMatrix xm(ctxt_,c_.n(),c_.n(),c_.nb(),c_.nb());
    ComplexMatrix t(ctxt_,c_.n(),c_.n(),c_.nb(),c_.nb());
691

Francois Gygi committed
692 693 694 695
    // s = 0.5 * ( I - A )
    s.herk('l','c',-0.5,c_,0.5);
    // r = ( I - B )
    r.gemm('c','n',-1.0,sd.c(),c_,1.0);
696

Francois Gygi committed
697 698
    xm = s;
    xm.symmetrize('l');
699

Francois Gygi committed
700 701 702
    // s = s + 0.5 * r^H * r
    s.herk('l','c',0.5,r,1.0);
    s.symmetrize('l');
703

Francois Gygi committed
704 705
    double diff = 1.0;
    const double epsilon = 1.e-10;
Francois Gygi committed
706
    const int maxiter = 5;
Francois Gygi committed
707
    int iter = 0;
708

Francois Gygi committed
709 710 711 712 713 714 715
    while ( iter < maxiter && diff > epsilon )
    {
      // x = s - 0.5 * ( r - xm )^H * ( r - xm )
      // Note: t and r are not hermitian, x, xm, and s are hermitian

      for ( int i = 0; i < t.size(); i++ )
        t[i] = r[i] - xm[i];
716

Francois Gygi committed
717 718 719
      x = s;
      x.herk('l','c',-0.5,t,1.0);
      x.symmetrize('l');
720

Francois Gygi committed
721 722
      for ( int i = 0; i < t.size(); i++ )
        t[i] = x[i] - xm[i];
723

Francois Gygi committed
724
      diff = t.nrm2();
725

Francois Gygi committed
726 727 728 729 730 731
      xm = x;
      iter++;
    }
    c_.hemm('r','l',1.0,x,sd.c(),1.0);
  }
}
732

733 734 735
////////////////////////////////////////////////////////////////////////////////
void SlaterDet::lowdin(void)
{
736
  cleanup();
737
  if ( basis_->real() )
738 739 740 741 742 743 744
  {
    ComplexMatrix c_tmp(c_);
    DoubleMatrix c_proxy(c_);
    DoubleMatrix c_tmp_proxy(c_tmp);
    DoubleMatrix l(ctxt_,c_.n(),c_.n(),c_.nb(),c_.nb());
    DoubleMatrix x(ctxt_,c_.n(),c_.n(),c_.nb(),c_.nb());
    DoubleMatrix t(ctxt_,c_.n(),c_.n(),c_.nb(),c_.nb());
745

746
    l.clear();
747
    l.syrk('l','t',2.0,c_proxy,0.0);
748
    l.syr('l',-1.0,c_proxy,0,'r');
749

750
    //cout << "SlaterDet::lowdin: A=\n" << l << endl;
751

752 753 754 755 756
    // Cholesky decomposition of A=Y^T Y
    l.potrf('l');
    // The lower triangle of l now contains the Cholesky factor of Y^T Y

    //cout << "SlaterDet::lowdin: L=\n" << l << endl;
757

758 759 760 761
    // Compute the polar decomposition of R = L^T

    x.transpose(1.0,l,0.0);
    // x now contains R
762

763
    const double tol = 1.e-6;
Francois Gygi committed
764
    const int maxiter = 3;
765
    x.polar(tol,maxiter);
766 767

    // x now contains the orthogonal polar factor U of the
768
    // polar decomposition R = UH
769

770
    //cout << " SlaterDet::lowdin: orthogonal polar factor=\n" << x << endl;
771

772 773 774
    // Compute L^-1
    l.trtri('l','n');
    // l now contains L^-1
775

776 777
    // Form the product L^-T U
    t.gemm('t','n',1.0,l,x,0.0);
778

779 780 781 782
    // Multiply c by L^-T U
    c_proxy.gemm('n','n',1.0,c_tmp_proxy,t,0.0);
  }
  else
783
  {
784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823
    // complex case
    ComplexMatrix c_tmp(c_);
    ComplexMatrix l(ctxt_,c_.n(),c_.n(),c_.nb(),c_.nb());
    ComplexMatrix x(ctxt_,c_.n(),c_.n(),c_.nb(),c_.nb());
    ComplexMatrix t(ctxt_,c_.n(),c_.n(),c_.nb(),c_.nb());

    l.clear();
    l.herk('l','c',1.0,c_,0.0);

    //cout << "SlaterDet::lowdin: A=\n" << l << endl;

    // Cholesky decomposition of A=Y^H Y
    l.potrf('l');
    // The lower triangle of l now contains the Cholesky factor of Y^T Y

    //cout << "SlaterDet::lowdin: L=\n" << l << endl;

    // Compute the polar decomposition of R = L^T

    x.transpose(1.0,l,0.0);
    // x now contains R

    const double tol = 1.e-6;
    const int maxiter = 3;
    x.polar(tol,maxiter);

    // x now contains the unitary polar factor U of the
    // polar decomposition R = UH

    //cout << " SlaterDet::lowdin: unitary polar factor=\n" << x << endl;

    // Compute L^-1
    l.trtri('l','n');
    // l now contains L^-1

    // Form the product L^-T U
    t.gemm('c','n',1.0,l,x,0.0);

    // Multiply c by L^-T U
    c_.gemm('n','n',1.0,c_tmp,t,0.0);
824 825 826 827 828 829 830
  }
}

////////////////////////////////////////////////////////////////////////////////
void SlaterDet::ortho_align(const SlaterDet& sd)
{
  // Orthogonalize *this and align with sd
831
  cleanup();
832
  if ( basis_->real() )
833 834 835 836 837 838 839
  {
    ComplexMatrix c_tmp(c_);
    DoubleMatrix c_proxy(c_);
    DoubleMatrix sdc_proxy(sd.c());
    DoubleMatrix c_tmp_proxy(c_tmp);
    DoubleMatrix l(ctxt_,c_.n(),c_.n(),c_.nb(),c_.nb());
    DoubleMatrix x(ctxt_,c_.n(),c_.n(),c_.nb(),c_.nb());
840

841 842 843 844
#if TIMING
    tmap["syrk"].reset();
    tmap["syrk"].start();
#endif
845
    l.clear();
846
    l.syrk('l','t',2.0,c_proxy,0.0);
847
    l.syr('l',-1.0,c_proxy,0,'r');
848 849 850
#if TIMING
    tmap["syrk"].stop();
#endif
851

852
    //cout << "SlaterDet::ortho_align: A=\n" << l << endl;
853

854
    // Cholesky decomposition of A=Y^T Y
855 856 857 858
#if TIMING
    tmap["potrf"].reset();
    tmap["potrf"].start();
#endif
859
    l.potrf('l');
860 861 862
#if TIMING
    tmap["potrf"].stop();
#endif
863 864 865
    // The lower triangle of l now contains the Cholesky factor of Y^T Y

    //cout << "SlaterDet::ortho_align: L=\n" << l << endl;
866

867 868
    // Compute the polar decomposition of L^-1 B
    // where B = C^T sd.C
869

870
    // Compute B: store result in x
871 872 873 874
#if TIMING
    tmap["gemm"].reset();
    tmap["gemm"].start();
#endif
875 876 877 878
    // factor -2.0 in next line: G and -G
    x.gemm('t','n',2.0,c_proxy,sdc_proxy,0.0);
    // rank-1 update using first row of sdc_proxy() and c_proxy
    x.ger(-1.0,c_proxy,0,sdc_proxy,0);
879 880 881
#if TIMING
    tmap["gemm"].stop();
#endif
882

883 884 885
    // Form the product L^-1 B, store result in x
    // triangular solve: L X = B
    // trtrs: solve op(*this) * X = Z, output in Z
886 887 888 889
#if TIMING
    tmap["trtrs"].reset();
    tmap["trtrs"].start();
#endif
890
    l.trtrs('l','n','n',x);
891 892 893
#if TIMING
    tmap["trtrs"].stop();
#endif
894 895
    // x now contains L^-1 B

896 897 898 899 900
    // compute the polar decomposition of X = L^-1 B
#if TIMING
    tmap["polar"].reset();
    tmap["polar"].start();
#endif
901 902 903
    const double tol = 1.e-6;
    const int maxiter = 2;
    x.polar(tol,maxiter);
904 905 906
#if TIMING
    tmap["polar"].stop();
#endif
907 908

    // x now contains the orthogonal polar factor X of the
909
    // polar decomposition L^-1 B = XH
910 911

    //cout << " SlaterDet::ortho_align: orthogonal polar factor=\n"
912
    //     << x << endl;
913

914 915
    // Form the product L^-T Q
    // Solve trans(L) Z = X
916 917 918 919
#if TIMING
    tmap["trtrs2"].reset();
    tmap["trtrs2"].start();
#endif
920
    l.trtrs('l','t','n',x);
921 922 923
#if TIMING
    tmap["trtrs2"].stop();
#endif
924

925
    // x now contains L^-T Q
926

927
    // Multiply c by L^-T Q
928 929 930 931
#if TIMING
    tmap["gemm2"].reset();
    tmap["gemm2"].start();
#endif
932
    c_proxy.gemm('n','n',1.0,c_tmp_proxy,x,0.0);
933 934 935
#if TIMING
    tmap["gemm2"].stop();
#endif
936 937
  }
  else
938
  {
939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
    // complex case
    ComplexMatrix c_tmp(c_);
    const ComplexMatrix& sdc = sd.c();
    ComplexMatrix l(ctxt_,c_.n(),c_.n(),c_.nb(),c_.nb());
    ComplexMatrix x(ctxt_,c_.n(),c_.n(),c_.nb(),c_.nb());

#if TIMING
    tmap["herk"].reset();
    tmap["herk"].start();
#endif
    l.clear();
    l.herk('l','c',1.0,c_,0.0);
#if TIMING
    tmap["herk"].stop();
#endif

    // Cholesky decomposition of A=Y^H Y
#if TIMING
    tmap["potrf"].reset();
    tmap["potrf"].start();
#endif
    l.potrf('l');
#if TIMING
    tmap["potrf"].stop();
#endif
    // The lower triangle of l now contains the Cholesky factor of Y^T Y

    //cout << "SlaterDet::ortho_align: L=\n" << l << endl;

    // Compute the polar decomposition of L^-1 B
    // where B = C^H sd.C

    // Compute B: store result in x
#if TIMING
    tmap["gemm"].reset();
    tmap["gemm"].start();
#endif
    x.gemm('c','n',1.0,c_,sdc,0.0);
#if TIMING
    tmap["gemm"].stop();
#endif

    // Form the product L^-1 B, store result in x
    // triangular solve: L X = B
    // trtrs: solve op(*this) * X = Z, output in Z
#if TIMING
    tmap["trtrs"].reset();
    tmap["trtrs"].start();
#endif
    l.trtrs('l','n','n',x);
#if TIMING
    tmap["trtrs"].stop();
#endif
    // x now contains L^-1 B

    // compute the polar decomposition of X = L^-1 B
#if TIMING
    tmap["polar"].reset();
    tmap["polar"].start();
#endif
    const double tol = 1.e-6;
    const int maxiter = 2;
    x.polar(tol,maxiter);
#if TIMING
    tmap["polar"].stop();
#endif

    // x now contains the unitary polar factor X of the
    // polar decomposition L^-1 B = XH

    //cout << " SlaterDet::ortho_align: unitary polar factor=\n"
    //     << x << endl;

    // Form the product L^-T Q
    // Solve trans(L) Z = X
#if TIMING
    tmap["trtrs2"].reset();
    tmap["trtrs2"].start();
#endif
    l.trtrs('l','c','n',x);
#if TIMING
    tmap["trtrs2"].stop();
#endif

    // x now contains L^-H Q

    // Multiply c by L^-H Q
#if TIMING
    tmap["gemm2"].reset();
    tmap["gemm2"].start();
#endif
    c_.gemm('n','n',1.0,c_tmp,x,0.0);
#if TIMING
    tmap["gemm2"].stop();
#endif

1035
  }
Francois Gygi committed
1036
#if TIMING
1037 1038 1039 1040 1041 1042 1043 1044 1045
  for ( TimerMap::iterator i = tmap.begin(); i != tmap.end(); i++ )
  {
    double time = (*i).second.real();
    double tmin = time;
    double tmax = time;
    ctxt_.dmin(1,1,&tmin,1);
    ctxt_.dmax(1,1,&tmax,1);
    if ( ctxt_.onpe0() )
    {
1046
      cout << "<timing name=\""
1047 1048 1049
           << (*i).first << "\""
           << " min=\"" << setprecision(3) << tmin << "\""
           << " max=\"" << setprecision(3) << tmax << "\"/>"
1050
           << endl;
1051 1052
    }
  }
Francois Gygi committed
1053
#endif
1054 1055 1056 1057 1058 1059
}

////////////////////////////////////////////////////////////////////////////////
void SlaterDet::align(const SlaterDet& sd)
{
  // Align *this with sd
1060
  if ( basis_->real() )
1061 1062 1063 1064 1065
  {
    ComplexMatrix c_tmp(c_);
    DoubleMatrix c_proxy(c_);
    DoubleMatrix sdc_proxy(sd.c());
    DoubleMatrix c_tmp_proxy(c_tmp);
1066

1067 1068
    DoubleMatrix x(ctxt_,c_.n(),c_.n(),c_.nb(),c_.nb());
    DoubleMatrix t(ctxt_,c_.n(),c_.n(),c_.nb(),c_.nb());
1069

1070
    // Compute the polar decomposition of B
1071
    // where B = C^H sd.C
1072

Francois Gygi committed
1073 1074 1075
#if TIMING
    tmap["align_gemm1"].start();
#endif
1076 1077 1078 1079 1080
    // Compute B: store result in x
    // factor -2.0 in next line: G and -G
    x.gemm('t','n',2.0,c_proxy,sdc_proxy,0.0);
    // rank-1 update using first row of sdc_proxy() and c_proxy
    x.ger(-1.0,c_proxy,0,sdc_proxy,0);
Francois Gygi committed
1081 1082 1083
#if TIMING
    tmap["align_gemm1"].stop();
#endif
1084

1085 1086 1087
    // x now contains B

    //cout << "SlaterDet::align: B=\n" << x << endl;
1088

1089
    // Compute the distance | c - sdc | before alignment
1090 1091
    //for ( int i = 0; i < c_proxy.size(); i++ )
    //  c_tmp_proxy[i] = c_proxy[i] - sdc_proxy[i];
Francois Gygi committed
1092 1093
    //cout << " SlaterDet::align: distance before: "
    //     << c_tmp_proxy.nrm2() << endl;
1094

1095
    // compute the polar decomposition of B
1096
    double tol = 1.e-6;
Francois Gygi committed
1097 1098
    const int maxiter = 3;
#if TIMING
1099
    tmap["align_polar"].start();
Francois Gygi committed
1100
#endif
1101
    x.polar(tol,maxiter);
Francois Gygi committed
1102 1103 1104
#if TIMING
    tmap["align_while"].stop();
#endif
1105 1106

    // x now contains the orthogonal polar factor X of the
1107
    // polar decomposition B = XH
1108

1109
    //cout << " SlaterDet::align: orthogonal polar factor=\n" << x << endl;
1110

Francois Gygi committed
1111 1112 1113
#if TIMING
    tmap["align_gemm2"].start();
#endif
1114 1115 1116
    // Multiply c by X
    c_tmp_proxy = c_proxy;
    c_proxy.gemm('n','n',1.0,c_tmp_proxy,x,0.0);
Francois Gygi committed
1117 1118 1119
#if TIMING
    tmap["align_gemm2"].stop();
#endif
1120

1121
    // Compute the distance | c - sdc | after alignment
Francois Gygi committed
1122 1123 1124 1125
    //for ( int i = 0; i < c_proxy.size(); i++ )
    //  c_tmp_proxy[i] = c_proxy[i] - sdc_proxy[i];
    //cout << " SlaterDet::align: distance after:  "
    //     << c_tmp_proxy.nrm2() << endl;
1126

1127 1128
  }
  else
1129
  {
1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189
    // complex case
    ComplexMatrix c_tmp(c_);
    const ComplexMatrix& sdc = sd.c();

    ComplexMatrix x(ctxt_,c_.n(),c_.n(),c_.nb(),c_.nb());
    ComplexMatrix t(ctxt_,c_.n(),c_.n(),c_.nb(),c_.nb());

    // Compute the polar decomposition of B
    // where B = C^H sd.C

#if TIMING
    tmap["align_gemm1"].start();
#endif
    // Compute B: store result in x
    x.gemm('c','n',1.0,c_,sdc,0.0);
#if TIMING
    tmap["align_gemm1"].stop();
#endif

    // x now contains B

    //cout << "SlaterDet::align: B=\n" << x << endl;

    // Compute the distance | c - sdc | before alignment
    //for ( int i = 0; i < c_proxy.size(); i++ )
    //  c_tmp_proxy[i] = c_proxy[i] - sdc_proxy[i];
    //cout << " SlaterDet::align: distance before: "
    //     << c_tmp_proxy.nrm2() << endl;

    // compute the polar decomposition of B
    double tol = 1.e-6;
    const int maxiter = 3;
#if TIMING
    tmap["align_polar"].start();
#endif
    x.polar(tol,maxiter);
#if TIMING
    tmap["align_while"].stop();
#endif

    // x now contains the unitary polar factor X of the
    // polar decomposition B = XH

    //cout << " SlaterDet::align: unitary polar factor=\n" << x << endl;

#if TIMING
    tmap["align_gemm2"].start();
#endif
    // Multiply c by X
    c_tmp = c_;
    c_.gemm('n','n',1.0,c_tmp,x,0.0);
#if TIMING
    tmap["align_gemm2"].stop();
#endif

    // Compute the distance | c - sdc | after alignment
    //for ( int i = 0; i < c_proxy.size(); i++ )
    //  c_tmp_proxy[i] = c_proxy[i] - sdc_proxy[i];
    //cout << " SlaterDet::align: distance after:  "
    //     << c_tmp_proxy.nrm2() << endl;
1190 1191 1192
  }
}

1193
////////////////////////////////////////////////////////////////////////////////
Francois Gygi committed
1194
complex<double> SlaterDet::dot(const SlaterDet& sd) const
1195
{
Francois Gygi committed
1196 1197
  // dot product of Slater determinants at the same kpoint: dot = tr (V^T W)
  assert(basis_->kpoint() == sd.kpoint());
1198
  if ( basis_->real() )
1199 1200 1201 1202 1203 1204
  {
    // DoubleMatrix proxy for c_ and sd.c()
    const DoubleMatrix c_proxy(c_);
    const DoubleMatrix sdc_proxy(sd.c());
    // factor 2.0: G and -G
    double d = 2.0 * c_proxy.dot(sdc_proxy);
1205

1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
    // correct double counting of first element
    double sum = 0.0;
    if ( ctxt_.myrow() == 0 )
    {
      // compute the scalar product of the first rows of c_ and sd.c_
      const double *c = c_proxy.cvalptr(0);
      const double *sdc = sdc_proxy.cvalptr(0);
      int len = c_proxy.nloc();
      // stride of scalar product is mloc
      int stride = c_proxy.mloc();
Francois Gygi committed
1216
      sum = ddot(&len,c,&stride,sdc,&stride);
1217 1218 1219 1220 1221 1222
    }
    ctxt_.dsum(1,1,&sum,1);
    return d - sum;
  }
  else
  {
Francois Gygi committed
1223
    return c_.dot(sd.c());
1224 1225 1226
  }
}

Francois Gygi committed
1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
////////////////////////////////////////////////////////////////////////////////
void SlaterDet::update_occ(int nel, int nspin)
{
  // compute occupation numbers as 0.0, 1.0 or 2.0
  // if nspin = 1: use 0, 1 or 2
  // if nspin = 2: use 0 or 1;
  assert (nel >= 0);
  assert (occ_.size() == c_.n());
  if ( nspin == 1 )
  {
    assert (nel <= 2*c_.n());
    int ndouble = nel/2;
    for ( int n = 0; n < ndouble; n++ )
      occ_[n] = 2.0;
    for ( int n = ndouble; n < ndouble+nel%2; n++ )
      occ_[n] = 1.0;
    for ( int n = ndouble+nel%2; n < c_.n(); n++ )
      occ_[n] = 0.0;
  }
  else if ( nspin == 2 )
  {
    assert (nel <= c_.n());
    for ( int n = 0; n < nel; n++ )
      occ_[n] = 1.0;
    for ( int n = nel; n < c_.n(); n++ )
      occ_[n] = 0.0;
  }
  else
  {
    // incorrect value of nspin_
    assert(false);
  }
}

////////////////////////////////////////////////////////////////////////////////
1262
double SlaterDet::total_charge(void) const
Francois Gygi committed
1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323
{
  // compute total charge from occ_[i]
  double sum = 0.0;
  for ( int n = 0; n < occ_.size(); n++ )
  {
    sum += occ_[n];
  }
  return sum;
}

////////////////////////////////////////////////////////////////////////////////
void SlaterDet::update_occ(int nspin, double mu, double temp)
{
  // compute occupation numbers using a Fermi distribution f(mu,temp)
  // and the eigenvalues in eig_[i]
  assert(nspin==1 || nspin==2);
  assert (occ_.size() == c_.n());
  assert (eig_.size() == c_.n());
  if ( nspin == 1 )
  {
    for ( int n = 0; n < eig_.size(); n++ )
    {
      occ_[n] = 2.0 * fermi(eig_[n],mu,temp);
    }
  }
  else if ( nspin == 2 )
  {
    for ( int n = 0; n < eig_.size(); n++ )
    {
      occ_[n] = fermi(eig_[n],mu,temp);
    }
  }
  else
  {
    // incorrect value of nspin_
    assert(false);
  }
}

////////////////////////////////////////////////////////////////////////////////
double SlaterDet::fermi(double e, double mu, double fermitemp)
{
  // e, mu in Hartree, fermitemp in Kelvin

  if ( fermitemp == 0.0 )
  {
    if ( e < mu ) return 1.0;
    else if ( e == mu ) return 0.5;
    else return 0.0;
  }
  const double kb = 3.1667907e-6; // Hartree/Kelvin
  const double kt = kb * fermitemp;
  double arg = ( e - mu ) / kt;

  if ( arg < -30.0 ) return 1.0;
  if ( arg >  30.0 ) return 0.0;

  return 1.0 / ( 1.0 + exp ( arg ) );
}

////////////////////////////////////////////////////////////////////////////////
1324
double SlaterDet::entropy(int nspin) const
Francois Gygi committed
1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343
{
  // return dimensionless entropy
  // the contribution to the free energy is - t_kelvin * k_boltz * wf.entropy()

  assert(nspin==1 || nspin==2);
  const double fac = ( nspin > 1 ) ? 1.0 : 2.0;
  double sum = 0.0;
  for ( int n = 0; n < occ_.size(); n++ )
  {
    const double f = occ_[n] / fac;
    if ( f > 0.0  &&  f < 1.0 )
    {
      sum -= fac * ( f * log(f) + (1.0-f) * log(1.0-f) );
    }
  }
  return sum;
}

////////////////////////////////////////////////////////////////////////////////
1344
double SlaterDet::ortho_error(void) const
Francois Gygi committed
1345 1346 1347
{
  // deviation from orthogonality of c_
  double error;
1348
  if ( basis_->real() )
Francois Gygi committed
1349 1350 1351 1352
  {
    // k = 0 case
    // declare a proxy DoubleMatrix for c_
    DoubleMatrix c_proxy(c_);
1353

Francois Gygi committed
1354
    DoubleMatrix s(ctxt_,c_.n(),c_.n(),c_.nb(),c_.nb());
1355

Francois Gygi committed
1356 1357 1358
    // real symmetric rank-k update
    // factor 2.0 in next line: G and -G
    s.syrk('l','t',2.0,c_proxy,0.0); // compute real overlap matrix
1359

Francois Gygi committed
1360 1361 1362
    // correct for double counting of G=0
    // symmetric rank-1 update using first row of c_proxy
    s.syr('l',-1.0,c_proxy,0,'r');
1363

Francois Gygi committed
1364 1365
    DoubleMatrix id(ctxt_,s.m(),s.n(),s.mb(),s.nb());
    id.identity();
1366

Francois Gygi committed
1367
    s -= id; // subtract identity matrix from S
1368

Francois Gygi committed
1369 1370 1371 1372 1373
    error = s.nrm2();
  }
  else
  {
    // k != 0 case
1374

Francois Gygi committed
1375 1376
    ComplexMatrix s(ctxt_,c_.n(),c_.n(),c_.nb(),c_.nb());
    s.herk('l','c',1.0,c_,0.0);
1377

Francois Gygi committed
1378 1379
    ComplexMatrix id(ctxt_,s.m(),s.n(),s.mb(),s.nb());
    id.identity();
1380

Francois Gygi committed
1381
    s -= id; // subtract identity matrix from S
1382

Francois Gygi committed
1383 1384 1385 1386 1387 1388 1389 1390
    error = s.nrm2();
  }
  return error;
}

////////////////////////////////////////////////////////////////////////////////
void SlaterDet::randomize(double amplitude)
{
1391 1392
  if ( basis_->size() == 0 )
    return;
1393

Francois Gygi committed
1394 1395 1396
  for ( int n = 0; n < c_.nloc(); n++ )
  {
    complex<double>* p = c_.valptr(c_.mloc()*n);
1397
    for ( int i = 0; i < basis_->localsize(); i++ )
Francois Gygi committed
1398 1399 1400 1401 1402 1403
    {
      double re = drand48();
      double im = drand48();
      p[i] += amplitude * complex<double>(re,im);
    }
  }
1404
  // gram does an initial cleanup
Francois Gygi committed
1405 1406 1407 1408 1409 1410
  gram();
}

////////////////////////////////////////////////////////////////////////////////
void SlaterDet::cleanup(void)
{
1411
  // set Im( c(G=0) ) to zero for real case and
Francois Gygi committed
1412
  // set the empty rows of the matrix c_ to zero
1413 1414 1415
  // The empty rows are located between i = basis_->localsize() and
  // c_.mloc(). Empty rows are necessary to insure that the
  // local size c_.mloc() is the same on all processes, while the
Francois Gygi committed
1416 1417 1418 1419 1420
  // local basis size is not.
  for ( int n = 0; n < c_.nloc(); n++ )
  {
    complex<double>* p = c_.valptr(c_.mloc()*n);
    // reset imaginary part of G=0 component to zero
1421
    if ( basis_->real() && c_.mloc() > 0 && ctxt_.myrow() == 0 )
Francois Gygi committed
1422 1423
    {
      // index of G=0 element
1424
      p[0] = complex<double> ( p[0].real(), 0.0);
Francois Gygi committed
1425 1426
    }
    // reset values of empty rows of c_ to zero
1427
    for ( int i = basis_->localsize(); i < c_.mloc(); i++ )
Francois Gygi committed
1428 1429 1430 1431 1432 1433 1434 1435 1436 1437
      p[i] = 0.0;
  }
}

////////////////////////////////////////////////////////////////////////////////
SlaterDet& SlaterDet::operator=(SlaterDet& rhs)
{
  if ( this == &rhs ) return *this;
  assert(ctxt_.ictxt() == rhs.context().ictxt());
  c_ = rhs.c_;
1438 1439
  occ_ = rhs.occ_;
  eig_ = rhs.eig_;
Francois Gygi committed
1440 1441 1442 1443 1444 1445
  return *this;
}

////////////////////////////////////////////////////////////////////////////////
double SlaterDet::memsize(void) const
{
1446
  return basis_->memsize() + c_.memsize();
Francois Gygi committed
1447 1448 1449 1450 1451
}

////////////////////////////////////////////////////////////////////////////////
double SlaterDet::localmemsize(void) const
{
1452
  return basis_->localmemsize() + c_.localmemsize();
Francois Gygi committed
1453 1454 1455
}

////////////////////////////////////////////////////////////////////////////////
Francois Gygi committed
1456
void SlaterDet::print(ostream& os, string encoding, double weight, int ispin,
1457
  int nspin) const
Francois Gygi committed
1458
{
1459
  FourierTransform ft(*basis_,basis_->np(0),basis_->np(1),basis_->np(2));
Francois Gygi committed
1460
  vector<complex<double> > wftmp(ft.np012loc());
Francois Gygi committed
1461
  const bool real_basis = basis_->real();
1462
  const int wftmpr_size = real_basis ? ft.np012() : 2*ft.np012();
1463
  const int wftmpr_loc_size = real_basis ? ft.np012loc() : 2*ft.np012loc();
Francois Gygi committed
1464
  vector<double> wftmpr(wftmpr_size);
Francois Gygi committed
1465
  Base64Transcoder xcdr;
1466

Francois Gygi committed
1467 1468
  if ( ctxt_.onpe0() )
  {
Francois Gygi committed
1469 1470 1471 1472 1473
    string spin = (ispin > 0) ? "down" : "up";
    os << "<slater_determinant";
    if ( nspin == 2 )
      os << " spin=\"" << spin << "\"";
    os << " kpoint=\"" << basis_->kpoint() << "\"\n"
1474
       << "  weight=\"" << setprecision(12) <<  weight << "\""
Francois Gygi committed
1475
       << " size=\"" << nst() << "\">" << endl;
1476 1477

    os << "<density_matrix form=\"diagonal\" size=\"" << nst() << "\">"
Francois Gygi committed
1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490
       << endl;
    os.setf(ios::fixed,ios::floatfield);
    os.setf(ios::right,ios::adjustfield);
    for ( int i = 0; i < nst(); i++ )
    {
      os << " " << setprecision(8) << occ_[i];
      if ( i%10 == 9 )
        os << endl;
    }
    if ( nst()%10 != 0 )
      os << endl;
    os << "</density_matrix>" << endl;
  }
1491

Francois Gygi committed
1492 1493
  for ( int n = 0; n < nst(); n++ )
  {
1494
    // Barrier to limit the number of messages sent to task 0
1495 1496
    // that don't have a receive posted
    ctxt_.barrier();
1497

1498
    // transform data on ctxt_.mycol()
Francois Gygi committed
1499 1500
    if ( c_.pc(n) == ctxt_.mycol() )
    {
1501
      //cout << " state " << n << " is stored on column "
Francois Gygi committed
1502 1503 1504
      //     << ctxt_.mycol() << " local index: " << c_.y(n) << endl;
      int nloc = c_.y(n); // local index
      ft.backward(c_.cvalptr(c_.mloc()*nloc),&wftmp[0]);
1505

Francois Gygi committed
1506 1507 1508 1509 1510 1511 1512 1513
      if ( real_basis )
      {
        double *a = (double*) &wftmp[0];
        for ( int i = 0; i < ft.np012loc(); i++ )
          wftmpr[i] = a[2