SlaterDet.C 50 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
  basis_(new Basis(*(rhs.basis_))),
81
  my_col_comm_(rhs.my_col_comm_), c_(rhs.c_){}
82

Francois Gygi committed
83
////////////////////////////////////////////////////////////////////////////////
84
SlaterDet::~SlaterDet()
85 86
{
  delete basis_;
Francois Gygi committed
87
  // cout << ctxt_.mype() << ": SlaterDet::dtor: ctxt=" << ctxt_;
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
#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 )
    {
      cout << "<timing name=\""
           << setw(15) << (*i).first << "\""
           << " min=\"" << setprecision(3) << setw(9) << tmin << "\""
           << " max=\"" << setprecision(3) << setw(9) << tmax << "\"/>"
           << endl;
    }
  }
#endif
Francois Gygi committed
106 107 108
}

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

Francois Gygi committed
121 122
  try
  {
123
    // create a temporary copy of the basis
124 125 126
    Basis btmp(*basis_);

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

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

135 136 137 138 139 140
    // 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
141
      init();
142

143 144 145
      // 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
146

147 148
      // consider only cases where the dimensions are finite
      if ( c_.m() > 0 && c_.n() > 0 )
149
      {
150 151
        // first case: only nst has changed
        if ( c_.m() == ctmp.m() && c_.n() != ctmp.n() )
152
        {
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
          //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();
168
        }
169 170 171
        // second case: basis was resized, nst unchanged
        if ( btmp.ecut() > 0.0 && basis_->ecut() > 0.0 &&
             c_.m() != ctmp.m() && c_.n() == ctmp.n() )
172
        {
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
          // 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()));
          }
193 194 195
        }
      }
    }
Francois Gygi committed
196 197 198 199 200 201
  }
  catch ( bad_alloc )
  {
    cout << " bad_alloc exception caught in SlaterDet::resize" << endl;
    throw;
  }
Francois Gygi committed
202
#if 0
203 204 205 206 207 208 209 210 211
  // 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
212
}
213
////////////////////////////////////////////////////////////////////////////////
Francois Gygi committed
214
void SlaterDet::init(void)
215 216
{
  // initialize coefficients with lowest plane waves
217
  if ( c_.n() <= basis_->size() )
218 219 220 221
  {
    // initialize c_
    c_.clear();
    const double s2i = 1.0 / sqrt(2.0);
222

223 224 225 226 227 228 229 230 231
    // 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;
232

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

246 247 248 249 250
      // find column hosting state n
      int pc = c_.pc(n);
      int pr = minrow;
      if ( pr == ctxt_.myrow() )
      {
251
        int iii = basis_->isort(ismallest);
252 253 254 255 256
        ismallest++; // increment on entire process row
        if ( pc == ctxt_.mycol() )
        {
          // cout << " n=" << n << " on process "
          //      << pr << "," << pc
257 258 259
          //      << " vector " << basis_->idx(3*iii) << " "
          //      << basis_->idx(3*iii+1) << " "
          //      << basis_->idx(3*iii+2) << " norm="
Francois Gygi committed
260
          //      << basis_->g2(iii) << " "
261 262 263 264 265 266 267 268 269
          //      << 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
270 271

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

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

284
  if ( basis_->real() )
Francois Gygi committed
285 286 287 288 289 290
  {
    // 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
291 292
      const double fac1 = weight * omega_inv * occ_[nn];
      const double fac2 = weight * omega_inv * occ_[nn+1];
293

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

Francois Gygi committed
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
      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
341
      const double fac = weight * omega_inv * occ_[nn];
342

Francois Gygi committed
343 344 345 346 347 348 349 350
      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]);
      }
    }
  }
351
  // cout << "SlaterDet: compute_density: ft_bwd time: "
Francois Gygi committed
352
  //      << tm_ft.real() << endl;
353
  // cout << "SlaterDet: compute_density: rhosum time: "
Francois Gygi committed
354
  //      << tm_rhosum.real() << endl;
Francois Gygi committed
355 356 357
}

////////////////////////////////////////////////////////////////////////////////
358
void SlaterDet::rs_mul_add(FourierTransform& ft,
Francois Gygi committed
359
  const double* v, SlaterDet& sdp) const
