Debian Codegraph @

src/apps/polar/desktop

raw
1 /*
2 This file is part of MADNESS.
3
4 Copyright (C) 2007,2010 Oak Ridge National Laboratory
5
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19
20 For more information please contact:
21
22 Robert J. Harrison
23 Oak Ridge National Laboratory
24 One Bethel Valley Road
25 P.O. Box 2008, MS-6367
26
27 email: [email protected]
28 tel: 865-241-3937
29 fax: 865-572-0680
30 */
31
32 /// \file moldft.cc
33 /// \brief Molecular HF and DFT code
34 /// \defgroup moldft The molecular density funcitonal and Hartree-Fock code
35
36 #define WORLD_INSTANTIATE_STATIC_TEMPLATES
37 #include <mra/mra.h>
38 #include <mra/lbdeux.h>
39 #include <mra/qmprop.h>
40
41 #include <misc/misc.h>
42 #include <misc/ran.h>
43
44 #include <tensor/systolic.h>
45 #include <linalg/solvers.h>
46 #include <linalg/elem.h>
47
48 #include <ctime>
49 #include <list>
50
51 using namespace madness;
52
53
54 #include <moldft/molecule.h>
55 #include <moldft/molecularbasis.h>
56 #include <moldft/corepotential.h>
57 #include <moldft/xcfunctional.h>
58
59 #include <moldft/potentialmanager.h>
60
61
62 //#include <jacob/abinitdftsolventsolver.h>
63 //#include <examples/molecularmask.h>
64
65 template<int NDIM>
66 struct unaryexp {
67 void operator()(const Key<NDIM>& key, Tensor<double_complex>& t) const {
68 //vzExp(t.size, t.ptr(), t.ptr());
69 UNARY_OPTIMIZED_ITERATOR(double_complex, t, *_p0 = exp(*_p0););
70 }
71 template <typename Archive>
72 void serialize(Archive& ar) {}
73 };
74
75 // Returns exp(-I*t*V)
76 Function<double_complex,3> make_exp(double t, const Function<double,3>& v) {
77 v.reconstruct();
78 Function<double_complex,3> expV = double_complex(0.0,-t)*v;
79 expV.unaryop(unaryexp<3>());
80 //expV.truncate(); expV.reconstruct();
81 return expV;
82 }
83
84 extern void drot(long n, double* restrict a, double* restrict b, double s, double c, long inc);
85
86 void drot3(long n, double* restrict a, double* restrict b, double s, double c, long inc) {
87 if (inc == 1) {
88 n*=3;
89 for (long i=0; i<n; i+=3) {
90 double aa0 = a[i ]*c - b[i ]*s;
91 double bb0 = b[i ]*c + a[i ]*s;
92 double aa1 = a[i+1]*c - b[i+1]*s;
93 double bb1 = b[i+1]*c + a[i+1]*s;
94 double aa2 = a[i+2]*c - b[i+2]*s;
95 double bb2 = b[i+2]*c + a[i+2]*s;
96 a[i ] = aa0;
97 b[i ] = bb0;
98 a[i+1] = aa1;
99 b[i+1] = bb1;
100 a[i+2] = aa2;
101 b[i+2] = bb2;
102 }
103 }
104 else {
105 inc*=3;
106 n*=inc;
107 for (long i=0; i<n; i+=inc) {
108 double aa0 = a[i ]*c - b[i ]*s;
109 double bb0 = b[i ]*c + a[i ]*s;
110 double aa1 = a[i+1]*c - b[i+1]*s;
111 double bb1 = b[i+1]*c + a[i+1]*s;
112 double aa2 = a[i+2]*c - b[i+2]*s;
113 double bb2 = b[i+2]*c + a[i+2]*s;
114 a[i ] = aa0;
115 b[i ] = bb0;
116 a[i+1] = aa1;
117 b[i+1] = bb1;
118 a[i+2] = aa2;
119 b[i+2] = bb2;
120 }
121 }
122 }
123
124 // class NuclearDensityFunctor : public FunctionFunctorInterface<double,3> {
125 // Molecule molecule;
126 // std::vector<coord_3d> specialpts;
127 // public:
128 // NuclearDensityFunctor(const Molecule& molecule) : molecule(molecule) {}
129
130 // double operator()(const Vector<double,3>& r) const {
131 // return molecule.mol_nuclear_charge_density(r[0], r[1], r[2]);
132 // }
133
134 // std::vector<coord_3d> special_points() const{
135 // return molecule.get_all_coords_vec();
136 // }
137
138 // Level special_level() {
139 // return 15;
140 // }
141 // };
142
143
144 typedef std::shared_ptr< WorldDCPmapInterface< Key<3> > > pmapT;
145 typedef Vector<double,3> coordT;
146 typedef std::shared_ptr< FunctionFunctorInterface<double,3> > functorT;
147 typedef Function<double,3> functionT;
148 typedef std::vector<functionT> vecfuncT;
149 typedef std::pair<vecfuncT,vecfuncT> pairvecfuncT;
150 typedef std::vector<pairvecfuncT> subspaceT;
151 typedef Tensor<double> tensorT;
152 typedef FunctionFactory<double,3> factoryT;
153 typedef SeparatedConvolution<double,3> operatorT;
154 typedef std::shared_ptr<operatorT> poperatorT;
155 typedef Function<std::complex<double>,3> complex_functionT;
156 typedef std::vector<complex_functionT> cvecfuncT;
157 typedef Convolution1D<double_complex> complex_operatorT;
158
159 extern tensorT distributed_localize_PM(World & world,
160 const vecfuncT & mo,
161 const vecfuncT & ao,
162 const std::vector<int> & set,
163 const std::vector<int> & at_to_bf,
164 const std::vector<int> & at_nbf,
165 const double thresh = 1e-9,
166 const double thetamax = 0.5,
167 const bool randomize = true,
168 const bool doprint = false);
169
170 static double ttt, sss;
171 void START_TIMER(World& world) {
172 world.gop.fence(); ttt=wall_time(); sss=cpu_time();
173 }
174
175 void END_TIMER(World& world, const char* msg) {
176 ttt=wall_time()-ttt; sss=cpu_time()-sss; if (world.rank()==0) printf("timer: %20.20s %8.2fs %8.2fs\n", msg, sss, ttt);
177 }
178
179
180 inline double mask1(double x) {
181 /* Iterated first beta function to switch smoothly
182 from 0->1 in [0,1]. n iterations produce 2*n-1
183 zero derivatives at the end points. Order of polyn
184 is 3^n.
185
186 Currently use one iteration so that first deriv.
187 is zero at interior boundary and is exactly representable
188 by low order multiwavelet without refinement */
189
190 x = (x*x*(3.-2.*x));
191 return x;
192 }
193
194 double mask3(const coordT& ruser) {
195 coordT rsim;
196 user_to_sim(ruser, rsim);
197 double x= rsim[0], y=rsim[1], z=rsim[2];
198 double lo = 0.0625, hi = 1.0-lo, result = 1.0;
199 double rlo = 1.0/lo;
200
201 if (x<lo)
202 result *= mask1(x*rlo);
203 else if (x>hi)
204 result *= mask1((1.0-x)*rlo);
205 if (y<lo)
206 result *= mask1(y*rlo);
207 else if (y>hi)
208 result *= mask1((1.0-y)*rlo);
209 if (z<lo)
210 result *= mask1(z*rlo);
211 else if (z>hi)
212 result *= mask1((1.0-z)*rlo);
213
214 return result;
215 }
216
217 // template<int NDIM>
218 // class DensityIsosurfaceCharacteristic {
219 // const double rho0, twobeta;
220
221 // double f(double rho) const {
222 // double r = std::max(rho,1e-12)/rho0;
223 // double r2b = std::pow(r,twobeta);
224 // return r2b/(1.0+r2b);
225 // }
226
227 // public:
228 // DensityIsosurfaceCharacteristic(double rho0, double beta)
229 // : rho0(rho0), twobeta(2.0*beta)
230 // {}
231
232 // void operator()(const Key<NDIM>& key, Tensor<double>& t) const {
233 // UNARY_OPTIMIZED_ITERATOR(double, t, *_p0 = f(*_p0););
234 // }
235 // template <typename Archive>
236 // void serialize(Archive& ar) {}
237 // };
238
239 // template<int NDIM>
240 // class DensityIsosurfaceCharacteristicDerivative {
241 // const double rho0, twobeta;
242
243 // double f(double rho) const {
244 // double r = std::max(rho,1e-12)/rho0;
245 // double r2b = std::pow(r,twobeta);
246 // return twobeta*r2b/(rho0*r*(1.0+r2b)*(1.0+r2b));
247 // }
248
249 // public:
250 // DensityIsosurfaceCharacteristicDerivative(double rho0, double beta)
251 // : rho0(rho0), twobeta(2.0*beta)
252 // {}
253
254 // void operator()(const Key<NDIM>& key, Tensor<double>& t) const {
255 // UNARY_OPTIMIZED_ITERATOR(double, t, *_p0 = f(*_p0););
256 // }
257 // template <typename Archive>
258 // void serialize(Archive& ar) {}
259 // };
260
261 class MolecularGuessDensityFunctor : public FunctionFunctorInterface<double,3> {
262 private:
263 const Molecule& molecule;
264 const AtomicBasisSet& aobasis;
265 public:
266 MolecularGuessDensityFunctor(const Molecule& molecule, const AtomicBasisSet& aobasis)
267 : molecule(molecule), aobasis(aobasis) {}
268
269 double operator()(const coordT& x) const {
270 return aobasis.eval_guess_density(molecule, x[0], x[1], x[2]);
271 }
272
273 std::vector<coordT> special_points() const {return molecule.get_all_coords_vec();}
274 };
275
276
277 class AtomicBasisFunctor : public FunctionFunctorInterface<double,3> {
278 private:
279 const AtomicBasisFunction aofunc;
280
281 public:
282 AtomicBasisFunctor(const AtomicBasisFunction& aofunc)
283 : aofunc(aofunc)
284 {}
285
286 double operator()(const coordT& x) const {
287 return aofunc(x[0], x[1], x[2]);
288 }
289
290 std::vector<coordT> special_points() const {
291 return std::vector<coordT>(1,aofunc.get_coords_vec());
292 }
293 };
294
295 class MolecularDerivativeFunctor : public FunctionFunctorInterface<double,3> {
296 private:
297 const Molecule& molecule;
298 const int atom;
299 const int axis;
300
301 public:
302 MolecularDerivativeFunctor(const Molecule& molecule, int atom, int axis)
303 : molecule(molecule), atom(atom), axis(axis)
304 {}
305
306 double operator()(const coordT& x) const {
307 return molecule.nuclear_attraction_potential_derivative(atom, axis, x[0], x[1], x[2]);
308 }
309
310 std::vector<coordT> special_points() const {
311 return std::vector<coordT>(1,molecule.get_atom(atom).get_coords());
312 }
313 };
314
315 class CorePotentialDerivativeFunctor : public FunctionFunctorInterface<double,3> {
316 private:
317 const Molecule& molecule;
318 const int atom;
319 const int axis;
320 std::vector<coordT> specialpt;
321 public:
322 CorePotentialDerivativeFunctor(const Molecule& molecule, int atom, int axis)
323 : molecule(molecule), atom(atom), axis(axis) {}
324
325 double operator()(const coordT& r) const {
326 return molecule.core_potential_derivative(atom, axis, r[0], r[1], r[2]);
327 }
328 };
329
330 /// A MADNESS functor to compute either x, y, or z
331 class DipoleFunctor : public FunctionFunctorInterface<double,3> {
332 private:
333 const int axis;
334 public:
335 DipoleFunctor(int axis) : axis(axis) {}
336 double operator()(const coordT& x) const {
337 return x[axis];
338 }
339 };
340
341 double rsquared(const coordT& r) {
342 return r[0]*r[0] + r[1]*r[1] + r[2]*r[2];
343 }
344
345 /// A MADNESS functor to compute the cartesian moment x^i * y^j * z^k (i, j, k integer and >= 0)
346 class MomentFunctor : public FunctionFunctorInterface<double,3> {
347 private:
348 const int i, j, k;
349 public:
350 MomentFunctor(int i, int j, int k) : i(i), j(j), k(k) {}
351 MomentFunctor(const std::vector<int>& x) : i(x[0]), j(x[1]), k(x[2]) {}
352 double operator()(const coordT& r) const {
353 double xi=1.0, yj=1.0, zk=1.0;
354 for (int p=0; p<i; ++p) xi *= r[0];
355 for (int p=0; p<j; ++p) yj *= r[1];
356 for (int p=0; p<k; ++p) zk *= r[2];
357 return xi*yj*zk;
358 }
359 };
360
361 /// A generic functor to compute external potential for TDDFT
362 template<typename T>
363 class VextCosFunctor {
364 double _omega;
365 Function<T,3> _f;
366 public:
367 VextCosFunctor(World& world,
368 // const std::shared_ptr<FunctionFunctorInterface<T,3> >& functor,
369 const FunctionFunctorInterface<T,3>* functor,
370 double omega) : _omega(omega)
371 {
372 // _f = factoryT(world).functor(functor);
373 _f = factoryT(world).functor(functorT(new DipoleFunctor(2)));
374 }
375 Function<T,3> operator()(const double t) const {
376 return std::cos(_omega * t) * _f;
377 }
378 };
379
380
381 /// Given overlap matrix, return rotation with 3rd order error to orthonormalize the vectors
382 tensorT Q3(const tensorT& s) {
383 tensorT Q = inner(s,s);
384 Q.gaxpy(0.2,s,-2.0/3.0);
385 for (int i=0; i<s.dim(0); ++i) Q(i,i) += 1.0;
386 return Q.scale(15.0/8.0);
387 }
388
389 /// Computes matrix square root (not used any more?)
390 tensorT sqrt(const tensorT& s, double tol=1e-8) {
391 int n=s.dim(0), m=s.dim(1);
392 MADNESS_ASSERT(n==m);
393 tensorT c, e;
394 //s.gaxpy(0.5,transpose(s),0.5); // Ensure exact symmetry
395 syev(s, c, e);
396 for (int i=0; i<n; ++i) {
397 if (e(i) < -tol) {
398 MADNESS_EXCEPTION("Matrix square root: negative eigenvalue",i);
399 }
400 else if (e(i) < tol) { // Ugh ..
401 print("Matrix square root: Warning: small eigenvalue ", i, e(i));
402 e(i) = tol;
403 }
404 e(i) = 1.0/sqrt(e(i));
405 }
406 for (int j=0; j<n; ++j) {
407 for (int i=0; i<n; ++i) {
408 c(j,i) *= e(i);
409 }
410 }
411 return c;
412 }
413
414 template <typename T, int NDIM>
415 struct lbcost {
416 double leaf_value;
417 double parent_value;
418 lbcost(double leaf_value=1.0, double parent_value=0.0) : leaf_value(leaf_value), parent_value(parent_value) {}
419 double operator()(const Key<NDIM>& key, const FunctionNode<T,NDIM>& node) const {
420 if (key.level() < 1) {
421 return 100.0*(leaf_value+parent_value);
422 }
423 else if (node.is_leaf()) {
424 return leaf_value;
425 }
426 else {
427 return parent_value;
428 }
429 }
430 };
431
432
433 struct CalculationParameters {
434 // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
435 // !!! !!!
436 // !!! If you add more data don't forget to add them to serialize method !!!
437 // !!! !!!
438 // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
439
440 // First list input parameters
441 double charge; ///< Total molecular charge
442 double smear; ///< Smearing parameter
443 double dconv; ///< Density convergence
444 double L; ///< User coordinates box size
445 double maxrotn; ///< Step restriction used in autoshift algorithm
446 int nvalpha; ///< Number of alpha virtuals to compute
447 int nvbeta; ///< Number of beta virtuals to compute
448 int nopen; ///< Number of unpaired electrons = napha-nbeta
449 int maxiter; ///< Maximum number of iterations
450 int nio; ///< No. of io servers to use
451 bool spin_restricted; ///< True if spin restricted
452 int plotlo,plothi; ///< Range of MOs to print (for both spins if polarized)
453 bool plotdens; ///< If true print the density at convergence
454 bool plotcoul; ///< If true plot the total coulomb potential at convergence
455 bool localize; ///< If true solve for localized orbitals
456 bool localize_pm; ///< If true use PM for localization
457 bool restart; ///< If true restart from orbitals on disk
458 bool save; ///< If true save orbitals to disk
459 unsigned int maxsub; ///< Size of iterative subspace ... set to 0 or 1 to disable
460 int npt_plot; ///< No. of points to use in each dim for plots
461 tensorT plot_cell; ///< lo hi in each dimension for plotting (default is all space)
462 std::string aobasis; ///< AO basis used for initial guess (6-31g or sto-3g)
463 std::string core_type; ///< core potential type ("" or "mcp")
464 bool derivatives; ///< If true calculate derivatives
465 bool dipole; ///< If true calculatio dipole moment
466 bool conv_only_dens; ///< If true remove bsh_residual from convergence criteria how ugly name is...
467 // Next list inferred parameters
468 int nalpha; ///< Number of alpha spin electrons
469 int nbeta; ///< Number of beta spin electrons
470 int nmo_alpha; ///< Number of alpha spin molecular orbitals
471 int nmo_beta; ///< Number of beta spin molecular orbitals
472 double lo; ///< Smallest length scale we need to resolve
473 std::string xc_data; ///< XC input line
474 std::vector<double> protocol_data; ///< Calculation protocol
475 bool gopt; ///< geometry optimizer
476 double gtol; ///< geometry tolerance
477 bool gtest; ///< geometry tolerance
478 double gval; ///< value precision
479 double gprec; ///< gradient precision
480 int gmaxiter; ///< optimization maxiter
481 std::string algopt; ///< algorithm used for optimization
482 bool tdksprop; ///< time-dependent Kohn-Sham equation propagate
483 //bool absolvent; ///< If true calculate solvation effects
484 //double epsilon_2; ///< dielectric constant of solvent
485 //double Gamma; ///< surface tension of solvent
486 //double beta; ///switching parameter controles boundary conditions of solvent cavity
487 //double rho_0; /// threshold density--determines size of molecular cavity
488 //double sigma; ///switching parameter controles boundary conditions of solvent cavity-(SVPE)
489 bool polar; ///< If true calculate polarizability on
490 int polar_ds; ///< Static or Dynamic
491 bool response; ///< If true calculate response on
492 int response_axis; ///< The axis for calculation response function
493 double response_freq; ///< Frequency for calculation response function
494 bool nonrotate; ///< If true do not molcule orient
495 double rconv; ///< Response convergence
496
497 template <typename Archive>
498 void serialize(Archive& ar) {
499 ar & charge & smear & dconv & L & maxrotn & nvalpha & nvbeta & nopen & maxiter & nio & spin_restricted;
500 ar & plotlo & plothi & plotdens & plotcoul & localize & localize_pm & restart & save & maxsub & npt_plot & plot_cell & aobasis;
501 ar & nalpha & nbeta & nmo_alpha & nmo_beta & lo;
502 ar & core_type & derivatives & conv_only_dens & dipole;
503 ar & xc_data & protocol_data;
504 ar & gopt & gtol & gtest & gval & gprec & gmaxiter & algopt & tdksprop;
505 //ar & absolvent & epsilon_2 & Gamma & Gamma & beta & rho_0 & sigma;
506 ar & polar & polar_ds;
507 ar & response & response_axis & response_freq;
508 ar & nonrotate;
509 ar & rconv;
510 }
511
512 CalculationParameters()
513 : charge(0.0)
514 , smear(0.0)
515 , dconv(1e-4)
516 , L(0.0)
517 , maxrotn(0.25)
518 , nvalpha(0)
519 , nvbeta(0)
520 , nopen(0)
521 , maxiter(20)
522 , nio(1)
523 , spin_restricted(true)
524 , plotlo(0)
525 , plothi(-1)
526 , plotdens(false)
527 , plotcoul(false)
528 , localize(true)
529 , localize_pm(true)
530 , restart(false)
531 , save(true)
532 , maxsub(8)
533 , npt_plot(101)
534 , aobasis("6-31g")
535 , core_type("")
536 , derivatives(false)
537 , dipole(false)
538 , conv_only_dens(false)
539 , nalpha(0)
540 , nbeta(0)
541 , nmo_alpha(0)
542 , nmo_beta(0)
543 , lo(1e-10)
544 , xc_data("lda")
545 , protocol_data(madness::vector_factory(1e-4, 1e-6))
546 , gopt(false)
547 , gtol(1e-3)
548 , gtest(false)
549 , gval(1e-5)
550 , gprec(1e-4)
551 , gmaxiter(20)
552 , algopt("BFGS")
553 , tdksprop(false)
554 //, absolvent(false)
555 //, epsilon_2(78.304)
556 //, Gamma(0.0719)
557 //, beta(1.3)
558 //, rho_0(0.00048)
559 //, sigma(0.3)
560 , polar(false)
561 , polar_ds(0)
562 , response(false)
563 , response_axis(0)
564 , response_freq(0.0)
565 , nonrotate(false)
566 , rconv(1e-6)
567 {}
568
569
570 void read_file(const std::string& filename) {
571 std::ifstream f(filename.c_str());
572 position_stream(f, "dft");
573 std::string s;
574 xc_data = "lda";
575 protocol_data = madness::vector_factory(1e-4, 1e-6);
576
577 while (f >> s) {
578 if (s == "end") {
579 break;
580 }
581 else if (s == "charge") {
582 f >> charge;
583 }
584 else if (s == "smear") {
585 f >> smear;
586 }
587 else if (s == "dconv") {
588 f >> dconv;
589 }
590 else if (s == "L") {
591 f >> L;
592 }
593 else if (s == "maxrotn") {
594 f >> maxrotn;
595 }
596 else if (s == "nvalpha") {
597 f >> nvalpha;
598 }
599 else if (s == "nvbeta") {
600 f >> nvbeta;
601 }
602 else if (s == "nopen") {
603 f >> nopen;
604 }
605 else if (s == "unrestricted") {
606 spin_restricted = false;
607 }
608 else if (s == "restricted") {
609 spin_restricted = true;
610 }
611 else if (s == "maxiter") {
612 f >> maxiter;
613 }
614 else if (s == "nio") {
615 f >> nio;
616 }
617 else if (s == "xc") {
618 char buf[1024];
619 f.getline(buf,sizeof(buf));
620 xc_data = buf;
621 }
622 else if (s == "protocol") {
623 std::string buf;
624 std::getline(f,buf);
625 protocol_data = std::vector<double>();
626 double d;
627 std::stringstream s(buf);
628 while (s >> d) protocol_data.push_back(d);
629 }
630 else if (s == "plotmos") {
631 f >> plotlo >> plothi;
632 }
633 else if (s == "plotdens") {
634 plotdens = true;
635 }
636 // else if (s == "absolvent") {
637 // absolvent = true;
638 // }
639 // else if (s == "dielec") {
640 // f >> epsilon_2;
641 // }
642 // else if (s == "Gamma") {
643 // f >> Gamma;
644 // }
645 // else if (s == "beta") {
646 // f >> beta;
647 // }
648 // else if (s == "rho_0") {
649 // f >> rho_0;
650 // }
651 // else if (s == "sigma") {
652 // f >> sigma;
653 // }
654 else if (s == "plotcoul") {
655 plotcoul = true;
656 }
657 else if (s == "plotnpt") {
658 f >> npt_plot;
659 }
660 else if (s == "plotcell") {
661 plot_cell = tensorT(3L,2L);
662 f >> plot_cell(0,0) >> plot_cell(0,1) >> plot_cell(1,0) >> plot_cell(1,1) >> plot_cell(2,0) >> plot_cell(2,1);
663 }
664 else if (s == "aobasis") {
665 f >> aobasis;
666 if (aobasis!="sto-3g" && aobasis!="sto-6g" && aobasis!="6-31g") {
667 std::cout << "moldft: unrecognized aobasis (sto-3g or sto-6g or 6-31g only): " << aobasis << std::endl;
668 MADNESS_EXCEPTION("input_error", 0);
669 }
670 }
671 else if (s == "canon") {
672 localize = false;
673 }
674 else if (s == "local") {
675 localize = true;
676 }
677 else if (s == "pm") {
678 localize_pm = true;
679 }
680 else if (s == "boys") {
681 localize_pm = false;
682 }
683 else if (s == "restart") {
684 restart = true;
685 }
686 else if (s == "save") {
687 f >> save;
688 }
689 else if (s == "maxsub") {
690 f >> maxsub;
691 if (maxsub <= 0) maxsub = 1;
692 if (maxsub > 20) maxsub = 20;
693 }
694 else if (s == "core_type") {
695 f >> core_type;
696 }
697 else if (s == "derivatives") {
698 derivatives = true;
699 }
700 else if (s == "dipole") {
701 dipole = true;
702 }
703 else if (s == "convonlydens") {
704 conv_only_dens = true;
705 }
706 else if (s == "gopt") {
707 gopt = true;
708 }
709 else if (s == "gtol") {
710 f >> gtol;
711 }
712 else if (s == "gtest") {
713 gtest = true;
714 }
715 else if (s == "gval") {
716 f >> gval;
717 }
718 else if (s == "gprec") {
719 f >> gprec;
720 }
721 else if (s == "gmaxiter") {
722 f >> gmaxiter;
723 }
724 else if (s == "algopt") {
725 char buf[1024];
726 f.getline(buf,sizeof(buf));
727 algopt = buf;
728 }
729 else if (s == "tdksprop") {
730 tdksprop = true;
731 }
732 else if (s == "polar") {
733 polar = true;
734 std::string ds;
735 f >> ds;
736 if(ds == "static")
737 polar_ds = 0;
738 else if (ds == "dynamic")
739 polar_ds = 1;
740 }
741 else if (s == "response") {
742 response = true;
743 std::string axis;
744 f >> axis;
745 if(axis == "x")
746 response_axis = 0;
747 else if (axis == "y")
748 response_axis = 1;
749 else if (axis == "z")
750 response_axis = 2;
751 }
752 else if (s == "response_freq") {
753 double freq;
754 f >> freq;
755 response_freq = freq;
756 }
757 else if (s == "nonrotate") {
758 nonrotate = true;
759 }
760 else if (s == "rconv") {
761 f >> rconv;
762 }
763 else {
764 std::cout << "moldft: unrecognized input keyword " << s << std::endl;
765 MADNESS_EXCEPTION("input error",0);
766 }
767 if (nopen != 0) spin_restricted = false;
768 }
769 }
770
771 void set_molecular_info(const Molecule& molecule, const AtomicBasisSet& aobasis, unsigned int n_core) {
772 double z = molecule.total_nuclear_charge();
773 int nelec = int(z - charge - n_core*2);
774 if (fabs(nelec+charge+n_core*2-z) > 1e-6) {
775 error("non-integer number of electrons?", nelec+charge+n_core*2-z);
776 }
777 nalpha = (nelec + nopen)/2;
778 nbeta = (nelec - nopen)/2;
779 if (nalpha < 0) error("negative number of alpha electrons?", nalpha);
780 if (nbeta < 0) error("negative number of beta electrons?", nbeta);
781 if ((nalpha+nbeta) != nelec) error("nalpha+nbeta != nelec", nalpha+nbeta);
782 nmo_alpha = nalpha + nvalpha;
783 nmo_beta = nbeta + nvbeta;
784 if (nalpha != nbeta) spin_restricted = false;
785
786 // Ensure we have enough basis functions to guess the requested
787 // number of states ... a minimal basis for a closed-shell atom
788 // might not have any functions for virtuals.
789 int nbf = aobasis.nbf(molecule);
790 nmo_alpha = std::min(nbf,nmo_alpha);
791 nmo_beta = std::min(nbf,nmo_beta);
792 if (nalpha>nbf || nbeta>nbf) error("too few basis functions?", nbf);
793 nvalpha = nmo_alpha - nalpha;
794 nvbeta = nmo_beta - nbeta;
795
796 // Unless overridden by the user use a cell big enough to
797 // have exp(-sqrt(2*I)*r) decay to 1e-6 with I=1ev=0.037Eh
798 // --> need 50 a.u. either side of the molecule
799
800 if (L == 0.0) {
801 L = molecule.bounding_cube() + 50.0;
802 }
803
804 lo = molecule.smallest_length_scale();
805 }
806
807 void print(World& world) const {
808 //time_t t = time((time_t *) 0);
809 //char *tmp = ctime(&t);
810 //tmp[strlen(tmp)-1] = 0; // lose the trailing newline
811
812 //madness::print(" date of calculation ", tmp);
813 madness::print(" restart ", restart);
814 madness::print(" number of processes ", world.size());
815 madness::print(" no. of io servers ", nio);
816 madness::print(" simulation cube ", -L, L);
817 madness::print(" total charge ", charge);
818 madness::print(" smearing ", smear);
819 madness::print(" number of electrons ", nalpha, nbeta);
820 madness::print(" number of orbitals ", nmo_alpha, nmo_beta);
821 madness::print(" spin restricted ", spin_restricted);
822 madness::print(" xc functional ", xc_data);
823 #ifdef MADNESS_HAS_LIBXC
824 madness::print(" xc libraray ", "libxc");
825 #else
826 madness::print(" xc libraray ", "default (lda only)");
827 #endif
828 if (core_type != "")
829 madness::print(" core type ", core_type);
830 madness::print(" initial guess basis ", aobasis);
831 madness::print(" max krylov subspace ", maxsub);
832 madness::print(" compute protocol ", protocol_data);
833 madness::print(" density convergence ", dconv);
834 madness::print(" response convergence ", rconv);
835 madness::print(" maximum rotation ", maxrotn);
836 if (conv_only_dens)
837 madness::print(" Convergence criterion is only density delta.");
838 else
839 madness::print(" Convergence criteria are density delta & BSH residual.");
840 madness::print(" plot density ", plotdens);
841 madness::print(" plot coulomb ", plotcoul);
842 madness::print(" plot orbital ", plotlo, plothi);
843 madness::print(" plot npoints ", npt_plot);
844 if (plot_cell.size() > 0)
845 madness::print(" plot volume ", plot_cell(0,0), plot_cell(0,1),
846 plot_cell(1,0), plot_cell(1,1), plot_cell(2,0), plot_cell(2,1));
847 else
848 madness::print(" plot volume ", "default");
849
850 std::string loctype = "pm";
851 if (!localize_pm) loctype = "boys";
852 if (localize)
853 madness::print(" localized orbitals ", loctype);
854 else
855 madness::print(" canonical orbitals ");
856 if (derivatives)
857 madness::print(" calc derivatives ");
858 if (dipole)
859 madness::print(" calc dipole ");
860 // if(absolvent){
861 // madness::print(" isodensity solvation ", absolvent);
862 // madness::print(" surface tension ", Gamma);
863 // madness::print(" switching param(beta)", beta);
864 // madness::print(" dielectric constant ", epsilon_2);
865 // madness::print(" threshold density ", rho_0);
866 // }
867 }
868 //};
869 void gprint(World& world) const {
870 madness::print(" Optimizer parameters: ");
871 madness::print(" Maximum iterations (gmaxiter) ", gmaxiter);
872 madness::print(" Tolerance (gtol) ", gtol);
873 madness::print(" Gradient value (gval) ", gval);
874 madness::print(" Gradient precision (gprec) ", gprec);
875 madness::print(" Optimization algorithm (algopt) ", algopt);
876 madness::print(" Gradient numerical test (gtest) ", gtest);
877 }
878 };
879
880 struct Calculation {
881 std::shared_ptr<PotentialManager> potentialmanager;
882 Molecule molecule;
883 CalculationParameters param;
884 XCfunctional xc;
885 AtomicBasisSet aobasis;
886 functionT vacuo_rho;
887 functionT rhoT;
888 functionT rho_elec;
889 functionT rhon;
890 functionT mol_mask;
891 functionT Uabinit;
892 functionT mask;
893 vecfuncT amo, bmo;
894 vecfuncT amo_p, bmo_p;
895 vecfuncT amo_m, bmo_m;
896 std::vector<int> aset, bset;
897 std::vector<int> aset_mp, bset_mp;
898 vecfuncT ao;
899 std::vector<int> at_to_bf, at_nbf;
900 tensorT aocc, bocc;
901 tensorT aocc_mp, bocc_mp;
902 tensorT aeps, beps;
903 tensorT aeps_mp, beps_mp;
904 poperatorT coulop;
905 std::vector< std::shared_ptr<real_derivative_3d> > gradop;
906 double vtol;
907 double current_energy;
908 double esol;//etot;
909 double vacuo_energy;
910 static const int vnucextra = 12; // load balance parameter for nuclear pot.
911
912 Calculation(World & world, const char *filename)
913 {
914 if(world.rank() == 0) {
915 molecule.read_file(filename);
916 param.read_file(filename);
917 unsigned int n_core = 0;
918 if (param.core_type != "") {
919 molecule.read_core_file(param.core_type);
920 param.aobasis = molecule.guess_file();
921 n_core = molecule.n_core_orb_all();
922 }
923 // if nonrotate : not rotate the axis
924 if (param.nonrotate){
925 molecule.center();
926 }
927 else {
928 molecule.orient();
929 }
930 aobasis.read_file(param.aobasis);
931 param.set_molecular_info(molecule, aobasis, n_core);
932 }
933 world.gop.broadcast_serializable(molecule, 0);
934 world.gop.broadcast_serializable(param, 0);
935 world.gop.broadcast_serializable(aobasis, 0);
936
937 xc.initialize(param.xc_data, !param.spin_restricted);
938 //xc.plot();
939
940 FunctionDefaults<3>::set_cubic_cell(-param.L, param.L);
941 set_protocol(world, 1e-4);
942
943 potentialmanager = std::shared_ptr<PotentialManager>(new PotentialManager(molecule, param.core_type));
944 }
945
946 void set_protocol(World & world, double thresh)
947 {
948 int k;
949 // Allow for imprecise conversion of threshold
950 if(thresh >= 0.9e-2)
951 k = 4;
952 else if(thresh >= 0.9e-4)
953 k = 6;
954 else if(thresh >= 0.9e-6)
955 k = 8;
956 else if(thresh >= 0.9e-8)
957 k = 10;
958 else
959 k = 12;
960
961 FunctionDefaults<3>::set_k(k);
962 FunctionDefaults<3>::set_thresh(thresh);
963 FunctionDefaults<3>::set_refine(true);
964 FunctionDefaults<3>::set_initial_level(2);
965 FunctionDefaults<3>::set_truncate_mode(1);
966 FunctionDefaults<3>::set_autorefine(false);
967 FunctionDefaults<3>::set_apply_randomize(false);
968 FunctionDefaults<3>::set_project_randomize(false);
969 GaussianConvolution1DCache<double>::map.clear();
970 double safety = 0.1;
971 vtol = FunctionDefaults<3>::get_thresh() * safety;
972 coulop = poperatorT(CoulombOperatorPtr(world, param.lo, thresh));
973 gradop = gradient_operator<double,3>(world);
974 mask = functionT(factoryT(world).f(mask3).initial_level(4).norefine());
975 if(world.rank() == 0){
976 print("\nSolving with thresh", thresh, " k", FunctionDefaults<3>::get_k(), " dconv", std::max(thresh, param.dconv), "\n");
977 }
978 }
979
980 void save_mos(World& world) {
981 archive::ParallelOutputArchive ar(world, "restartdata", param.nio);
982 ar & param.spin_restricted;
983 ar & (unsigned int)(amo.size());
984 ar & aeps & aocc & aset;
985 for (unsigned int i=0; i<amo.size(); ++i) ar & amo[i];
986 if (!param.spin_restricted) {
987 ar & (unsigned int)(bmo.size());
988 ar & beps & bocc & bset;
989 for (unsigned int i=0; i<bmo.size(); ++i) ar & bmo[i];
990 }
991 }
992
993 void load_mos(World& world) {
994 const double trantol = vtol / std::min(30.0, double(param.nalpha));
995 const double thresh = FunctionDefaults<3>::get_thresh();
996 const int k = FunctionDefaults<3>::get_k();
997 unsigned int nmo = 0;
998 bool spinrest = false;
999 amo.clear(); bmo.clear();
1000
1001 archive::ParallelInputArchive ar(world, "restartdata");
1002
1003 /*
1004 File format:
1005
1006 bool spinrestricted --> if true only alpha orbitals are present
1007
1008 unsigned int nmo_alpha;
1009 Tensor<double> aeps;
1010 Tensor<double> aocc;
1011 vector<int> aset;
1012 for i from 0 to nalpha-1:
1013 . Function<double,3> amo[i]
1014
1015 repeat for beta if !spinrestricted
1016
1017 */
1018
1019 // LOTS OF LOGIC MISSING HERE TO CHANGE OCCUPATION NO., SET,
1020 // EPS, SWAP, ... sigh
1021
1022 ar & spinrest;
1023
1024 ar & nmo;
1025 MADNESS_ASSERT(nmo >= unsigned(param.nmo_alpha));
1026 ar & aeps & aocc & aset;
1027 amo.resize(nmo);
1028 for (unsigned int i=0; i<amo.size(); ++i) ar & amo[i];
1029 unsigned int n_core = molecule.n_core_orb_all();
1030 if (nmo > unsigned(param.nmo_alpha)) {
1031 aset = vector<int>(aset.begin()+n_core, aset.begin()+n_core+param.nmo_alpha);
1032 amo = vecfuncT(amo.begin()+n_core, amo.begin()+n_core+param.nmo_alpha);
1033 aeps = copy(aeps(Slice(n_core, n_core+param.nmo_alpha-1)));
1034 aocc = copy(aocc(Slice(n_core, n_core+param.nmo_alpha-1)));
1035 }
1036
1037 if (amo[0].k() != k) {
1038 reconstruct(world,amo);
1039 for(unsigned int i = 0;i < amo.size();++i) amo[i] = madness::project(amo[i], k, thresh, false);
1040 world.gop.fence();
1041 }
1042 normalize(world, amo);
1043 amo = transform(world, amo, Q3(matrix_inner(world, amo, amo)), trantol, true);
1044 truncate(world, amo);
1045 normalize(world, amo);
1046
1047 if (!param.spin_restricted) {
1048
1049 if (spinrest) { // Only alpha spin orbitals were on disk
1050 MADNESS_ASSERT(param.nmo_alpha >= param.nmo_beta);
1051 bmo.resize(param.nmo_beta);
1052 bset.resize(param.nmo_beta);
1053 beps = copy(aeps(Slice(0,param.nmo_beta-1)));
1054 bocc = copy(aocc(Slice(0,param.nmo_beta-1)));
1055 for (int i=0; i<param.nmo_beta; ++i) bmo[i] = copy(amo[i]);
1056 }
1057 else {
1058 ar & nmo;
1059 ar & beps & bocc & bset;
1060
1061 bmo.resize(nmo);
1062 for (unsigned int i=0; i<bmo.size(); ++i) ar & bmo[i];
1063
1064 if (nmo > unsigned(param.nmo_beta)) {
1065 bset = vector<int>(bset.begin()+n_core, bset.begin()+n_core+param.nmo_beta);
1066 bmo = vecfuncT(bmo.begin()+n_core, bmo.begin()+n_core+param.nmo_beta);
1067 beps = copy(beps(Slice(n_core, n_core+param.nmo_beta-1)));
1068 bocc = copy(bocc(Slice(n_core, n_core+param.nmo_beta-1)));
1069 }
1070
1071 if (bmo[0].k() != k) {
1072 reconstruct(world,bmo);
1073 for(unsigned int i = 0;i < bmo.size();++i) bmo[i] = madness::project(bmo[i], k, thresh, false);
1074 world.gop.fence();
1075 }
1076
1077 normalize(world, bmo);
1078 bmo = transform(world, bmo, Q3(matrix_inner(world, bmo, bmo)), trantol, true);
1079 truncate(world, bmo);
1080 normalize(world, bmo);
1081
1082 }
1083 }
1084 }
1085
1086 void do_plots(World& world) {
1087 START_TIMER(world);
1088
1089 std::vector<long> npt(3,param.npt_plot);
1090
1091 if (param.plot_cell.size() == 0)
1092 param.plot_cell = copy(FunctionDefaults<3>::get_cell());
1093
1094 if (param.plotdens || param.plotcoul) {
1095 functionT rho;
1096 rho = make_density(world, aocc, amo);
1097
1098 if (param.spin_restricted) {
1099 rho.scale(2.0);
1100 }
1101 else {
1102 functionT rhob = make_density(world, bocc, bmo);
1103 functionT rho_spin = rho - rhob;
1104 rho += rhob;
1105 plotdx(rho_spin, "spin_density.dx", param.plot_cell, npt, true);
1106
1107 }
1108 plotdx(rho, "total_density.dx", param.plot_cell, npt, true);
1109 if (param.plotcoul) {
1110 real_function_3d vnuc = potentialmanager->vnuclear();
1111 functionT vlocl = vnuc + apply(*coulop, rho);
1112 vlocl.truncate();
1113 vlocl.reconstruct();
1114 plotdx(vlocl, "coulomb.dx", param.plot_cell, npt, true);
1115 }
1116 }
1117
1118 for (int i=param.plotlo; i<=param.plothi; ++i) {
1119 char fname[256];
1120 if (i < param.nalpha) {
1121 sprintf(fname, "amo-%5.5d.dx", i);
1122 plotdx(amo[i], fname, param.plot_cell, npt, true);
1123 }
1124 if (!param.spin_restricted && i < param.nbeta) {
1125 sprintf(fname, "bmo-%5.5d.dx", i);
1126 plotdx(bmo[i], fname, param.plot_cell, npt, true);
1127 }
1128 }
1129 END_TIMER(world, "plotting");
1130 }
1131
1132 void project(World & world)
1133 {
1134 reconstruct(world, amo);
1135 for(unsigned int i = 0;i < amo.size();++i){
1136 amo[i] = madness::project(amo[i], FunctionDefaults<3>::get_k(), FunctionDefaults<3>::get_thresh(), false);
1137 }
1138 world.gop.fence();
1139 truncate(world, amo);
1140 normalize(world, amo);
1141 if(param.nbeta && !param.spin_restricted){
1142 reconstruct(world, bmo);
1143 for(unsigned int i = 0;i < bmo.size();++i){
1144 bmo[i] = madness::project(bmo[i], FunctionDefaults<3>::get_k(), FunctionDefaults<3>::get_thresh(), false);
1145 }
1146 world.gop.fence();
1147 truncate(world, bmo);
1148 normalize(world, bmo);
1149 }
1150 }
1151
1152 void make_nuclear_potential(World & world)
1153 {
1154 START_TIMER(world);
1155 potentialmanager->make_nuclear_potential(world);
1156 END_TIMER(world, "Project vnuclear");
1157 }
1158
1159 void project_ao_basis(World & world)
1160 {
1161 // Make at_to_bf, at_nbf ... map from atom to first bf on atom, and nbf/atom
1162 aobasis.atoms_to_bfn(molecule, at_to_bf, at_nbf);
1163
1164 START_TIMER(world);
1165 ao = vecfuncT(aobasis.nbf(molecule));
1166 for(int i = 0;i < aobasis.nbf(molecule);++i){
1167 functorT aofunc(new AtomicBasisFunctor(aobasis.get_atomic_basis_function(molecule, i)));
1168 ao[i] = factoryT(world).functor(aofunc).truncate_on_project().nofence().truncate_mode(1);
1169 }
1170 world.gop.fence();
1171 truncate(world, ao);
1172 normalize(world, ao);
1173 END_TIMER(world, "project ao basis");
1174 print_meminfo(world.rank(), "project ao basis");
1175 }
1176
1177 double PM_q(const tensorT & S, const double * restrict Ci, const double * restrict Cj, int lo, int nbf)
1178 {
1179 double qij = 0.0;
1180 if (nbf == 1) { // H atom in STO-3G ... often lots of these!
1181 qij = Ci[lo]*S(0,0)*Cj[lo];
1182 }
1183 else {
1184 for(int mu = 0;mu < nbf;++mu){
1185 double Smuj = 0.0;
1186 for(int nu = 0;nu < nbf;++nu){
1187 Smuj += S(mu, nu) * Cj[nu + lo];
1188 }
1189 qij += Ci[mu + lo] * Smuj;
1190 }
1191 }
1192
1193 return qij;
1194 }
1195
1196
1197 void localize_PM_ij(const int seti, const int setj,
1198 const double tol, const double thetamax,
1199 const int natom, const int nao, const int nmo,
1200 const std::vector<tensorT>& Svec,
1201 const std::vector<int>& at_to_bf, const std::vector<int>& at_nbf,
1202 long& ndone_iter, double& maxtheta,
1203 double * restrict Qi, double * restrict Qj,
1204 double * restrict Ci, double * restrict Cj,
1205 double * restrict Ui, double * restrict Uj)
1206 {
1207 if(seti == setj){
1208 // Q could be recomputed for each ij, but by saving it we reduce computation by a factor
1209 // of 2 when far from convergence, and as we approach convergence we save more since
1210 // most work is associated with computing ovij.
1211
1212 double ovij = 0.0;
1213 for(long a = 0;a < natom;++a)
1214 ovij += Qi[a] * Qj[a];
1215
1216 print("ovij", ovij);
1217 if(fabs(ovij) > tol * tol){
1218 double aij = 0.0;
1219 double bij = 0.0;
1220 for(long a = 0;a < natom;++a){
1221 double qiia = Qi[a];
1222 double qija = PM_q(Svec[a], Ci, Cj, at_to_bf[a], at_nbf[a]);
1223 double qjja = Qj[a];
1224 double d = qiia - qjja;
1225 aij += qija * qija - 0.25 * d * d;
1226 bij += qija * d;
1227 }
1228 double theta = 0.25 * acos(-aij / sqrt(aij * aij + bij * bij));
1229
1230 if(bij > 0.0)
1231 theta = -theta;
1232
1233 print("theta", theta);
1234 if(theta > thetamax)
1235 theta = thetamax;
1236 else
1237 if(theta < -thetamax)
1238 theta = -thetamax;
1239
1240 maxtheta = std::max(fabs(theta), maxtheta);
1241 if(fabs(theta) >= tol){
1242 ++ndone_iter;
1243 double c = cos(theta);
1244 double s = sin(theta);
1245 print(c,s);
1246 drot(nao, Ci, Cj, s, c, 1);
1247 drot(nmo, Ui, Uj, s, c, 1);
1248 for(long a = 0;a < natom;++a){
1249 Qi[a] = PM_q(Svec[a], Ci, Ci, at_to_bf[a], at_nbf[a]);
1250 Qj[a] = PM_q(Svec[a], Cj, Cj, at_to_bf[a], at_nbf[a]);
1251 }
1252 }
1253 }
1254 }
1255 }
1256
1257
1258
1259 void localize_PM_task_kernel(tensorT & Q, std::vector<tensorT> & Svec, tensorT & C,
1260 const bool & doprint, const std::vector<int> & set,
1261 const double thetamax, tensorT & U, const double thresh)
1262 {
1263 long nmo = C.dim(0);
1264 long nao = C.dim(1);
1265 long natom = molecule.natom();
1266
1267 for(long i = 0;i < nmo;++i){
1268 for(long a = 0;a < natom;++a){
1269 Q(i, a) = PM_q(Svec[a], &C(i,0), &C(i,0), at_to_bf[a], at_nbf[a]);
1270 }
1271 }
1272
1273 print("Q\n", Q);
1274
1275 double tol = 0.1;
1276 long ndone = 0;
1277 for(long iter = 0;iter < 100;++iter){
1278
1279 // Diagnostics at beginning of iteration
1280 double sum = 0.0;
1281 for(long i = 0;i < nmo;++i){
1282 for(long a = 0;a < natom;++a){
1283 double qiia = Q(i, a);
1284 sum += qiia * qiia;
1285 }
1286 }
1287 if(doprint)
1288 printf("iteration %ld sum=%.4f ndone=%ld tol=%.2e\n", iter, sum, ndone, tol);
1289 // End diagnostics at beginning of iteration
1290
1291 // Initialize variables for convergence test
1292 long ndone_iter = 0;
1293 double maxtheta = 0.0;
1294 for(long i = 0;i < nmo;++i){
1295 for(long j = 0;j < i;++j){
1296
1297 localize_PM_ij(set[i], set[j],
1298 tol, thetamax,
1299 natom, nao, nmo,
1300 Svec,
1301 at_to_bf, at_nbf,
1302 ndone_iter, maxtheta,
1303 &Q(i,0), &Q(j,0),
1304 &C(i,0), &C(j,0),
1305 &U(i,0), &U(j,0));
1306
1307 }
1308 }
1309
1310 ndone += ndone_iter;
1311 if(ndone_iter == 0 && tol == thresh){
1312 if(doprint)
1313 print("PM localization converged in", ndone,"steps");
1314
1315 break;
1316 }
1317 tol = std::max(0.1 * std::min(maxtheta, tol), thresh);
1318 }
1319 }
1320
1321 tensorT localize_PM(World & world, const vecfuncT & mo, const std::vector<int> & set, const double thresh = 1e-9, const double thetamax = 0.5, const bool randomize = true, const bool doprint = false)
1322 {
1323 START_TIMER(world);
1324 tensorT UT = distributed_localize_PM(world, mo, ao, set, at_to_bf, at_nbf, thresh, thetamax, randomize, doprint);
1325 END_TIMER(world, "Pipek-Mezy distributed ");
1326 //print(UT);
1327
1328 return UT;
1329
1330
1331 START_TIMER(world);
1332 long nmo = mo.size();
1333 long natom = molecule.natom();
1334
1335 tensorT S = matrix_inner(world, ao, ao, true);
1336 std::vector<tensorT> Svec(natom);
1337 for(long a = 0;a < natom;++a){
1338 Slice as(at_to_bf[a], at_to_bf[a] + at_nbf[a] - 1);
1339 Svec[a] = copy(S(as, as));
1340 }
1341 S = tensorT();
1342 tensorT C = matrix_inner(world, mo, ao);
1343 tensorT U(nmo, nmo);
1344 tensorT Q(nmo, natom);
1345 if(world.rank() == 0){
1346 for(long i = 0;i < nmo;++i)
1347 U(i, i) = 1.0;
1348
1349 localize_PM_task_kernel(Q, Svec, C, doprint, set, thetamax, U, thresh);
1350 U = transpose(U);
1351
1352 // Fix orbital orders
1353 bool switched = true;
1354 while (switched) {
1355 switched = false;
1356 for (int i=0; i<nmo; i++) {
1357 for (int j=i+1; j<nmo; j++) {
1358 if (set[i] == set[j]) {
1359 double sold = U(i,i)*U(i,i) + U(j,j)*U(j,j);
1360 double snew = U(i,j)*U(i,j) + U(j,i)*U(j,i);
1361 if (snew > sold) {
1362 tensorT tmp = copy(U(_,i));
1363 U(_,i) = U(_,j);
1364 U(_,j) = tmp;
1365 switched = true;
1366 }
1367 }
1368 }
1369 }
1370 }
1371
1372 // Fix phases.
1373 for (long i=0; i<nmo; ++i) {
1374 if (U(i,i) < 0.0) U(_,i).scale(-1.0);
1375 }
1376 }
1377 world.gop.broadcast(U.ptr(), U.size(), 0);
1378 END_TIMER(world, "Pipek-Mezy localize");
1379 print_meminfo(world.rank(), "Pipek-Mezy localize");
1380 return U;
1381 }
1382
1383 void analyze_vectors(World & world, const vecfuncT & mo, const tensorT & occ = tensorT(), const tensorT & energy = tensorT(), const std::vector<int> & set = std::vector<int>())
1384 {
1385 tensorT Saomo = matrix_inner(world, ao, mo);
1386 tensorT Saoao = matrix_inner(world, ao, ao, true);
1387 int nmo = mo.size();
1388 tensorT rsq, dip(3, nmo);
1389 {
1390 functionT frsq = factoryT(world).f(rsquared).initial_level(4);
1391 rsq = inner(world, mo, mul_sparse(world, frsq, mo, vtol));
1392 for(int axis = 0;axis < 3;++axis){
1393 functionT fdip = factoryT(world).functor(functorT(new DipoleFunctor(axis))).initial_level(4);
1394 dip(axis, _) = inner(world, mo, mul_sparse(world, fdip, mo, vtol));
1395 for(int i = 0;i < nmo;++i)
1396 rsq(i) -= dip(axis, i) * dip(axis, i);
1397
1398 }
1399 }
1400 tensorT C;
1401
1402 START_TIMER(world);
1403 gesvp(world, Saoao, Saomo, C);
1404 END_TIMER(world, " compute eigen gesv analize vectors");
1405 if(world.rank() == 0){
1406 C = transpose(C);
1407 long nmo = mo.size();
1408 for(long i = 0;i < nmo;++i){
1409 printf(" MO%4ld : ", i);
1410 if(set.size())
1411 printf("set=%d : ", set[i]);
1412
1413 if(occ.size())
1414 printf("occ=%.2f : ", occ(i));
1415
1416 if(energy.size())
1417 printf("energy=%13.8f : ", energy(i));
1418
1419 printf("center=(%.2f,%.2f,%.2f) : radius=%.2f\n", dip(0, i), dip(1, i), dip(2, i), sqrt(rsq(i)));
1420 aobasis.print_anal(molecule, C(i, _));
1421 }
1422 }
1423
1424 }
1425
1426 inline double DIP(const tensorT & dip, int i, int j, int k, int l)
1427 {
1428 return dip(i, j, 0) * dip(k, l, 0) + dip(i, j, 1) * dip(k, l, 1) + dip(i, j, 2) * dip(k, l, 2);
1429 }
1430
1431 tensorT localize_boys(World & world, const vecfuncT & mo, const std::vector<int> & set, const double thresh = 1e-9, const double thetamax = 0.5, const bool randomize = true)
1432 {
1433 START_TIMER(world);
1434 const bool doprint = false;
1435 long nmo = mo.size();
1436 tensorT dip(nmo, nmo, 3);
1437 for(int axis = 0;axis < 3;++axis){
1438 functionT fdip = factoryT(world).functor(functorT(new DipoleFunctor(axis))).initial_level(4);
1439 dip(_, _, axis) = matrix_inner(world, mo, mul_sparse(world, fdip, mo, vtol), true);
1440 }
1441 tensorT U(nmo, nmo);
1442 if(world.rank() == 0){
1443 for(long i = 0;i < nmo;++i)
1444 U(i, i) = 1.0;
1445
1446 double tol = thetamax;
1447 long ndone = 0;
1448 bool converged = false;
1449 for(long iter = 0;iter < 300;++iter){
1450 double sum = 0.0;
1451 for(long i = 0;i < nmo;++i){
1452 sum += DIP(dip, i, i, i, i);
1453 }
1454 long ndone_iter = 0;
1455 double maxtheta = 0.0;
1456 if(doprint)
1457 printf("iteration %ld sum=%.4f ndone=%ld tol=%.2e\n", iter, sum, ndone, tol);
1458
1459 for(long i = 0;i < nmo;++i){
1460 for(long j = 0;j < i;++j){
1461 if (set[i] == set[j]) {
1462 double g = DIP(dip, i, j, j, j) - DIP(dip, i, j, i, i);
1463 double h = 4.0 * DIP(dip, i, j, i, j) + 2.0 * DIP(dip, i, i, j, j) - DIP(dip, i, i, i, i) - DIP(dip, j, j, j, j);
1464 double sij = DIP(dip, i, j, i, j);
1465 bool doit = false;
1466 if(h >= 0.0){
1467 doit = true;
1468 if(doprint)
1469 print(" forcing negative h", i, j, h);
1470
1471 h = -1.0;
1472 }
1473 double theta = -g / h;
1474 maxtheta = std::max<double>(std::abs(theta), maxtheta);
1475 if(fabs(theta) > thetamax){
1476 doit = true;
1477 if(doprint)
1478 print(" restricting", i, j);
1479
1480 if(g < 0)
1481 theta = -thetamax;
1482
1483 else
1484 theta = thetamax * 0.8;
1485
1486 }
1487 bool randomized = false;
1488 if(randomize && iter == 0 && sij > 0.01 && fabs(theta) < 0.01){
1489 randomized = true;
1490 if(doprint)
1491 print(" randomizing", i, j);
1492
1493 theta += (RandomValue<double>() - 0.5);
1494 }
1495 if(fabs(theta) >= tol || randomized || doit){
1496 ++ndone_iter;
1497 if(doprint)
1498 print(" rotating", i, j, theta);
1499
1500 double c = cos(theta);
1501 double s = sin(theta);
1502 drot3(nmo, &dip(i, 0, 0), &dip(j, 0, 0), s, c, 1);
1503 drot3(nmo, &dip(0, i, 0), &dip(0, j, 0), s, c, nmo);
1504 drot(nmo, &U(i, 0), &U(j, 0), s, c, 1);
1505 }
1506 }
1507 }
1508 }
1509
1510 ndone += ndone_iter;
1511 if(ndone_iter == 0 && tol == thresh){
1512 if(doprint)
1513 print("Boys localization converged in", ndone,"steps");
1514
1515 converged = true;
1516 break;
1517 }
1518 tol = std::max(0.1 * maxtheta, thresh);
1519 }
1520
1521 if(!converged){
1522 print("warning: boys localization did not fully converge: ", ndone);
1523 }
1524 U = transpose(U);
1525
1526 bool switched = true;
1527 while (switched) {
1528 switched = false;
1529 for (int i=0; i<nmo; i++) {
1530 for (int j=i+1; j<nmo; j++) {
1531 if (set[i] == set[j]) {
1532 double sold = U(i,i)*U(i,i) + U(j,j)*U(j,j);
1533 double snew = U(i,j)*U(i,j) + U(j,i)*U(j,i);
1534 if (snew > sold) {
1535 tensorT tmp = copy(U(_,i));
1536 U(_,i) = U(_,j);
1537 U(_,j) = tmp;
1538 switched = true;
1539 }
1540 }
1541 }
1542 }
1543 }
1544
1545 // Fix phases.
1546 for (long i=0; i<nmo; ++i) {
1547 if (U(i,i) < 0.0) U(_,i).scale(-1.0);
1548 }
1549
1550 }
1551
1552 world.gop.broadcast(U.ptr(), U.size(), 0);
1553 END_TIMER(world, "Boys localize");
1554 return U;
1555 }
1556
1557 tensorT kinetic_energy_matrix(World & world, const vecfuncT & v)
1558 {
1559 reconstruct(world, v);
1560 int n = v.size();
1561 tensorT r(n, n);
1562 for(int axis = 0;axis < 3;++axis){
1563 vecfuncT dv = apply(world, *(gradop[axis]), v);
1564 r += matrix_inner(world, dv, dv, true);
1565 dv.clear();
1566 }
1567 return r.scale(0.5);
1568 }
1569
1570
1571 vecfuncT core_projection(World & world, const vecfuncT & psi, const bool include_Bc = true)
1572 {
1573 int npsi = psi.size();
1574 if (npsi == 0) return psi;
1575 int natom = molecule.natom();
1576 vecfuncT proj = zero_functions<double,3>(world, npsi);
1577 tensorT overlap_sum(static_cast<long>(npsi));
1578
1579 for (int i=0; i<natom; ++i) {
1580 Atom at = molecule.get_atom(i);
1581 unsigned int atn = at.atomic_number;
1582 unsigned int nshell = molecule.n_core_orb(atn);
1583 if (nshell == 0) continue;
1584 for (unsigned int c=0; c<nshell; ++c) {
1585 unsigned int l = molecule.get_core_l(atn, c);
1586 int max_m = (l+1)*(l+2)/2;
1587 nshell -= max_m - 1;
1588 for (int m=0; m<max_m; ++m) {
1589 functionT core = factoryT(world).functor(functorT(new CoreOrbitalFunctor(molecule, i, c, m)));
1590 tensorT overlap = inner(world, core, psi);
1591 overlap_sum += overlap;
1592 for (int j=0; j<npsi; ++j) {
1593 if (include_Bc) overlap[j] *= molecule.get_core_bc(atn, c);
1594 proj[j] += core.scale(overlap[j]);
1595 }
1596 }
1597 }
1598 world.gop.fence();
1599 }
1600 if (world.rank() == 0) print("sum_k <core_k|psi_i>:", overlap_sum);
1601 return proj;
1602 }
1603
1604 double core_projector_derivative(World & world, const vecfuncT & mo, const tensorT & occ, int atom, int axis)
1605 {
1606 vecfuncT cores, dcores;
1607 std::vector<double> bc;
1608 unsigned int atn = molecule.get_atom(atom).atomic_number;
1609 unsigned int ncore = molecule.n_core_orb(atn);
1610
1611 // projecting core & d/dx core
1612 for (unsigned int c=0; c<ncore; ++c) {
1613 unsigned int l = molecule.get_core_l(atn, c);
1614 int max_m = (l+1)*(l+2)/2;
1615 for (int m=0; m<max_m; ++m) {
1616 functorT func = functorT(new CoreOrbitalFunctor(molecule, atom, c, m));
1617 cores.push_back(functionT(factoryT(world).functor(func).truncate_on_project()));
1618 func = functorT(new CoreOrbitalDerivativeFunctor(molecule, atom, axis, c, m));
1619 dcores.push_back(functionT(factoryT(world).functor(func).truncate_on_project()));
1620 bc.push_back(molecule.get_core_bc(atn, c));
1621 }
1622 }
1623
1624 // calc \sum_i occ_i <psi_i|(\sum_c Bc d/dx |core><core|)|psi_i>
1625 double r = 0.0;
1626 for (unsigned int c=0; c<cores.size(); ++c) {
1627 double rcore= 0.0;
1628 tensorT rcores = inner(world, cores[c], mo);
1629 tensorT rdcores = inner(world, dcores[c], mo);
1630 for (unsigned int i=0; i<mo.size(); ++i) {
1631 rcore += rdcores[i] * rcores[i] * occ[i];
1632 }
1633 r += 2.0 * bc[c] * rcore;
1634 }
1635
1636 return r;
1637 }
1638
1639 void initial_guess(World & world)
1640 {
1641 START_TIMER(world);
1642 if (param.restart) {
1643 load_mos(world);
1644 }
1645 else {
1646 // Use the initial density and potential to generate a better process map
1647 functionT rho = factoryT(world).functor(functorT(new MolecularGuessDensityFunctor(molecule, aobasis))).truncate_on_project();
1648 END_TIMER(world, "guess density");
1649 double nel = rho.trace();
1650 if(world.rank() == 0)
1651 print("guess dens trace", nel);
1652
1653 if(world.size() > 1) {
1654 START_TIMER(world);
1655 LoadBalanceDeux<3> lb(world);
1656 real_function_3d vnuc = potentialmanager->vnuclear();
1657 lb.add_tree(vnuc, lbcost<double,3>(vnucextra*1.0, vnucextra*8.0), false);
1658 lb.add_tree(rho, lbcost<double,3>(1.0, 8.0), true);
1659
1660 FunctionDefaults<3>::redistribute(world, lb.load_balance(6.0));
1661 END_TIMER(world, "guess loadbal");
1662 }
1663
1664 // Diag approximate fock matrix to get initial mos
1665 functionT vlocal;
1666 if(param.nalpha + param.nbeta > 1){
1667 START_TIMER(world);
1668 real_function_3d vnuc = potentialmanager->vnuclear();
1669 vlocal = vnuc + apply(*coulop, rho);
1670 END_TIMER(world, "guess Coulomb potn");
1671 bool save = param.spin_restricted;
1672 param.spin_restricted = true;
1673 vlocal = vlocal + make_lda_potential(world, rho);
1674 vlocal.truncate();
1675 param.spin_restricted = save;
1676 } else {
1677 real_function_3d vnuc = potentialmanager->vnuclear();
1678 vlocal = vnuc;
1679 }
1680 rho.clear();
1681 vlocal.reconstruct();
1682 if(world.size() > 1){
1683 LoadBalanceDeux<3> lb(world);
1684 real_function_3d vnuc = potentialmanager->vnuclear();
1685 lb.add_tree(vnuc, lbcost<double,3>(vnucextra*1.0, vnucextra*8.0), false);
1686 for(unsigned int i = 0;i < ao.size();++i){
1687 lb.add_tree(ao[i], lbcost<double,3>(1.0, 8.0), false);
1688 }
1689
1690 FunctionDefaults<3>::redistribute(world, lb.load_balance(6.0));
1691 }
1692
1693 tensorT overlap = matrix_inner(world, ao, ao, true);
1694 START_TIMER(world);
1695 tensorT kinetic = kinetic_energy_matrix(world, ao);
1696 END_TIMER(world, "guess Kinet potn");
1697 reconstruct(world, ao);
1698 vlocal.reconstruct();
1699 vecfuncT vpsi = mul_sparse(world, vlocal, ao, vtol);
1700 compress(world, vpsi);
1701 truncate(world, vpsi);
1702 compress(world, ao);
1703 tensorT potential = matrix_inner(world, vpsi, ao, true);
1704 vpsi.clear();
1705 tensorT fock = kinetic + potential;
1706 fock = 0.5 * (fock + transpose(fock));
1707 tensorT c, e;
1708
1709 START_TIMER(world);
1710 sygvp(world, fock, overlap, 1, c, e);
1711 END_TIMER(world, "guess eigen sol");
1712 print_meminfo(world.rank(), "guess eigen sol");
1713
1714 // NAR 7/5/2013
1715 // commented out because it generated a lot of output
1716 // if(world.rank() == 0 && 0){
1717 // print("initial eigenvalues");
1718 // print(e);
1719 // print("\n\nWSTHORNTON: initial eigenvectors");
1720 // print(c);
1721 // }
1722
1723 compress(world, ao);
1724
1725 unsigned int ncore = 0;
1726 if (param.core_type != "") {
1727 ncore = molecule.n_core_orb_all();
1728 }
1729 amo = transform(world, ao, c(_, Slice(ncore, ncore + param.nmo_alpha - 1)), 0.0, true);
1730 truncate(world, amo);
1731 normalize(world, amo);
1732 aeps = e(Slice(ncore, ncore + param.nmo_alpha - 1));
1733
1734 aocc = tensorT(param.nmo_alpha);
1735 for(int i = 0;i < param.nalpha;++i)
1736 aocc[i] = 1.0;
1737
1738 aset = std::vector<int>(param.nmo_alpha,0);
1739 if(world.rank() == 0)
1740 std::cout << "alpha set " << 0 << " " << 0 << "-";
1741
1742 for(int i = 1;i < param.nmo_alpha;++i) {
1743 aset[i] = aset[i - 1];
1744 //vamastd::cout << "aeps -" << i << "- " << aeps[i] << std::endl;
1745 if(aeps[i] - aeps[i - 1] > 1.5 || aocc[i] != 1.0){
1746 ++(aset[i]);
1747 if(world.rank() == 0){
1748 std::cout << i - 1 << std::endl;
1749 std::cout << "alpha set " << aset[i] << " " << i << "-";
1750 }
1751 }
1752 }
1753 if(world.rank() == 0)
1754 std::cout << param.nmo_alpha - 1 << std::endl;
1755
1756 if(param.nbeta && !param.spin_restricted){
1757 bmo = transform(world, ao, c(_, Slice(ncore, ncore + param.nmo_beta - 1)), 0.0, true);
1758 truncate(world, bmo);
1759 normalize(world, bmo);
1760 beps = e(Slice(ncore, ncore + param.nmo_beta - 1));
1761 bocc = tensorT(param.nmo_beta);
1762 for(int i = 0;i < param.nbeta;++i)
1763 bocc[i] = 1.0;
1764
1765 bset = std::vector<int>(param.nmo_beta,0);
1766 if(world.rank() == 0)
1767 std::cout << " beta set " << 0 << " " << 0 << "-";
1768
1769 for(int i = 1;i < param.nmo_beta;++i) {
1770 bset[i] = bset[i - 1];
1771 if(beps[i] - beps[i - 1] > 1.5 || bocc[i] != 1.0){
1772 ++(bset[i]);
1773 if(world.rank() == 0){
1774 std::cout << i - 1 << std::endl;
1775 std::cout << " beta set " << bset[i] << " " << i << "-";
1776 }
1777 }
1778 }
1779 if(world.rank() == 0)
1780 std::cout << param.nmo_beta - 1 << std::endl;
1781 }
1782 }
1783 }
1784
1785 void initial_guess_mp(World & world)
1786 {
1787 START_TIMER(world);
1788 if (param.restart) {
1789 load_mos(world);
1790 }
1791 else {
1792 // Use the initial density and potential to generate a better process map
1793 functionT rho = factoryT(world).functor(functorT(new MolecularGuessDensityFunctor(molecule, aobasis))).truncate_on_project();
1794 END_TIMER(world, "guess density");
1795 double nel = rho.trace();
1796 if(world.rank() == 0)
1797 print("guess dens trace", nel);
1798
1799 if(world.size() > 1) {
1800 START_TIMER(world);
1801 LoadBalanceDeux<3> lb(world);
1802 real_function_3d vnuc = potentialmanager->vnuclear();
1803 lb.add_tree(vnuc, lbcost<double,3>(vnucextra*1.0, vnucextra*8.0), false);
1804 lb.add_tree(rho, lbcost<double,3>(1.0, 8.0), true);
1805
1806 FunctionDefaults<3>::redistribute(world, lb.load_balance(6.0));
1807 END_TIMER(world, "guess loadbal");
1808 }
1809
1810 // Diag approximate fock matrix to get initial mos
1811 functionT vlocal;
1812 if(param.nalpha + param.nbeta > 1){
1813 START_TIMER(world);
1814 real_function_3d vnuc = potentialmanager->vnuclear();
1815 vlocal = vnuc + apply(*coulop, rho);
1816 END_TIMER(world, "guess Coulomb potn");
1817 bool save = param.spin_restricted;
1818 param.spin_restricted = true;
1819 vlocal = vlocal + make_lda_potential(world, rho);
1820 vlocal.truncate();
1821 param.spin_restricted = save;
1822 } else {
1823 real_function_3d vnuc = potentialmanager->vnuclear();
1824 vlocal = vnuc;
1825 }
1826 rho.clear();
1827 vlocal.reconstruct();
1828 if(world.size() > 1){
1829 LoadBalanceDeux<3> lb(world);
1830 real_function_3d vnuc = potentialmanager->vnuclear();
1831 lb.add_tree(vnuc, lbcost<double,3>(vnucextra*1.0, vnucextra*8.0), false);
1832 for(unsigned int i = 0;i < ao.size();++i){
1833 lb.add_tree(ao[i], lbcost<double,3>(1.0, 8.0), false);
1834 }
1835
1836 FunctionDefaults<3>::redistribute(world, lb.load_balance(6.0));
1837 }
1838
1839 tensorT overlap = matrix_inner(world, ao, ao, true);
1840 START_TIMER(world);
1841 tensorT kinetic = kinetic_energy_matrix(world, ao);
1842 END_TIMER(world, "guess Kinet potn");
1843 reconstruct(world, ao);
1844 vlocal.reconstruct();
1845 vecfuncT vpsi = mul_sparse(world, vlocal, ao, vtol);
1846 compress(world, vpsi);
1847 truncate(world, vpsi);
1848 compress(world, ao);
1849 tensorT potential = matrix_inner(world, vpsi, ao, true);
1850 vpsi.clear();
1851 tensorT fock = kinetic + potential;
1852 fock = 0.5 * (fock + transpose(fock));
1853 tensorT c, e;
1854
1855 START_TIMER(world);
1856 sygvp(world, fock, overlap, 1, c, e);
1857 END_TIMER(world, "guess eigen sol");
1858 print_meminfo(world.rank(), "guess eigen sol");
1859
1860 // NAR 7/5/2013
1861 // commented out because it generated a lot of output
1862 // if(world.rank() == 0 && 0){
1863 // print("initial eigenvalues");
1864 // print(e);
1865 // print("\n\nWSTHORNTON: initial eigenvectors");
1866 // print(c);
1867 // }
1868
1869 compress(world, ao);
1870
1871 unsigned int ncore = 0;
1872 if (param.core_type != "") {
1873 ncore = molecule.n_core_orb_all();
1874 }
1875 amo_p = transform(world, ao, c(_, Slice(ncore, ncore + param.nmo_alpha - 1)), 0.0, true);
1876 amo_m = transform(world, ao, c(_, Slice(ncore, ncore + param.nmo_alpha - 1)), 0.0, true);
1877 truncate(world, amo_p);
1878 truncate(world, amo_m);
1879 normalize(world, amo_p);
1880 normalize(world, amo_m);
1881 aeps_mp = e(Slice(ncore, ncore + param.nmo_alpha - 1));
1882
1883 aocc_mp = tensorT(param.nmo_alpha);
1884 for(int i = 0;i < param.nalpha;++i)
1885 aocc_mp[i] = 1.0;
1886
1887 aset_mp = std::vector<int>(param.nmo_alpha,0);
1888 if(world.rank() == 0)
1889 std::cout << "alpha set mp " << 0 << " " << 0 << "-";
1890
1891 for(int i = 1;i < param.nmo_alpha;++i) {
1892 aset_mp[i] = aset_mp[i - 1];
1893 //vamastd::cout << "aeps -" << i << "- " << aeps[i] << std::endl;
1894 if(aeps_mp[i] - aeps_mp[i - 1] > 1.5 || aocc_mp[i] != 1.0){
1895 ++(aset_mp[i]);
1896 if(world.rank() == 0){
1897 std::cout << i - 1 << std::endl;
1898 std::cout << "alpha set mp " << aset_mp[i] << " " << i << "-";
1899 }
1900 }
1901 }
1902 if(world.rank() == 0)
1903 std::cout << param.nmo_alpha - 1 << std::endl;
1904
1905 if(param.nbeta && !param.spin_restricted){
1906 bmo_p = transform(world, ao, c(_, Slice(ncore, ncore + param.nmo_beta - 1)), 0.0, true);
1907 bmo_m = transform(world, ao, c(_, Slice(ncore, ncore + param.nmo_beta - 1)), 0.0, true);
1908 truncate(world, bmo_p);
1909 truncate(world, bmo_m);
1910 normalize(world, bmo_p);
1911 normalize(world, bmo_m);
1912 beps_mp = e(Slice(ncore, ncore + param.nmo_beta - 1));
1913 bocc_mp = tensorT(param.nmo_beta);
1914 for(int i = 0;i < param.nbeta;++i)
1915 bocc_mp[i] = 1.0;
1916
1917 bset_mp = std::vector<int>(param.nmo_beta,0);
1918 if(world.rank() == 0)
1919 std::cout << " beta set mp " << 0 << " " << 0 << "-";
1920
1921 for(int i = 1;i < param.nmo_beta;++i) {
1922 bset_mp[i] = bset_mp[i - 1];
1923 if(beps_mp[i] - beps_mp[i - 1] > 1.5 || bocc_mp[i] != 1.0){
1924 ++(bset_mp[i]);
1925 if(world.rank() == 0){
1926 std::cout << i - 1 << std::endl;
1927 std::cout << " beta set mp " << bset_mp[i] << " " << i << "-";
1928 }
1929 }
1930 }
1931 if(world.rank() == 0)
1932 std::cout << param.nmo_beta - 1 << std::endl;
1933 }
1934 }
1935 }
1936
1937 void initial_load_bal(World & world)
1938 {
1939 LoadBalanceDeux<3> lb(world);
1940 real_function_3d vnuc = potentialmanager->vnuclear();
1941 lb.add_tree(vnuc, lbcost<double,3>(vnucextra*1.0, vnucextra*8.0));
1942
1943 FunctionDefaults<3>::redistribute(world, lb.load_balance(6.0));
1944 }
1945
1946 functionT make_density(World & world, const tensorT & occ, const vecfuncT & v)
1947 {
1948 vecfuncT vsq = square(world, v);
1949 compress(world, vsq);
1950 functionT rho = factoryT(world);
1951 rho.compress();
1952 for(unsigned int i = 0;i < vsq.size();++i){
1953 if(occ[i])
1954 rho.gaxpy(1.0, vsq[i], occ[i], false);
1955
1956 }
1957 world.gop.fence();
1958 vsq.clear();
1959 return rho;
1960 }
1961
1962 functionT make_density(World & world, const tensorT & occ, const cvecfuncT & v)
1963 {
1964 reconstruct(world, v); // For max parallelism
1965 std::vector<functionT> vsq(v.size());
1966 for (unsigned int i=0; i < v.size(); i++) {
1967 vsq[i] = abssq(v[i], false);
1968 }
1969 world.gop.fence();
1970
1971 compress(world, vsq); // since will be using gaxpy for accumulation
1972 functionT rho = factoryT(world);
1973 rho.compress();
1974
1975 for(unsigned int i = 0; i < vsq.size();++i) {
1976 if(occ[i])
1977 rho.gaxpy(1.0, vsq[i], occ[i], false);
1978
1979 }
1980 world.gop.fence();
1981 vsq.clear();
1982 rho.truncate();
1983
1984 return rho;
1985 }
1986
1987 std::vector<poperatorT> make_bsh_operators(World & world, const tensorT & evals)
1988 {
1989 int nmo = evals.dim(0);
1990 std::vector<poperatorT> ops(nmo);
1991 double tol = FunctionDefaults<3>::get_thresh();
1992 for(int i = 0;i < nmo;++i){
1993 double eps = evals(i);
1994 if(eps > 0){
1995 if(world.rank() == 0){
1996 print("bsh: warning: positive eigenvalue", i, eps);
1997 }
1998 eps = -0.1;
1999 }
2000
2001 ops[i] = poperatorT(BSHOperatorPtr3D(world, sqrt(-2.0 * eps), param.lo, tol));
2002 }
2003
2004 return ops;
2005 }
2006
2007 vecfuncT apply_hf_exchange(World & world, const tensorT & occ, const vecfuncT & psi, const vecfuncT & f)
2008 {
2009 const bool same = (&psi == &f);
2010 int nocc = psi.size();
2011 int nf = f.size();
2012 double tol = FunctionDefaults<3>::get_thresh(); /// Important this is consistent with Coulomb
2013 vecfuncT Kf = zero_functions<double,3>(world, nf);
2014 compress(world, Kf);
2015 reconstruct(world, psi);
2016 norm_tree(world, psi);
2017 if (!same) {
2018 reconstruct(world, f);
2019 norm_tree(world, f);
2020 }
2021
2022 // // Smaller memory algorithm ... possible 2x saving using i-j sym
2023 // for(int i=0; i<nocc; ++i){
2024 // if(occ[i] > 0.0){
2025 // vecfuncT psif = mul_sparse(world, psi[i], f, tol); /// was vtol
2026 // truncate(world, psif);
2027 // psif = apply(world, *coulop, psif);
2028 // truncate(world, psif);
2029 // psif = mul_sparse(world, psi[i], psif, tol); /// was vtol
2030 // gaxpy(world, 1.0, Kf, occ[i], psif);
2031 // }
2032 // }
2033
2034 // Larger memory algorithm ... use i-j sym if psi==f
2035 vecfuncT psif;
2036 for (int i=0; i<nocc; ++i) {
2037 int jtop = nf;
2038 if (same) jtop = i+1;
2039 for (int j=0; j<jtop; ++j) {
2040 psif.push_back(mul_sparse(psi[i], f[j], tol, false));
2041 }
2042 }
2043
2044 world.gop.fence();
2045 truncate(world, psif);
2046 psif = apply(world, *coulop, psif);
2047 truncate(world, psif, tol);
2048 reconstruct(world, psif);
2049 norm_tree(world, psif);
2050 vecfuncT psipsif = zero_functions<double,3>(world, nf*nocc);
2051 int ij = 0;
2052 for (int i=0; i<nocc; ++i) {
2053 int jtop = nf;
2054 if (same) jtop = i+1;
2055 for (int j=0; j<jtop; ++j,++ij) {
2056 psipsif[i*nf+j] = mul_sparse(psif[ij],psi[i],false);
2057 if (same && i!=j) {
2058 psipsif[j*nf+i] = mul_sparse(psif[ij],psi[j],false);
2059 }
2060 }
2061 }
2062 world.gop.fence();
2063 psif.clear();
2064 world.gop.fence();
2065 compress(world, psipsif);
2066 for (int i=0; i<nocc; ++i) {
2067 for (int j=0; j<nf; ++j) {
2068 Kf[j].gaxpy(1.0,psipsif[i*nf+j],occ[i],false);
2069 }
2070 }
2071 world.gop.fence();
2072 psipsif.clear();
2073 world.gop.fence();
2074
2075 truncate(world, Kf, tol);
2076 return Kf;
2077 }
2078
2079 // Used only for initial guess that is always spin-restricted LDA
2080 functionT make_lda_potential(World & world, const functionT & arho)
2081 {
2082 functionT vlda = copy(arho);
2083 vlda.reconstruct();
2084 vlda.unaryop(xc_lda_potential());
2085 return vlda;
2086 }
2087
2088
2089 functionT make_dft_potential(World & world, const vecfuncT& vf, int ispin, int what)
2090 {
2091 return multiop_values<double, xc_potential, 3>(xc_potential(xc, ispin, what), vf);
2092 }
2093
2094 double make_dft_energy(World & world, const vecfuncT& vf, int ispin)
2095 {
2096 functionT vlda = multiop_values<double, xc_functional, 3>(xc_functional(xc, ispin), vf);
2097 return vlda.trace();
2098 }
2099
2100 vecfuncT apply_potential(World & world, const tensorT & occ, const vecfuncT & amo,
2101 const vecfuncT& vf, const vecfuncT& delrho, const functionT & vlocal, double & exc, int ispin)
2102 {
2103 functionT vloc = vlocal;
2104 exc = 0.0;
2105
2106 //print("DFT", xc.is_dft(), "LDA", xc.is_lda(), "GGA", xc.is_gga(), "POLAR", xc.is_spin_polarized());
2107 if (xc.is_dft() && !(xc.hf_exchange_coefficient()==1.0)) {
2108 START_TIMER(world);
2109 #ifdef MADNESS_HAS_LIBXC
2110 exc = make_dft_energy(world, vf, ispin);
2111 #else
2112 if (ispin == 0) exc = make_dft_energy(world, vf, ispin);
2113 #endif
2114 vloc = vloc + make_dft_potential(world, vf, ispin, 0);
2115 //print("VLOC1", vloc.trace(), vloc.norm2());
2116
2117 #ifdef MADNESS_HAS_LIBXC
2118 if (xc.is_gga() ) {
2119 if (world.rank() == 0) print(" WARNING GGA XC functionals must be used with caution in this version \n");
2120 real_function_3d vsig = make_dft_potential(world, vf, ispin, 1);
2121 //print("VSIG", vsig.trace(), vsig.norm2());
2122 real_function_3d vr(world);
2123 for (int axis=0; axis<3; axis++) {
2124 vr += (*gradop[axis])(vsig);
2125 //, int flagprint("VR", vr.trace(), vr.norm2());
2126 }
2127 vloc = vloc - vr;
2128 }
2129 #endif
2130 END_TIMER(world, "DFT potential");
2131 }
2132
2133
2134 START_TIMER(world);
2135 vecfuncT Vpsi = mul_sparse(world, vloc, amo, vtol);
2136 END_TIMER(world, "V*psi");
2137 print_meminfo(world.rank(), "V*psi");
2138 if(xc.hf_exchange_coefficient()){
2139 START_TIMER(world);
2140 vecfuncT Kamo = apply_hf_exchange(world, occ, amo, amo);
2141 tensorT excv = inner(world, Kamo, amo);
2142 double exchf = 0.0;
2143 for(unsigned long i = 0;i < amo.size();++i){
2144 exchf -= 0.5 * excv[i] * occ[i];
2145 }
2146 if (!xc.is_spin_polarized()) exchf *= 2.0;
2147 gaxpy(world, 1.0, Vpsi, -xc.hf_exchange_coefficient(), Kamo);
2148 Kamo.clear();
2149 END_TIMER(world, "HF exchange");
2150 exc = exchf* xc.hf_exchange_coefficient() + exc;
2151 }
2152 potentialmanager->apply_nonlocal_potential(world, amo, Vpsi);
2153
2154 if (param.core_type.substr(0,3) == "mcp") {
2155 START_TIMER(world);
2156 gaxpy(world, 1.0, Vpsi, 1.0, core_projection(world, amo));
2157 END_TIMER(world, "MCP Core Projector");
2158 }
2159
2160 START_TIMER(world);
2161 truncate(world, Vpsi);
2162 END_TIMER(world, "Truncate Vpsi");
2163 print_meminfo(world.rank(), "Truncate Vpsi");
2164 world.gop.fence();
2165 return Vpsi;
2166 }
2167
2168 vecfuncT apply_potential_response(World & world, const tensorT & occ, const vecfuncT & dmo,
2169 const vecfuncT& vf, const functionT & vlocal, double & exc, int ispin)
2170 {
2171 functionT vloc = vlocal;
2172 exc = 0.0;
2173
2174 //print("DFT", xc.is_dft(), "LDA", xc.is_lda(), "GGA", xc.is_gga(), "POLAR", xc.is_spin_polarized());
2175 if (xc.is_dft() && !(xc.hf_exchange_coefficient()==1.0)) {
2176 START_TIMER(world);
2177 #ifdef MADNESS_HAS_LIBXC
2178 exc = make_dft_energy(world, vf, ispin);
2179 #else
2180 if (ispin == 0) exc = make_dft_energy(world, vf, ispin);
2181 #endif
2182 vloc = vloc + make_dft_potential(world, vf, ispin, 0);
2183 //print("VLOC1", vloc.trace(), vloc.norm2());
2184
2185 #ifdef MADNESS_HAS_LIBXC
2186 if (xc.is_gga() ) {
2187 if (world.rank() == 0) print(" WARNING GGA XC functionals must be used with caution in this version \n");
2188 real_function_3d vsig = make_dft_potential(world, vf, ispin, 1);
2189 //print("VSIG", vsig.trace(), vsig.norm2());
2190 real_function_3d vr(world);
2191 for (int axis=0; axis<3; axis++) {
2192 vr += (*gradop[axis])(vsig);
2193 //, int flagprint("VR", vr.trace(), vr.norm2());
2194 }
2195 vloc = vloc - vr;
2196 }
2197 #endif
2198 END_TIMER(world, "DFT potential");
2199 }
2200
2201
2202 START_TIMER(world);
2203 vecfuncT Vdmo = mul_sparse(world, vloc, dmo, vtol);
2204 END_TIMER(world, "V*dmo");
2205 print_meminfo(world.rank(), "V*dmo");
2206 if(xc.hf_exchange_coefficient()){
2207 START_TIMER(world);
2208 vecfuncT Kdmo = apply_hf_exchange(world, occ, dmo, dmo);
2209 tensorT excv = inner(world, Kdmo, dmo);
2210 double exchf = 0.0;
2211 for(unsigned long i = 0;i < dmo.size();++i){
2212 exchf -= 0.5 * excv[i] * occ[i];
2213 }
2214 if (!xc.is_spin_polarized()) exchf *= 2.0;
2215 gaxpy(world, 1.0, Vdmo, -xc.hf_exchange_coefficient(), Kdmo);
2216 Kdmo.clear();
2217 END_TIMER(world, "HF exchange");
2218 //exc = exchf* xc.hf_exchange_coefficient() + exc;
2219 }
2220 potentialmanager->apply_nonlocal_potential(world, dmo, Vdmo);
2221
2222 if (param.core_type.substr(0,3) == "mcp") {
2223 START_TIMER(world);
2224 gaxpy(world, 1.0, Vdmo, 1.0, core_projection(world, dmo));
2225 END_TIMER(world, "MCP Core Projector");
2226 }
2227
2228 START_TIMER(world);
2229 truncate(world, Vdmo);
2230 END_TIMER(world, "Truncate Vdmo");
2231 print_meminfo(world.rank(), "Truncate Vdmo");
2232 world.gop.fence();
2233 return Vdmo;
2234 }
2235
2236 vecfuncT apply_potential_mp(World & world, const tensorT & occ, const vecfuncT & amo_mp,
2237 const vecfuncT& vf, const vecfuncT& delrho, const functionT & vlocal,
2238 double & exc, int ispin, int flag, int & axis, double & ep)
2239 {
2240 functionT vloc = vlocal;
2241 exc = 0.0;
2242
2243 //print("DFT", xc.is_dft(), "LDA", xc.is_lda(), "GGA", xc.is_gga(), "POLAR", xc.is_spin_polarized());
2244 if (xc.is_dft() && !(xc.hf_exchange_coefficient()==1.0)) {
2245 START_TIMER(world);
2246 #ifdef MADNESS_HAS_LIBXC
2247 exc = make_dft_energy(world, vf, ispin);
2248 #else
2249 if (ispin == 0) exc = make_dft_energy(world, vf, ispin);
2250 #endif
2251 vloc = vloc + make_dft_potential(world, vf, ispin, 0);
2252 //print("VLOC1", vloc.trace(), vloc.norm2());
2253
2254 #ifdef MADNESS_HAS_LIBXC
2255 if (xc.is_gga() ) {
2256 if (world.rank() == 0) print(" WARNING GGA XC functionals must be used with caution in this version \n");
2257 real_function_3d vsig = make_dft_potential(world, vf, ispin, 1);
2258 //print("VSIG", vsig.trace(), vsig.norm2());
2259 real_function_3d vr(world);
2260 for (int axis=0; axis<3; axis++) {
2261 vr += (*gradop[axis])(vsig);
2262 //print("VR", vr.trace(), vr.norm2());
2263 }
2264 vloc = vloc - vr;
2265 }
2266 #endif
2267 END_TIMER(world, "DFT potential");
2268 }
2269
2270 //vecfuncT perturbation = zero_functions<double,3>(world, 3) ;
2271
2272 print("Vloc1", vloc.trace(), vloc.norm2());
2273 std::vector<int> f(3, 0);
2274 f[axis] = true;
2275 functionT dipolefunc = factoryT(world).functor(functorT(new MomentFunctor(f)));
2276 dipolefunc.scale(ep);
2277 print("Vdip", dipolefunc.trace(), dipolefunc.norm2());
2278 //perturbation = dipolefunc;
2279 //if (flag == 0) vloc = vloc + perturbation[i];
2280 if (flag == 0) vloc = vloc + dipolefunc;
2281 //else if(flag == 1) vloc = vloc - perturbation[i];
2282 else if(flag == 1) vloc = vloc - dipolefunc;
2283 //vloc = vloc - dipolefunc;
2284 print("Vloc2", vloc.trace(), vloc.norm2());
2285
2286 START_TIMER(world);
2287 vecfuncT Vpsi = mul_sparse(world, vloc, amo_mp, vtol);
2288 END_TIMER(world, "V*psi");
2289 print_meminfo(world.rank(), "V*psi");
2290 if(xc.hf_exchange_coefficient()){
2291 START_TIMER(world);
2292 vecfuncT Kamo = apply_hf_exchange(world, occ, amo_mp, amo_mp);
2293 tensorT excv = inner(world, Kamo, amo_mp);
2294 double exchf = 0.0;
2295 for(unsigned long i = 0;i < amo_mp.size();++i){
2296 exchf -= 0.5 * excv[i] * occ[i];
2297 }
2298 if (!xc.is_spin_polarized()) exchf *= 2.0;
2299 gaxpy(world, 1.0, Vpsi, -xc.hf_exchange_coefficient(), Kamo);
2300 Kamo.clear();
2301 END_TIMER(world, "HF exchange");
2302 exc = exchf* xc.hf_exchange_coefficient() + exc;
2303 }
2304 potentialmanager->apply_nonlocal_potential(world, amo_mp, Vpsi);
2305
2306 if (param.core_type.substr(0,3) == "mcp") {
2307 START_TIMER(world);
2308 gaxpy(world, 1.0, Vpsi, 1.0, core_projection(world, amo_mp));
2309 END_TIMER(world, "MCP Core Projector");
2310 }
2311
2312 START_TIMER(world);
2313 truncate(world, Vpsi);
2314 END_TIMER(world, "Truncate Vpsi");
2315 print_meminfo(world.rank(), "Truncate Vpsi");
2316 world.gop.fence();
2317 return Vpsi;
2318 }
2319
2320 tensorT derivatives(World & world)
2321 {
2322 START_TIMER(world);
2323
2324 functionT rho = make_density(world, aocc, amo);
2325 functionT brho = rho;
2326 if (!param.spin_restricted) brho = make_density(world, bocc, bmo);
2327 rho.gaxpy(1.0, brho, 1.0);
2328
2329 vecfuncT dv(molecule.natom() * 3);
2330 vecfuncT du = zero_functions<double,3>(world, molecule.natom() * 3);
2331 tensorT rc(molecule.natom() * 3);
2332 for(int atom = 0;atom < molecule.natom();++atom){
2333 for(int axis = 0;axis < 3;++axis){
2334 functorT func(new MolecularDerivativeFunctor(molecule, atom, axis));
2335 dv[atom * 3 + axis] = functionT(factoryT(world).functor(func).nofence().truncate_on_project());
2336 if (param.core_type != "" && molecule.is_potential_defined_atom(atom)) {
2337 // core potential contribution
2338 func = functorT(new CorePotentialDerivativeFunctor(molecule, atom, axis));
2339 du[atom * 3 + axis] = functionT(factoryT(world).functor(func).truncate_on_project());
2340
2341 // core projector contribution
2342 rc[atom * 3 + axis] = potentialmanager->core_projector_derivative(world, amo, aocc, atom, axis);
2343 if (!param.spin_restricted) {
2344 if (param.nbeta) rc[atom * 3 + axis] += potentialmanager->core_projector_derivative(world, bmo, bocc, atom, axis);
2345 }
2346 else {
2347 rc[atom * 3 + axis] *= 2 * 2;
2348 // because of 2 electrons in each valence orbital bra+ket
2349 }
2350 }
2351 }
2352 }
2353
2354 world.gop.fence();
2355 tensorT r = inner(world, rho, dv);
2356 world.gop.fence();
2357 tensorT ru = inner(world, rho, du);
2358 dv.clear();
2359 du.clear();
2360 world.gop.fence();
2361 tensorT ra(r.size());
2362 for(int atom = 0;atom < molecule.natom();++atom){
2363 for(int axis = 0;axis < 3;++axis){
2364 ra[atom * 3 + axis] = molecule.nuclear_repulsion_derivative(atom, axis);
2365 }
2366 }
2367 //if (world.rank() == 0) print("derivatives:\n", r, ru, rc, ra);
2368 r += ra + ru + rc;
2369 END_TIMER(world,"derivatives");
2370
2371 if (world.rank() == 0) {
2372 print("\n Derivatives (a.u.)\n -----------\n");
2373 print(" atom x y z dE/dx dE/dy dE/dz");
2374 print(" ------ ------------ ------------ ------------ ------------ ------------ ------------");
2375 for (int i=0; i<molecule.natom(); ++i) {
2376 const Atom& atom = molecule.get_atom(i);
2377 printf(" %5d %12.6f %12.6f %12.6f %12.6f %12.6f %12.6f\n",
2378 i, atom.x, atom.y, atom.z,
2379 r[i*3+0], r[i*3+1], r[i*3+2]);
2380 }
2381 }
2382 return r;
2383 }
2384
2385 tensorT dipole(World & world)
2386 {
2387 START_TIMER(world);
2388 tensorT mu(3);
2389 for (unsigned int axis=0; axis<3; ++axis) {
2390 std::vector<int> x(3, 0);
2391 x[axis] = true;
2392 functionT dipolefunc = factoryT(world).functor(functorT(new MomentFunctor(x)));
2393 functionT rho = make_density(world, aocc, amo);
2394 if (!param.spin_restricted) {
2395 if (param.nbeta) rho += make_density(world, bocc, bmo);
2396 }
2397 else {
2398 rho.scale(2.0);
2399 }
2400 mu[axis] = -dipolefunc.inner(rho);
2401 mu[axis] += molecule.nuclear_dipole(axis);
2402 }
2403
2404 if (world.rank() == 0) {
2405 print("\n Dipole Moment (a.u.)\n -----------\n");
2406 print(" x: ", mu[0]);
2407 print(" y: ", mu[1]);
2408 print(" z: ", mu[2]);
2409 print(" Total Dipole Moment: ", mu.normf());
2410 }
2411 END_TIMER(world, "dipole");
2412
2413 return mu;
2414 }
2415
2416 void vector_stats(const std::vector<double> & v, double & rms, double & maxabsval)
2417 {
2418 rms = 0.0;
2419 maxabsval = v[0];
2420 for(unsigned int i = 0;i < v.size();++i){
2421 rms += v[i] * v[i];
2422 maxabsval = std::max<double>(maxabsval, std::abs(v[i]));
2423 }
2424 rms = sqrt(rms / v.size());
2425 }
2426
2427 vecfuncT compute_residual(World & world, tensorT & occ, tensorT & fock, const vecfuncT & psi, vecfuncT & Vpsi, double & err)
2428 {
2429 double trantol = vtol / std::min(30.0, double(psi.size()));
2430 int nmo = psi.size();
2431
2432 tensorT eps(nmo);
2433 for(int i = 0;i < nmo;++i){
2434 eps(i) = std::min(-0.05, fock(i, i));
2435 fock(i, i) -= eps(i);
2436 }
2437 vecfuncT fpsi = transform(world, psi, fock, trantol, true);
2438
2439 for(int i = 0;i < nmo;++i){ // Undo the damage
2440 fock(i, i) += eps(i);
2441 }
2442
2443 gaxpy(world, 1.0, Vpsi, -1.0, fpsi);
2444 fpsi.clear();
2445 std::vector<double> fac(nmo, -2.0);
2446 scale(world, Vpsi, fac);
2447 std::vector<poperatorT> ops = make_bsh_operators(world, eps);
2448 set_thresh(world, Vpsi, FunctionDefaults<3>::get_thresh());
2449 if(world.rank() == 0)
2450 std::cout << "entering apply\n";
2451
2452 START_TIMER(world);
2453 vecfuncT new_psi = apply(world, ops, Vpsi);
2454 END_TIMER(world, "Apply BSH");
2455 ops.clear();
2456 Vpsi.clear();
2457 world.gop.fence();
2458
2459 // Thought it was a bad idea to truncate *before* computing the residual
2460 // but simple tests suggest otherwise ... no more iterations and
2461 // reduced iteration time from truncating.
2462 START_TIMER(world);
2463 truncate(world, new_psi);
2464 END_TIMER(world, "Truncate new psi");
2465
2466 vecfuncT r = sub(world, psi, new_psi);
2467 std::vector<double> rnorm = norm2s(world, r);
2468 if (world.rank() == 0) print("residuals", rnorm);
2469 double rms, maxval;
2470 vector_stats(rnorm, rms, maxval);
2471 err = maxval;
2472 if(world.rank() == 0)
2473 print("BSH residual: rms", rms, " max", maxval);
2474
2475 return r;
2476 }
2477
2478 tensorT make_fock_matrix(World & world, const vecfuncT & psi, const vecfuncT & Vpsi, const tensorT & occ, double & ekinetic)
2479 {
2480 START_TIMER(world);
2481 tensorT pe = matrix_inner(world, Vpsi, psi, true);
2482 END_TIMER(world, "PE matrix");
2483 START_TIMER(world);
2484 tensorT ke = kinetic_energy_matrix(world, psi);
2485 END_TIMER(world, "KE matrix");
2486 START_TIMER(world);
2487 int nocc = occ.size();
2488 ekinetic = 0.0;
2489 for(int i = 0;i < nocc;++i){
2490 ekinetic += occ[i] * ke(i, i);
2491 }
2492 ke += pe;
2493 pe = tensorT();
2494 ke.gaxpy(0.5, transpose(ke), 0.5);
2495 END_TIMER(world, "Make fock matrix rest");
2496 return ke;
2497 }
2498
2499 /// Compute the two-electron integrals over the provided set of orbitals
2500
2501 /// Returned is a *replicated* tensor of \f$(ij|kl)\f$ with \f$i>=j\f$
2502 /// and \f$k>=l\f$. The symmetry \f$(ij|kl)=(kl|ij)\f$ is enforced.
2503 Tensor<double> twoint(World& world, const vecfuncT& psi) {
2504 double tol = FunctionDefaults<3>::get_thresh(); /// Important this is consistent with Coulomb
2505 reconstruct(world, psi);
2506 norm_tree(world, psi);
2507
2508 // Efficient version would use mul_sparse vector interface
2509 vecfuncT pairs;
2510 for (unsigned int i=0; i<psi.size(); ++i) {
2511 for (unsigned int j=0; j<=i; ++j) {
2512 pairs.push_back(mul_sparse(psi[i], psi[j], tol, false));
2513 }
2514 }
2515
2516 world.gop.fence();
2517 truncate(world, pairs);
2518 vecfuncT Vpairs = apply(world, *coulop, pairs);
2519
2520 return matrix_inner(world, pairs, Vpairs, true);
2521 }
2522
2523 tensorT matrix_exponential(const tensorT& A) {
2524 const double tol = 1e-13;
2525 MADNESS_ASSERT(A.dim((0) == A.dim(1)));
2526
2527 // Scale A by a power of 2 until it is "small"
2528 double anorm = A.normf();
2529 int n = 0;
2530 double scale = 1.0;
2531 while (anorm*scale > 0.1) {
2532 ++n;
2533 scale *= 0.5;
2534 }
2535 tensorT B = scale*A; // B = A*2^-n
2536
2537 // Compute exp(B) using Taylor series
2538 tensorT expB = tensorT(2, B.dims());
2539 for (int i=0; i<expB.dim(0); ++i) expB(i,i) = 1.0;
2540
2541 int k = 1;
2542 tensorT term = B;
2543 while (term.normf() > tol) {
2544 expB += term;
2545 term = inner(term,B);
2546 ++k;
2547 term.scale(1.0/k);
2548 }
2549
2550 // Repeatedly square to recover exp(A)
2551 while (n--) {
2552 expB = inner(expB,expB);
2553 }
2554
2555 return expB;
2556 }
2557
2558 tensorT diag_fock_matrix(World & world, tensorT& fock, vecfuncT & psi, vecfuncT & Vpsi, tensorT & evals, const tensorT & occ, double thresh)
2559 {
2560 long nmo = psi.size();
2561 tensorT overlap = matrix_inner(world, psi, psi, true);
2562
2563 START_TIMER(world);
2564 tensorT U;
2565 sygvp(world, fock, overlap, 1, U, evals);
2566 END_TIMER(world, "Diagonalization Fock-mat w sygv");
2567
2568 START_TIMER(world);
2569 // Within blocks with the same occupation number attempt to
2570 // keep orbitals in the same order (to avoid confusing the
2571 // non-linear solver).
2572 // !!!!!!!!!!!!!!!!! NEED TO RESTRICT TO OCCUPIED STATES?
2573 bool switched = true;
2574 while (switched) {
2575 switched = false;
2576 for (int i=0; i<nmo; i++) {
2577 for (int j=i+1; j<nmo; j++) {
2578 if (occ(i) == occ(j)) {
2579 double sold = U(i,i)*U(i,i) + U(j,j)*U(j,j);
2580 double snew = U(i,j)*U(i,j) + U(j,i)*U(j,i);
2581 if (snew > sold) {
2582 tensorT tmp = copy(U(_,i));
2583 U(_,i) = U(_,j);
2584 U(_,j) = tmp;
2585 std::swap(evals[i],evals[j]);
2586 switched = true;
2587 }
2588 }
2589 }
2590 }
2591 }
2592 // Fix phases.
2593 for (long i=0; i<nmo; ++i) {
2594 if (U(i,i) < 0.0) U(_,i).scale(-1.0);
2595 }
2596
2597 // Rotations between effectively degenerate states confound
2598 // the non-linear equation solver ... undo these rotations
2599 long ilo = 0; // first element of cluster
2600 while (ilo < nmo-1) {
2601 long ihi = ilo;
2602 while (fabs(evals[ilo]-evals[ihi+1]) < thresh*10.0*std::max(fabs(evals[ilo]),1.0)) {
2603 ++ihi;
2604 if (ihi == nmo-1) break;
2605 }
2606 long nclus = ihi - ilo + 1;
2607 if (nclus > 1) {
2608 //print(" found cluster", ilo, ihi);
2609 tensorT q = copy(U(Slice(ilo,ihi),Slice(ilo,ihi)));
2610 //print(q);
2611 // Special code just for nclus=2
2612 // double c = 0.5*(q(0,0) + q(1,1));
2613 // double s = 0.5*(q(0,1) - q(1,0));
2614 // double r = sqrt(c*c + s*s);
2615 // c /= r;
2616 // s /= r;
2617 // q(0,0) = q(1,1) = c;
2618 // q(0,1) = -s;
2619 // q(1,0) = s;
2620
2621 // Iteratively construct unitary rotation by
2622 // exponentiating the antisymmetric part of the matrix
2623 // ... is quadratically convergent so just do 3
2624 // iterations
2625 tensorT rot = matrix_exponential(-0.5*(q - transpose(q)));
2626 q = inner(q,rot);
2627 tensorT rot2 = matrix_exponential(-0.5*(q - transpose(q)));
2628 q = inner(q,rot2);
2629 tensorT rot3 = matrix_exponential(-0.5*(q - transpose(q)));
2630 q = inner(rot,inner(rot2,rot3));
2631 U(_,Slice(ilo,ihi)) = inner(U(_,Slice(ilo,ihi)),q);
2632 }
2633 ilo = ihi+1;
2634 }
2635
2636 // if (world.rank() == 0) {
2637 // print("Fock");
2638 // print(fock);
2639 // print("Evec");
2640 // print(U);;
2641 // print("Eval");
2642 // print(evals);
2643 // }
2644
2645 world.gop.broadcast(U.ptr(), U.size(), 0);
2646 world.gop.broadcast(evals.ptr(), evals.size(), 0);
2647
2648 fock = 0;
2649 for (unsigned int i=0; i<psi.size(); ++i) fock(i,i) = evals(i);
2650
2651 Vpsi = transform(world, Vpsi, U, vtol / std::min(30.0, double(psi.size())), false);
2652 psi = transform(world, psi, U, FunctionDefaults<3>::get_thresh() / std::min(30.0, double(psi.size())), true);
2653 truncate(world, Vpsi, vtol, false);
2654 truncate(world, psi);
2655 normalize(world, psi);
2656
2657 END_TIMER(world, "Diagonalization rest");
2658 return U;
2659 }
2660
2661 void loadbal(World & world, functionT & arho, functionT & brho, functionT & arho_old, functionT & brho_old, subspaceT & subspace)
2662 {
2663 if(world.size() == 1)
2664 return;
2665
2666 LoadBalanceDeux<3> lb(world);
2667 real_function_3d vnuc = potentialmanager->vnuclear();
2668 lb.add_tree(vnuc, lbcost<double,3>(vnucextra*1.0, vnucextra*8.0), false);
2669 lb.add_tree(arho, lbcost<double,3>(1.0, 8.0), false);
2670 for(unsigned int i = 0;i < amo.size();++i){
2671 lb.add_tree(amo[i], lbcost<double,3>(1.0, 8.0), false);
2672 }
2673 if(param.nbeta && !param.spin_restricted){
2674 lb.add_tree(brho, lbcost<double,3>(1.0, 8.0), false);
2675 for(unsigned int i = 0;i < bmo.size();++i){
2676 lb.add_tree(bmo[i], lbcost<double,3>(1.0, 8.0), false);
2677 }
2678 }
2679 world.gop.fence();
2680
2681 FunctionDefaults<3>::redistribute(world, lb.load_balance(6.0)); // 6.0 needs retuning after vnucextra
2682 }
2683
2684 void rotate_subspace(World& world, const tensorT& U, subspaceT& subspace, int lo, int nfunc, double trantol) {
2685 for (unsigned int iter=0; iter<subspace.size(); ++iter) {
2686 vecfuncT& v = subspace[iter].first;
2687 vecfuncT& r = subspace[iter].second;
2688 transform(world, vecfuncT(&v[lo],&v[lo+nfunc]), U, trantol, false);
2689 transform(world, vecfuncT(&r[lo],&r[lo+nfunc]), U, trantol, true);
2690 }
2691 }
2692
2693 void update_response_subspace(World & world,
2694 vecfuncT & ax, vecfuncT & ay,
2695 vecfuncT & bx, vecfuncT & by,
2696 vecfuncT & rax, vecfuncT & ray,
2697 vecfuncT & rbx, vecfuncT & rby,
2698 subspaceT & subspace, tensorT & Q)
2699 {
2700 vecfuncT vm = ax;
2701 //print(" vm : ", norm2s(world, vm));
2702 vm.insert(vm.end(), ay.begin(), ay.end());
2703 //print(" vm. insert : ", norm2s(world, vm));
2704
2705 vecfuncT rm = rax;
2706 rm.insert(rm.end(), ray.begin(), ray.end());
2707
2708 if(param.nbeta != 0 && !param.spin_restricted){
2709 vm.insert(vm.end(), bx.begin(), bx.end());
2710 vm.insert(vm.end(), by.begin(), by.end());
2711 rm.insert(rm.end(), rbx.begin(), rbx.end());
2712 rm.insert(rm.end(), rby.begin(), rby.end());
2713 }
2714 compress(world, vm, false);
2715 compress(world, rm, false);
2716 world.gop.fence();
2717 subspace.push_back(pairvecfuncT(vm, rm));
2718 int m = subspace.size();
2719 tensorT ms(m);
2720 tensorT sm(m);
2721 for(int s = 0;s < m;++s){
2722 const vecfuncT & vs = subspace[s].first;
2723 const vecfuncT & rs = subspace[s].second;
2724 for(unsigned int i = 0;i < vm.size();++i){
2725 ms[s] += vm[i].inner_local(rs[i]);
2726 sm[s] += vs[i].inner_local(rm[i]);
2727 //print("ms[", s, "] : ",ms[s]);
2728 //print("sm[", s, "] : ",sm[s]);
2729 }
2730 }
2731
2732 world.gop.sum(ms.ptr(), m);
2733 world.gop.sum(sm.ptr(), m);
2734 tensorT newQ(m, m);
2735 if(m > 1)
2736 newQ(Slice(0, -2), Slice(0, -2)) = Q;
2737
2738 newQ(m - 1, _) = ms;
2739 newQ(_, m - 1) = sm;
2740 Q = newQ;
2741 //if (world.rank() == 0) { print("kain Q"); print(Q); }
2742 tensorT c;
2743 if(world.rank() == 0){
2744 double rcond = 1e-12;
2745 while(1){
2746 c = KAIN(Q, rcond);
2747 //if (world.rank() == 0) print("kain c:", c);
2748 if(std::abs(c[m - 1]) < 3.0){
2749 break;
2750 } else if(rcond < 0.01){
2751 print("Increasing subspace singular value threshold ", c[m - 1], rcond);
2752 rcond *= 100;
2753 } else {
2754 print("Forcing full step due to subspace malfunction");
2755 c = 0.0;
2756 c[m - 1] = 1.0;
2757 break;
2758 }
2759 }
2760 }
2761
2762 world.gop.broadcast_serializable(c, 0);
2763 if(world.rank() == 0){
2764 print("Response Subspace solution", c);
2765 }
2766 START_TIMER(world);
2767 vecfuncT ax_new = zero_functions<double,3>(world, ax.size());
2768 vecfuncT ay_new = zero_functions<double,3>(world, ay.size());
2769 vecfuncT bx_new = zero_functions<double,3>(world, bx.size());
2770 vecfuncT by_new = zero_functions<double,3>(world, by.size());
2771 compress(world, ax_new, false);
2772 compress(world, ay_new, false);
2773 compress(world, bx_new, false);
2774 compress(world, by_new, false);
2775 world.gop.fence();
2776
2777 for(unsigned int m = 0;m < subspace.size();++m){
2778 const vecfuncT & vm = subspace[m].first;
2779 const vecfuncT & rm = subspace[m].second;
2780 const vecfuncT vmax(vm.begin(), vm.begin() + ax.size());
2781 const vecfuncT vmay(vm.begin() + ax.size(), vm.begin() + ax.size() + ay.size());
2782 const vecfuncT rmax(rm.begin(), rm.begin() + rax.size());
2783 const vecfuncT rmay(rm.begin() + rax.size(), rm.begin() + rax.size() + ray.size());
2784 gaxpy(world, 1.0, ax_new, c(m), vmax, false);
2785 gaxpy(world, 1.0, ay_new, c(m), vmay, false);
2786 gaxpy(world, 1.0, ax_new, -c(m), rmax, false);
2787 gaxpy(world, 1.0, ay_new, -c(m), rmay, false);
2788 if(param.nbeta != 0 && !param.spin_restricted){
2789 const vecfuncT vmbx(vm.end() - bx.size(), vm.end() - by.size());
2790 const vecfuncT vmby(vm.end() - by.size(), vm.end());
2791 const vecfuncT rmbx(rm.end() - rbx.size(), rm.end() - rby.size());
2792 const vecfuncT rmby(rm.end() - rby.size(), rm.end());
2793 gaxpy(world, 1.0, bx_new, c(m), vmbx, false);
2794 gaxpy(world, 1.0, by_new, c(m), vmby, false);
2795 gaxpy(world, 1.0, bx_new, -c(m), rmbx, false);
2796 gaxpy(world, 1.0, by_new, -c(m), rmby, false);
2797 }
2798 }
2799 world.gop.fence();
2800 END_TIMER(world, "Subspace transform");
2801 if(param.maxsub <= 1){
2802 subspace.clear();
2803 } else if(subspace.size() == param.maxsub){
2804 subspace.erase(subspace.begin());
2805 Q = Q(Slice(1, -1), Slice(1, -1));
2806 }
2807
2808 std::vector<double> axnorm = norm2s(world, sub(world, ax, ax_new));
2809 std::vector<double> aynorm = norm2s(world, sub(world, ay, ay_new));
2810 std::vector<double> bxnorm = norm2s(world, sub(world, bx, bx_new));
2811 std::vector<double> bynorm = norm2s(world, sub(world, by, by_new));
2812 int nres = 0;
2813 for(unsigned int i = 0;i < ax.size();++i){
2814 if(axnorm[i] > param.maxrotn){
2815 double s = param.maxrotn / axnorm[i];
2816 ++nres;
2817 if(world.rank() == 0){
2818 if(nres == 1)
2819 printf(" restricting step for alpha orbitals:");
2820
2821 printf(" %d", i);
2822 }
2823 ax_new[i].gaxpy(s, ax[i], 1.0 - s, false);
2824 }
2825
2826 }
2827 if(nres > 0 && world.rank() == 0)
2828 printf("\n");
2829
2830 nres = 0;
2831 for(unsigned int i = 0;i < ay.size();++i){
2832 if(aynorm[i] > param.maxrotn){
2833 double s = param.maxrotn / aynorm[i];
2834 ++nres;
2835 if(world.rank() == 0){
2836 if(nres == 1)
2837 printf(" restricting step for alpha orbitals:");
2838
2839 printf(" %d", i);
2840 }
2841 ay_new[i].gaxpy(s, ay[i], 1.0 - s, false);
2842 }
2843
2844 }
2845 if(nres > 0 && world.rank() == 0)
2846 printf("\n");
2847
2848 if(param.nbeta != 0 && !param.spin_restricted){
2849 nres = 0;
2850 for(unsigned int i = 0;i < bx.size();++i){
2851 if(bxnorm[i] > param.maxrotn){
2852 double s = param.maxrotn / bxnorm[i];
2853 ++nres;
2854 if(world.rank() == 0){
2855 if(nres == 1)
2856 printf(" restricting step for beta orbitals:");
2857
2858 printf(" %d", i);
2859 }
2860 bx_new[i].gaxpy(s, bx[i], 1.0 - s, false);
2861 }
2862
2863 }
2864 if(nres > 0 && world.rank() == 0)
2865 printf("\n");
2866
2867 nres = 0;
2868 for(unsigned int i = 0;i < by.size();++i){
2869 if(bynorm[i] > param.maxrotn){
2870 double s = param.maxrotn / bynorm[i];
2871 ++nres;
2872 if(world.rank() == 0){
2873 if(nres == 1)
2874 printf(" restricting step for beta orbitals:");
2875
2876 printf(" %d", i);
2877 }
2878 by_new[i].gaxpy(s, by[i], 1.0 - s, false);
2879 }
2880
2881 }
2882 if(nres > 0 && world.rank() == 0)
2883 printf("\n");
2884 }
2885
2886 world.gop.fence();
2887 double rms, maxval;
2888 vector_stats(axnorm, rms, maxval);
2889 vector_stats(aynorm, rms, maxval);
2890 if(world.rank() == 0)
2891 print("Norm of vector changes alpha: rms", rms, " max", maxval);
2892
2893 if(bxnorm.size()){
2894 vector_stats(bxnorm, rms, maxval);
2895 vector_stats(bynorm, rms, maxval);
2896 if(world.rank() == 0)
2897 print("Norm of vector changes beta: rms", rms, " max", maxval);
2898
2899 }
2900 //START_TIMER(world);
2901 //double trantol = vtol / std::min(30.0, double(ax.size()));
2902 //normalize(world, ax_new);
2903 //normalize(world, ay_new);
2904 //ax_new = transform(world, ax_new, Q3(matrix_inner(world, ax_new, ax_new)), trantol, true);
2905 //ay_new = transform(world, ay_new, Q3(matrix_inner(world, ay_new, ay_new)), trantol, true);
2906 truncate(world, ax_new);
2907 truncate(world, ay_new);
2908 //normalize(world, ax_new);
2909 //normalize(world, ay_new);
2910 if(param.nbeta != 0 && !param.spin_restricted){
2911 //normalize(world, bx_new);
2912 //normalize(world, by_new);
2913 //bx_new = transform(world, bx_new, Q3(matrix_inner(world, bx_new, bx_new)), trantol, true);
2914 //by_new = transform(world, by_new, Q3(matrix_inner(world, by_new, by_new)), trantol, true);
2915 truncate(world, bx_new);
2916 truncate(world, by_new);
2917 //normalize(world, bx_new);
2918 //normalize(world, by_new);
2919 }
2920 //END_TIMER(world, "Orthonormalize");
2921 ax = ax_new;
2922 ay = ay_new;
2923 bx = bx_new;
2924 by = by_new;
2925
2926 }
2927
2928 void update_subspace(World & world,
2929 vecfuncT & Vpsia, vecfuncT & Vpsib,
2930 tensorT & focka, tensorT & fockb,
2931 subspaceT & subspace, tensorT & Q,
2932 double & bsh_residual, double & update_residual)
2933 {
2934 double aerr = 0.0, berr = 0.0;
2935 vecfuncT vm = amo;
2936
2937 // Orbitals with occ!=1.0 exactly must be solved for as eigenfunctions
2938 // so zero out off diagonal lagrange multipliers
2939 for (int i=0; i<param.nmo_alpha; i++) {
2940 if (aocc[i] != 1.0) {
2941 double tmp = focka(i,i);
2942 focka(i,_) = 0.0;
2943 focka(_,i) = 0.0;
2944 focka(i,i) = tmp;
2945 }
2946 }
2947
2948 vecfuncT rm = compute_residual(world, aocc, focka, amo, Vpsia, aerr);
2949 if(param.nbeta != 0 && !param.spin_restricted){
2950 for (int i=0; i<param.nmo_beta; i++) {
2951 if (bocc[i] != 1.0) {
2952 double tmp = fockb(i,i);
2953 fockb(i,_) = 0.0;
2954 fockb(_,i) = 0.0;
2955 fockb(i,i) = tmp;
2956 }
2957 }
2958
2959 vecfuncT br = compute_residual(world, bocc, fockb, bmo, Vpsib, berr);
2960 vm.insert(vm.end(), bmo.begin(), bmo.end());
2961 rm.insert(rm.end(), br.begin(), br.end());
2962 }
2963 bsh_residual = std::max(aerr, berr);
2964 world.gop.broadcast(bsh_residual, 0);
2965 compress(world, vm, false);
2966 compress(world, rm, false);
2967 world.gop.fence();
2968 subspace.push_back(pairvecfuncT(vm, rm));
2969 int m = subspace.size();
2970 tensorT ms(m);
2971 tensorT sm(m);
2972 for(int s = 0;s < m;++s){
2973 const vecfuncT & vs = subspace[s].first;
2974 const vecfuncT & rs = subspace[s].second;
2975 for(unsigned int i = 0;i < vm.size();++i){
2976 ms[s] += vm[i].inner_local(rs[i]);
2977 sm[s] += vs[i].inner_local(rm[i]);
2978 }
2979 }
2980
2981 world.gop.sum(ms.ptr(), m);
2982 world.gop.sum(sm.ptr(), m);
2983 tensorT newQ(m, m);
2984 if(m > 1)
2985 newQ(Slice(0, -2), Slice(0, -2)) = Q;
2986
2987 newQ(m - 1, _) = ms;
2988 newQ(_, m - 1) = sm;
2989 Q = newQ;
2990 //if (world.rank() == 0) { print("kain Q"); print(Q); }
2991 tensorT c;
2992 if(world.rank() == 0){
2993 double rcond = 1e-12;
2994 while(1){
2995 c = KAIN(Q, rcond);
2996 //if (world.rank() == 0) print("kain c:", c);
2997 if(std::abs(c[m - 1]) < 3.0){
2998 break;
2999 } else if(rcond < 0.01){
3000 print("Increasing subspace singular value threshold ", c[m - 1], rcond);
3001 rcond *= 100;
3002 } else {
3003 print("Forcing full step due to subspace malfunction");
3004 c = 0.0;
3005 c[m - 1] = 1.0;
3006 break;
3007 }
3008 }
3009 }
3010
3011 world.gop.broadcast_serializable(c, 0);
3012 if(world.rank() == 0){
3013 print("Subspace solution", c);
3014 }
3015 START_TIMER(world);
3016 vecfuncT amo_new = zero_functions<double,3>(world, amo.size());
3017 vecfuncT bmo_new = zero_functions<double,3>(world, bmo.size());
3018 compress(world, amo_new, false);
3019 compress(world, bmo_new, false);
3020 world.gop.fence();
3021 for(unsigned int m = 0;m < subspace.size();++m){
3022 const vecfuncT & vm = subspace[m].first;
3023 const vecfuncT & rm = subspace[m].second;
3024 const vecfuncT vma(vm.begin(), vm.begin() + amo.size());
3025 const vecfuncT rma(rm.begin(), rm.begin() + amo.size());
3026 const vecfuncT vmb(vm.end() - bmo.size(), vm.end());
3027 const vecfuncT rmb(rm.end() - bmo.size(), rm.end());
3028 gaxpy(world, 1.0, amo_new, c(m), vma, false);
3029 gaxpy(world, 1.0, amo_new, -c(m), rma, false);
3030 gaxpy(world, 1.0, bmo_new, c(m), vmb, false);
3031 gaxpy(world, 1.0, bmo_new, -c(m), rmb, false);
3032 }
3033 world.gop.fence();
3034 END_TIMER(world, "Subspace transform");
3035 if(param.maxsub <= 1){
3036 subspace.clear();
3037 } else if(subspace.size() == param.maxsub){
3038 subspace.erase(subspace.begin());
3039 Q = Q(Slice(1, -1), Slice(1, -1));
3040 }
3041
3042 std::vector<double> anorm = norm2s(world, sub(world, amo, amo_new));
3043 std::vector<double> bnorm = norm2s(world, sub(world, bmo, bmo_new));
3044 int nres = 0;
3045 for(unsigned int i = 0;i < amo.size();++i){
3046 if(anorm[i] > param.maxrotn){
3047 double s = param.maxrotn / anorm[i];
3048 ++nres;
3049 if(world.rank() == 0){
3050 if(nres == 1)
3051 printf(" restricting step for alpha orbitals:");
3052
3053 printf(" %d", i);
3054 }
3055 amo_new[i].gaxpy(s, amo[i], 1.0 - s, false);
3056 }
3057
3058 }
3059 if(nres > 0 && world.rank() == 0)
3060 printf("\n");
3061
3062 nres = 0;
3063 for(unsigned int i = 0;i < bmo.size();++i){
3064 if(bnorm[i] > param.maxrotn){
3065 double s = param.maxrotn / bnorm[i];
3066 ++nres;
3067 if(world.rank() == 0){
3068 if(nres == 1)
3069 printf(" restricting step for beta orbitals:");
3070
3071 printf(" %d", i);
3072 }
3073 bmo_new[i].gaxpy(s, bmo[i], 1.0 - s, false);
3074 }
3075
3076 }
3077 if(nres > 0 && world.rank() == 0)
3078 printf("\n");
3079
3080 world.gop.fence();
3081 double rms, maxval;
3082 vector_stats(anorm, rms, maxval);
3083 if(world.rank() == 0)
3084 print("Norm of vector changes alpha: rms", rms, " max", maxval);
3085
3086 update_residual = maxval;
3087 if(bnorm.size()){
3088 vector_stats(bnorm, rms, maxval);
3089 if(world.rank() == 0)
3090 print("Norm of vector changes beta: rms", rms, " max", maxval);
3091
3092 update_residual = std::max(update_residual, maxval);
3093 }
3094 START_TIMER(world);
3095 double trantol = vtol / std::min(30.0, double(amo.size()));
3096 normalize(world, amo_new);
3097 amo_new = transform(world, amo_new, Q3(matrix_inner(world, amo_new, amo_new)), trantol, true);
3098 truncate(world, amo_new);
3099 normalize(world, amo_new);
3100 if(param.nbeta != 0 && !param.spin_restricted){
3101 normalize(world, bmo_new);
3102 bmo_new = transform(world, bmo_new, Q3(matrix_inner(world, bmo_new, bmo_new)), trantol, true);
3103 truncate(world, bmo_new);
3104 normalize(world, bmo_new);
3105 }
3106 END_TIMER(world, "Orthonormalize");
3107 amo = amo_new;
3108 bmo = bmo_new;
3109 }
3110
3111 void update_subspace_mp(World & world,
3112 vecfuncT & Vpsia, vecfuncT & Vpsib,
3113 tensorT & focka, tensorT & fockb,
3114 subspaceT & subspace, tensorT & Q,
3115 double & bsh_residual, double & update_residual,
3116 int & mflag,
3117 vecfuncT & amo_mp, vecfuncT & bmo_mp)
3118 {
3119 double aerr = 0.0, berr = 0.0;
3120 #if 0
3121
3122 if(mflag == 1) {
3123 amo_mp = copy(world, amo_m);
3124 bmo_mp = copy(world, bmo_m);
3125 }
3126 else {
3127 amo_mp = copy(world, amo_p);
3128 bmo_mp = copy(world, bmo_p);
3129 }
3130 #endif
3131 vecfuncT vm = amo_mp;
3132
3133 // Orbitals with occ!=1.0 exactly must be solved for as eigenfunctions
3134 // so zero out off diagonal lagrange multipliers
3135 for (int i=0; i<param.nmo_alpha; i++) {
3136 if (aocc_mp[i] != 1.0) {
3137 double tmp = focka(i,i);
3138 focka(i,_) = 0.0;
3139 focka(_,i) = 0.0;
3140 focka(i,i) = tmp;
3141 }
3142 }
3143
3144 vecfuncT rm = compute_residual(world, aocc_mp, focka, amo_mp, Vpsia, aerr);
3145 if(param.nbeta != 0 && !param.spin_restricted){
3146 for (int i=0; i<param.nmo_beta; i++) {
3147 if (bocc_mp[i] != 1.0) {
3148 double tmp = fockb(i,i);
3149 fockb(i,_) = 0.0;
3150 fockb(_,i) = 0.0;
3151 fockb(i,i) = tmp;
3152 }
3153 }
3154
3155 vecfuncT br = compute_residual(world, bocc, fockb, bmo_mp, Vpsib, berr);
3156 vm.insert(vm.end(), bmo_mp.begin(), bmo_mp.end());
3157 rm.insert(rm.end(), br.begin(), br.end());
3158 }
3159 bsh_residual = std::max(aerr, berr);
3160 world.gop.broadcast(bsh_residual, 0);
3161 compress(world, vm, false);
3162 compress(world, rm, false);
3163 world.gop.fence();
3164 subspace.push_back(pairvecfuncT(vm, rm));
3165 int m = subspace.size();
3166 tensorT ms(m);
3167 tensorT sm(m);
3168 for(int s = 0;s < m;++s){
3169 const vecfuncT & vs = subspace[s].first;
3170 const vecfuncT & rs = subspace[s].second;
3171 for(unsigned int i = 0;i < vm.size();++i){
3172 ms[s] += vm[i].inner_local(rs[i]);
3173 sm[s] += vs[i].inner_local(rm[i]);
3174 }
3175 }
3176
3177 world.gop.sum(ms.ptr(), m);
3178 world.gop.sum(sm.ptr(), m);
3179 tensorT newQ(m, m);
3180 if(m > 1)
3181 newQ(Slice(0, -2), Slice(0, -2)) = Q;
3182
3183 newQ(m - 1, _) = ms;
3184 newQ(_, m - 1) = sm;
3185 Q = newQ;
3186 //if (world.rank() == 0) { print("kain Q"); print(Q); }
3187 tensorT c;
3188 if(world.rank() == 0){
3189 double rcond = 1e-12;
3190 while(1){
3191 c = KAIN(Q, rcond);
3192 //if (world.rank() == 0) print("kain c:", c);
3193 if(std::abs(c[m - 1]) < 3.0){
3194 break;
3195 } else if(rcond < 0.01){
3196 print("Increasing subspace singular value threshold ", c[m - 1], rcond);
3197 rcond *= 100;
3198 } else {
3199 print("Forcing full step due to subspace malfunction");
3200 c = 0.0;
3201 c[m - 1] = 1.0;
3202 break;
3203 }
3204 }
3205 }
3206
3207 world.gop.broadcast_serializable(c, 0);
3208 if(world.rank() == 0){
3209 print("Subspace solution", c);
3210 }
3211 START_TIMER(world);
3212 vecfuncT amo_new = zero_functions<double,3>(world, amo_mp.size());
3213 vecfuncT bmo_new = zero_functions<double,3>(world, bmo_mp.size());
3214 compress(world, amo_new, false);
3215 compress(world, bmo_new, false);
3216 world.gop.fence();
3217 for(unsigned int m = 0;m < subspace.size();++m){
3218 const vecfuncT & vm = subspace[m].first;
3219 const vecfuncT & rm = subspace[m].second;
3220 const vecfuncT vma(vm.begin(), vm.begin() + amo_mp.size());
3221 const vecfuncT rma(rm.begin(), rm.begin() + amo_mp.size());
3222 const vecfuncT vmb(vm.end() - bmo_mp.size(), vm.end());
3223 const vecfuncT rmb(rm.end() - bmo_mp.size(), rm.end());
3224 gaxpy(world, 1.0, amo_new, c(m), vma, false);
3225 gaxpy(world, 1.0, amo_new, -c(m), rma, false);
3226 gaxpy(world, 1.0, bmo_new, c(m), vmb, false);
3227 gaxpy(world, 1.0, bmo_new, -c(m), rmb, false);
3228 }
3229 world.gop.fence();
3230 END_TIMER(world, "Subspace transform");
3231 if(param.maxsub <= 1){
3232 subspace.clear();
3233 } else if(subspace.size() == param.maxsub){
3234 subspace.erase(subspace.begin());
3235 Q = Q(Slice(1, -1), Slice(1, -1));
3236 }
3237
3238 std::vector<double> anorm = norm2s(world, sub(world, amo_mp, amo_new));
3239 std::vector<double> bnorm = norm2s(world, sub(world, bmo_mp, bmo_new));
3240 int nres = 0;
3241 for(unsigned int i = 0;i < amo_mp.size();++i){
3242 if(anorm[i] > param.maxrotn){
3243 double s = param.maxrotn / anorm[i];
3244 ++nres;
3245 if(world.rank() == 0){
3246 if(nres == 1)
3247 printf(" restricting step for alpha orbitals:");
3248
3249 printf(" %d", i);
3250 }
3251 amo_new[i].gaxpy(s, amo_mp[i], 1.0 - s, false);
3252 }
3253
3254 }
3255 if(nres > 0 && world.rank() == 0)
3256 printf("\n");
3257
3258 nres = 0;
3259 for(unsigned int i = 0;i < bmo_mp.size();++i){
3260 if(bnorm[i] > param.maxrotn){
3261 double s = param.maxrotn / bnorm[i];
3262 ++nres;
3263 if(world.rank() == 0){
3264 if(nres == 1)
3265 printf(" restricting step for beta orbitals:");
3266
3267 printf(" %d", i);
3268 }
3269 bmo_new[i].gaxpy(s, bmo_mp[i], 1.0 - s, false);
3270 }
3271
3272 }
3273 if(nres > 0 && world.rank() == 0)
3274 printf("\n");
3275
3276 world.gop.fence();
3277 double rms, maxval;
3278 vector_stats(anorm, rms, maxval);
3279 if(world.rank() == 0)
3280 print("Norm of vector changes alpha: rms", rms, " max", maxval);
3281
3282 update_residual = maxval;
3283 if(bnorm.size()){
3284 vector_stats(bnorm, rms, maxval);
3285 if(world.rank() == 0)
3286 print("Norm of vector changes beta: rms", rms, " max", maxval);
3287
3288 update_residual = std::max(update_residual, maxval);
3289 }
3290 START_TIMER(world);
3291 double trantol = vtol / std::min(30.0, double(amo_mp.size()));
3292 normalize(world, amo_new);
3293 amo_new = transform(world, amo_new, Q3(matrix_inner(world, amo_new, amo_new)), trantol, true);
3294 truncate(world, amo_new);
3295 normalize(world, amo_new);
3296 if(param.nbeta != 0 && !param.spin_restricted){
3297 normalize(world, bmo_new);
3298 bmo_new = transform(world, bmo_new, Q3(matrix_inner(world, bmo_new, bmo_new)), trantol, true);
3299 truncate(world, bmo_new);
3300 normalize(world, bmo_new);
3301 }
3302 END_TIMER(world, "Orthonormalize");
3303 amo_mp = amo_new;
3304 bmo_mp = bmo_new;
3305 }
3306
3307 // template <typename Func>
3308 // void propagate(World& world, const Func& Vext, int step0)
3309 void propagate(World& world, double omega, int step0)
3310 {
3311 // Load molecular orbitals
3312 set_protocol(world,1e-4);
3313 make_nuclear_potential(world);
3314 initial_load_bal(world);
3315 load_mos(world);
3316
3317 int nstep = 1000;
3318 double time_step = 0.05;
3319
3320 double strength = 0.1;
3321
3322 // temporary way of doing this for now
3323 // VextCosFunctor<double> Vext(world,new DipoleFunctor(2),omega);
3324 functionT fdipx = factoryT(world).functor(functorT(new DipoleFunctor(0))).initial_level(4);
3325 functionT fdipy = factoryT(world).functor(functorT(new DipoleFunctor(1))).initial_level(4);
3326 functionT fdipz = factoryT(world).functor(functorT(new DipoleFunctor(2))).initial_level(4);
3327
3328 world.gop.broadcast(time_step);
3329 world.gop.broadcast(nstep);
3330
3331 // Need complex orbitals :(
3332 double thresh = 1e-4;
3333 cvecfuncT camo = zero_functions<double_complex,3>(world, param.nalpha);
3334 cvecfuncT cbmo = zero_functions<double_complex,3>(world, param.nbeta);
3335 for (int iorb = 0; iorb < param.nalpha; iorb++)
3336 {
3337 camo[iorb] = std::exp(double_complex(0.0,2*constants::pi*strength))*amo[iorb];
3338 camo[iorb].truncate(thresh);
3339 }
3340 if (!param.spin_restricted && param.nbeta) {
3341 for (int iorb = 0; iorb < param.nbeta; iorb++)
3342 {
3343 cbmo[iorb] = std::exp(double_complex(0.0,2*constants::pi*strength))*bmo[iorb];
3344 cbmo[iorb].truncate(thresh);
3345 }
3346 }
3347
3348 // Create free particle propagator
3349 // Have no idea what to set "c" to
3350 double c = 20.0;
3351 printf("Creating G\n");
3352 Convolution1D<double_complex>* G = qm_1d_free_particle_propagator(FunctionDefaults<3>::get_k(), c, 0.5*time_step, 2.0*param.L);
3353 printf("Done creating G\n");
3354
3355 // Start iteration over time
3356 for (int step = 0; step < nstep; step++)
3357 {
3358 // if (world.rank() == 0) printf("Iterating step %d:\n\n", step);
3359 double t = time_step*step;
3360 // iterate_trotter(world, G, Vext, camo, cbmo, t, time_step);
3361 iterate_trotter(world, G, camo, cbmo, t, time_step, thresh);
3362 functionT arho = make_density(world,aocc,camo);
3363 functionT brho = (!param.spin_restricted && param.nbeta) ?
3364 make_density(world,aocc,camo) : copy(arho);
3365 functionT rho = arho + brho;
3366 double xval = inner(fdipx,rho);
3367 double yval = inner(fdipy,rho);
3368 double zval = inner(fdipz,rho);
3369 if (world.rank() == 0) printf("%15.7f%15.7f%15.7f%15.7f\n", t, xval, yval, zval);
3370 }
3371
3372
3373 }
3374
3375 complex_functionT APPLY(const complex_operatorT* q1d, const complex_functionT& psi) {
3376 complex_functionT r = psi; // Shallow copy violates constness !!!!!!!!!!!!!!!!!
3377 coordT lo, hi;
3378 lo[2] = -10;
3379 hi[2] = +10;
3380
3381 r.reconstruct();
3382 r.broaden();
3383 r.broaden();
3384 r.broaden();
3385 r.broaden();
3386 r = apply_1d_realspace_push(*q1d, r, 2); r.sum_down();
3387 r = apply_1d_realspace_push(*q1d, r, 1); r.sum_down();
3388 r = apply_1d_realspace_push(*q1d, r, 0); r.sum_down();
3389
3390 return r;
3391 }
3392
3393 void iterate_trotter(World& world,
3394 Convolution1D<double_complex>* G,
3395 cvecfuncT& camo,
3396 cvecfuncT& cbmo,
3397 double t,
3398 double time_step,
3399 double thresh)
3400 {
3401
3402 // first kinetic energy apply
3403 cvecfuncT camo2 = zero_functions<double_complex,3>(world, param.nalpha);
3404 cvecfuncT cbmo2 = zero_functions<double_complex,3>(world, param.nbeta);
3405 for (int iorb = 0; iorb < param.nalpha; iorb++)
3406 {
3407 // if (world.rank()) printf("Apply free-particle Green's function to alpha orbital %d\n", iorb);
3408 camo2[iorb] = APPLY(G,camo[iorb]);
3409 camo2[iorb].truncate(thresh);
3410 }
3411 if(!param.spin_restricted && param.nbeta)
3412 {
3413 for (int iorb = 0; iorb < param.nbeta; iorb++)
3414 {
3415 cbmo2[iorb] = APPLY(G,cbmo[iorb]);
3416 cbmo2[iorb].truncate(thresh);
3417 }
3418 }
3419 // Construct new density
3420 // START_TIMER(world);
3421 functionT arho = make_density(world, aocc, amo), brho;
3422
3423 if (param.nbeta) {
3424 if (param.spin_restricted) {
3425 brho = arho;
3426 }
3427 else {
3428 brho = make_density(world, bocc, bmo);
3429 }
3430 }
3431 else {
3432 brho = functionT(world); // zero
3433 }
3434 functionT rho = arho + brho;
3435 // END_TIMER(world, "Make densities");
3436
3437 // Do RPA only for now
3438 real_function_3d vnuc = potentialmanager->vnuclear();
3439 functionT vlocal = vnuc;
3440 // START_TIMER(world);
3441 functionT vcoul = apply(*coulop, rho);
3442 // END_TIMER(world, "Coulomb");
3443 // vlocal += vcoul + Vext(t+0.5*time_step);
3444 // vlocal += vcoul + std::cos(0.1*(t+0.5*time_step))*fdip;
3445
3446 // exponentiate potential
3447 // if (world.rank()) printf("Apply Kohn-Sham potential to orbitals\n");
3448 complex_functionT expV = make_exp(time_step, vlocal);
3449 cvecfuncT camo3 = mul_sparse(world,expV,camo2,vtol,false);
3450 world.gop.fence();
3451
3452
3453 // second kinetic energy apply
3454 for (int iorb = 0; iorb < param.nalpha; iorb++)
3455 {
3456 // if (world.rank() == 0) printf("Apply free-particle Green's function to alpha orbital %d\n", iorb);
3457 camo3[iorb].truncate(thresh);
3458 camo[iorb] = APPLY(G,camo3[iorb]);
3459 camo[iorb].truncate();
3460 }
3461 if (!param.spin_restricted && param.nbeta)
3462 {
3463 cvecfuncT cbmo3 = mul_sparse(world,expV,cbmo2,vtol,false);
3464
3465 // second kinetic energy apply
3466 for (int iorb = 0; iorb < param.nbeta; iorb++)
3467 {
3468 cbmo[iorb] = APPLY(G,cbmo3[iorb]);
3469 cbmo[iorb].truncate();
3470 }
3471 }
3472 }
3473
3474 // void solve_gas_phase(World & world)
3475 // {
3476 // functionT arho_old, brho_old;
3477 // const double dconv = std::max(FunctionDefaults<3>::get_thresh(), param.dconv);
3478 // const double trantol = vtol / std::min(30.0, double(amo.size()));
3479 // const double tolloc = 1e-3;
3480 // double update_residual = 0.0, bsh_residual = 0.0;
3481 // subspaceT subspace;
3482 // tensorT Q;
3483 // bool do_this_iter = true;
3484 // // Shrink subspace until stop localizing/canonicalizing
3485 // int maxsub_save = param.maxsub;
3486 // param.maxsub = 2;
3487
3488 // for(int iter = 0;iter < param.maxiter;++iter){
3489 // if(world.rank() == 0)
3490 // printf("\nIteration %d at time %.1fs\n\n", iter, wall_time());
3491
3492 // if (iter > 0 && update_residual < 0.1) {
3493 // //do_this_iter = false;
3494 // param.maxsub = maxsub_save;
3495 // }
3496
3497 // if(param.localize && do_this_iter) {
3498 // tensorT U;
3499 // if (param.localize_pm) {
3500 // U = localize_PM(world, amo, aset, tolloc, 0.25, iter == 0);
3501 // }
3502 // else {
3503 // U = localize_boys(world, amo, aset, tolloc, 0.25, iter==0);
3504 // }
3505 // amo = transform(world, amo, U, trantol, true);
3506 // truncate(world, amo);
3507 // normalize(world, amo);
3508 // rotate_subspace(world, U, subspace, 0, amo.size(), trantol);
3509 // if(!param.spin_restricted && param.nbeta != 0 ){
3510 // if (param.localize_pm) {
3511 // U = localize_PM(world, bmo, bset, tolloc, 0.25, iter == 0);
3512 // }
3513 // else {
3514 // U = localize_boys(world, bmo, bset, tolloc, 0.25, iter==0);
3515 // }
3516 // bmo = transform(world, bmo, U, trantol, true);
3517 // truncate(world, bmo);
3518 // normalize(world, bmo);
3519 // rotate_subspace(world, U, subspace, amo.size(), bmo.size(), trantol);
3520 // }
3521 // }
3522
3523 // START_TIMER(world);
3524 // functionT arho = make_density(world, aocc, amo), brho;
3525
3526 // if (param.nbeta) {
3527 // if (param.spin_restricted) {
3528 // brho = arho;
3529 // }
3530 // else {
3531 // brho = make_density(world, bocc, bmo);
3532 // }
3533 // }
3534 // else {
3535 // brho = functionT(world); // zero
3536 // }
3537 // END_TIMER(world, "Make densities");
3538
3539 // if(iter < 2 || (iter % 10) == 0){
3540 // START_TIMER(world);
3541 // loadbal(world, arho, brho, arho_old, brho_old, subspace);
3542 // END_TIMER(world, "Load balancing");
3543 // }
3544 // double da = 0.0, db = 0.0;
3545 // if(iter > 0){
3546 // da = (arho - arho_old).norm2();
3547 // db = (brho - brho_old).norm2();
3548 // if(world.rank() == 0)
3549 // print("delta rho", da, db, "residuals", bsh_residual, update_residual);
3550
3551 // }
3552
3553 // arho_old = arho;
3554 // brho_old = brho;
3555 // functionT rho = arho + brho;
3556 // vacuo_rho = arho + brho;
3557 // //double Xrhotrace = rho.trace(); // DEBUG
3558 // rho.truncate();
3559 // double enuclear = inner(rho, vnuc);
3560
3561 // // DEBUG
3562 // // double rhotrace = rho.trace();
3563 // // double vnuctrace = vnuc.trace();
3564 // // if (world.rank() == 0) printf("DEBUG %.12f %.12f %.12f\n", Xrhotrace, rhotrace, vnuctrace);
3565 // // END DEBUG
3566
3567 // START_TIMER(world);
3568 // functionT vcoul = apply(*coulop, rho);
3569 // END_TIMER(world, "Coulomb");
3570
3571 // double ecoulomb = 0.5 * inner(rho, vcoul);
3572 // rho.clear(false);
3573 // functionT vlocal = vcoul + vnuc;
3574 // vcoul.clear(false);
3575 // vlocal.truncate();
3576 // double exca = 0.0, excb = 0.0;
3577
3578 // vecfuncT vf, delrho;
3579 // if (xc.is_dft()) {
3580 // arho.reconstruct();
3581 // if (param.nbeta != 0 && xc.is_spin_polarized()) brho.reconstruct();
3582 // // brho.reconstruct();
3583
3584 // vf.push_back(arho);
3585
3586 // if (xc.is_spin_polarized()) vf.push_back(brho);
3587
3588 // if (xc.is_gga()) {
3589
3590 // for (int axis=0; axis<3; ++axis) delrho.push_back((*gradop[axis])(arho,false)); // delrho
3591 // if (xc.is_spin_polarized())
3592 // for (int axis=0; axis<3; ++axis) delrho.push_back((*gradop[axis])(brho,true));
3593
3594
3595 // world.gop.fence(); // NECESSARY
3596
3597 // vf.push_back(delrho[0]*delrho[0]+delrho[1]*delrho[1]+delrho[2]*delrho[2]); // sigma_aa
3598
3599 // if (xc.is_spin_polarized())
3600 // vf.push_back(delrho[0]*delrho[3]+delrho[1]*delrho[4]+delrho[2]*delrho[5]); // sigma_ab
3601 // if (xc.is_spin_polarized())
3602 // vf.push_back(delrho[3]*delrho[3]+delrho[4]*delrho[4]+delrho[5]*delrho[5]); // sigma_bb
3603
3604 // for (int axis=0; axis<3; ++axis) vf.push_back(delrho[axis]); // dda_x
3605
3606 // if (xc.is_spin_polarized())
3607 // for (int axis=0; axis<3; ++axis) vf.push_back(delrho[axis + 3]); // ddb_x
3608 // world.gop.fence(); // NECESSARY
3609 // }
3610 // if (vf.size()) {
3611 // reconstruct(world, vf);
3612 // arho.refine_to_common_level(vf); // Ugly but temporary (I hope!)
3613 // }
3614 // }
3615
3616 // vecfuncT Vpsia = apply_potential(world, aocc, amo, vf, delrho, vlocal, exca, 0);
3617 // vecfuncT Vpsib;
3618 // if(!param.spin_restricted && param.nbeta) {
3619 // Vpsib = apply_potential(world, bocc, bmo, vf, delrho, vlocal, excb, 1);
3620 // }
3621
3622 // double ekina = 0.0, ekinb = 0.0;
3623 // tensorT focka = make_fock_matrix(world, amo, Vpsia, aocc, ekina);
3624 // tensorT fockb = focka;
3625
3626 // if (!param.spin_restricted && param.nbeta != 0)
3627 // fockb = make_fock_matrix(world, bmo, Vpsib, bocc, ekinb);
3628 // else if (param.nbeta != 0) {
3629 // ekinb = ekina;
3630 // }
3631 // if (!param.localize && do_this_iter) {
3632 // tensorT U = diag_fock_matrix(world, focka, amo, Vpsia, aeps, aocc, FunctionDefaults<3>::get_thresh());
3633 // rotate_subspace(world, U, subspace, 0, amo.size(), trantol);
3634 // if (!param.spin_restricted && param.nbeta != 0) {
3635 // U = diag_fock_matrix(world, fockb, bmo, Vpsib, beps, bocc, FunctionDefaults<3>::get_thresh());
3636 // rotate_subspace(world, U, subspace, amo.size(), bmo.size(), trantol);
3637 // }
3638 // }
3639
3640
3641 // double enrep = molecule.nuclear_repulsion_energy();
3642 // double ekinetic = ekina + ekinb;
3643 // double exc = exca + excb;
3644 // double etot = ekinetic + enuclear + ecoulomb + exc + enrep;
3645 // current_energy = etot;
3646 // vacuo_energy = etot;
3647
3648 // if(world.rank() == 0){
3649 // printf("\n kinetic %16.8f\n", ekinetic);
3650 // printf(" nuclear attraction %16.8f\n", enuclear);
3651 // printf(" coulomb %16.8f\n", ecoulomb);
3652 // printf(" exchange-correlation %16.8f\n", exc);
3653 // printf(" nuclear-repulsion %16.8f\n", enrep);
3654 // printf(" total %16.8f\n\n", etot);
3655 // }
3656
3657 // if(iter > 0){
3658 // //print("##convergence criteria: density delta=", da < dconv * molecule.natom() && db < dconv * molecule.natom(), ", bsh_residual=", (param.conv_only_dens || bsh_residual < 5.0*dconv));
3659 // if(da < dconv * molecule.natom() && db < dconv * molecule.natom() && (param.conv_only_dens || bsh_residual < 5.0*dconv)){
3660 // if(world.rank() == 0) {
3661 // print("\nConverged!\n");
3662 // }
3663
3664 // // Diagonalize to get the eigenvalues and if desired the final eigenvectors
3665 // START_TIMER(world);
3666 // tensorT U;
3667 // tensorT overlap = matrix_inner(world, amo, amo, true);
3668
3669 // sygvp(world, focka, overlap, 1, U, aeps);
3670 // END_TIMER(world, " compute eigen alpha sygv ");
3671
3672 // if (!param.localize) {
3673 // amo = transform(world, amo, U, trantol, true);
3674 // truncate(world, amo);
3675 // normalize(world, amo);
3676 // }
3677
3678 // if(param.nbeta != 0 && !param.spin_restricted){
3679 // START_TIMER(world);
3680 // overlap = matrix_inner(world, bmo, bmo, true);
3681
3682 // sygvp(world, fockb, overlap, 1, U, beps);
3683 // END_TIMER(world, " compute eigen beta sygv");
3684
3685 // if (!param.localize) {
3686 // bmo = transform(world, bmo, U, trantol, true);
3687 // truncate(world, bmo);
3688 // normalize(world, bmo);
3689 // }
3690 // }
3691
3692 // if(world.rank() == 0) {
3693 // print(" ");
3694 // print("alpha eigenvalues");
3695 // print(aeps);
3696 // if(param.nbeta != 0.0 && !param.spin_restricted){
3697 // print("beta eigenvalues");
3698 // print(beps);
3699 // }
3700 // }
3701
3702 // if (param.localize) {
3703 // // Restore the diagonal elements for the analysis
3704 // for (unsigned int i=0; i<amo.size(); ++i) aeps[i] = focka(i,i);
3705 // for (unsigned int i=0; i<bmo.size(); ++i) beps[i] = fockb(i,i);
3706 // }
3707
3708 // break;
3709 // }
3710
3711 // }
3712
3713 // update_subspace(world, Vpsia, Vpsib, focka, fockb, subspace, Q, bsh_residual, update_residual);
3714 // }
3715
3716
3717 // {
3718 // // Analyze molecule volume and surface areas
3719 // functionT arho = make_density(world, aocc, amo), brho;
3720 // if (param.nbeta) {
3721 // if (param.spin_restricted) {
3722 // brho = arho;
3723 // }
3724 // else {
3725 // brho = make_density(world, bocc, bmo);
3726 // }
3727 // }
3728 // //const double rho0 = 0.00048;
3729 // const double rho0 = 0.00078;
3730 // const double beta = 1.3;
3731 // arho += brho; // total density
3732 // functionT c = copy(arho);
3733 // c.unaryop(DensityIsosurfaceCharacteristic<3>(rho0,beta));
3734 // plot_line("density.dat",1001, {0.0,0.0,-20.0}, {0.0,0.0,20.0}, arho);
3735 // plot_line("volume.dat",1001, {0.0,0.0,-20.0}, {0.0,0.0,20.0}, c);
3736
3737 // double volume = c.trace();
3738 // double facvol = std::pow(constants::atomic_unit_of_length*1e10,3.0);
3739 // if (world.rank() == 0) print("\nMolecular volume:",volume,"a.u.",volume*facvol,"Angstrom^3");
3740 // if (world.rank() == 0) print("Equivalent sphere radius",std::pow(3.0*volume/4.0/constants::pi,1.0/3.0),"a.u.");
3741
3742 // c = copy(arho);
3743 // c.unaryop(DensityIsosurfaceCharacteristicDerivative<3>(rho0,beta));
3744 // plot_line("surface.dat",1001, {0.0,0.0,-20.0}, {0.0,0.0,20.0}, c);
3745
3746 // c = c*c*((*gradop[0])(arho).square() + (*gradop[1])(arho).square() + (*gradop[2])(arho).square());
3747 // double area = c.trace();
3748 // double facarea = std::pow(constants::atomic_unit_of_length*1e10,2.0);
3749 // if (world.rank() == 0) print("\nMolecular surface area:",area,"a.u.",area*facarea,"Angstrom^2");
3750 // if (world.rank() == 0) print("Equivalent sphere radius",std::sqrt(area/4.0/constants::pi),"a.u.");
3751 // }
3752
3753 // if (world.rank() == 0) {
3754 // if (param.localize) print("Orbitals are localized - energies are diagonal Fock matrix elements\n");
3755 // else print("Orbitals are eigenvectors - energies are eigenvalues\n");
3756 // print("Analysis of alpha MO vectors");
3757 // }
3758
3759 // analyze_vectors(world, amo, aocc, aeps);
3760 // if (param.nbeta != 0 && !param.spin_restricted) {
3761 // if (world.rank() == 0)
3762 // print("Analysis of beta MO vectors");
3763
3764 // analyze_vectors(world, bmo, bocc, beps);
3765 // }
3766 // if(world.rank()==0){
3767 // print("\n\n\n");
3768 // print(" ------------------------------------------------------------------------------");
3769 // print(" | MADNESS SOLVATION MODULE |");
3770 // print(" ------------------------------------------------------------------------------");
3771 // print(" \n\n");
3772 // }
3773 // //print("Entrying Solvation Module \n\n");
3774 // }// end gas_phase function
3775 // // For given protocol, solve the DFT/HF/response equations
3776 void solve(World & world)
3777 {
3778 functionT arho_old, brho_old;
3779 const double dconv = std::max(FunctionDefaults<3>::get_thresh(), param.dconv);
3780 const double trantol = vtol / std::min(30.0, double(amo.size()));
3781 const double tolloc = 1e-3;
3782 double update_residual = 0.0, bsh_residual = 0.0;
3783 subspaceT subspace;
3784 tensorT Q;
3785 bool do_this_iter = true;
3786 // Shrink subspace until stop localizing/canonicalizing
3787 int maxsub_save = param.maxsub;
3788 param.maxsub = 2;
3789
3790 // if(param.absolvent){ //param.physisorption||param.svpe||
3791 // functorT rhon_functor(new NuclearDensityFunctor(molecule));
3792 // if (world.rank()==0)
3793 // print("Projecting Nuclear Charge Density");
3794 // rhon = real_factory_3d(world).functor(rhon_functor).truncate_on_project().truncate_mode(0); // nuclear charge density//Jacob added
3795 // rhon.truncate();
3796 // // coord_3d lo(0.0), hi(0.0);
3797 // //lo[0] = -20.0;
3798 // // hi[0] = 20.0;
3799 // double total_rhon = rhon.trace();
3800 // if(world.rank()==0)
3801 // print("Nuclear Charge ", total_rhon);
3802
3803 // }
3804 /* //Initial electrostatic potential for DFT solvation moldel
3805 if(param.absolvent){
3806 rhoT = rhon - vacuo_rho;
3807 real_convolution_3d op = madness::CoulombOperator(world, param.lo, param.lo);
3808 functionT U_guess = op(rhoT);
3809 print("TOTAL CHARGE", rhoT.trace());
3810 DFTSolventSolver DFTSsolver(vacuo_rho,rhoT,param.rho_0,param.epsilon_2,param.maxiter,world,param.Gamma,param.beta \
3811 ,std::max(1e-5,1e-7));
3812 Uabinit = DFTSsolver.ESP(U_guess);
3813 }*/
3814 for(int iter = 0;iter < param.maxiter;++iter){
3815 if(world.rank() == 0)
3816 printf("\nIteration %d at time %.1fs\n\n", iter, wall_time());
3817
3818 if (iter > 0 && update_residual < 0.1) {
3819 //do_this_iter = false;
3820 param.maxsub = maxsub_save;
3821 }
3822
3823 if(param.localize && do_this_iter) {
3824 tensorT U;
3825 if (param.localize_pm) {
3826 U = localize_PM(world, amo, aset, tolloc, 0.25, iter == 0, true);
3827 }
3828 else {
3829 U = localize_boys(world, amo, aset, tolloc, 0.25, iter==0);
3830 }
3831 amo = transform(world, amo, U, trantol, true);
3832 truncate(world, amo);
3833 normalize(world, amo);
3834 rotate_subspace(world, U, subspace, 0, amo.size(), trantol);
3835 if(!param.spin_restricted && param.nbeta != 0 ){
3836 if (param.localize_pm) {
3837 U = localize_PM(world, bmo, bset, tolloc, 0.25, iter == 0, true);
3838 }
3839 else {
3840 U = localize_boys(world, bmo, bset, tolloc, 0.25, iter==0);
3841 }
3842 bmo = transform(world, bmo, U, trantol, true);
3843 truncate(world, bmo);
3844 normalize(world, bmo);
3845 rotate_subspace(world, U, subspace, amo.size(), bmo.size(), trantol);
3846 }
3847 }
3848
3849 START_TIMER(world);
3850 functionT arho = make_density(world, aocc, amo), brho;
3851
3852 if (param.nbeta) {
3853 if (param.spin_restricted) {
3854 brho = arho;
3855 }
3856 else {
3857 brho = make_density(world, bocc, bmo);
3858 }
3859 }
3860 else {
3861 brho = functionT(world); // zero
3862 }
3863 END_TIMER(world, "Make densities");
3864 print_meminfo(world.rank(), "Make densities");
3865
3866 if(iter < 2 || (iter % 10) == 0){
3867 START_TIMER(world);
3868 loadbal(world, arho, brho, arho_old, brho_old, subspace);
3869 END_TIMER(world, "Load balancing");
3870 print_meminfo(world.rank(), "Load balancing");
3871 }
3872 double da = 0.0, db = 0.0;
3873 if(iter > 0){
3874 da = (arho - arho_old).norm2();
3875 db = (brho - brho_old).norm2();
3876 if(world.rank() == 0)
3877 print("delta rho", da, db, "residuals", bsh_residual, update_residual);
3878
3879 }
3880
3881 arho_old = arho;
3882 brho_old = brho;
3883 functionT rho = arho + brho;
3884 // rho_elec = rho;// to be used in the solvent solver
3885 //print("Rho Elec Solvent , Gas Phase Density ", rho_elec.trace(), vacuo_rho.trace()); // DEBUG
3886 // double Xrhoetrace = rho_elec.trace(); //DEBUG
3887 rho.truncate();
3888 real_function_3d vnuc = potentialmanager->vnuclear();
3889 double enuclear = inner(rho, vnuc);
3890
3891 // DEBUG
3892 //double rhotrace = rho.trace();
3893 //double vnuctrace = vnuc.trace();
3894 // if (world.rank() == 0) printf("DEBUG %.12f %.12f %.12f\n", Xrhoetrace, rhotrace, vnuctrace);
3895 // END DEBUG
3896
3897 START_TIMER(world);
3898 functionT vcoul = apply(*coulop, rho);
3899 functionT vlocal;
3900 END_TIMER(world, "Coulomb");
3901 print_meminfo(world.rank(), "Coulomb");
3902
3903 double ecoulomb = 0.5 * inner(rho, vcoul);
3904 rho.clear(false);
3905 // /*==========================================================================================
3906 // Instantiating SVPE and Isodensity solvation models
3907 // ============================================================================================*/
3908 // if (param.absolvent){
3909 // //Abinitio Solvation Model
3910 // rhoT = rhon - rho_elec;
3911 // // print("DEBUG TOTAL CHARGE", rhoT.trace());
3912 // DFTSolventSolver DFTSsolver(vacuo_rho,rhoT,param.rho_0,param.epsilon_2,param.maxiter,world,param.Gamma,param.beta
3913 // ,std::max(1e-5,1e-6));
3914 // Uabinit = DFTSsolver.ESP();
3915 // real_functor_3d molecular_mask_functor(new MolecularVolumeMask(param.sigma,molecule.atomic_radii
3916 // ,molecule.get_all_coords_vec()));
3917 // //print("DEBUG Interaction Pot", Uabinit.trace());
3918 // // mol_mask = real_factory_3d(world).functor(molecular_mask_functor);
3919 // }
3920 // if(param.absolvent)
3921 // vlocal = vcoul + vnuc + Uabinit;
3922 // else
3923 vlocal = vcoul + vnuc ;
3924
3925 vcoul.clear(false);
3926 vlocal.truncate();
3927 double exca = 0.0, excb = 0.0;
3928
3929 vecfuncT vf, delrho;
3930 if (xc.is_dft()) {
3931 arho.reconstruct();
3932 if (param.nbeta != 0 && xc.is_spin_polarized()) brho.reconstruct();
3933 // brho.reconstruct();
3934
3935 vf.push_back(arho);
3936
3937 if (xc.is_spin_polarized()) vf.push_back(brho);
3938
3939 if (xc.is_gga()) {
3940
3941 for (int axis=0; axis<3; ++axis) delrho.push_back((*gradop[axis])(arho,false)); // delrho
3942 if (xc.is_spin_polarized())
3943 for (int axis=0; axis<3; ++axis) delrho.push_back((*gradop[axis])(brho,false));
3944
3945
3946 world.gop.fence(); // NECESSARY
3947
3948 vf.push_back(delrho[0]*delrho[0]+delrho[1]*delrho[1]+delrho[2]*delrho[2]); // sigma_aa
3949
3950 if (xc.is_spin_polarized())
3951 vf.push_back(delrho[0]*delrho[3]+delrho[1]*delrho[4]+delrho[2]*delrho[5]); // sigma_ab
3952 if (xc.is_spin_polarized())
3953 vf.push_back(delrho[3]*delrho[3]+delrho[4]*delrho[4]+delrho[5]*delrho[5]); // sigma_bb
3954
3955 for (int axis=0; axis<3; ++axis) vf.push_back(delrho[axis]); // dda_x
3956
3957 if (xc.is_spin_polarized())
3958 for (int axis=0; axis<3; ++axis) vf.push_back(delrho[axis + 3]); // ddb_x
3959 world.gop.fence(); // NECESSARY
3960 }
3961 if (vf.size()) {
3962 reconstruct(world, vf);
3963 arho.refine_to_common_level(vf); // Ugly but temporary (I hope!)
3964 }
3965 }
3966
3967 vecfuncT Vpsia = apply_potential(world, aocc, amo, vf, delrho, vlocal, exca, 0);
3968
3969 vecfuncT Vpsib;
3970 if(!param.spin_restricted && param.nbeta) {
3971 Vpsib = apply_potential(world, bocc, bmo, vf, delrho, vlocal, excb, 1);
3972 }
3973
3974 double ekina = 0.0, ekinb = 0.0;
3975 tensorT focka = make_fock_matrix(world, amo, Vpsia, aocc, ekina);
3976 tensorT fockb = focka;
3977
3978 if (!param.spin_restricted && param.nbeta != 0)
3979 fockb = make_fock_matrix(world, bmo, Vpsib, bocc, ekinb);
3980 else if (param.nbeta != 0) {
3981 ekinb = ekina;
3982 }
3983
3984 if (!param.localize && do_this_iter) {
3985 tensorT U = diag_fock_matrix(world, focka, amo, Vpsia, aeps, aocc, FunctionDefaults<3>::get_thresh());
3986 rotate_subspace(world, U, subspace, 0, amo.size(), trantol);
3987 if (!param.spin_restricted && param.nbeta != 0) {
3988 U = diag_fock_matrix(world, fockb, bmo, Vpsib, beps, bocc, FunctionDefaults<3>::get_thresh());
3989 rotate_subspace(world, U, subspace, amo.size(), bmo.size(), trantol);
3990 }
3991 }
3992
3993 double enrep = molecule.nuclear_repulsion_energy();
3994 double ekinetic = ekina + ekinb;
3995 double exc = exca + excb;
3996 //double etot = ekinetic + enuclear + ecoulomb + exc + enrep + edipole;
3997 double etot = ekinetic + enuclear + ecoulomb + exc + enrep;
3998 current_energy = etot;
3999 esol = etot;
4000
4001 if(world.rank() == 0){
4002 printf("\n kinetic %16.8f\n", ekinetic);
4003 printf(" nuclear attraction %16.8f\n", enuclear);
4004 printf(" coulomb %16.8f\n", ecoulomb);
4005 printf(" exchange-correlation %16.8f\n", exc);
4006 printf(" nuclear-repulsion %16.8f\n", enrep);
4007 printf(" total %16.8f\n\n", etot);
4008 }
4009
4010 if(iter > 0){
4011 //print("##convergence criteria: density delta=", da < dconv * molecule.natom() && db < dconv * molecule.natom(), ", bsh_residual=", (param.conv_only_dens || bsh_residual < 5.0*dconv));
4012 if(da < dconv * molecule.natom() && db < dconv * molecule.natom() && (param.conv_only_dens || bsh_residual < 5.0*dconv)){
4013 if(world.rank() == 0) {
4014 print("\nConverged!\n");
4015 }
4016
4017 // Diagonalize to get the eigenvalues and if desired the final eigenvectors
4018 tensorT U;
4019 tensorT overlap = matrix_inner(world, amo, amo, true);
4020
4021 START_TIMER(world);
4022 sygvp(world, focka, overlap, 1, U, aeps);
4023 END_TIMER(world, "focka eigen sol");
4024
4025 if (!param.localize) {
4026 amo = transform(world, amo, U, trantol, true);
4027 truncate(world, amo);
4028 normalize(world, amo);
4029 }
4030 if(param.nbeta != 0 && !param.spin_restricted){
4031 overlap = matrix_inner(world, bmo, bmo, true);
4032
4033 START_TIMER(world);
4034 sygvp(world, fockb, overlap, 1, U, beps);
4035 END_TIMER(world, "fockb eigen sol");
4036
4037 if (!param.localize) {
4038 bmo = transform(world, bmo, U, trantol, true);
4039 truncate(world, bmo);
4040 normalize(world, bmo);
4041 }
4042 }
4043
4044 if(world.rank() == 0) {
4045 print(" ");
4046 print("alpha eigenvalues");
4047 print(aeps);
4048 if(param.nbeta==0.0 && !param.spin_restricted){
4049 print("beta eigenvalues");
4050 print(beps);
4051 }
4052 }
4053
4054 if (param.localize) {
4055 // Restore the diagonal elements for the analysis
4056 for (unsigned int i=0; i<amo.size(); ++i) aeps[i] = focka(i,i);
4057 for (unsigned int i=0; i<bmo.size(); ++i) beps[i] = fockb(i,i);
4058 }
4059
4060 break;
4061 }
4062
4063 }
4064
4065 update_subspace(world, Vpsia, Vpsib, focka, fockb, subspace, Q, bsh_residual, update_residual);
4066 }
4067 // if(param.absolvent){
4068 // rhoT = rhon - rho_elec;
4069 // // print("TOTAL CHARGE", rhoT.trace());
4070 // DFTSolventSolver DFTSsolver(vacuo_rho,rhoT,param.rho_0,param.epsilon_2,param.maxiter,world,
4071 // param.Gamma,param.beta,std::max(1e-5,1e-7));
4072 // //DFTSsolver.dftsolverplots();
4073 // //functionT vsolvent = DFTSsolver.ESP();
4074 // //realfunc FF = DFTSsolver.make_electric_field(vsolvent);
4075 // //double Fxyz = DFTSsolver.ave_rxn_field(Uabinit,mol_mask);
4076 // double E_es = 0.5*rhoT.inner(Uabinit);
4077 // double E_cav = DFTSsolver.cavitation_energy();
4078 // double Surface = DFTSsolver.make_surface().trace();
4079 // double Volume = DFTSsolver.make_characteristic_func().trace();
4080 // double E_free = esol + E_es - vacuo_energy;
4081 // double G_sol = E_free + E_cav;
4082 // // print("Electrostatic energy ",E_es);
4083
4084 // if(world.rank() == 0) {
4085 // print("\n\n");
4086 // print(" MADNESS SOLVATION RESULTS ");
4087 // print(" _________________ \n ");
4088 // printf(" (electrostatic) solvation energy: %16.8f %s %12.8f %s\n ",E_es, "(",E_es*627.503,"kcal/mol)");
4089 // printf("(electrostatic)solvation free energy: %16.8f %s %12.8f %s\n ",E_free, "(",E_free*627.503,"kcal/mol)");
4090 // printf(" solvation free energy: %16.8f %s %12.8f %s\n ",G_sol, "(",G_sol*627.503,"kcal/mol)");
4091 // // print(" solute-solvent reflected field: ",Fxyz,"a.u.");
4092 // printf(" cavitation energy: %16.8f\n ",E_cav*627.503);
4093 // printf(" gas phase energy: %16.8f\n ",vacuo_energy);
4094 // printf(" solution phase energy: %16.8f\n ",esol);
4095 // printf(" Molecular Volume: %16.8f\n ",Volume);
4096 // printf(" Molecular Surface: %16.8f\n\n ",Surface);
4097 // }
4098 // }
4099
4100 if (world.rank() == 0) {
4101 if (param.localize) print("Orbitals are localized - energies are diagonal Fock matrix elements\n");
4102 else print("Orbitals are eigenvectors - energies are eigenvalues\n");
4103 print("Analysis of alpha MO vectors");
4104 }
4105
4106 analyze_vectors(world, amo, aocc, aeps);
4107 if (param.nbeta != 0 && !param.spin_restricted) {
4108 if (world.rank() == 0)
4109 print("Analysis of beta MO vectors");
4110
4111 analyze_vectors(world, bmo, bocc, beps);
4112 }
4113
4114
4115 }// end solve function
4116
4117 void solve_finite_mo(World & world) {
4118
4119 double ep = 1e-2;
4120
4121 if(param.response_freq != 0.0)
4122 error("Frequency should be ZERO.");
4123
4124 print("**********************");
4125 print(" start solve plus ");
4126 print("**********************");
4127 // amo_p, bmo_p
4128 solve_mp(world, amo_p, bmo_p, 0, ep);
4129
4130 print("**********************");
4131 print(" start solve minus ");
4132 print("**********************");
4133 // amo_m, bmo_m
4134 solve_mp(world, amo_m, bmo_m, 1, ep);
4135 }
4136
4137 void solve_polar(World & world)
4138 {
4139 double ep = 1e-2;
4140 subspaceT subspace;
4141 tensorT Q;
4142 //bool do_this_iter = true;
4143 // Shrink subspace until stop localizing/canonicalizing
4144
4145 int aflag = 0;
4146 int bflag = 1;
4147
4148 // X:axis=0, Y:axis=1, Z:axis=2
4149 double omega = 0.0;
4150 int axis = param.response_axis;
4151 response_frequency(axis, omega);
4152
4153 const double rconv = std::max(FunctionDefaults<3>::get_thresh(), param.rconv);
4154 vecfuncT ax = zero_functions<double, 3>(world, param.nalpha);
4155 vecfuncT ay = zero_functions<double, 3>(world, param.nalpha);
4156 vecfuncT bx = zero_functions<double, 3>(world, param.nbeta);
4157 vecfuncT by = zero_functions<double, 3>(world, param.nbeta);
4158
4159 // new response function
4160 vecfuncT ax_old = zero_functions<double,3>(world, param.nalpha);
4161 vecfuncT ay_old = zero_functions<double,3>(world, param.nalpha);
4162 vecfuncT bx_old = zero_functions<double,3>(world, param.nbeta);
4163 vecfuncT by_old = zero_functions<double,3>(world, param.nbeta);
4164
4165 print("\n\n\n");
4166 print(" ------------------------------------------------------------------------------");
4167 print(" | MADNESS FINITE FIELD SOLVATION MODULE |");
4168 print(" ------------------------------------------------------------------------------");
4169 print(" \n\n");
4170
4171
4172 for(int iter = 0;iter < param.maxiter;++iter){
4173 if(world.rank() == 0)
4174 printf("\nIteration %d at time %.1fs\n\n", iter, wall_time());
4175 double residual = 0.0;
4176
4177 for(int p=0; p<param.nalpha; ++p) {
4178 ax[p] = amo_p[p] - amo_m[p];
4179 ax[p].scale(1/(2*ep));
4180 }
4181 if(!param.spin_restricted && param.nbeta != 0) {
4182 for(int p=0; p<param.nbeta; ++p) {
4183 bx[p] = bmo_p[p] - bmo_m[p];
4184 bx[p].scale(1/(2*ep));
4185 }
4186 }
4187
4188 if(iter > 0) {
4189 #if 0
4190 vecfuncT rax = zero_functions<double,3>(world, param.nalpha); //residual alpha x
4191 vecfuncT ray = zero_functions<double,3>(world, param.nalpha); //residual alpha y
4192 vecfuncT rbx = zero_functions<double,3>(world, param.nbeta); //residual beta x
4193 vecfuncT rby = zero_functions<double,3>(world, param.nbeta); //residual beta y
4194
4195 rax = sub(world, ax, ax_old);
4196 ray = sub(world, ay, ay_old);
4197
4198 if(!param.spin_restricted && param.nbeta != 0) {
4199 // bxerr = (bx_new - bx).norm2()
4200 rbx = sub(world, bx, bx_old);
4201 rby = sub(world, by, by_old);
4202 }
4203 u
4204 update_response_subspace(world, ax, ay, bx, by, rax, ray, rbx, rby, subspace, Q);
4205 #endif
4206 orthogonalize_response(ax, ay, aflag);
4207 orthogonalize_response(bx, by, bflag);
4208
4209 if(!param.spin_restricted && param.nbeta != 0) residual = norm2(world, sub(world, ax, ax_old)) + norm2(world, sub(world, bx, bx_old));
4210 else if (param.nbeta != 0) residual = 2 * norm2(world, sub(world, ax, ax_old));
4211 else residual = norm2(world, sub(world, ax, ax_old));
4212
4213 print("\nOLD response function (plus, alpha_spin) = ", norm2(world, ax_old));
4214 print("NEW response function (plus, alpha_spin) = ", norm2(world, ax));
4215 print("\nresiduals_response (final) = ", residual);
4216 print("rconv *(param.nalpha + param.nbeta)*2", rconv *(param.nalpha + param.nbeta)*2);
4217
4218 // 収束判定
4219 if( residual < (rconv *(param.nalpha + param.nbeta)*2))
4220 {
4221 print("\n\n\n");
4222 print(" ------------------------------------------------------------------------------");
4223 print(" | MADNESS CALCULATION POLARIZABILITY |");
4224 print(" ------------------------------------------------------------------------------");
4225 print(" \n\n");
4226
4227 break;
4228 }
4229 }
4230 ax_old = ax;
4231 ay_old = ay;
4232 bx_old = bx;
4233 by_old = by;
4234
4235 } // end iteration
4236
4237 print("\nConverged response function!!\n");
4238
4239 double polar_alpha_p, polar_alpha_m, polar_beta_p, polar_beta_m;
4240 double total_polar;
4241 polar_alpha_p = polar_alpha_m = polar_beta_p = polar_beta_m = 0.0;
4242
4243 std::vector<int> f(3, 0);
4244 f[axis] = true;
4245 functionT dipolefunc = factoryT(world).functor(functorT(new MomentFunctor(f)));
4246
4247 vecfuncT damo = zero_functions<double,3>(world, param.nalpha); // dipolefunc * amo
4248 vecfuncT dbmo = zero_functions<double,3>(world, param.nbeta); // dipolefunc * bmo
4249
4250 for(int i = 0; i<param.nalpha; ++i) {
4251 damo[i] = dipolefunc * amo[i];
4252
4253 polar_alpha_p += -2 * inner(ax[i], damo[i]);
4254 polar_alpha_m += -2 * inner(ay[i], damo[i]);
4255 }
4256 if(!param.spin_restricted && param.nbeta != 0) {
4257 for(int i = 0; i<param.nbeta; ++i) {
4258 dbmo[i] = dipolefunc * bmo[i];
4259
4260 polar_beta_p += -2 * inner(bx[i], dbmo[i]);
4261 polar_beta_m += -2 * inner(by[i], dbmo[i]);
4262 }
4263 }
4264
4265 if(!param.spin_restricted && param.nbeta != 0) {
4266 total_polar = polar_alpha_p + polar_beta_p;
4267 }
4268 else if(param.nbeta != 0) total_polar = 2 * polar_alpha_p;
4269 else total_polar = polar_alpha_p;
4270
4271 if(!param.spin_restricted && param.nbeta != 0) {
4272 if(axis == 0) {
4273 print("Static Polarizability alpha [X][X]", polar_alpha_p);
4274 print("Static Polarizability beta [X][X]", polar_beta_p);
4275 print("Static Polarizability TOTAL [X][X]", total_polar);
4276 }
4277 if(axis == 1) {
4278 print("Static Polarizability alpha [Y][Y]", polar_alpha_p);
4279 print("Static Polarizability beta [Y][Y]", polar_beta_p);
4280 print("Static Polarizability TOTAL [Y][Y]", total_polar);
4281 }
4282 if(axis == 2) {
4283 print("Static Polarizability alpha [Z][Z]", polar_alpha_p);
4284 print("Static Polarizability beta [Z][Z]", polar_beta_p);
4285 print("Static Polarizability TOTAL [Z][Z]", total_polar);
4286 }
4287 }
4288 else {
4289 if(axis == 0) {
4290 print("Static Polarizability alpha [X][X]", polar_alpha_p);
4291 print("Static Polarizability TOTAL [X][X]", total_polar);
4292 }
4293 if(axis == 1) {
4294 print("Static Polarizability alpha [Y][Y]", polar_alpha_p);
4295 print("Static Polarizability TOTAL [Y][Y]", total_polar);
4296 }
4297 if(axis == 2) {
4298 print("Static Polarizability alpha [Z][Z]", polar_alpha_p);
4299 print("Static Polarizability TOTAL [Z][Z]", total_polar);
4300 }
4301 }
4302
4303 } // end solve_polar function
4304
4305 void solve_mp(World & world, vecfuncT & amo_mp, vecfuncT & bmo_mp, int mflag, double & ep)
4306 {
4307
4308 functionT arho_old, brho_old;
4309 const double dconv = std::max(FunctionDefaults<3>::get_thresh(), param.dconv);
4310 const double trantol = vtol / std::min(30.0, double(amo_mp.size()));
4311 const double tolloc = 1e-3;
4312 double update_residual = 0.0, bsh_residual = 0.0;
4313 subspaceT subspace;
4314 tensorT Q;
4315 bool do_this_iter = true;
4316 int maxsub_save = param.maxsub;
4317 param.maxsub = 2;
4318
4319 for(int iter = 0;iter < param.maxiter;++iter){
4320 if(world.rank() == 0)
4321 printf("\nIteration %d at time %.1fs\n\n", iter, wall_time());
4322
4323 if (iter > 0 && update_residual < 0.1) {
4324 //do_this_iter = false;
4325 param.maxsub = maxsub_save;
4326 }
4327 if(param.localize && do_this_iter) {
4328 tensorT U;
4329 if (param.localize_pm) {
4330 U = localize_PM(world, amo_mp, aset_mp, tolloc, 0.25, iter == 0, true);
4331 }
4332 else {
4333 U = localize_boys(world, amo_mp, aset_mp, tolloc, 0.25, iter==0);
4334 }
4335
4336 amo_mp = transform(world, amo_mp, U, trantol, true);
4337 truncate(world, amo_mp);
4338 normalize(world, amo_mp);
4339 rotate_subspace(world, U, subspace, 0, amo_mp.size(), trantol);
4340 if(!param.spin_restricted && param.nbeta != 0 ){
4341 if (param.localize_pm) {
4342 U = localize_PM(world, bmo_mp, bset_mp, tolloc, 0.25, iter == 0, true);
4343 }
4344 else {
4345 U = localize_boys(world, bmo_mp, bset_mp, tolloc, 0.25, iter==0);
4346 }
4347 bmo_mp = transform(world, bmo_mp, U, trantol, true);
4348 truncate(world, bmo_mp);
4349 normalize(world, bmo_mp);
4350 rotate_subspace(world, U, subspace, amo_mp.size(), bmo_mp.size(), trantol);
4351 }
4352 }
4353
4354 START_TIMER(world);
4355 functionT arho, brho;
4356 if(iter == 0) arho = make_density(world, aocc, amo);
4357 else arho = make_density(world, aocc_mp, amo_mp);
4358
4359 if (param.nbeta) {
4360 if (param.spin_restricted) {
4361 brho = arho;
4362 }
4363 else {
4364 if(iter == 0) brho = make_density(world, bocc, bmo);
4365 else brho = make_density(world, bocc_mp, bmo_mp);
4366 }
4367 }
4368 else {
4369 brho = functionT(world); // zero
4370 }
4371 END_TIMER(world, "Make densities");
4372 print_meminfo(world.rank(), "Make densities");
4373
4374 if(iter < 2 || (iter % 10) == 0){
4375 START_TIMER(world);
4376 loadbal(world, arho, brho, arho_old, brho_old, subspace);
4377 END_TIMER(world, "Load balancing");
4378 print_meminfo(world.rank(), "Load balancing");
4379 }
4380 double da = 0.0, db = 0.0;
4381 if(iter > 0){
4382 da = (arho - arho_old).norm2();
4383 db = (brho - brho_old).norm2();
4384 if(world.rank() == 0)
4385 print("delta rho", da, db, "residuals", bsh_residual, update_residual);
4386
4387 }
4388
4389 arho_old = arho;
4390 brho_old = brho;
4391 functionT rho = arho + brho;
4392 rho.truncate();
4393 print("rho = ", rho.norm2());
4394 real_function_3d vnuc = potentialmanager->vnuclear();
4395 double enuclear = inner(rho, vnuc);
4396
4397 START_TIMER(world);
4398 functionT vcoul = apply(*coulop, rho);
4399 functionT vlocal;
4400 END_TIMER(world, "Coulomb");
4401 print_meminfo(world.rank(), "Coulomb");
4402
4403 double ecoulomb = 0.5 * inner(rho, vcoul);
4404 //rho.clear(false);
4405 vlocal = vcoul + vnuc ;
4406
4407 print("Vloc1", vlocal.trace(), vlocal.norm2());
4408 std::vector<int> f(3, 0);
4409 f[param.response_axis] = true; // 2 -> axis = z
4410 functionT dipolefunc = factoryT(world).functor(functorT(new MomentFunctor(f)));
4411 dipolefunc.scale(ep);
4412 dipolefunc.truncate();
4413 printf("\n ep %16.8f\n", ep);
4414 print("Vdip", dipolefunc.trace(), dipolefunc.norm2());
4415 if (mflag == 1) vlocal = vlocal - dipolefunc;
4416 else vlocal = vlocal + dipolefunc;
4417 print("Vloc2", vlocal.trace(), vlocal.norm2());
4418
4419 double edipole = inner(rho, dipolefunc);
4420 print("Energy of finite field = ", edipole);
4421
4422 rho.clear(false);
4423
4424 vcoul.clear(false);
4425 vlocal.truncate();
4426 double exca = 0.0, excb = 0.0;
4427
4428 vecfuncT vf, delrho;
4429 if (xc.is_dft()) {
4430 arho.reconstruct();
4431 if (param.nbeta != 0 && xc.is_spin_polarized()) brho.reconstruct();
4432 // brho.reconstruct();
4433
4434 vf.push_back(arho);
4435
4436 if (xc.is_spin_polarized()) vf.push_back(brho);
4437
4438 if (xc.is_gga()) {
4439
4440 for (int axis=0; axis<3; ++axis) delrho.push_back((*gradop[axis])(arho,false)); // delrho
4441 if (xc.is_spin_polarized())
4442 for (int axis=0; axis<3; ++axis) delrho.push_back((*gradop[axis])(brho,false));
4443
4444
4445 world.gop.fence(); // NECESSARY
4446
4447 vf.push_back(delrho[0]*delrho[0]+delrho[1]*delrho[1]+delrho[2]*delrho[2]); // sigma_aa
4448
4449 if (xc.is_spin_polarized())
4450 vf.push_back(delrho[0]*delrho[3]+delrho[1]*delrho[4]+delrho[2]*delrho[5]); // sigma_ab
4451 if (xc.is_spin_polarized())
4452 vf.push_back(delrho[3]*delrho[3]+delrho[4]*delrho[4]+delrho[5]*delrho[5]); // sigma_bb
4453
4454 for (int axis=0; axis<3; ++axis) vf.push_back(delrho[axis]); // dda_x
4455
4456 if (xc.is_spin_polarized())
4457 for (int axis=0; axis<3; ++axis) vf.push_back(delrho[axis + 3]); // ddb_x
4458 world.gop.fence(); // NECESSARY
4459 }
4460 if (vf.size()) {
4461 reconstruct(world, vf);
4462 arho.refine_to_common_level(vf); // Ugly but temporary (I hope!)
4463 }
4464 }
4465
4466 vecfuncT Vpsia = apply_potential(world, aocc_mp, amo_mp, vf, delrho, vlocal, exca, 0);
4467
4468 vecfuncT Vpsib;
4469 if(!param.spin_restricted && param.nbeta) {
4470 Vpsib = apply_potential(world, bocc_mp, bmo_mp, vf, delrho, vlocal, excb, 1);
4471 }
4472
4473 double ekina = 0.0, ekinb = 0.0;
4474 tensorT focka = make_fock_matrix(world, amo_mp, Vpsia, aocc_mp, ekina);
4475 tensorT fockb = focka;
4476
4477 if (!param.spin_restricted && param.nbeta != 0)
4478 fockb = make_fock_matrix(world, bmo_mp, Vpsib, bocc_mp, ekinb);
4479 else if (param.nbeta != 0) {
4480 ekinb = ekina;
4481 }
4482
4483 if (!param.localize && do_this_iter) {
4484 tensorT U = diag_fock_matrix(world, focka, amo_mp, Vpsia, aeps_mp, aocc_mp, FunctionDefaults<3>::get_thresh());
4485 rotate_subspace(world, U, subspace, 0, amo_mp.size(), trantol);
4486 if (!param.spin_restricted && param.nbeta != 0) {
4487 U = diag_fock_matrix(world, fockb, bmo_mp, Vpsib, beps_mp, bocc_mp, FunctionDefaults<3>::get_thresh());
4488 rotate_subspace(world, U, subspace, amo_mp.size(), bmo_mp.size(), trantol);
4489 }
4490 }
4491
4492 double enrep = molecule.nuclear_repulsion_energy();
4493 double ekinetic = ekina + ekinb;
4494 double exc = exca + excb;
4495 double etot = ekinetic + enuclear + ecoulomb + exc + enrep + edipole;
4496 current_energy = etot;
4497 esol = etot;
4498
4499 if(world.rank() == 0){
4500 printf("\n kinetic %16.8f\n", ekinetic);
4501 printf(" nuclear attraction %16.8f\n", enuclear);
4502 printf(" coulomb %16.8f\n", ecoulomb);
4503 printf(" exchange-correlation %16.8f\n", exc);
4504 printf(" nuclear-repulsion %16.8f\n", enrep);
4505 printf(" total %16.8f\n\n", etot);
4506 }
4507
4508 if(iter > 0){
4509 //print("##convergence criteria: density delta=", da < dconv * molecule.natom() && db < dconv * molecule.natom(), ", bsh_residual=", (param.conv_only_dens || bsh_residual < 5.0*dconv));
4510 if(da < dconv * molecule.natom() && db < dconv * molecule.natom() && (param.conv_only_dens || bsh_residual < 5.0*dconv)){
4511 if(world.rank() == 0) {
4512 print("\nConverged!\n");
4513 }
4514
4515 // Diagonalize to get the eigenvalues and if desired the final eigenvectors
4516 tensorT U;
4517 tensorT overlap = matrix_inner(world, amo_mp, amo_mp, true);
4518
4519 START_TIMER(world);
4520 sygvp(world, focka, overlap, 1, U, aeps_mp);
4521 END_TIMER(world, "focka eigen sol");
4522
4523 if (!param.localize) {
4524 amo_mp = transform(world, amo_mp, U, trantol, true);
4525 truncate(world, amo_mp);
4526 normalize(world, amo_mp);
4527 }
4528 if(param.nbeta != 0 && !param.spin_restricted){
4529 overlap = matrix_inner(world, bmo_mp, bmo_mp, true);
4530
4531 START_TIMER(world);
4532 sygvp(world, fockb, overlap, 1, U, beps_mp);
4533 END_TIMER(world, "fockb eigen sol");
4534
4535 if (!param.localize) {
4536 bmo_mp = transform(world, bmo_mp, U, trantol, true);
4537 truncate(world, bmo_mp);
4538 normalize(world, bmo_mp);
4539 }
4540 }
4541
4542 if(world.rank() == 0) {
4543 print(" ");
4544 print("alpha mp eigenvalues");
4545 print(aeps_mp);
4546 if(param.nbeta==0.0 && !param.spin_restricted){
4547 print("beta mp eigenvalues");
4548 print(beps_mp);
4549 }
4550 }
4551
4552 if (param.localize) {
4553 // Restore the diagonal elements for the analysis
4554 for (unsigned int i=0; i<amo_mp.size(); ++i) aeps_mp[i] = focka(i,i);
4555 for (unsigned int i=0; i<bmo_mp.size(); ++i) beps_mp[i] = fockb(i,i);
4556 }
4557
4558 break;
4559 }
4560 }
4561 update_subspace_mp(world, Vpsia, Vpsib, focka, fockb, subspace, Q, bsh_residual, update_residual, mflag, amo_mp, bmo_mp);
4562 }
4563 if (world.rank() == 0) {
4564 if (param.localize) print("Orbitals are localized - energies are diagonal Fock matrix elements\n");
4565 else print("Orbitals are eigenvectors - energies are eigenvalues\n");
4566 print("Analysis of alpha MO vectors");
4567 }
4568
4569 analyze_vectors(world, amo_mp, aocc_mp, aeps_mp);
4570 if (param.nbeta != 0 && !param.spin_restricted) {
4571 if (world.rank() == 0)
4572 print("Analysis of beta MO vectors");
4573
4574 analyze_vectors(world, bmo_mp, bocc_mp, beps_mp);
4575 }
4576
4577 }// end solve mp function
4578
4579 void response_frequency(int & axis, double & omega)
4580 {
4581 if(axis == 0) {
4582 print(" AXIS of frequency = x");
4583 }
4584 else if(axis == 1) {
4585 print(" AXIS of frequency = y");
4586 }
4587 else if(axis == 2) {
4588 print(" AXIS of frequency = z");
4589 }
4590 print(" Frequency for response function = ", omega);
4591 }
4592
4593 functionT calc_dipole_mo(World & world, int & axis, int & p, int & flag)
4594 {
4595 functionT dipolemo = factoryT(world);
4596
4597 std::vector<int> f(3, 0);
4598 f[axis] = true;
4599 //print("f = ", f[0]," ", f[1], " ", f[2]);
4600 functionT dipolefunc = factoryT(world).functor(functorT(new MomentFunctor(f)));
4601
4602 // dipolefunc * amo[iter]
4603 if(flag == 0){
4604 dipolemo = dipolefunc * amo[p];
4605 }
4606 else {
4607 dipolemo = dipolefunc * bmo[p];
4608 }
4609
4610 //if (world.rank() == 0) {
4611 //}
4612
4613 return dipolemo;
4614 }
4615
4616 void calc_freq(double & omega, tensorT & akx, tensorT & aky, tensorT & bkx, tensorT & bky)
4617 {
4618 print(" eps_alpha = ", aeps);
4619 if(!param.spin_restricted && param.nbeta != 0) print(" eps_beta = ", beps);
4620 else if(param.nbeta != 0) print(" RHF ");
4621
4622 print(" frequency = ", omega);
4623 print(" number of alpha orbital = ", param.nalpha);
4624 print(" number of beta orbital = ", param.nbeta);
4625
4626 for(int i=0; i<param.nalpha; ++i){
4627 akx[i] = sqrt(-2.0 * (aeps[i] + omega));
4628 aky[i] = sqrt(-2.0 * (aeps[i] - omega));
4629 print(" kx(alpha) [", i, "] : sqrt(-2 * (eps + omega)) = ", akx[i]);
4630 print(" ky(alpha) [", i, "] : sqrt(-2 * (eps - omega)) = ", aky[i]);
4631 }
4632 if(!param.spin_restricted && param.nbeta != 0) {
4633 for(int i=0; i<param.nbeta; ++i){
4634 bkx[i] = sqrt(-2.0 * (beps[i] + omega));
4635 bky[i] = sqrt(-2.0 * (beps[i] - omega));
4636 print(" kx(beta) [", i, "]: sqrt(-2 * (eps + omega)) = ", bkx[i]);
4637 print(" ky(beta) [", i, "]: sqrt(-2 * (eps - omega)) = ", bky[i]);
4638 }
4639 }
4640 }
4641
4642 void make_BSHOperatorPtr(World & world, tensorT & akx, tensorT & aky, tensorT & bkx, tensorT & bky,
4643 std::vector<poperatorT> & aopx, std::vector<poperatorT> & aopy,
4644 std::vector<poperatorT> & bopx, std::vector<poperatorT> & bopy)
4645 {
4646 for(int i=0; i<param.nalpha; ++i) {
4647 aopx[i] = poperatorT(BSHOperatorPtr3D(world, akx[i], 0.001, 1e-6));
4648 aopy[i] = poperatorT(BSHOperatorPtr3D(world, aky[i], 0.001, 1e-6));
4649 }
4650 if(!param.spin_restricted && param.nbeta != 0) {
4651 for(int i=0; i<param.nbeta; ++i) {
4652 bopx[i] = poperatorT(BSHOperatorPtr3D(world, bkx[i], 0.001, 1e-6));
4653 bopy[i] = poperatorT(BSHOperatorPtr3D(world, bky[i], 0.001, 1e-6));
4654 }
4655 }
4656 }
4657
4658 functionT initial_guess_response(World & world, functionT & dipolemo) {
4659 functionT rhs = factoryT(world);
4660 rhs = dipolemo;
4661 rhs.scale(-2.0).truncate();
4662 return rhs;
4663 }
4664
4665 functionT make_density_ground(World & world, functionT & arho, functionT & brho)
4666 {
4667 functionT rho = factoryT(world);
4668
4669 START_TIMER(world);
4670
4671 arho = make_density(world, aocc, amo);
4672 brho = factoryT(world);
4673
4674 if (param.nbeta) {
4675 if (param.spin_restricted) {
4676 brho = arho;
4677 }
4678 else {
4679 brho = make_density(world, bocc, bmo);
4680 }
4681 }
4682 else {
4683 brho = functionT(world); // zero
4684 }
4685 END_TIMER(world, "Make densities");
4686
4687 rho = arho + brho;
4688 rho.truncate();
4689
4690 //double enuclear = inner(rho, vnuc);
4691
4692 return rho;
4693 }
4694
4695 vecfuncT calc_drho(World & world, functionT & arho, functionT & brho)
4696 {
4697
4698 vecfuncT vf, delrho;
4699 if (xc.is_dft()) {
4700 arho.reconstruct();
4701 if (param.nbeta != 0 && xc.is_spin_polarized()) brho.reconstruct();
4702 // brho.reconstruct();
4703
4704 vf.push_back(arho);
4705
4706 if (xc.is_spin_polarized()) vf.push_back(brho);
4707
4708 if (xc.is_gga()) {
4709
4710 for (int axis=0; axis<3; ++axis) delrho.push_back((*gradop[axis])(arho,false)); // delrho
4711 if (xc.is_spin_polarized())
4712 for (int axis=0; axis<3; ++axis) delrho.push_back((*gradop[axis])(brho,false));
4713
4714
4715 world.gop.fence(); // NECESSARY
4716
4717 vf.push_back(delrho[0]*delrho[0]+delrho[1]*delrho[1]+delrho[2]*delrho[2]); // sigma_aa
4718
4719 if (xc.is_spin_polarized())
4720 vf.push_back(delrho[0]*delrho[3]+delrho[1]*delrho[4]+delrho[2]*delrho[5]); // sigma_ab
4721 if (xc.is_spin_polarized())
4722 vf.push_back(delrho[3]*delrho[3]+delrho[4]*delrho[4]+delrho[5]*delrho[5]); // sigma_bb
4723
4724 for (int axis=0; axis<3; ++axis) vf.push_back(delrho[axis]); // dda_x
4725
4726 if (xc.is_spin_polarized())
4727 for (int axis=0; axis<3; ++axis) vf.push_back(delrho[axis + 3]); // ddb_x
4728 world.gop.fence(); // NECESSARY
4729 }
4730 if (vf.size()) {
4731 reconstruct(world, vf);
4732 arho.refine_to_common_level(vf); // Ugly but temporary (I hope!)
4733 }
4734 }
4735 return vf;
4736 }
4737
4738 functionT make_potential(World & world, functionT & rho)
4739 {
4740 real_function_3d vnuc = potentialmanager->vnuclear();
4741 //double enuclear = inner(rho, vnuc);
4742
4743 START_TIMER(world);
4744 functionT vcoul = apply(*coulop, rho);
4745 functionT vlocal;
4746 END_TIMER(world, "Coulomb");
4747 print_meminfo(world.rank(), "Coulomb");
4748
4749 rho.clear(false);
4750 vcoul.scale(2.0);
4751 vlocal = vcoul + vnuc ;
4752
4753 vcoul.clear(false);
4754 vlocal.truncate();
4755
4756 return vlocal;
4757 }
4758
4759 functionT make_derivative_density(World & world, vecfuncT & x, vecfuncT & y,
4760 int & flag, int & size)
4761 {
4762 functionT drho = factoryT(world);
4763
4764 if(flag == 0){
4765 for(int i=0; i<size; ++i) {
4766 drho += (amo[i] * x[i]) + (amo[i] * y[i]);
4767 }
4768 //drho.scale(2.0);
4769 }
4770 else{
4771 for(int i=0; i<size; ++i) {
4772 drho += (bmo[i] * x[i]) + (bmo[i] * y[i]);
4773 }
4774 }
4775 return drho;
4776 }
4777
4778 functionT calc_derivative_Jmo(World & world, int & p,
4779 vecfuncT & dmo1, vecfuncT & dmo2,
4780 vecfuncT & mo, int & size)
4781 {
4782 functionT dJ = factoryT(world);
4783 functionT dJmo = factoryT(world);
4784
4785 functionT j1 = factoryT(world);
4786 functionT j2 = factoryT(world);
4787 for(int i=0; i<size; ++i) {
4788 j1 = apply(*coulop, ( dmo1[i] * mo[i] ));
4789 j2 = apply(*coulop, ( dmo2[i] * mo[i] ));
4790 dJ = dJ + (j1 + j2);
4791 j1.clear(false);
4792 j2.clear(false);
4793 }
4794 dJmo = dJ * mo[p];
4795
4796 return dJmo;
4797 }
4798
4799 functionT calc_derivative_Kmo(World & world, int & p,
4800 vecfuncT & dmo1, vecfuncT & dmo2,
4801 vecfuncT & mo, int & size)
4802 {
4803 functionT dKmo = factoryT(world);
4804
4805 functionT k1 = factoryT(world);
4806 functionT k2 = factoryT(world);
4807 for(int i=0; i<size; ++i) {
4808 k1 = apply(*coulop, ( mo[i] * mo[p] )) * dmo1[i];
4809 k2 = apply(*coulop, ( mo[p] * dmo2[i] )) * mo[i];
4810 dKmo = dKmo + (k1 + k2);
4811 k1.clear(false);
4812 k2.clear(false);
4813 }
4814 return dKmo;
4815 }
4816
4817 functionT calc_djkmo(World & world, int & p, vecfuncT & dmo1,
4818 vecfuncT & dmo2, vecfuncT & mo, int & flag)
4819 {
4820 int size = 0;
4821
4822 functionT djkmo = factoryT(world);
4823
4824 if(flag == 0) size = param.nalpha;
4825 else if(flag == 1) size = param.nbeta;
4826
4827 functionT dJmo = calc_derivative_Jmo(world, p, dmo1, dmo2, mo, size);
4828 functionT dKmo = calc_derivative_Kmo(world, p, dmo1, dmo2, mo, size);
4829
4830 dJmo.scale(2.0);
4831 djkmo = dJmo - dKmo;
4832
4833 dJmo.clear(false);
4834 dKmo.clear(false);
4835
4836 return djkmo;
4837 }
4838
4839 functionT calc_rhs(World & world, functionT & Vdmo, functionT & dipolemo, functionT & djkmo)
4840 {
4841 functionT dmo_rhs = factoryT(world);
4842 //dmo_rhs = Vdmo - dmo_q + dipolemo + djkmo;
4843 dmo_rhs = Vdmo + dipolemo + djkmo;
4844 //dmo_rhs = Vdmo + dipolemo;
4845 dmo_rhs.scale(-2.0);
4846
4847 dmo_rhs.truncate();
4848
4849 return dmo_rhs;
4850 }
4851
4852 void calc_response_function(World & world, vecfuncT & x, vecfuncT & y,
4853 std::vector<poperatorT> & opx, std::vector<poperatorT> & opy,
4854 vecfuncT & xrhs, vecfuncT & yrhs)
4855 {
4856 //double damping = 0.8;
4857
4858 // new response function
4859 // BSHOperatorPrt3D : opx
4860 x = apply(world, opx, xrhs);
4861 y = apply(world, opy, yrhs);
4862 truncate(world, x);
4863 truncate(world, y);
4864 //scale(world, x, damping);
4865 //scale(world, y, damping);
4866 }
4867
4868 // orthogonalization
4869 void orthogonalize_response(vecfuncT & x, vecfuncT & y, int & flag)
4870 {
4871 if(flag == 0){
4872 for(int i=0; i<param.nalpha; ++i){
4873 for (int j=0; j<param.nalpha; ++j){
4874 // new_x = new_x - < psi | new_x > * psi
4875 x[i] = x[i] - x[i].inner(amo[j])*amo[j];
4876 y[i] = y[i] - y[i].inner(amo[j])*amo[j];
4877 }
4878 }
4879 }
4880 else{
4881 if(!param.spin_restricted && param.nbeta != 0) {
4882 for(int i=0; i<param.nbeta; ++i){
4883 for (int j=0; j<param.nbeta; ++j){
4884 // new_x = new_x - < psi | new_x > * psi
4885 x[i] = x[i] - x[i].inner(bmo[j])*bmo[j];
4886 y[i] = y[i] - y[i].inner(bmo[j])*bmo[j];
4887 }
4888 }
4889 }
4890 }
4891 }
4892
4893 // solve response function
4894 void solve_response(World & world)
4895 {
4896 print("\n\n\n");
4897 print(" ------------------------------------------------------------------------------");
4898 print(" | MADNESS RESPONSE FUNCTION SOLVATION MODULE |");
4899 print(" ------------------------------------------------------------------------------");
4900 print(" \n\n");
4901
4902 const double rconv = std::max(FunctionDefaults<3>::get_thresh(), param.rconv);
4903 subspaceT subspace;
4904 tensorT Q;
4905
4906 int aflag = 0;
4907 int bflag = 1;
4908
4909 // X:axis=0, Y:axis=1, Z:axis=2
4910 double omega = param.response_freq;
4911 int axis = param.response_axis;
4912 response_frequency(axis, omega);
4913
4914 // Green's function
4915 tensorT akx(param.nalpha);
4916 tensorT aky(param.nalpha);
4917 tensorT bkx(param.nbeta);
4918 tensorT bky(param.nbeta);
4919
4920 //calculate frequency term
4921 calc_freq(omega, akx, aky, bkx, bky);
4922
4923 // make response function x, y
4924 vecfuncT ax = zero_functions<double,3>(world, param.nalpha);
4925 vecfuncT ay = zero_functions<double,3>(world, param.nalpha);
4926 vecfuncT bx = zero_functions<double,3>(world, param.nbeta);
4927 vecfuncT by = zero_functions<double,3>(world, param.nbeta);
4928
4929 // new response function
4930 //vecfuncT ax_new = zero_functions<double,3>(world, param.nalpha);
4931 //vecfuncT ay_new = zero_functions<double,3>(world, param.nalpha);
4932 //vecfuncT bx_new = zero_functions<double,3>(world, param.nbeta);
4933 //vecfuncT by_new = zero_functions<double,3>(world, param.nbeta);
4934 vecfuncT ax_old = zero_functions<double,3>(world, param.nalpha);
4935 vecfuncT ay_old = zero_functions<double,3>(world, param.nalpha);
4936 vecfuncT bx_old = zero_functions<double,3>(world, param.nbeta);
4937 vecfuncT by_old = zero_functions<double,3>(world, param.nbeta);
4938
4939 // BSHOperatorPtr
4940 std::vector<poperatorT> aopx(param.nalpha);
4941 std::vector<poperatorT> bopx(param.nbeta);
4942 std::vector<poperatorT> aopy(param.nalpha);
4943 std::vector<poperatorT> bopy(param.nbeta);
4944 make_BSHOperatorPtr(world, akx, aky, bkx, bky, aopx, aopy, bopx, bopy);
4945
4946 // make potential * wave function
4947 vecfuncT aVx = zero_functions<double,3>(world, param.nalpha);
4948 vecfuncT aVy = zero_functions<double,3>(world, param.nalpha);
4949 vecfuncT bVx = zero_functions<double,3>(world, param.nbeta);
4950 vecfuncT bVy = zero_functions<double,3>(world, param.nbeta);
4951
4952 // make density matrix
4953 functionT arho = factoryT(world);
4954 functionT brho = factoryT(world);
4955 functionT rho = make_density_ground(world, arho, brho);
4956
4957 vecfuncT vf = calc_drho(world, arho, brho);
4958
4959 // vlocal = vnuc + 2*J
4960 functionT vlocal = make_potential(world, rho);
4961
4962 // make (dJ-dK)*2*mo
4963 vecfuncT djkamox = zero_functions<double,3>(world, param.nalpha);
4964 vecfuncT djkamoy = zero_functions<double,3>(world, param.nalpha);
4965 vecfuncT djkbmox = zero_functions<double,3>(world, param.nbeta);
4966 vecfuncT djkbmoy = zero_functions<double,3>(world, param.nbeta);
4967
4968 vecfuncT axrhs = zero_functions<double,3>(world, param.nalpha);
4969 vecfuncT ayrhs = zero_functions<double,3>(world, param.nalpha);
4970 vecfuncT bxrhs = zero_functions<double,3>(world, param.nbeta);
4971 vecfuncT byrhs = zero_functions<double,3>(world, param.nbeta);
4972
4973 for(int iter=0; iter<param.maxiter; ++iter) {
4974 print("\n iteration : ", iter);
4975 double residual = 0.0;
4976 double exca = 0.0, excb = 0.0;
4977
4978 if(iter > 0) {
4979 aVx = apply_potential_response(world, aocc, ax_old, vf, vlocal, exca, 0);
4980 aVy = apply_potential_response(world, aocc, ay_old, vf, vlocal, exca, 0);
4981 if(!param.spin_restricted && param.nbeta != 0) {
4982 bVx = apply_potential_response(world, bocc, bx_old, vf, vlocal, excb, 1);
4983 bVy = apply_potential_response(world, bocc, by_old, vf, vlocal, excb, 1);
4984 }
4985 }
4986
4987 for(int p=0; (p<param.nalpha && p<param.nbeta); ++p) {
4988
4989 //dipole operator * mo
4990 functionT dipoleamo = calc_dipole_mo(world, axis, p, aflag), dipolebmo;
4991 if(!param.spin_restricted && param.nbeta != 0)
4992 dipolebmo = calc_dipole_mo(world, axis, p, bflag);
4993
4994 if(iter == 0) {
4995 // iter = 0 initial_guess
4996 axrhs[p] = initial_guess_response(world, dipoleamo);
4997 ayrhs[p] = initial_guess_response(world, dipoleamo);
4998 if(!param.spin_restricted && param.nbeta != 0) {
4999 bxrhs[p] = initial_guess_response(world, dipolebmo);
5000 byrhs[p] = initial_guess_response(world, dipolebmo);
5001 }
5002 }
5003 else {
5004 #if 0
5005 // calculate "[nuclear_potential + ( 2 * coulomb_potential)] * x"
5006 aVx[p] = ax_old[p] * vlocal;
5007 aVy[p] = ay_old[p] * vlocal;
5008 if(!param.spin_restricted && param.nbeta != 0) {
5009 bVx[p] = bx_old[p] * vlocal;
5010 bVy[p] = by_old[p] * vlocal;
5011 }
5012 #endif
5013 // calculate (dJ-dK)*2*mo
5014 djkamox[p] = calc_djkmo(world, p, ax_old, ay_old, amo, aflag);
5015 djkamoy[p] = calc_djkmo(world, p, ay_old, ax_old, amo, aflag);
5016 if(!param.spin_restricted && param.nbeta != 0) {
5017 djkbmox[p] = calc_djkmo(world, p, bx_old, by_old, bmo, bflag);
5018 djkbmoy[p] = calc_djkmo(world, p, by_old, bx_old, bmo, bflag);
5019 }
5020 #if 0
5021 // calculate_last_item
5022 functionT ax_q = factoryT(world);
5023 functionT ay_q = factoryT(world);
5024 functionT bx_q = factoryT(world);
5025 functionT by_q = factoryT(world);
5026 for(int i=0; i<param.nalpha; ++i){
5027 ax_q = apply(*coulop, (amo[i] * ax_old[p])) * amo[i];
5028 ay_q = apply(*coulop, (amo[i] * ay_old[p])) * amo[i];
5029 }
5030 if(!param.spin_restricted && param.nbeta != 0) {
5031 for(int i=0; i<param.nalpha; ++i){
5032 bx_q = apply(*coulop, (bmo[i] * bx_old[p])) * bmo[i];
5033 by_q = apply(*coulop, (bmo[i] * by_old[p])) * bmo[i];
5034 }
5035 }
5036 #endif
5037 // axrhs[p] = -2.0 * (aVx + dipoleamo + duamo)
5038 axrhs[p] = calc_rhs(world, aVx[p], dipoleamo, djkamox[p]);
5039 ayrhs[p] = calc_rhs(world, aVy[p], dipoleamo, djkamoy[p]);
5040 //axrhs[p] = calc_rhs(world, aVx[p], dipoleamo, ax_q, djkamox[p]);
5041 //ayrhs[p] = calc_rhs(world, aVy[p], dipoleamo, ay_q, djkamoy[p]);
5042 if(!param.spin_restricted && param.nbeta != 0) {
5043 // bxrhs[p] = -2.0 * (bVx + dipolebmo + dubmo)
5044 bxrhs[p] = calc_rhs(world, bVx[p], dipolebmo, djkbmox[p]);
5045 byrhs[p] = calc_rhs(world, bVy[p], dipolebmo, djkbmoy[p]);
5046 //bxrhs[p] = calc_rhs(world, bVx[p], dipolebmo, bx_q, djkbmox[p]);
5047 //byrhs[p] = calc_rhs(world, bVy[p], dipolebmo, by_q, djkbmoy[p]);
5048 }
5049 }
5050 dipoleamo.clear(false);
5051 dipolebmo.clear(false);
5052 print("old_ax norm2() : ", norm2(world, ax_old));
5053 }
5054
5055 // ax_new = G * axrhs;
5056 calc_response_function(world, ax, ay, aopx, aopy, axrhs, ayrhs);
5057 if(!param.spin_restricted && param.nbeta != 0) {
5058 // bx_new = G * bxrhs;
5059 calc_response_function(world, bx, by, bopx, bopy, bxrhs, byrhs);
5060 }
5061
5062 orthogonalize_response(ax, ay, aflag);
5063 orthogonalize_response(bx, by, bflag);
5064
5065 truncate(world, ax);
5066 truncate(world, ay);
5067 truncate(world, bx);
5068 truncate(world, by);
5069
5070 if(iter > 0) {
5071
5072 vecfuncT rax = zero_functions<double,3>(world, param.nalpha); //residual alpha x
5073 vecfuncT ray = zero_functions<double,3>(world, param.nalpha); //residual alpha y
5074 vecfuncT rbx = zero_functions<double,3>(world, param.nbeta); //residual beta x
5075 vecfuncT rby = zero_functions<double,3>(world, param.nbeta); //residual beta y
5076
5077 rax = sub(world, ax, ax_old);
5078 ray = sub(world, ay, ay_old);
5079 residual = norm2(world, rax) + norm2(world, ray);
5080 if(!param.spin_restricted && param.nbeta != 0) {
5081 // bxerr = (bx_new - bx).norm2()
5082 rbx = sub(world, bx, bx_old);
5083 rby = sub(world, by, by_old);
5084
5085 residual = residual + norm2(world, rbx) + norm2(world, rby);
5086 }
5087
5088 print("***************************");
5089 print("CURRENT_X_norm2() = ", norm2(world, ax));
5090 print("residual first = ", residual);
5091 update_response_subspace(world, ax, ay, bx, by, rax, ray, rbx, rby, subspace, Q);
5092
5093 //residual = 0.0;
5094 residual = norm2(world, sub(world, ax, ax_old)) + norm2(world, sub(world, ay, ay_old));
5095 if(!param.spin_restricted && param.nbeta != 0) residual = residual + norm2(world, sub(world, bx, bx_old)) + norm2(world, sub(world, by, by_old));
5096 else if(param.nbeta != 0) residual = 2.0 * residual;
5097
5098 print("new X (alpha) norm2() = ", norm2(world, ax));
5099 print("new Y (alpha) norm2() = ", norm2(world, ay));
5100
5101 print("\nresiduals_response (final) = ", residual);
5102 print("rconv *(param.nalpha + param.nbeta)*2", rconv *(param.nalpha + param.nbeta)*2);
5103
5104 // 収束判定
5105 if( residual < (rconv *(param.nalpha + param.nbeta)*2))
5106 {
5107 print("\n\n\n");
5108 print(" ------------------------------------------------------------------------------");
5109 print(" | MADNESS CALCULATION POLARIZABILITY |");
5110 print(" ------------------------------------------------------------------------------");
5111 print(" \n\n");
5112
5113 break;
5114 }
5115 }
5116 //ax_old = ax;
5117 //ay_old = ay;
5118 //bx_old = bx;
5119 //by_old = by;
5120 ax_old = copy(world, ax);
5121 ay_old = copy(world, ay);
5122 bx_old = copy(world, bx);
5123 by_old = copy(world, by);
5124
5125
5126 } //end iteration
5127 // end solve response function
5128
5129 print("\nConverged response function!!\n");
5130
5131 // derivative density matrix
5132 functionT drho = factoryT(world);
5133 functionT adrho = make_derivative_density(world, ax, ay, aflag, param.nalpha), bdrho;
5134 if(!param.spin_restricted && param.nbeta != 0)
5135 bdrho = make_derivative_density(world, bx, by ,bflag, param.nbeta);
5136 else if(param.nbeta != 0)
5137 bdrho = adrho;
5138 else bdrho = factoryT(world);
5139 drho = adrho + bdrho;
5140
5141 double total_Dpolar, Dpolar_alpha, Dpolar_beta;
5142 total_Dpolar = Dpolar_alpha = Dpolar_beta = 0.0;
5143
5144 std::vector<int> f(3, 0);
5145 f[axis] = true;
5146 functionT dipolefunc = factoryT(world).functor(functorT(new MomentFunctor(f)));
5147
5148 #if 0
5149 Dpolar_alpha = dipolefunc.inner(adrho);
5150 if(!param.spin_restricted && param.nbeta != 0) {
5151 Dpolar_beta = dipolefunc.inner(bdrho);
5152 total_Dpolar = -2 * (Dpolar_alpha + Dpolar_beta);
5153 }
5154 else if (param.nbeta != 0) total_Dpolar = -4 * Dpolar_alpha;
5155 else total_Dpolar = -2 * Dpolar_alpha;
5156 #endif
5157
5158 Dpolar_alpha = -2 * dipolefunc.inner(adrho);
5159 if(param.nbeta != 0)
5160 Dpolar_beta = -2 * dipolefunc.inner(bdrho);
5161 total_Dpolar = -2 * (dipolefunc.inner(drho));
5162
5163 if(axis == 0) print("Dynamic Polarizability alpha [X][X]", Dpolar_alpha);
5164 if(axis == 1) print("Dynamic Polarizability alpha [Y][Y]", Dpolar_alpha);
5165 if(axis == 2) print("Dynamic Polarizability alpha [Z][Z]", Dpolar_alpha);
5166
5167 if(!param.spin_restricted) {
5168 if(axis == 0) print("Dynamic Polarizability beta [X][X]", Dpolar_alpha);
5169 if(axis == 1) print("Dynamic Polarizability beta [Y][Y]", Dpolar_alpha);
5170 if(axis == 2) print("Dynamic Polarizability beta [Z][Z]", Dpolar_alpha);
5171 }
5172 else if(param.nbeta != 0) {
5173 if(axis == 0) print("Dynamic Polarizability beta [X][X]", Dpolar_beta);
5174 if(axis == 1) print("Dynamic Polarizability beta [Y][Y]", Dpolar_beta);
5175 if(axis == 2) print("Dynamic Polarizability beta [Z][Z]", Dpolar_beta);
5176 }
5177
5178 if(axis == 0) print("Dynamic Polarizability TOTAL [X][X]", total_Dpolar);
5179 if(axis == 1) print("Dynamic Polarizability TOTAL [Y][Y]", total_Dpolar);
5180 if(axis == 2) print("Dynamic Polarizability TOTAL [Z][Z]", total_Dpolar);
5181
5182 adrho.clear(false);
5183 bdrho.clear(false);
5184 dipolefunc.clear(false);
5185
5186 } // end of solving polarizability
5187 };
5188 // Computes molecular energy as a function of the geometry
5189 // This is cludgy ... need better factorization of functionality
5190 // between calculation, main program and this ... or just merge it all.
5191 class MolecularEnergy : public OptimizationTargetInterface {
5192 World& world;
5193 Calculation& calc;
5194 mutable double coords_sum; // sum of square of coords at last solved geometry
5195 mutable double E; //< Current energy
5196
5197 public:
5198 MolecularEnergy(World& world, Calculation& calc)
5199 : world(world)
5200 , calc(calc)
5201 , coords_sum(-1.0)
5202 {}
5203
5204 bool provides_gradient() const {return true;}
5205
5206 double value(const Tensor<double>& x) {
5207 double xsq = x.sumsq();
5208 if (xsq == coords_sum) {
5209 return calc.current_energy;
5210 }
5211 calc.molecule.set_all_coords(x.reshape(calc.molecule.natom(),3));
5212 coords_sum = xsq;
5213
5214 // The below is missing convergence test logic, etc.
5215
5216 // Make the nuclear potential, initial orbitals, etc.
5217 for (unsigned int proto=0; proto<calc.param.protocol_data.size(); proto++) {
5218 calc.set_protocol(world,calc.param.protocol_data[proto]);
5219 calc.make_nuclear_potential(world);
5220 calc.project_ao_basis(world);
5221
5222 if (proto == 0) {
5223 if (calc.param.restart) {
5224 calc.load_mos(world);
5225 }
5226 else {
5227 calc.initial_guess(world);
5228 if(calc.param.polar == true) {
5229 if(calc.param.polar_ds == 0)
5230 calc.initial_guess_mp(world);
5231 }
5232 //calc.param.restart = true;
5233 }
5234 }
5235 else {
5236 calc.project(world);
5237 }
5238
5239 // If the basis for the inital guess was not sto-3g
5240 // switch to sto-3g since this is needed for analysis
5241 // of the MOs and orbital localization
5242 if (calc.param.aobasis != "sto-3g") {
5243 calc.param.aobasis = "sto-3g";
5244 calc.project_ao_basis(world);
5245 }
5246 //if(proto==0){
5247 // if(calc.param.absolvent)//||calc.param.svpe)
5248 // calc.solve_gas_phase(world);// computes vacuo density and energy
5249 // //}// calc.save_mos(world); //debugging
5250
5251 calc.solve(world);
5252 if(calc.param.polar == true) {
5253 if(calc.param.polar_ds == 0) {
5254 calc.solve_finite_mo(world);
5255 calc.solve_polar(world);
5256 }
5257 else if (calc.param.polar_ds == 1) {
5258 calc.solve_response(world);
5259 }
5260 }
5261 if (calc.param.save)
5262 calc.save_mos(world);
5263 }
5264 return calc.current_energy;
5265 }
5266
5267 madness::Tensor<double> gradient(const Tensor<double>& x) {
5268 value(x); // Ensures DFT equations are solved at this geometry
5269
5270 return calc.derivatives(world);
5271 }
5272 };
5273
5274 int main(int argc, char** argv) {
5275 initialize(argc, argv);
5276
5277 { // limit lifetime of world so that finalize() can execute cleanly
5278 World world(SafeMPI::COMM_WORLD);
5279
5280 try {
5281 // Load info for MADNESS numerical routines
5282 startup(world,argc,argv);
5283 print_meminfo(world.rank(), "startup");
5284 FunctionDefaults<3>::set_pmap(pmapT(new LevelPmap< Key<3> >(world)));
5285
5286 std::cout.precision(6);
5287
5288 // Process 0 reads input information and broadcasts
5289 const char * inpname = "input";
5290 for (int i=1; i<argc; i++) {
5291 if (argv[i][0] != '-') {
5292 inpname = argv[i];
5293 break;
5294 }
5295 }
5296 if (world.rank() == 0) print(inpname);
5297 Calculation calc(world, inpname);
5298
5299 // Warm and fuzzy for the user
5300 if (world.rank() == 0) {
5301 print("\n\n");
5302 print(" MADNESS Hartree-Fock and Density Functional Theory Program");
5303 print(" ----------------------------------------------------------\n");
5304 print("\n");
5305 calc.molecule.print();
5306 print("\n");
5307 calc.param.print(world);
5308 }
5309
5310 // Come up with an initial OK data map
5311 if (world.size() > 1) {
5312 calc.set_protocol(world,1e-4);
5313 calc.make_nuclear_potential(world);
5314 calc.initial_load_bal(world);
5315 }
5316 //vama
5317 calc.set_protocol(world,calc.param.protocol_data[0]);
5318
5319
5320 if ( calc.param.gopt) {
5321 print("\n\n Geometry Optimization ");
5322 print(" ----------------------------------------------------------\n");
5323 calc.param.gprint(world);
5324
5325 Tensor<double> geomcoord = calc.molecule.get_all_coords().flat();
5326 QuasiNewton geom(std::shared_ptr<OptimizationTargetInterface>(new MolecularEnergy(world, calc)),
5327 calc.param.gmaxiter,
5328 calc.param.gtol, //tol
5329 calc.param.gval, //value prec
5330 calc.param.gprec); // grad prec
5331 geom.set_update(calc.param.algopt);
5332 geom.set_test(calc.param.gtest);
5333 long ncoord = calc.molecule.natom()*3;
5334 Tensor<double> h(ncoord,ncoord);
5335 for (int i=0; i<ncoord; ++i) h(i,i) = 0.5;
5336 geom.set_hessian(h);
5337 geom.optimize(geomcoord);
5338 }
5339 else if (calc.param.tdksprop) {
5340 print("\n\n Propagation of Kohn-Sham equation ");
5341 print(" ----------------------------------------------------------\n");
5342 // calc.propagate(world,VextCosFunctor<double>(world,new DipoleFunctor(2),0.1),0);
5343 calc.propagate(world,0.1,0);
5344 }
5345 else {
5346 MolecularEnergy E(world, calc);
5347 E.value(calc.molecule.get_all_coords().flat()); // ugh!
5348 if (calc.param.derivatives) calc.derivatives(world);
5349 if (calc.param.dipole) calc.dipole(world);
5350 }
5351
5352 // if (calc.param.twoint) {
5353 //Tensor<double> g = calc.twoint(world,calc.amo);
5354 //cout << g;
5355 // }
5356
5357 calc.do_plots(world);
5358
5359 }
5360 catch (const SafeMPI::Exception& e) {
5361 print(e);
5362 error("caught an MPI exception");
5363 }
5364 catch (const madness::MadnessException& e) {
5365 print(e);
5366 error("caught a MADNESS exception");
5367 }
5368 catch (const madness::TensorException& e) {
5369 print(e);
5370 error("caught a Tensor exception");
5371 }
5372 catch (char* s) {
5373 print(s);
5374 error("caught a string exception");
5375 }
5376 catch (const char* s) {
5377 print(s);
5378 error("caught a string exception");
5379 }
5380 catch (const std::string& s) {
5381 print(s);
5382 error("caught a string (class) exception");
5383 }
5384 catch (const std::exception& e) {
5385 print(e.what());
5386 error("caught an STL exception");
5387 }
5388 catch (...) {
5389 error("caught unhandled exception");
5390 }
5391
5392 // Nearly all memory will be freed at this point
5393 world.gop.fence();
5394 world.gop.fence();
5395 print_stats(world);
5396 } // world is dead -- ready to finalize
5397 finalize();
5398
5399 return 0;
5400 }