Francois Gygi committed
360 361 362 363
{
  // 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]
364

Francois Gygi committed
365 366
  vector<complex<double> > tmp(ft.np012loc());
  vector<complex<double> > ctmp(2*c_.mloc());
367

Francois Gygi committed
368 369 370 371
  const int np012loc = ft.np012loc();
  const int mloc = c_.mloc();
  double* dcp = (double*) sdp.c().valptr();

372
  if ( basis_->real() )
Francois Gygi committed
373 374 375 376 377 378
  {
    // 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
379 380

      #pragma omp parallel for
Francois Gygi committed
381
      for ( int i = 0; i < np012loc; i++ )
Francois Gygi committed
382 383
        tmp[i] *= v[i];

Francois Gygi committed
384 385 386 387
      ft.forward(&tmp[0], &ctmp[0], &ctmp[mloc]);
      int len = 4 * mloc;
      int inc1 = 1;
      double alpha = 1.0;
Francois Gygi committed
388
      daxpy(&len,&alpha,(double*)&ctmp[0],&inc1,&dcp[2*n*mloc],&inc1);
Francois Gygi committed
389 390 391 392 393
    }
    if ( nstloc() % 2 != 0 )
    {
      const int n = nstloc()-1;
      ft.backward(c_.cvalptr(n*mloc),&tmp[0]);
Francois Gygi committed
394 395

      #pragma omp parallel for
Francois Gygi committed
396
      for ( int i = 0; i < np012loc; i++ )
Francois Gygi committed
397 398
        tmp[i] *= v[i];

Francois Gygi committed
399 400 401 402
      ft.forward(&tmp[0], &ctmp[0]);
      int len = 2 * mloc;
      int inc1 = 1;
      double alpha = 1.0;
Francois Gygi committed
403
      daxpy(&len,&alpha,(double*)&ctmp[0],&inc1,&dcp[2*n*mloc],&inc1);
Francois Gygi committed
404 405 406 407 408 409 410 411
    }
  }
  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
412 413

      #pragma omp parallel for
Francois Gygi committed
414 415
      for ( int i = 0; i < np012loc; i++ )
        tmp[i] *= v[i];
Francois Gygi committed
416

Francois Gygi committed
417 418 419 420
      ft.forward(&tmp[0], &ctmp[0]);
      int len = 2 * mloc;
      int inc1 = 1;
      double alpha = 1.0;
Francois Gygi committed
421
      daxpy(&len,&alpha,(double*)&ctmp[0],&inc1,&dcp[2*n*mloc],&inc1);
Francois Gygi committed
422 423
    }
  }
424

Francois Gygi committed
425 426 427 428 429
}

////////////////////////////////////////////////////////////////////////////////
void SlaterDet::gram(void)
{
430
  cleanup();
431
  if ( basis_->real() )
Francois Gygi committed
432 433 434 435 436
  {
    // k = 0 case
    // create a DoubleMatrix proxy for c_
    DoubleMatrix c_proxy(c_);
    DoubleMatrix s(ctxt_,c_.n(),c_.n(),c_.nb(),c_.nb());
437 438 439
#if TIMING
    tmap["syrk"].start();
#endif
440
    s.syrk('l','t',2.0,c_proxy,0.0);
441 442 443 444
#if TIMING
    tmap["syrk"].stop();
    tmap["syr"].start();
#endif
Francois Gygi committed
445
    s.syr('l',-1.0,c_proxy,0,'r');
446 447 448 449 450
#if TIMING
    tmap["syr"].stop();
    tmap["potrf"].start();
#endif

451 452
#ifdef CHOLESKY_REMAP
    // create a square context for the Cholesky decomposition
453 454
    // int nsq = (int) sqrt((double) ctxt_.size());
    int nsq = CHOLESKY_REMAP;
455 456 457 458 459
    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);
460 461
#else
    s.potrf('l'); // Cholesky decomposition: S = L * L^T
462
#endif
Francois Gygi committed
463
    // solve triangular system X * L^T = C
464 465 466 467
#if TIMING
    tmap["potrf"].stop();
    tmap["trsm"].start();
#endif
Francois Gygi committed
468
    c_proxy.trsm('r','l','t','n',1.0,s);
469 470 471
#if TIMING
    tmap["trsm"].stop();
#endif
Francois Gygi committed
472 473 474 475 476
  }
  else
  {
    // k != 0 case
    ComplexMatrix s(ctxt_,c_.n(),c_.n(),c_.nb(),c_.nb());
477
    s.herk('l','c',1.0,c_,0.0);
478 479
    s.potrf('l'); // Cholesky decomposition: S = L * L^H
    // solve triangular system X * L^H = C
Francois Gygi committed
480 481 482 483 484
    c_.trsm('r','l','c','n',1.0,s);
  }
}

////////////////////////////////////////////////////////////////////////////////
Francois Gygi committed
485
void SlaterDet::riccati(const SlaterDet& sd)
Francois Gygi committed
486
{
487
  cleanup();
488
  if ( basis_->real() )
Francois Gygi committed
489 490 491 492 493 494
  {
    // 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();
495

Francois Gygi committed
496 497 498
    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());
499

Francois Gygi committed
500 501 502
    // DoubleMatrix proxy for c_ and sd.c()
    DoubleMatrix c_proxy(c_);
    DoubleMatrix sdc_proxy(sd.c());
503

Francois Gygi committed
504 505 506
#if TIMING
    tmap["riccati_syrk"].start();
#endif
Francois Gygi committed
507 508 509 510
    // 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
511 512 513 514
#if TIMING
    tmap["riccati_syrk"].stop();
    tmap["riccati_gemm"].start();
#endif
Francois Gygi committed
515 516 517 518
    // 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
519 520 521
#if TIMING
    tmap["riccati_gemm"].stop();
#endif
522

Francois Gygi committed
523 524
    xm = s;
    xm.symmetrize('l');
525

Francois Gygi committed
526 527 528
#if TIMING
    tmap["riccati_while"].start();
#endif
Francois Gygi committed
529 530
    s.syrk('l','t',0.5,r,1.0); // s = s + 0.5 * r^T * r
    s.symmetrize('l');
531

Francois Gygi committed
532 533
    double diff = 1.0;
    const double epsilon = 1.e-10;
Francois Gygi committed
534
    const int maxiter = 5;
Francois Gygi committed
535
    int iter = 0;
536

Francois Gygi committed
537 538 539 540 541 542 543
    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];
544

Francois Gygi committed
545 546
      x = s;
      x.syrk('l','t',-0.5,t,1.0);
547

Francois Gygi committed
548 549
      // get full matrix x
      x.symmetrize('l');
550

Francois Gygi committed
551 552
      for ( int i = 0; i < t.size(); i++ )
        t[i] = x[i] - xm[i];
553

Francois Gygi committed
554
      diff = t.nrm2();
555

Francois Gygi committed
556 557 558
      xm = x;
      iter++;
    }
Francois Gygi committed
559 560 561 562
#if TIMING
    tmap["riccati_while"].stop();
    tmap["riccati_symm"].start();
#endif
Francois Gygi committed
563
    c_proxy.symm('r','l',1.0,x,sdc_proxy,1.0);
Francois Gygi committed
564 565 566
#if TIMING
    tmap["riccati_symm"].stop();
#endif
Francois Gygi committed
567 568 569 570 571 572 573 574
  }
  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();
575

Francois Gygi committed
576 577 578
    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());
579

Francois Gygi committed
580 581 582 583
    // 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);
584

Francois Gygi committed
585 586
    xm = s;
    xm.symmetrize('l');
587

Francois Gygi committed
588 589 590
    // s = s + 0.5 * r^H * r
    s.herk('l','c',0.5,r,1.0);
    s.symmetrize('l');
591

Francois Gygi committed
592 593
    double diff = 1.0;
    const double epsilon = 1.e-10;
Francois Gygi committed
594
    const int maxiter = 5;
Francois Gygi committed
595
    int iter = 0;
596

Francois Gygi committed
597 598 599 600 601 602 603
    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];
604

Francois Gygi committed
605 606 607
      x = s;
      x.herk('l','c',-0.5,t,1.0);
      x.symmetrize('l');
608

Francois Gygi committed
609 610
      for ( int i = 0; i < t.size(); i++ )
        t[i] = x[i] - xm[i];
611

Francois Gygi committed
612
      diff = t.nrm2();
613

Francois Gygi committed
614 615 616 617 618 619
      xm = x;
      iter++;
    }
    c_.hemm('r','l',1.0,x,sd.c(),1.0);
  }
}
620

621 622 623
////////////////////////////////////////////////////////////////////////////////
void SlaterDet::lowdin(void)
{
624
  cleanup();
625
  if ( basis_->real() )
626 627 628 629 630 631 632
  {
    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());
633

634
    l.clear();
635
    l.syrk('l','t',2.0,c_proxy,0.0);
636
    l.syr('l',-1.0,c_proxy,0,'r');
637

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

640 641 642 643 644
    // 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;
645

646 647 648 649
    // Compute the polar decomposition of R = L^T

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

651
    const double tol = 1.e-6;
Francois Gygi committed
652
    const int maxiter = 3;
653
    x.polar(tol,maxiter);
654 655

    // x now contains the orthogonal polar factor U of the
656
    // polar decomposition R = UH
657

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

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

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

667 668 669 670
    // Multiply c by L^-T U
    c_proxy.gemm('n','n',1.0,c_tmp_proxy,t,0.0);
  }
  else
671
  {
672
    // complex case: not implemented
Francois Gygi committed
673 674 675 676
    if ( ctxt_.onpe0() )
      cout << " SlaterDet::lowdin: not implemented, reverting to Gram-Schmidt"
           << endl;
    gram();
677 678 679 680 681 682 683
  }
}

////////////////////////////////////////////////////////////////////////////////
void SlaterDet::ortho_align(const SlaterDet& sd)
{
  // Orthogonalize *this and align with sd
684
  cleanup();
685
  if ( basis_->real() )
686 687 688 689 690 691 692
  {
    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());
693

694 695 696 697
#if TIMING
    tmap["syrk"].reset();
    tmap["syrk"].start();
#endif
698
    l.clear();
699
    l.syrk('l','t',2.0,c_proxy,0.0);
700
    l.syr('l',-1.0,c_proxy,0,'r');
701 702 703
#if TIMING
    tmap["syrk"].stop();
#endif
704

705
    //cout << "SlaterDet::ortho_align: A=\n" << l << endl;
706

707
    // Cholesky decomposition of A=Y^T Y
708 709 710 711
#if TIMING
    tmap["potrf"].reset();
    tmap["potrf"].start();
#endif
712
    l.potrf('l');
713 714 715
#if TIMING
    tmap["potrf"].stop();
#endif
716 717 718
    // The lower triangle of l now contains the Cholesky factor of Y^T Y

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

720 721
    // Compute the polar decomposition of L^-1 B
    // where B = C^T sd.C
722

723
    // Compute B: store result in x
724 725 726 727
#if TIMING
    tmap["gemm"].reset();
    tmap["gemm"].start();
#endif
728 729 730 731
    // 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);
732 733 734
#if TIMING
    tmap["gemm"].stop();
#endif
735

736 737 738
    // Form the product L^-1 B, store result in x
    // triangular solve: L X = B
    // trtrs: solve op(*this) * X = Z, output in Z
739 740 741 742
#if TIMING
    tmap["trtrs"].reset();
    tmap["trtrs"].start();
#endif
743
    l.trtrs('l','n','n',x);
744 745 746
#if TIMING
    tmap["trtrs"].stop();
#endif
747 748
    // x now contains L^-1 B

749 750 751 752 753
    // compute the polar decomposition of X = L^-1 B
#if TIMING
    tmap["polar"].reset();
    tmap["polar"].start();
#endif
754 755 756
    const double tol = 1.e-6;
    const int maxiter = 2;
    x.polar(tol,maxiter);
757 758 759
#if TIMING
    tmap["polar"].stop();
#endif
760 761

    // x now contains the orthogonal polar factor X of the
762
    // polar decomposition L^-1 B = XH
763 764

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

767 768
    // Form the product L^-T Q
    // Solve trans(L) Z = X
769 770 771 772
#if TIMING
    tmap["trtrs2"].reset();
    tmap["trtrs2"].start();
#endif
773
    l.trtrs('l','t','n',x);
774 775 776
#if TIMING
    tmap["trtrs2"].stop();
#endif
777

778
    // x now contains L^-T Q
779

780
    // Multiply c by L^-T Q
781 782 783 784
#if TIMING
    tmap["gemm2"].reset();
    tmap["gemm2"].start();
#endif
785
    c_proxy.gemm('n','n',1.0,c_tmp_proxy,x,0.0);
786 787 788
#if TIMING
    tmap["gemm2"].stop();
#endif
789

790 791
  }
  else
792
  {
793
    // complex case: not implemented
Francois Gygi committed
794 795 796 797
    if ( ctxt_.onpe0() )
      cout << " SlaterDet::lowdin: not implemented, reverting to riccati"
           << endl;
    riccati(sd);
798
  }
Francois Gygi committed
799
#if TIMING
800 801 802 803 804 805 806 807 808
  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() )
    {
809 810 811 812 813
      cout << "<timing name=\""
           << setw(15) << (*i).first << "\""
           << " min=\"" << setprecision(3) << setw(9) << tmin << "\""
           << " max=\"" << setprecision(3) << setw(9) << tmax << "\"/>"
           << endl;
814 815
    }
  }
Francois Gygi committed
816
#endif
817 818 819 820 821 822
}

////////////////////////////////////////////////////////////////////////////////
void SlaterDet::align(const SlaterDet& sd)
{
  // Align *this with sd
823
  if ( basis_->real() )
824 825 826 827 828
  {
    ComplexMatrix c_tmp(c_);
    DoubleMatrix c_proxy(c_);
    DoubleMatrix sdc_proxy(sd.c());
    DoubleMatrix c_tmp_proxy(c_tmp);
829

830 831
    DoubleMatrix x(ctxt_,c_.n(),c_.n(),c_.nb(),c_.nb());
    DoubleMatrix t(ctxt_,c_.n(),c_.n(),c_.nb(),c_.nb());
832

833 834
    // Compute the polar decomposition of B
    // where B = C^T sd.C
835

Francois Gygi committed
836 837 838
#if TIMING
    tmap["align_gemm1"].start();
#endif
839 840 841 842 843
    // 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
844 845 846
#if TIMING
    tmap["align_gemm1"].stop();
#endif
847

848 849 850
    // x now contains B

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

852
    // Compute the distance | c - sdc | before alignment
853 854
    //for ( int i = 0; i < c_proxy.size(); i++ )
    //  c_tmp_proxy[i] = c_proxy[i] - sdc_proxy[i];
Francois Gygi committed
855 856
    //cout << " SlaterDet::align: distance before: "
    //     << c_tmp_proxy.nrm2() << endl;
857

858
    // compute the polar decomposition of B
859
    double tol = 1.e-6;
Francois Gygi committed
860 861
    const int maxiter = 3;
#if TIMING
862
    tmap["align_polar"].start();
Francois Gygi committed
863
#endif
864
    x.polar(tol,maxiter);
Francois Gygi committed
865 866 867
#if TIMING
    tmap["align_while"].stop();
#endif
868 869

    // x now contains the orthogonal polar factor X of the
870
    // polar decomposition B = XH
871

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

Francois Gygi committed
874 875 876
#if TIMING
    tmap["align_gemm2"].start();
#endif
877 878 879
    // 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
880 881 882
#if TIMING
    tmap["align_gemm2"].stop();
#endif
883

884
    // Compute the distance | c - sdc | after alignment
Francois Gygi committed
885 886 887 888
    //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;
889

890 891
  }
  else
892
  {
893
    // complex case: not implemented
Francois Gygi committed
894 895 896
    if ( ctxt_.onpe0() )
      cout << " SlaterDet::align: not implemented, alignment skipped"
           << endl;
897 898 899
  }
}

900
////////////////////////////////////////////////////////////////////////////////
Francois Gygi committed
901
complex<double> SlaterDet::dot(const SlaterDet& sd) const
902
{
Francois Gygi committed
903 904
  // dot product of Slater determinants at the same kpoint: dot = tr (V^T W)
  assert(basis_->kpoint() == sd.kpoint());
905
  if ( basis_->real() )
906 907 908 909 910 911
  {
    // 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);
912

913 914 915 916 917 918 919 920 921 922
    // 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
923
      sum = ddot(&len,c,&stride,sdc,&stride);
924 925 926 927 928 929
    }
    ctxt_.dsum(1,1,&sum,1);
    return d - sum;
  }
  else
  {
Francois Gygi committed
930
    return c_.dot(sd.c());
931 932 933
  }
}

Francois Gygi committed
934 935 936 937 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
////////////////////////////////////////////////////////////////////////////////
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);
  }
}

////////////////////////////////////////////////////////////////////////////////
969
double SlaterDet::total_charge(void) const
Francois Gygi committed
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
{
  // 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 ) );
}

////////////////////////////////////////////////////////////////////////////////
1031
double SlaterDet::entropy(int nspin) const
Francois Gygi committed
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
{
  // 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;
}

////////////////////////////////////////////////////////////////////////////////
1051
double SlaterDet::ortho_error(void) const
Francois Gygi committed
1052 1053 1054
{
  // deviation from orthogonality of c_
  double error;
1055
  if ( basis_->real() )
Francois Gygi committed
1056 1057 1058 1059
  {
    // k = 0 case
    // declare a proxy DoubleMatrix for c_
    DoubleMatrix c_proxy(c_);
1060

Francois Gygi committed
1061
    DoubleMatrix s(ctxt_,c_.n(),c_.n(),c_.nb(),c_.nb());
1062

Francois Gygi committed
1063 1064 1065
    // 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
1066

Francois Gygi committed
1067 1068 1069
    // 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');
1070

Francois Gygi committed
1071 1072
    DoubleMatrix id(ctxt_,s.m(),s.n(),s.mb(),s.nb());
    id.identity();
1073

Francois Gygi committed
1074
    s -= id; // subtract identity matrix from S
1075

Francois Gygi committed
1076 1077 1078 1079 1080
    error = s.nrm2();
  }
  else
  {
    // k != 0 case
1081

Francois Gygi committed
1082 1083
    ComplexMatrix s(ctxt_,c_.n(),c_.n(),c_.nb(),c_.nb());
    s.herk('l','c',1.0,c_,0.0);
1084

Francois Gygi committed
1085 1086
    ComplexMatrix id(ctxt_,s.m(),s.n(),s.mb(),s.nb());
    id.identity();
1087

Francois Gygi committed
1088
    s -= id; // subtract identity matrix from S
1089

Francois Gygi committed
1090 1091 1092 1093 1094 1095 1096 1097
    error = s.nrm2();
  }
  return error;
}

////////////////////////////////////////////////////////////////////////////////
void SlaterDet::randomize(double amplitude)
{
1098 1099
  if ( basis_->size() == 0 )
    return;
1100

Francois Gygi committed
1101 1102 1103
  for ( int n = 0; n < c_.nloc(); n++ )
  {
    complex<double>* p = c_.valptr(c_.mloc()*n);
1104
    for ( int i = 0; i < basis_->localsize(); i++ )
Francois Gygi committed
1105 1106 1107 1108 1109 1110
    {
      double re = drand48();
      double im = drand48();
      p[i] += amplitude * complex<double>(re,im);
    }
  }
1111
  // gram does an initial cleanup
Francois Gygi committed
1112 1113 1114 1115 1116 1117
  gram();
}

////////////////////////////////////////////////////////////////////////////////
void SlaterDet::cleanup(void)
{
1118
  // set Im( c(G=0) ) to zero for real case and
Francois Gygi committed
1119
  // set the empty rows of the matrix c_ to zero
1120 1121 1122
  // 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
1123 1124 1125 1126 1127
  // 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
1128
    if ( basis_->real() && c_.mloc() > 0 && ctxt_.myrow() == 0 )
Francois Gygi committed
1129 1130
    {
      // index of G=0 element
1131
      p[0] = complex<double> ( p[0].real(), 0.0);
Francois Gygi committed
1132 1133
    }
    // reset values of empty rows of c_ to zero
1134
    for ( int i = basis_->localsize(); i < c_.mloc(); i++ )
Francois Gygi committed
1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
      p[i] = 0.0;
  }
}

////////////////////////////////////////////////////////////////////////////////
SlaterDet& SlaterDet::operator=(SlaterDet& rhs)
{
  if ( this == &rhs ) return *this;
  assert(ctxt_.ictxt() == rhs.context().ictxt());
  c_ = rhs.c_;
1145 1146
  occ_ = rhs.occ_;
  eig_ = rhs.eig_;
Francois Gygi committed
1147 1148 1149 1150 1151 1152
  return *this;
}

////////////////////////////////////////////////////////////////////////////////
double SlaterDet::memsize(void) const
{
1153
  return basis_->memsize() + c_.memsize();
Francois Gygi committed
1154 1155 1156 1157 1158
}

////////////////////////////////////////////////////////////////////////////////
double SlaterDet::localmemsize(void) const
{
1159
  return basis_->localmemsize() + c_.localmemsize();
Francois Gygi committed
1160 1161 1162
}

////////////////////////////////////////////////////////////////////////////////
Francois Gygi committed
1163
void SlaterDet::print(ostream& os, string encoding, double weight, int ispin,
1164
  int nspin) const
Francois Gygi committed
1165
{
1166
  FourierTransform ft(*basis_,basis_->np(0),basis_->np(1),basis_->np(2));
Francois Gygi committed
1167
  vector<complex<double> > wftmp(ft.np012loc());
Francois Gygi committed
1168
  const bool real_basis = basis_->real();
1169
  const int wftmpr_size = real_basis ? ft.np012() : 2*ft.np012();
1170
  const int wftmpr_loc_size = real_basis ? ft.np012loc() : 2*ft.np012loc();
Francois Gygi committed
1171
  vector<double> wftmpr(wftmpr_size);
Francois Gygi committed
1172
  Base64Transcoder xcdr;
1173

Francois Gygi committed
1174 1175
  if ( ctxt_.onpe0() )
  {
Francois Gygi committed
1176 1177 1178 1179 1180
    string spin = (ispin > 0) ? "down" : "up";
    os << "<slater_determinant";
    if ( nspin == 2 )
      os << " spin=\"" << spin << "\"";
    os << " kpoint=\"" << basis_->kpoint() << "\"\n"
1181
       << "  weight=\"" << setprecision(12) <<  weight << "\""
Francois Gygi committed
1182
       << " size=\"" << nst() << "\">" << endl;
1183 1184

    os << "<density_matrix form=\"diagonal\" size=\"" << nst() << "\">"
Francois Gygi committed
1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197
       << 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;
  }
1198

Francois Gygi committed
1199 1200
  for ( int n = 0; n < nst(); n++ )
  {
1201
    // Barrier to limit the number of messages sent to task 0
1202 1203
    // that don't have a receive posted
    ctxt_.barrier();
1204

1205
    // transform data on ctxt_.mycol()
Francois Gygi committed
1206 1207
    if ( c_.pc(n) == ctxt_.mycol() )
    {
1208
      //cout << " state " << n << " is stored on column "
Francois Gygi committed
1209 1210 1211
      //     << ctxt_.mycol() << " local index: " << c_.y(n) << endl;
      int nloc = c_.y(n); // local index
      ft.backward(c_.cvalptr(c_.mloc()*nloc),&wftmp[0]);
1212

Francois Gygi committed
1213 1214 1215 1216 1217 1218 1219 1220
      if ( real_basis )
      {
        double *a = (double*) &wftmp[0];
        for ( int i = 0; i < ft.np012loc(); i++ )
          wftmpr[i] = a[2*i];
      }
      else
      {
1221 1222
        memcpy((void*)&wftmpr[0],(void*)&wftmp[0],
               ft.np012loc()*sizeof(complex<double>));
Francois Gygi committed
1223
      }
1224
    }
1225

1226 1227 1228 1229
    // send blocks of wftmpr to pe0
    for ( int i = 0; i < ctxt_.nprow(); i++ )
    {
      bool iamsending = c_.pc(n) == ctxt_.mycol() && i == ctxt_.myrow();
1230

1231 1232 1233
      // send size of wftmpr block
      int size=-1;
      if ( ctxt_.onpe0() )
Francois Gygi committed
1234
      {
1235
        if ( iamsending )
Francois Gygi committed
1236
        {
1237 1238 1239 1240 1241 1242 1243 1244 1245
          // sending to self, size not needed
        }
        else
          ctxt_.irecv(1,1,&size,1,i,c_.pc(n));
      }
      else
      {
        if ( iamsending )
        {
1246
          size = wftmpr_loc_size;
Francois Gygi committed
1247
          ctxt_.isend(1,1,&size,1,0,0);
1248 1249
        }
      }
1250

1251 1252 1253 1254 1255 1256 1257 1258 1259 1260
      // send wftmpr block
      if ( ctxt_.onpe0() )
      {
        if ( iamsending )
        {
          // do nothing, data is already in place
        }
        else
        {
          int istart = ft.np0() * ft.np1() * ft.np2_first(i);
Francois Gygi committed
1261 1262
          if ( !real_basis )
            istart *= 2;
1263
          ctxt_.drecv(size,1,&wftmpr[istart],size,i,c_.pc(n));
1264 1265 1266 1267 1268 1269
        }
      }
      else
      {
        if ( iamsending )
        {
1270
          ctxt_.dsend(size,1,&wftmpr[0],size,0,0);
Francois Gygi committed
1271 1272 1273
        }
      }
    }
1274

1275
    // process the data
Francois Gygi committed
1276 1277 1278
    if ( ctxt_.onpe0() )
    {
      // wftmpr is now complete on task 0
Francois Gygi committed
1279 1280 1281
      // wftmpr contains either a real of a complex array

      const string element_type = real_basis ? "double" : "complex";
Francois Gygi committed
1282 1283 1284

      if ( encoding == "base64" )
      {
Francois Gygi committed
1285
        #if PLT_BIG_ENDIAN
Francois Gygi committed
1286
        xcdr.byteswap_double(wftmpr_size,&wftmpr[0]);
Francois Gygi committed
1287
        #endif
Francois Gygi committed
1288
        int nbytes = wftmpr_size*sizeof(double);
1289 1290
        int outlen = xcdr.nchars(nbytes);
        char* b = new char[outlen];
Francois Gygi committed
1291
        assert(b!=0);
1292
        xcdr.encode(nbytes,(byte*) &wftmpr[0],b);
Francois Gygi committed
1293
        // Note: optional x0,y0,z0 attributes not used, default is zero
Francois Gygi committed
1294
        os << "<grid_function type=\"" << element_type << "\""
Francois Gygi committed
1295 1296 1297
           << " nx=\"" << ft.np0()
           << "\" ny=\"" << ft.np1() << "\" nz=\"" << ft.np2() << "\""
           << " encoding=\"base64\">" << endl;
1298
        xcdr.print(outlen,(char*) b, os);
Francois Gygi committed
1299
        os << "</grid_function>\n";
Francois Gygi committed
1300
        delete [] b;
Francois Gygi committed
1301 1302 1303 1304 1305
      }
      else
      {
        // encoding == "text" or unknown encoding
        // Note: optional x0,y0,z0 attributes not used, default is zero
Francois Gygi committed
1306
        os << "<grid_function type=\"" << element_type << "\""
Francois Gygi committed
1307 1308 1309 1310 1311 1312 1313 1314
           << " nx=\"" << ft.np0()
           << "\" ny=\"" << ft.np1() << "\" nz=\"" << ft.np2() << "\""
           << " encoding=\"text\">" << endl;
        int count = 0;
        for ( int k = 0; k < ft.np2(); k++ )
          for ( int j = 0; j < ft.np1(); j++ )
            for ( int i = 0; i < ft.np0(); i++ )
            {
Francois Gygi committed
1315 1316 1317 1318 1319
              int index = ft.index(i,j,k);
              if ( real_basis )
                os << " " << wftmpr[index];
              else
                os << " " << wftmpr[2*index] << " " << wftmpr[2*index+1];
Francois Gygi committed
1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333
              if ( count++%4 == 3)
                os << "\n";
            }
        if ( count%4 != 0 )
          os << "\n";
        os << "</grid_function>\n";
      }
    }
  }
  if ( ctxt_.onpe0() )
    os << "</slater_determinant>" << endl;
}

////////////////////////////////////////////////////////////////////////////////
Francois Gygi committed
1334
void SlaterDet::write(SharedFilePtr& sfp, string encoding, double weight,
Francois Gygi committed
1335
  int ispin, int nspin) const
Francois Gygi committed
1336
{
1337
  FourierTransform ft(*basis_,basis_->np(0),basis_->np(1),basis_->np(2));
Francois Gygi committed
1338
  vector<complex<double> > wftmp(ft.np012loc());
Francois Gygi committed
1339
  const bool real_basis = basis_->real();
1340
  const int wftmpr_loc_size = real_basis ? ft.np012loc() : 2*ft.np012loc();
1341
  vector<double> wftmpr(wftmpr_loc_size);
Francois Gygi committed
1342
  Base64Transcoder xcdr;
1343

1344