source: src/bin/mpqc/mpqc.cc@ 2d0bba

Last change on this file since 2d0bba was 2d0bba, checked in by Frederik Heber <heber@…>, 13 years ago

FIX: Charge density was sampled off by one sampling width.

  • this was because we first add delta and then sample.
  • Property mode set to 100644
File size: 59.5 KB
Line 
1//
2// mpqc.cc
3//
4// Copyright (C) 1996 Limit Point Systems, Inc.
5//
6// Author: Edward Seidl <seidl@janed.com>
7// Maintainer: LPS
8//
9// This file is part of MPQC.
10//
11// MPQC is free software; you can redistribute it and/or modify
12// it under the terms of the GNU General Public License as published by
13// the Free Software Foundation; either version 2, or (at your option)
14// any later version.
15//
16// MPQC is distributed in the hope that it will be useful,
17// but WITHOUT ANY WARRANTY; without even the implied warranty of
18// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19// GNU General Public License for more details.
20//
21// You should have received a copy of the GNU General Public License
22// along with the MPQC; see the file COPYING. If not, write to
23// the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
24//
25// The U.S. Government is granted a limited license as per AL 91-7.
26//
27
28// This is needed to make GNU extensions available, such as
29// feenableexcept and fedisableexcept.
30#ifndef _GNU_SOURCE
31# define _GNU_SOURCE
32#endif
33
34#ifdef HAVE_CONFIG_H
35#include <scconfig.h>
36#endif
37
38#ifdef HAVE_TIME_H
39#include <time.h>
40#endif
41
42#include <scdirlist.h>
43
44#include <new>
45#include <stdexcept>
46#include <string.h>
47#include <unistd.h>
48#include <sys/stat.h>
49#include <fstream>
50
51#include <boost/bind.hpp>
52#include <boost/function.hpp>
53
54#include <scconfig.h>
55#ifdef HAVE_SSTREAM
56# include <sstream>
57#else
58# include <strstream.h>
59#endif
60
61#ifdef HAVE_SYS_RESOURCE_H
62# include <sys/resource.h>
63#endif
64#ifdef HAVE_SYS_TIME_H
65# include <sys/time.h>
66#endif
67
68#include <util/options/GetLongOpt.h>
69#include <util/class/scexception.h>
70#include <util/misc/newstring.h>
71#include <util/keyval/keyval.h>
72#include <util/state/state_bin.h>
73#include <util/group/message.h>
74#include <util/group/memory.h>
75#include <util/group/mstate.h>
76#include <util/group/thread.h>
77#include <util/group/pregtime.h>
78#include <util/misc/bug.h>
79#include <util/misc/formio.h>
80#include <util/misc/exenv.h>
81#ifdef HAVE_CHEMISTRY_CCA
82 #include <util/misc/ccaenv.h>
83#endif
84#include <util/render/render.h>
85
86#include <math/optimize/opt.h>
87
88#include <chemistry/molecule/coor.h>
89#include <chemistry/molecule/energy.h>
90#include <chemistry/molecule/molfreq.h>
91#include <chemistry/molecule/fdhess.h>
92#include <chemistry/molecule/formula.h>
93#include <chemistry/qc/wfn/wfn.h>
94
95// Force linkages:
96#include <util/group/linkage.h>
97#include <chemistry/qc/wfn/linkage.h>
98#include <chemistry/qc/scf/linkage.h>
99#include <chemistry/qc/dft/linkage.h>
100#include <chemistry/qc/mbpt/linkage.h>
101#ifdef HAVE_SC_SRC_LIB_CHEMISTRY_QC_MBPTR12
102# include <chemistry/qc/mbptr12/linkage.h>
103#endif
104#ifdef HAVE_SC_SRC_LIB_CHEMISTRY_QC_CINTS
105# include <chemistry/qc/cints/linkage.h>
106#endif
107//#include <chemistry/qc/psi/linkage.h>
108#include <util/state/linkage.h>
109#ifdef HAVE_SC_SRC_LIB_CHEMISTRY_QC_CC
110# include <chemistry/qc/cc/linkage.h>
111#endif
112#ifdef HAVE_SC_SRC_LIB_CHEMISTRY_QC_PSI
113# include <chemistry/qc/psi/linkage.h>
114#endif
115#ifdef HAVE_SC_SRC_LIB_CHEMISTRY_QC_INTCCA
116# include <chemistry/qc/intcca/linkage.h>
117#endif
118
119#ifdef HAVE_MPI
120#define MPICH_SKIP_MPICXX
121#include <mpi.h>
122#include <util/group/messmpi.h>
123#endif
124
125#ifdef HAVE_JOBMARKET
126// include headers that implement a archive in simple text format
127// otherwise BOOST_CLASS_EXPORT_IMPLEMENT has no effect
128#include <boost/archive/text_oarchive.hpp>
129#include <boost/archive/text_iarchive.hpp>
130#include <boost/bind.hpp>
131#include <boost/tokenizer.hpp>
132
133#include "JobMarket/Results/FragmentResult.hpp"
134#include "JobMarket/poolworker_main.hpp"
135
136#include "chemistry/qc/scf/scfops.h"
137
138#ifdef HAVE_MPQCDATA
139#include "Jobs/MPQCJob.hpp"
140#include "Jobs/MPQCData.hpp"
141
142#include <chemistry/qc/basis/obint.h>
143#include <chemistry/qc/basis/symmint.h>
144#endif
145
146#include <algorithm>
147#include <stdlib.h>
148#endif
149
150using namespace std;
151using namespace sc;
152
153#include "mpqcin.h"
154
155//////////////////////////////////////////////////////////////////////////
156
157const KeyValValueboolean truevalue(1), falsevalue(0);
158const char *devnull = "/dev/null";
159
160
161static void
162trash_stack_b(int &i, char *&ichar)
163{
164 char stack;
165 ichar = &stack;
166 ichar -= 10;
167 for (i=0; i<1000; i++) {
168 *ichar-- = 0xfe;
169 }
170}
171
172static void
173trash_stack()
174{
175 int i;
176 char *ichar;
177 trash_stack_b(i,ichar);
178}
179
180static void
181clean_up(void)
182{
183 MemoryGrp::set_default_memorygrp(0);
184 ThreadGrp::set_default_threadgrp(0);
185 SCMatrixKit::set_default_matrixkit(0);
186 Integral::set_default_integral(0);
187 RegionTimer::set_default_regiontimer(0);
188}
189
190static void
191final_clean_up(void)
192{
193 MessageGrp::set_default_messagegrp(0);
194}
195
196#include <signal.h>
197
198#ifdef HAVE_FENV_H
199# include <fenv.h>
200#endif
201
202static void
203print_unseen(const Ref<ParsedKeyVal> &parsedkv,
204 const char *input)
205{
206 if (parsedkv->have_unseen()) {
207 ExEnv::out0() << endl;
208 ExEnv::out0() << indent
209 << "The following keywords in \"" << input << "\" were ignored:"
210 << endl;
211 ExEnv::out0() << incindent;
212 parsedkv->print_unseen(ExEnv::out0());
213 ExEnv::out0() << decindent;
214 }
215}
216
217double EvaluateDensity(
218 SCVector3 &r,
219 Ref<Integral> &intgrl,
220 GaussianBasisSet::ValueData &vdat,
221 Ref<Wavefunction> &wfn);
222
223/** Places all known options into \a options and parses them from argc,argv.
224 *
225 * \param options options structure
226 * \param argc argument count
227 * \param argv argument array
228 * \return return value by GetLongOpt::parse() function
229 */
230int ParseOptions(
231 GetLongOpt &options,
232 int argc,
233 char **argv)
234{
235 options.usage("[options] [filename]");
236 options.enroll("f", GetLongOpt::MandatoryValue,
237 "the name of an object format input file", 0);
238 options.enroll("o", GetLongOpt::MandatoryValue,
239 "the name of the output file", 0);
240 options.enroll("n", GetLongOpt::MandatoryValue,
241 "listen for incoming object format input files", 0);
242 options.enroll("messagegrp", GetLongOpt::MandatoryValue,
243 "which message group to use", 0);
244 options.enroll("threadgrp", GetLongOpt::MandatoryValue,
245 "which thread group to use", 0);
246 options.enroll("memorygrp", GetLongOpt::MandatoryValue,
247 "which memory group to use", 0);
248 options.enroll("integral", GetLongOpt::MandatoryValue,
249 "which integral evaluator to use", 0);
250 options.enroll("l", GetLongOpt::MandatoryValue, "basis set limit", "0");
251 options.enroll("W", GetLongOpt::MandatoryValue,
252 "set the working directory", ".");
253 options.enroll("c", GetLongOpt::NoValue, "check input then exit", 0);
254 options.enroll("v", GetLongOpt::NoValue, "print the version number", 0);
255 options.enroll("w", GetLongOpt::NoValue, "print the warranty", 0);
256 options.enroll("L", GetLongOpt::NoValue, "print the license", 0);
257 options.enroll("k", GetLongOpt::NoValue, "print key/value assignments", 0);
258 options.enroll("i", GetLongOpt::NoValue, "convert simple to OO input", 0);
259 options.enroll("d", GetLongOpt::NoValue, "debug", 0);
260 options.enroll("h", GetLongOpt::NoValue, "print this message", 0);
261 options.enroll("cca-path", GetLongOpt::OptionalValue,
262 "cca component path", "");
263 options.enroll("cca-load", GetLongOpt::OptionalValue,
264 "cca components to load", "");
265
266 int optind = options.parse(argc, argv);
267
268 return optind;
269}
270
271/** Checks for each known option and acts accordingly.
272 *
273 * \param options option structure
274 * \param *output name of outputfile on return
275 * \param *outstream open output stream on return
276 */
277void ComputeOptions(
278 GetLongOpt &options,
279 const char *&output,
280 ostream *&outstream)
281{
282 output = options.retrieve("o");
283 outstream = 0;
284 if (output != 0) {
285 outstream = new ofstream(output);
286 ExEnv::set_out(outstream);
287 }
288
289 if (options.retrieve("h")) {
290 ExEnv::out0()
291 << indent << "MPQC version " << SC_VERSION << endl
292 << indent << "compiled for " << TARGET_ARCH << endl
293 << SCFormIO::copyright << endl;
294 options.usage(ExEnv::out0());
295 exit(0);
296 }
297
298 if (options.retrieve("v")) {
299 ExEnv::out0()
300 << indent << "MPQC version " << SC_VERSION << endl
301 << indent << "compiled for " << TARGET_ARCH << endl
302 << SCFormIO::copyright;
303 exit(0);
304 }
305
306 if (options.retrieve("w")) {
307 ExEnv::out0()
308 << indent << "MPQC version " << SC_VERSION << endl
309 << indent << "compiled for " << TARGET_ARCH << endl
310 << SCFormIO::copyright << endl
311 << SCFormIO::warranty;
312 exit(0);
313 }
314
315 if (options.retrieve("L")) {
316 ExEnv::out0()
317 << indent << "MPQC version " << SC_VERSION << endl
318 << indent << "compiled for " << TARGET_ARCH << endl
319 << SCFormIO::copyright << endl
320 << SCFormIO::license;
321 exit(0);
322 }
323
324 if (options.retrieve("d"))
325 SCFormIO::set_debug(1);
326
327 // set the working dir
328 if (strcmp(options.retrieve("W"),"."))
329 int retval = chdir(options.retrieve("W"));
330
331 // check that n and f/o are not given at the same time
332 if ((options.retrieve("n")) && ((options.retrieve("f")) || (options.retrieve("o")))) {
333 throw invalid_argument("-n must not be given with -f or -o");
334 }
335}
336
337/** Temporary structure for storing information from command-line
338 *
339 * This structure has been introduced to gather the various calls to GetLongOpts
340 * at one (initial) place and to abstract it from the source of command-lines.
341 * This temporary object can be set by other means, too. I.e. we become
342 * independent of usage in command-line programs.
343 */
344struct OptionValues {
345 const char *keyvalue; // option "k"
346 const char *debug; // option ""
347 int limit; // option "l"
348 const char *check; // option "c"
349 const char *simple_input; // option "i"
350 string executablename;
351
352#ifdef HAVE_CHEMISTRY_CCA
353 string cca_load; // option "cca-path"
354 string cc_path; // option "cca-load"
355#endif
356};
357
358/** Parse remainder options not treated by ComputeOptions() into temporary storage.
359 *
360 * \param options option structure to obtain values from
361 * \param values remaining option values which are processed later and now
362 * stored in a temporary structure
363 */
364void parseRemainderOptions(
365 GetLongOpt &options,
366 struct OptionValues &values,
367 int argc,
368 char **argv)
369{
370 values.keyvalue = options.retrieve("k");
371 values.debug = options.retrieve("d");
372 values.limit = atoi(options.retrieve("l"));
373 values.check = options.retrieve("c");
374 values.simple_input = options.retrieve("i");
375 values.executablename = argv[0];
376
377#ifdef HAVE_CHEMISTRY_CCA
378 values.cca_load = options.retrieve("cca-load");
379 values.cca_path = options.retrieve("cca-path");
380#endif
381}
382
383/** Sets object and generic input file names.
384 *
385 * \param object_input filename of object-oriented input
386 * \param generic_input filename of generic input
387 * \param options (command-line)option structure
388 * \param argc argument count
389 * \param argv argument array
390 */
391void getInputFileNames(
392 const char *&object_input,
393 const char *&generic_input,
394 GetLongOpt &options,
395 int optind,
396 int argc,
397 char **argv)
398{
399 // initialize keyval input
400 object_input = options.retrieve("f");
401 generic_input = 0;
402 if (argc - optind == 0) {
403 generic_input = 0;
404 }
405 else if (argc - optind == 1) {
406 generic_input = argv[optind];
407 }
408 else if (!options.retrieve("n")) {
409 options.usage();
410 throw invalid_argument("extra arguments given");
411 }
412
413 if (object_input == 0 && generic_input == 0) {
414 generic_input = "mpqc.in";
415 }
416 else if (object_input && !options.retrieve("n") && generic_input) {
417 options.usage();
418 throw invalid_argument("only one of -f and a file argument can be given");
419 }
420}
421
422/** Gets the MPI Message group.
423 *
424 * \param grp reference to obtained group
425 * \param argc argument count
426 * \param argv argument array
427 */
428void getMessageGroup(
429 Ref<MessageGrp> &grp,
430 int argc,
431 char **argv)
432{
433#if defined(HAVE_MPI) && defined(ALWAYS_USE_MPI)
434 grp = new MPIMessageGrp(&argc, &argv);
435#endif
436 if (grp.null()) grp = MessageGrp::initial_messagegrp(argc, argv);
437 if (grp.nonnull())
438 MessageGrp::set_default_messagegrp(grp);
439 else
440 grp = MessageGrp::get_default_messagegrp();
441}
442
443/** Sets the base name of output files.
444 *
445 * \param input input file name
446 * \param output output file name
447 */
448void setOutputBaseName(const char *input, const char *output)
449{
450 const char *basename_source;
451 if (output) basename_source = output;
452 else basename_source = input;
453 const char *baseprefix = ::strrchr(basename_source, '.');
454 int nfilebase = 1;
455 if (baseprefix == NULL) {
456 std::cerr << "setOutputBaseName() - ERROR: basename_source "
457 << basename_source << " contains no dot (.)." << std::endl;
458 nfilebase = ::strlen(basename_source);
459 } else
460 nfilebase = (int) (baseprefix - basename_source);
461 char *basename = new char[nfilebase + 1];
462 strncpy(basename, basename_source, nfilebase);
463 basename[nfilebase] = '\0';
464 SCFormIO::set_default_basename(basename);
465 delete[] basename;
466}
467
468/** Prints current key values.
469 *
470 * \param keyval key value structure
471 * \param opt optimization structure
472 * \param molname name of molecule
473 * \param restartfile name of restartfile
474 */
475void printOptions(
476 Ref<KeyVal> &keyval,
477 Ref<Optimize> &opt,
478 const char *molname,
479 const char *restartfile)
480{
481 int restart = keyval->booleanvalue("restart",truevalue);
482
483 int checkpoint = keyval->booleanvalue("checkpoint",truevalue);
484
485 int savestate = keyval->booleanvalue("savestate",truevalue);
486
487 int do_energy = keyval->booleanvalue("do_energy",truevalue);
488
489 int do_grad = keyval->booleanvalue("do_gradient",falsevalue);
490
491 int do_opt = keyval->booleanvalue("optimize",truevalue);
492
493 int do_pdb = keyval->booleanvalue("write_pdb",falsevalue);
494
495 int print_mole = keyval->booleanvalue("print_mole",truevalue);
496
497 int print_timings = keyval->booleanvalue("print_timings",truevalue);
498
499 // sanity checks for the benefit of reasonable looking output
500 if (opt.null()) do_opt=0;
501
502 ExEnv::out0() << endl << indent
503 << "MPQC options:" << endl << incindent
504 << indent << "matrixkit = <"
505 << SCMatrixKit::default_matrixkit()->class_name() << ">" << endl
506 << indent << "filename = " << molname << endl
507 << indent << "restart_file = " << restartfile << endl
508 << indent << "restart = " << (restart ? "yes" : "no") << endl
509 << indent << "checkpoint = " << (checkpoint ? "yes" : "no") << endl
510 << indent << "savestate = " << (savestate ? "yes" : "no") << endl
511 << indent << "do_energy = " << (do_energy ? "yes" : "no") << endl
512 << indent << "do_gradient = " << (do_grad ? "yes" : "no") << endl
513 << indent << "optimize = " << (do_opt ? "yes" : "no") << endl
514 << indent << "write_pdb = " << (do_pdb ? "yes" : "no") << endl
515 << indent << "print_mole = " << (print_mole ? "yes" : "no") << endl
516 << indent << "print_timings = " << (print_timings ? "yes" : "no")
517 << endl << decindent;
518
519}
520
521/** Saves the current state to checkpoint file.
522 *
523 * \param keyval key value structure
524 * \param opt optimization structure
525 * \param grp message group
526 * \param mole MolecularEnergy object
527 * \param molname name of molecule
528 * \param ckptfile name of check point file
529 */
530void saveState(
531 char *wfn_file,
532 int savestate,
533 Ref<Optimize> &opt,
534 Ref<MessageGrp> &grp,
535 Ref<MolecularEnergy> &mole,
536 char *&molname,
537 char *&ckptfile)
538{
539 // function stuff
540 if (savestate) {
541 if (opt.nonnull()) {
542 if (grp->me() == 0) {
543 ckptfile = new char[strlen(molname)+6];
544 sprintf(ckptfile,"%s.ckpt",molname);
545 }
546 else {
547 ckptfile = new char[strlen(devnull)+1];
548 strcpy(ckptfile, devnull);
549 }
550
551 StateOutBin so(ckptfile);
552 SavableState::save_state(opt.pointer(),so);
553 so.close();
554
555 delete[] ckptfile;
556 }
557
558 if (mole.nonnull()) {
559 if (grp->me() == 0) {
560 if (wfn_file == 0) {
561 wfn_file = new char[strlen(molname)+6];
562 sprintf(wfn_file,"%s.wfn",molname);
563 }
564 }
565 else {
566 delete[] wfn_file;
567 wfn_file = new char[strlen(devnull)+1];
568 strcpy(wfn_file, devnull);
569 }
570
571 StateOutBin so(wfn_file);
572 SavableState::save_state(mole.pointer(),so);
573 so.close();
574
575 }
576 }
577 delete[] wfn_file;
578}
579
580/** Sets up indentation and output modes.
581 *
582 * \param grp message group
583 */
584void setupSCFormIO(
585 Ref<MessageGrp> &grp
586 )
587{
588 SCFormIO::setindent(ExEnv::outn(), 2);
589 SCFormIO::setindent(ExEnv::errn(), 2);
590 SCFormIO::setindent(cout, 2);
591 SCFormIO::setindent(cerr, 2);
592
593 SCFormIO::set_printnode(0);
594 if (grp->n() > 1)
595 SCFormIO::init_mp(grp->me());
596}
597
598/** Initialises the timer.
599 *
600 * \param grp message group
601 * \param keyval key value structure
602 * \param tim timing structure
603 */
604void initTimings(
605 Ref<MessageGrp> &grp,
606 Ref<KeyVal> &keyval,
607 Ref<RegionTimer> &tim
608 )
609{
610 grp->sync(); // make sure nodes are sync'ed before starting timings
611 if (keyval->exists("timer")) tim << keyval->describedclassvalue("timer");
612 else tim = new ParallelRegionTimer(grp,"mpqc",1,1);
613 RegionTimer::set_default_regiontimer(tim);
614
615 if (tim.nonnull()) tim->enter("input");
616}
617
618/** Prints the header of the output.
619 *
620 * \param tim timing structure
621 */
622void makeAnnouncement(
623 Ref<RegionTimer> &tim
624 )
625{
626 const char title1[] = "MPQC: Massively Parallel Quantum Chemistry";
627 int ntitle1 = sizeof(title1);
628 const char title2[] = "Version " SC_VERSION;
629 int ntitle2 = sizeof(title2);
630 ExEnv::out0() << endl;
631 ExEnv::out0() << indent;
632 for (int i=0; i<(80-ntitle1)/2; i++) ExEnv::out0() << ' ';
633 ExEnv::out0() << title1 << endl;
634 ExEnv::out0() << indent;
635 for (int i=0; i<(80-ntitle2)/2; i++) ExEnv::out0() << ' ';
636 ExEnv::out0() << title2 << endl << endl;
637
638 const char *tstr = 0;
639#if defined(HAVE_TIME) && defined(HAVE_CTIME)
640 time_t t;
641 time(&t);
642 tstr = ctime(&t);
643#endif
644 if (!tstr) {
645 tstr = "UNKNOWN";
646 }
647
648 ExEnv::out0()
649 << indent << scprintf("Machine: %s", TARGET_ARCH) << endl
650 << indent << scprintf("User: %s@%s",
651 ExEnv::username(), ExEnv::hostname()) << endl
652 << indent << scprintf("Start Time: %s", tstr) << endl;
653}
654
655/** Parse the input configuration from char array into keyvalue container.
656 *
657 * \param parsedkv key value container to foll
658 * \param values temporary options value structure
659 * \param in_char_array char array with input file
660 * \param use_simple_input whether the format in \a in_char_array is simple (1)
661 * or object-oriented (0)
662 */
663void parseIntoKeyValue(
664 Ref<ParsedKeyVal> &parsedkv,
665 struct OptionValues &values,
666 char *&in_char_array,
667 int use_simple_input)
668{
669 if (use_simple_input) {
670 MPQCIn mpqcin;
671 char *simple_input_text = mpqcin.parse_string(in_char_array);
672 if (values.simple_input) {
673 ExEnv::out0() << "Generated object-oriented input file:" << endl
674 << simple_input_text
675 << endl;
676 exit(0);
677 }
678 parsedkv = new ParsedKeyVal();
679 parsedkv->parse_string(simple_input_text);
680 delete[] simple_input_text;
681 } else {
682 parsedkv = new ParsedKeyVal();
683 parsedkv->parse_string(in_char_array);
684 }
685}
686
687/** Parse the input file into the key value container.
688 *
689 * \param grp message group
690 * \param parsedkev keyvalue container on return
691 * \param values (command-line) options structure
692 * \param input input file name
693 * \param generic_input filename of generic input
694 * \param in_char_array char array with input file's contents on return
695 * \param use_simple_input whether the file contents is in simple format (1)
696 * or object-oriented (0)
697 */
698void parseInputfile(
699 Ref<MessageGrp> &grp,
700 Ref<ParsedKeyVal> &parsedkv,
701 struct OptionValues &values,
702 const char *&input,
703 const char *&generic_input,
704 char *&in_char_array,
705 int &use_simple_input
706 )
707{
708 // read the input file on only node 0
709 if (grp->me() == 0) {
710 ifstream is(input);
711#ifdef HAVE_SSTREAM
712 ostringstream ostrs;
713 is >> ostrs.rdbuf();
714 int n = 1 + strlen(ostrs.str().c_str());
715 in_char_array = strcpy(new char[n],ostrs.str().c_str());
716#else
717 ostrstream ostrs;
718 is >> ostrs.rdbuf();
719 ostrs << ends;
720 in_char_array = ostrs.str();
721 int n = ostrs.pcount();
722#endif
723 grp->bcast(n);
724 grp->bcast(in_char_array, n);
725 }
726 else {
727 int n;
728 grp->bcast(n);
729 in_char_array = new char[n];
730 grp->bcast(in_char_array, n);
731 }
732
733 if (generic_input && grp->me() == 0) {
734 MPQCIn mpqcin;
735 use_simple_input = mpqcin.check_string(in_char_array);
736 }
737 else {
738 use_simple_input = 0;
739 }
740 grp->bcast(use_simple_input);
741}
742
743/** Get the thread group.
744 *
745 * \param keyval keyvalue container
746 * \param thread thread group on return
747 * \param argc argument count
748 * \param argv argument array
749 */
750void getThreadGroup(
751 Ref<KeyVal> &keyval,
752 Ref<ThreadGrp> &thread,
753 int argc,
754 char **argv)
755{
756 //first try the commandline and environment
757 thread = ThreadGrp::initial_threadgrp(argc, argv);
758
759 // if we still don't have a group, try reading the thread group
760 // from the input
761 if (thread.null()) {
762 thread << keyval->describedclassvalue("thread");
763 }
764
765 if (thread.nonnull())
766 ThreadGrp::set_default_threadgrp(thread);
767 else
768 thread = ThreadGrp::get_default_threadgrp();
769}
770
771/** Get the memory group.
772 *
773 * \param keyval keyvalue container
774 * \param memory memory group on return
775 * \param argc argument count
776 * \param argv argument array
777 */
778void getMemoryGroup(
779 Ref<KeyVal> &keyval,
780 Ref<MemoryGrp> &memory,
781 int argc,
782 char **argv)
783{
784 // first try the commandline and environment
785 memory = MemoryGrp::initial_memorygrp(argc, argv);
786
787 // if we still don't have a group, try reading the memory group
788 // from the input
789 if (memory.null()) {
790 memory << keyval->describedclassvalue("memory");
791 }
792
793 if (memory.nonnull())
794 MemoryGrp::set_default_memorygrp(memory);
795 else
796 memory = MemoryGrp::get_default_memorygrp();
797}
798
799/** Prepares CCA component if available.
800 *
801 * \param keyval keyvalue container
802 * \param values parsed (command-line) options
803 */
804void prepareCCA(
805 Ref<KeyVal> &keyval,
806 struct OptionValues &values
807 )
808{
809#ifdef HAVE_CHEMISTRY_CCA
810 // initialize cca framework
811 KeyValValuestring emptystring("");
812 bool do_cca = keyval->booleanvalue("do_cca",falsevalue);
813
814 string cca_path(values.cca_path);
815 string cca_load(values.cca_load);
816 if(cca_path.size()==0)
817 cca_path = keyval->stringvalue("cca_path",emptystring);
818 if(cca_load.size()==0)
819 cca_load = keyval->stringvalue("cca_load",emptystring);
820
821 if( !do_cca && (cca_load.size() > 0 || cca_path.size() > 0) )
822 do_cca = true;
823
824 if(cca_path.size()==0) {
825 #ifdef CCA_PATH
826 cca_path = CCA_PATH;
827 #endif
828 }
829 if(cca_load.size()==0) {
830 cca_load += "MPQC.IntegralEvaluatorFactory";
831 }
832
833 if( cca_load.size() > 0 && cca_path.size() > 0 && do_cca ) {
834 string cca_args = "--path " + cca_path + " --load " + cca_load;
835 ExEnv::out0() << endl << indent << "Initializing CCA framework with args: "
836 << endl << indent << cca_args << endl;
837 CCAEnv::init( cca_args );
838 }
839#endif
840}
841
842/** Setup debugger.
843 *
844 * \param keyval keyvalue container
845 * \param grp message group
846 * \param debugger debugger structure
847 * \param options parsed command line options
848 */
849void setupDebugger(
850 Ref<KeyVal> &keyval,
851 Ref<MessageGrp> &grp,
852 Ref<Debugger> &debugger,
853 struct OptionValues &values)
854{
855 debugger << keyval->describedclassvalue("debug");
856 if (debugger.nonnull()) {
857 Debugger::set_default_debugger(debugger);
858 debugger->set_exec(values.executablename.c_str());
859 debugger->set_prefix(grp->me());
860 if (values.debug)
861 debugger->debug("Starting debugger because -d given on command line.");
862 }
863}
864
865/** Get integral factory.
866 *
867 * \param keyval keyvalue container
868 * \param integral integral group on return
869 * \param argc argument count
870 * \param argv argument array
871 */
872void getIntegralFactory(
873 Ref<KeyVal> &keyval,
874 Ref<Integral> &integral,
875 int argc,
876 char **argv)
877{
878 // first try commandline and environment
879 integral = Integral::initial_integral(argc, argv);
880
881 // if we still don't have a integral, try reading the integral
882 // from the input
883 if (integral.null()) {
884 integral << keyval->describedclassvalue("integrals");
885 }
886
887 if (integral.nonnull())
888 Integral::set_default_integral(integral);
889 else
890 integral = Integral::get_default_integral();
891
892}
893
894void performRestart(
895 Ref<KeyVal> &keyval,
896 Ref<MessageGrp> &grp,
897 Ref<Optimize> &opt,
898 Ref<MolecularEnergy> &mole,
899 char *&restartfile
900 )
901{
902 int restart = keyval->booleanvalue("restart",truevalue);
903 struct stat sb;
904 int statresult, statsize;
905 if (restart) {
906 if (grp->me() == 0) {
907 statresult = stat(restartfile,&sb);
908 statsize = (statresult==0) ? sb.st_size : 0;
909 }
910 grp->bcast(statresult);
911 grp->bcast(statsize);
912 }
913 if (restart && statresult==0 && statsize) {
914 BcastStateInBin si(grp,restartfile);
915 if (keyval->exists("override")) {
916 si.set_override(new PrefixKeyVal(keyval,"override"));
917 }
918 char *suf = strrchr(restartfile,'.');
919 if (!strcmp(suf,".wfn")) {
920 mole << SavableState::key_restore_state(si,"mole");
921 ExEnv::out0() << endl
922 << indent << "Restored <" << mole->class_name()
923 << "> from " << restartfile << endl;
924
925 opt << keyval->describedclassvalue("opt");
926 if (opt.nonnull())
927 opt->set_function(mole.pointer());
928 }
929 else {
930 opt << SavableState::key_restore_state(si,"opt");
931 if (opt.nonnull()) {
932 mole << opt->function();
933 ExEnv::out0() << endl << indent
934 << "Restored <Optimize> from " << restartfile << endl;
935 }
936 }
937 } else {
938 mole << keyval->describedclassvalue("mole");
939 opt << keyval->describedclassvalue("opt");
940 }
941}
942
943char *setMolecularCheckpointFile(
944 Ref<KeyVal> &keyval,
945 Ref<MessageGrp> &grp,
946 Ref<MolecularEnergy> &mole,
947 char *mole_ckpt_file
948 )
949{
950 int checkpoint = keyval->booleanvalue("checkpoint",truevalue);
951 int checkpoint_freq = keyval->intvalue("checkpoint_freq",KeyValValueint(1));
952 if (mole.nonnull()) {
953 MolecularFormula mf(mole->molecule());
954 ExEnv::out0() << endl << indent
955 << "Molecular formula " << mf.formula() << endl;
956 if (checkpoint) {
957 mole->set_checkpoint();
958 if (grp->me() == 0) mole->set_checkpoint_file(mole_ckpt_file);
959 else mole->set_checkpoint_file(devnull);
960 mole->set_checkpoint_freq(checkpoint_freq);
961 }
962 }
963}
964
965/** Checks whether limit on command-line exceeds the basis functions.
966 *
967 * \param mole molecular energy object
968 * \param values temporarily storage for (command-line) options
969 * \return 0 - not exceeded, 1 - exceeded
970 */
971int checkBasisSetLimit(
972 Ref<MolecularEnergy> &mole,
973 struct OptionValues &values
974 )
975{
976 int check = (values.check != (const char *)0);
977 int limit = values.limit;
978 if (limit) {
979 Ref<Wavefunction> wfn; wfn << mole;
980 if (wfn.nonnull() && wfn->ao_dimension()->n() > limit) {
981 ExEnv::out0() << endl << indent
982 << "The limit of " << limit << " basis functions has been exceeded."
983 << endl;
984 check = 1;
985 }
986 }
987 return check;
988}
989
990/** Performs the energy optimization.
991 *
992 * \param opt optimization object
993 * \param mole molecular energy object
994 * \return 0 - not read for frequency calculation, 1 - ready
995 */
996int performEnergyOptimization(
997 Ref<Optimize> &opt,
998 Ref<MolecularEnergy> &mole
999 )
1000{
1001 int ready_for_freq = 0;
1002 int result = opt->optimize();
1003 if (result) {
1004 ExEnv::out0() << indent
1005 << "The optimization has converged." << endl << endl;
1006 ExEnv::out0() << indent
1007 << scprintf("Value of the MolecularEnergy: %15.10f",
1008 mole->energy())
1009 << endl << endl;
1010 ready_for_freq = 1;
1011 } else {
1012 ExEnv::out0() << indent
1013 << "The optimization has NOT converged." << endl << endl;
1014 ready_for_freq = 0;
1015 }
1016 return ready_for_freq;
1017}
1018
1019/** Performs gradient calculation.
1020 *
1021 * \param mole molecular energy object
1022 */
1023void performGradientCalculation(
1024 Ref<MolecularEnergy> &mole
1025 )
1026{
1027 mole->do_gradient(1);
1028 ExEnv::out0() << endl << indent
1029 << scprintf("Value of the MolecularEnergy: %15.10f",
1030 mole->energy())
1031 << endl;
1032 if (mole->value_result().actual_accuracy()
1033 > mole->value_result().desired_accuracy()) {
1034 ExEnv::out0() << indent
1035 << "WARNING: desired accuracy not achieved in energy" << endl;
1036 }
1037 ExEnv::out0() << endl;
1038 // Use result_noupdate since the energy might not have converged
1039 // to the desired accuracy in which case grabbing the result will
1040 // start up the calculation again. However the gradient might
1041 // not have been computed (if we are restarting and the gradient
1042 // isn't in the save file for example).
1043 RefSCVector grad;
1044 if (mole->gradient_result().computed()) {
1045 grad = mole->gradient_result().result_noupdate();
1046 }
1047 else {
1048 grad = mole->gradient();
1049 }
1050 if (grad.nonnull()) {
1051 grad.print("Gradient of the MolecularEnergy:");
1052 if (mole->gradient_result().actual_accuracy()
1053 > mole->gradient_result().desired_accuracy()) {
1054 ExEnv::out0() << indent
1055 << "WARNING: desired accuracy not achieved in gradient" << endl;
1056 }
1057 }
1058}
1059
1060/** Performs frequency calculation.
1061 *
1062 * \param mole molecular energy object
1063 * \param molhess molecular hessian object
1064 * \param molfreq molecular frequency object
1065 */
1066void performFrequencyCalculation(
1067 Ref<MolecularEnergy> &mole,
1068 Ref<MolecularHessian> &molhess,
1069 Ref<MolecularFrequencies> &molfreq
1070
1071 )
1072{
1073 RefSymmSCMatrix xhessian;
1074 if (molhess.nonnull()) {
1075 // if "hess" input was given, use it to compute the hessian
1076 xhessian = molhess->cartesian_hessian();
1077 }
1078 else if (mole->hessian_implemented()) {
1079 // if mole can compute the hessian, use that hessian
1080 xhessian = mole->get_cartesian_hessian();
1081 }
1082 else if (mole->gradient_implemented()) {
1083 // if mole can compute gradients, use gradients at finite
1084 // displacements to compute the hessian
1085 molhess = new FinDispMolecularHessian(mole);
1086 xhessian = molhess->cartesian_hessian();
1087 }
1088 else {
1089 ExEnv::out0() << "mpqc: WARNING: Frequencies cannot be computed" << endl;
1090 }
1091
1092 if (xhessian.nonnull()) {
1093 char *hessfile = SCFormIO::fileext_to_filename(".hess");
1094 MolecularHessian::write_cartesian_hessian(hessfile,
1095 mole->molecule(), xhessian);
1096 delete[] hessfile;
1097
1098 molfreq->compute_frequencies(xhessian);
1099 // DEGENERACY IS NOT CORRECT FOR NON-SINGLET CASES:
1100 molfreq->thermochemistry(1);
1101 }
1102}
1103
1104/** Renders some objects.
1105 *
1106 * \param renderer renderer object
1107 * \param keyval keyvalue container
1108 * \param tim timing object
1109 * \param grp message group
1110 */
1111void renderObjects(
1112 Ref<Render> &renderer,
1113 Ref<KeyVal> &keyval,
1114 Ref<RegionTimer> &tim,
1115 Ref<MessageGrp> &grp
1116 )
1117{
1118 Ref<RenderedObject> rendered;
1119 rendered << keyval->describedclassvalue("rendered");
1120 Ref<AnimatedObject> animated;
1121 animated << keyval->describedclassvalue("rendered");
1122 if (rendered.nonnull()) {
1123 if (tim.nonnull()) tim->enter("render");
1124 if (grp->me() == 0) renderer->render(rendered);
1125 if (tim.nonnull()) tim->exit("render");
1126 }
1127 else if (animated.nonnull()) {
1128 if (tim.nonnull()) tim->enter("render");
1129 if (grp->me() == 0) renderer->animate(animated);
1130 if (tim.nonnull()) tim->exit("render");
1131 }
1132 else {
1133 if (tim.nonnull()) tim->enter("render");
1134 int n = keyval->count("rendered");
1135 for (int i=0; i<n; i++) {
1136 rendered << keyval->describedclassvalue("rendered",i);
1137 animated << keyval->describedclassvalue("rendered",i);
1138 if (rendered.nonnull()) {
1139 // make sure the object has a name so we don't overwrite its file
1140 if (rendered->name() == 0) {
1141 char ic[64];
1142 sprintf(ic,"%02d",i);
1143 rendered->set_name(ic);
1144 }
1145 if (grp->me() == 0) renderer->render(rendered);
1146 }
1147 else if (animated.nonnull()) {
1148 // make sure the object has a name so we don't overwrite its file
1149 if (animated->name() == 0) {
1150 char ic[64];
1151 sprintf(ic,"%02d",i);
1152 animated->set_name(ic);
1153 }
1154 if (grp->me() == 0) renderer->animate(animated);
1155 }
1156 }
1157 if (tim.nonnull()) tim->exit("render");
1158 }
1159}
1160
1161/** Save the molecule to PDB file.
1162 *
1163 * \param do_pdb whether to save as pdb (1) or not (0)
1164 * \param grp message group
1165 * \param mole molecular energy object
1166 * \param molname name of output file
1167 */
1168void saveToPdb(
1169 int do_pdb,
1170 Ref<MessageGrp> &grp,
1171 Ref<MolecularEnergy> &mole,
1172 const char *molname
1173 )
1174{
1175 if (do_pdb && grp->me() == 0) {
1176 char *ckptfile = new char[strlen(molname)+5];
1177 sprintf(ckptfile, "%s.pdb", molname);
1178 ofstream pdbfile(ckptfile);
1179 mole->molecule()->print_pdb(pdbfile);
1180 delete[] ckptfile;
1181 }
1182}
1183
1184void init()
1185{
1186 //trash_stack();
1187
1188 int i;
1189 atexit(clean_up);
1190
1191#ifdef HAVE_FEENABLEEXCEPT
1192 // this uses a glibc extension to trap on individual exceptions
1193# ifdef FE_DIVBYZERO
1194 feenableexcept(FE_DIVBYZERO);
1195# endif
1196# ifdef FE_INVALID
1197 feenableexcept(FE_INVALID);
1198# endif
1199# ifdef FE_OVERFLOW
1200 feenableexcept(FE_OVERFLOW);
1201# endif
1202#endif
1203
1204#ifdef HAVE_FEDISABLEEXCEPT
1205 // this uses a glibc extension to not trap on individual exceptions
1206# ifdef FE_UNDERFLOW
1207 fedisableexcept(FE_UNDERFLOW);
1208# endif
1209# ifdef FE_INEXACT
1210 fedisableexcept(FE_INEXACT);
1211# endif
1212#endif
1213
1214#if defined(HAVE_SETRLIMIT)
1215 struct rlimit rlim;
1216 rlim.rlim_cur = 0;
1217 rlim.rlim_max = 0;
1218 setrlimit(RLIMIT_CORE,&rlim);
1219#endif
1220}
1221
1222/** Performs the main work to calculate the ground state energies, gradients, etc.
1223 *
1224 * @param grp message group
1225 * @param values temporary value storage for parsed command-line
1226 * @param input input file name
1227 * @param generic_input generic input file name
1228 * @param in_char_array either NULL or contains char array with read input
1229 * @param argc argument count
1230 * @param argv argument array
1231 */
1232void mainFunction(
1233 Ref<MessageGrp> grp,
1234 struct OptionValues &values,
1235 const char *&output,
1236 const char *&input,
1237 const char *&generic_input,
1238 char *&in_char_array,
1239 int argc,
1240 char **argv
1241#ifdef HAVE_MPQCDATA
1242 , MPQCData &data
1243#endif
1244 )
1245{
1246 // get the basename for output files
1247 setOutputBaseName(input, output);
1248
1249 // parse input into keyvalue container
1250 Ref<ParsedKeyVal> parsedkv;
1251 int use_simple_input = 0; // default is object-oriented if in_char_array is given
1252 if (!in_char_array) // obtain from file
1253 parseInputfile(grp, parsedkv, values, input, generic_input, in_char_array, use_simple_input);
1254 parseIntoKeyValue(parsedkv, values, in_char_array, use_simple_input);
1255 delete[] in_char_array;
1256
1257 // prefix parsed values wit "mpqc"
1258 if (values.keyvalue) parsedkv->verbose(1);
1259 Ref<KeyVal> keyval = new PrefixKeyVal(parsedkv.pointer(),"mpqc");
1260
1261 // set up output classes
1262 setupSCFormIO(grp);
1263
1264 // initialize timing for mpqc
1265 Ref<RegionTimer> tim;
1266 initTimings(grp, keyval, tim);
1267
1268 // announce ourselves
1269 makeAnnouncement(tim);
1270
1271 // get the thread group.
1272 Ref<ThreadGrp> thread;
1273 getThreadGroup(keyval, thread, argc, argv);
1274
1275 // get the memory group.
1276 Ref<MemoryGrp> memory;
1277 getMemoryGroup(keyval, memory, argc, argv);
1278
1279 ExEnv::out0() << indent
1280 << "Using " << grp->class_name()
1281 << " for message passing (number of nodes = " << grp->n() << ")." << endl
1282 << indent
1283 << "Using " << thread->class_name()
1284 << " for threading (number of threads = " << thread->nthread() << ")." << endl
1285 << indent
1286 << "Using " << memory->class_name()
1287 << " for distributed shared memory." << endl
1288 << indent
1289 << "Total number of processors = " << grp->n() * thread->nthread() << endl;
1290
1291 // prepare CCA if available
1292 prepareCCA(keyval, values);
1293
1294 // now set up the debugger
1295 Ref<Debugger> debugger;
1296 setupDebugger(keyval, grp, debugger, values);
1297
1298 // now check to see what matrix kit to use
1299 if (keyval->exists("matrixkit"))
1300 SCMatrixKit::set_default_matrixkit(
1301 dynamic_cast<SCMatrixKit*>(
1302 keyval->describedclassvalue("matrixkit").pointer()));
1303
1304 // get the integral factory.
1305 Ref<Integral> integral;
1306 getIntegralFactory(keyval, integral, argc, argv);
1307 ExEnv::out0() << endl << indent
1308 << "Using " << integral->class_name()
1309 << " by default for molecular integrals evaluation" << endl << endl;
1310
1311 // create some filenames for molecule, checkpoint, basename of output
1312 const char *basename = SCFormIO::default_basename();
1313 KeyValValueString molnamedef(basename);
1314 char * molname = keyval->pcharvalue("filename", molnamedef);
1315 if (strcmp(molname, basename))
1316 SCFormIO::set_default_basename(molname);
1317
1318 char * ckptfile = new char[strlen(molname)+6];
1319 sprintf(ckptfile,"%s.ckpt",molname);
1320
1321 KeyValValueString restartfiledef(ckptfile);
1322 char * restartfile = keyval->pcharvalue("restart_file", restartfiledef);
1323
1324 char * wfn_file = keyval->pcharvalue("wfn_file");
1325 if (wfn_file == 0) {
1326 wfn_file = new char[strlen(molname)+6];
1327 sprintf(wfn_file,"%s.wfn",molname);
1328 }
1329 char *mole_ckpt_file = new char[strlen(wfn_file)+1];
1330 sprintf(mole_ckpt_file,"%s",wfn_file);
1331
1332 int savestate = keyval->booleanvalue("savestate",truevalue);
1333
1334 // setup molecular energy and optimization instances
1335 Ref<MolecularEnergy> mole;
1336 Ref<Optimize> opt;
1337
1338 // read in restart file if we do restart
1339 performRestart(keyval, grp, opt, mole, restartfile);
1340
1341 // setup molecule checkpoint file
1342 setMolecularCheckpointFile(keyval, grp, mole, mole_ckpt_file);
1343 delete[] mole_ckpt_file;
1344
1345 int checkpoint = keyval->booleanvalue("checkpoint",truevalue);
1346 if (checkpoint && opt.nonnull()) {
1347 opt->set_checkpoint();
1348 if (grp->me() == 0) opt->set_checkpoint_file(ckptfile);
1349 else opt->set_checkpoint_file(devnull);
1350 }
1351
1352 // see if frequencies are wanted
1353 Ref<MolecularHessian> molhess;
1354 molhess << keyval->describedclassvalue("hess");
1355 Ref<MolecularFrequencies> molfreq;
1356 molfreq << keyval->describedclassvalue("freq");
1357
1358 // check basis set limit
1359 const int check = checkBasisSetLimit(mole, values);
1360 if (check) {
1361 ExEnv::out0() << endl << indent
1362 << "Exiting since the check option is on." << endl;
1363 exit(0);
1364 }
1365
1366 // from now on we time the calculations
1367 if (tim.nonnull()) tim->change("calc");
1368
1369 int do_energy = keyval->booleanvalue("do_energy",truevalue);
1370
1371 int do_grad = keyval->booleanvalue("do_gradient",falsevalue);
1372
1373 int do_opt = keyval->booleanvalue("optimize",truevalue);
1374
1375 int do_pdb = keyval->booleanvalue("write_pdb",falsevalue);
1376
1377 int print_mole = keyval->booleanvalue("print_mole",truevalue);
1378
1379 int print_timings = keyval->booleanvalue("print_timings",truevalue);
1380
1381 // print all current options (keyvalues)
1382 printOptions(keyval, opt, molname, restartfile);
1383
1384 // see if any pictures are desired
1385 Ref<Render> renderer;
1386 renderer << keyval->describedclassvalue("renderer");
1387
1388 // If we have a renderer, then we will read in some more info
1389 // below. Otherwise we can get rid of the keyval's, to eliminate
1390 // superfluous references to objects that we might otherwise be
1391 // able to delete. We cannot read in the remaining rendering
1392 // objects now, since some of their KeyVal CTOR's are heavyweight,
1393 // requiring optimized geometries, etc.
1394 if (renderer.null()) {
1395 if (parsedkv.nonnull()) print_unseen(parsedkv, input);
1396 keyval = 0;
1397 parsedkv = 0;
1398 }
1399
1400 delete[] restartfile;
1401 delete[] ckptfile;
1402
1403 int ready_for_freq = 1;
1404 if (mole.nonnull()) {
1405 if (((do_opt && opt.nonnull()) || do_grad)
1406 && !mole->gradient_implemented()) {
1407 ExEnv::out0() << indent
1408 << "WARNING: optimization or gradient requested but the given"
1409 << endl
1410 << " MolecularEnergy object cannot do gradients."
1411 << endl;
1412 }
1413
1414 if (do_opt && opt.nonnull() && mole->gradient_implemented()) {
1415
1416 ready_for_freq = performEnergyOptimization(opt, mole);
1417
1418 } else if (do_grad && mole->gradient_implemented()) {
1419
1420 performGradientCalculation(mole);
1421
1422 } else if (do_energy && mole->value_implemented()) {
1423 ExEnv::out0() << endl << indent
1424 << scprintf("Value of the MolecularEnergy: %15.10f",
1425 mole->energy())
1426 << endl << endl;
1427 }
1428 }
1429
1430 // stop timing of calculations
1431 if (tim.nonnull()) tim->exit("calc");
1432
1433 // save this before doing the frequency stuff since that obsoletes the
1434 saveState(wfn_file, savestate, opt, grp, mole, molname, ckptfile);
1435
1436 // Frequency calculation.
1437 if (ready_for_freq && molfreq.nonnull()) {
1438 performFrequencyCalculation(mole, molhess, molfreq);
1439 }
1440
1441 if (renderer.nonnull()) {
1442 renderObjects(renderer, keyval, tim, grp);
1443
1444 Ref<MolFreqAnimate> molfreqanim;
1445 molfreqanim << keyval->describedclassvalue("animate_modes");
1446 if (ready_for_freq && molfreq.nonnull()
1447 && molfreqanim.nonnull()) {
1448 if (tim.nonnull()) tim->enter("render");
1449 molfreq->animate(renderer, molfreqanim);
1450 if (tim.nonnull()) tim->exit("render");
1451 }
1452 }
1453
1454 if (mole.nonnull()) {
1455 if (print_mole)
1456 mole->print(ExEnv::out0());
1457
1458 saveToPdb(do_pdb, grp, mole, molname);
1459
1460 }
1461 else {
1462 ExEnv::out0() << "mpqc: The molecular energy object is null" << endl
1463 << " make sure \"mole\" specifies a MolecularEnergy derivative"
1464 << endl;
1465 }
1466 if (parsedkv.nonnull()) print_unseen(parsedkv, input);
1467
1468 if (print_timings)
1469 if (tim.nonnull()) tim->print(ExEnv::out0());
1470
1471 // here, we may gather the results
1472 // we start to fill the MPQC_Data object
1473 {
1474 Ref<Wavefunction> wfn;
1475 wfn << mole;
1476// ExEnv::out0() << "The number of atomic orbitals: " << wfn->ao_dimension()->n() << endl;
1477// ExEnv::out0() << "The AO density matrix is ";
1478// wfn->ao_density()->print(ExEnv::out0());
1479// ExEnv::out0() << "The natural density matrix is ";
1480// wfn->natural_density()->print(ExEnv::out0());
1481// ExEnv::out0() << "The Gaussian basis is " << wfn->basis()->name() << endl;
1482// ExEnv::out0() << "The Gaussians sit at the following centers: " << endl;
1483// for (int nr = 0; nr< wfn->basis()->ncenter(); ++nr) {
1484// ExEnv::out0() << nr << " basis function has its center at ";
1485// for (int i=0; i < 3; ++i)
1486// ExEnv::out0() << wfn->basis()->r(nr,i) << "\t";
1487// ExEnv::out0() << endl;
1488// }
1489 // print the energy
1490 data.energies.total = mole->energy();
1491 data.energies.nuclear_repulsion = wfn->nuclear_repulsion_energy();
1492 {
1493 CLHF *clhf = dynamic_cast<CLHF*>(wfn.pointer());
1494 if (clhf != NULL) {
1495 double ex, ec;
1496 clhf->two_body_energy(ec, ex);
1497 data.energies.electron_coulomb = ec;
1498 data.energies.electron_exchange = ex;
1499 clhf = NULL;
1500 } else {
1501 ExEnv::out0() << "INFO: There is no CLHF information available." << endl;
1502 data.energies.electron_coulomb = 0.;
1503 data.energies.electron_exchange = 0.;
1504 }
1505 }
1506 SCF *scf = NULL;
1507 {
1508 MBPT2 *mbpt2 = dynamic_cast<MBPT2*>(wfn.pointer());
1509 if (mbpt2 != NULL) {
1510 data.energies.correlation = mbpt2->corr_energy();
1511 scf = mbpt2->ref().pointer();
1512 mbpt2 = 0;
1513 } else {
1514 ExEnv::out0() << "INFO: There is no MBPT2 information available." << endl;
1515 data.energies.correlation = 0.;
1516 scf = dynamic_cast<SCF*>(wfn.pointer());
1517 if (scf == NULL)
1518 abort();
1519 }
1520 }
1521 {
1522 // taken from clscf.cc: CLSCF::scf_energy() (but see also Szabo/Ostlund)
1523
1524 RefSymmSCMatrix t = scf->overlap();
1525 RefSymmSCMatrix cl_dens_ = scf->ao_density();
1526
1527 SCFEnergy *eop = new SCFEnergy;
1528 eop->reference();
1529 Ref<SCElementOp2> op = eop;
1530 t.element_op(op,cl_dens_);
1531 op=0;
1532 eop->dereference();
1533
1534 data.energies.overlap = eop->result();
1535
1536 delete eop;
1537 t = 0;
1538 cl_dens_ = 0;
1539 }
1540 {
1541 // taken from Wavefunction::core_hamiltonian()
1542 RefSymmSCMatrix hao(scf->basis()->basisdim(), scf->basis()->matrixkit());
1543 hao.assign(0.0);
1544 Ref<PetiteList> pl = scf->integral()->petite_list();
1545 Ref<SCElementOp> hc =
1546 new OneBodyIntOp(new SymmOneBodyIntIter(scf->integral()->kinetic(), pl));
1547 hao.element_op(hc);
1548 hc=0;
1549
1550 RefSymmSCMatrix h(scf->so_dimension(), scf->basis_matrixkit());
1551 pl->symmetrize(hao,h);
1552
1553 // taken from clscf.cc: CLSCF::scf_energy() (but see also Szabo/Ostlund)
1554 RefSymmSCMatrix cl_dens_ = scf->ao_density();
1555
1556 SCFEnergy *eop = new SCFEnergy;
1557 eop->reference();
1558 Ref<SCElementOp2> op = eop;
1559 h.element_op(op,cl_dens_);
1560 op=0;
1561 eop->dereference();
1562
1563 data.energies.kinetic = eop->result();
1564
1565 delete eop;
1566 hao = 0;
1567 h = 0;
1568 cl_dens_ = 0;
1569 }
1570 {
1571 RefSymmSCMatrix t = scf->core_hamiltonian();
1572 RefSymmSCMatrix cl_dens_ = scf->ao_density();
1573
1574 SCFEnergy *eop = new SCFEnergy;
1575 eop->reference();
1576 Ref<SCElementOp2> op = eop;
1577 t.element_op(op,cl_dens_);
1578 op=0;
1579 eop->dereference();
1580
1581 data.energies.hcore = eop->result();
1582
1583 delete eop;
1584 t = 0;
1585 cl_dens_ = 0;
1586 }
1587 ExEnv::out0() << endl << indent
1588 << scprintf("Value of the MolecularEnergy: %15.10f",
1589 mole->energy())
1590 << endl;
1591 // print the gradient
1592 RefSCVector grad;
1593 if (mole->gradient_result().computed()) {
1594 grad = mole->gradient_result().result_noupdate();
1595 }
1596 else {
1597 grad = mole->gradient();
1598 }
1599 if (grad.nonnull()) {
1600 data.forces.resize(grad.dim()/3);
1601 for (int j=0;j<grad.dim()/3; ++j) {
1602 data.forces[j].resize(3, 0.);
1603 }
1604 std::cout << "Gradient of the MolecularEnergy:" << std::endl;
1605 for (int j=0;j<grad.dim()/3; ++j) {
1606 std::cout << "\t";
1607 for (int i=0; i< 3; ++i) {
1608 data.forces[j][i] = grad[3*j+i];
1609 std::cout << grad[3*j+i] << "\t";
1610 }
1611 std::cout << endl;
1612 }
1613 }
1614 grad = NULL;
1615 {
1616 // times obtain from key "mpqc" which should be the first
1617 double *cpu_time = new double[tim->nregion()];
1618 double *wall_time = new double[tim->nregion()];
1619 double *flops = new double[tim->nregion()];
1620 tim->get_cpu_times(cpu_time);
1621 tim->get_wall_times(wall_time);
1622 tim->get_flops(flops);
1623 if (cpu_time != NULL)
1624 data.times.cputime = cpu_time[0];
1625 if (wall_time != NULL)
1626 data.times.walltime = wall_time[0];
1627 if (flops != NULL)
1628 data.times.flops = flops[0];
1629 delete[] cpu_time;
1630 delete[] wall_time;
1631 delete[] flops;
1632 }
1633
1634 {
1635 // eigenvalues (this only works if we have a OneBodyWavefunction, i.e. SCF procedure)
1636 SCF *scf = dynamic_cast<SCF*>(wfn.pointer());
1637 if (scf != NULL) {
1638 RefDiagSCMatrix evals = scf->eigenvalues();
1639
1640 for(int i=0;i<wfn->oso_dimension(); ++i) {
1641 data.energies.eigenvalues.push_back(evals(i));
1642 //std::cout << i << "th eigenvalue is " << evals(i) << std::endl;
1643 }
1644 }
1645 }
1646 {
1647 // fill positions and charges (converting from bohr radii to angstroem)
1648 const double AtomicLengthToAngstroem = 0.52917721;
1649 data.positions.reserve(wfn->molecule()->natom());
1650 data.charges.reserve(wfn->molecule()->natom());
1651 for (int iatom=0;iatom < wfn->molecule()->natom(); ++iatom) {
1652 data.charges.push_back(wfn->molecule()->Z(iatom));
1653 std::vector<double> pos(3, 0.);
1654 for (int j=0;j<3;++j)
1655 pos[j] = wfn->molecule()->r(iatom, j)*AtomicLengthToAngstroem;
1656 data.positions.push_back(pos);
1657 }
1658 std::cout << "We have "
1659 << data.positions.size() << " positions and "
1660 << data.charges.size() << " charges." << std::endl;
1661 }
1662 {
1663 // we now need to sample the density on the grid
1664 // 1. get max and min over all basis function positions
1665 assert( scf->basis()->ncenter() > 0 );
1666 SCVector3 bmin( scf->basis()->r(0,0), scf->basis()->r(0,1), scf->basis()->r(0,2) );
1667 SCVector3 bmax( scf->basis()->r(0,0), scf->basis()->r(0,1), scf->basis()->r(0,2) );
1668 for (int nr = 1; nr< scf->basis()->ncenter(); ++nr) {
1669 for (int i=0; i < 3; ++i) {
1670 if (scf->basis()->r(nr,i) < bmin(i))
1671 bmin(i) = scf->basis()->r(nr,i);
1672 if (scf->basis()->r(nr,i) > bmax(i))
1673 bmax(i) = scf->basis()->r(nr,i);
1674 }
1675 }
1676 std::cout << "Basis min is at " << bmin << " and max is at " << bmax << std::endl;
1677
1678 // 2. choose an appropriately large grid
1679 // we have to pay attention to capture the right amount of the exponential decay
1680 // and also to have a power of two size of the grid at best
1681 double boundary = 5.; // boundary extent around compact domain containing basis functions
1682 double delta = 1.; // step width in density sampling
1683
1684 // for the moment we always generate a grid of full size
1685 // (converting grid dimensions from angstroem to bohr radii)
1686 const double AtomicLengthToAngstroem = 0.52917721;
1687 SCVector3 min;
1688 SCVector3 max;
1689 min.x() = data.sampled_grid.begin[0]/AtomicLengthToAngstroem;
1690 min.y() = data.sampled_grid.begin[1]/AtomicLengthToAngstroem;
1691 min.z() = data.sampled_grid.begin[2]/AtomicLengthToAngstroem;
1692 max.x() = min.x() + data.sampled_grid.size/AtomicLengthToAngstroem;
1693 max.y() = min.y() + data.sampled_grid.size/AtomicLengthToAngstroem;
1694 max.z() = min.z() + data.sampled_grid.size/AtomicLengthToAngstroem;
1695 const int gridpoints = pow(2,data.sampled_grid.level);
1696 delta = (data.sampled_grid.size/AtomicLengthToAngstroem) / (double) gridpoints;
1697 std::cout << "Grid starts at " << min
1698 << " and ends at " << max
1699 << " with a delta of " << delta
1700 << " to get " << gridpoints << " gridpoints."
1701 << std::endl;
1702
1703 // 3. sample the atomic density
1704 SCVector3 r;
1705 data.sampled_grid.sampled_grid.clear();
1706 data.sampled_grid.sampled_grid.reserve(gridpoints*gridpoints*gridpoints);
1707 r = min;
1708 const double element_volume_conversion =
1709 1./AtomicLengthToAngstroem/AtomicLengthToAngstroem/AtomicLengthToAngstroem;
1710 for (size_t x=0; x< gridpoints; ++x, r.x() += delta) {
1711 std::cout << "Sampling now for x=" << r.x() << std::endl;
1712 for (size_t y=0; y< gridpoints; ++y, r.y() += delta) {
1713 for (size_t z=0; z< gridpoints; ++z, r.z() += delta) {
1714 if (((r.x() < bmin.x()-boundary) || (r.x() > bmax.x()+boundary))
1715 || ((r.y() < bmin.y()-boundary) || (r.y() > bmax.y()+boundary))
1716 || ((r.z() < bmin.z()-boundary) || (r.z() > bmax.y()+boundary))) {
1717 data.sampled_grid.sampled_grid.push_back(0.);
1718 } else {
1719 const double dens_at_r = scf->density(r) * element_volume_conversion;
1720// if (fabs(dens_at_r) > 1e-4)
1721// std::cout << "Electron density at " << r << " is " << dens_at_r << std::endl;
1722 data.sampled_grid.sampled_grid.push_back(dens_at_r);
1723 }
1724 }
1725 r.z() = min.z();
1726 }
1727 r.y() = min.y();
1728 }
1729 assert( data.sampled_grid.sampled_grid.size() == gridpoints*gridpoints*gridpoints);
1730 // normalization of electron charge to equal electron number
1731 {
1732 double integral_value = 0.;
1733 for (std::vector<double>::const_iterator diter = data.sampled_grid.sampled_grid.begin();
1734 diter != data.sampled_grid.sampled_grid.end(); ++diter)
1735 integral_value += *diter;
1736 integral_value *= pow(delta*AtomicLengthToAngstroem,3);
1737 const double normalization = scf->nelectron()/integral_value;
1738 std::cout << "Created " << data.sampled_grid.sampled_grid.size() << " grid points "
1739 << " with integral value of " << integral_value
1740 << " against nelectron of " << scf->nelectron() << "." << std::endl;
1741 for (std::vector<double>::iterator diter = data.sampled_grid.sampled_grid.begin();
1742 diter != data.sampled_grid.sampled_grid.end(); ++diter)
1743 *diter *= normalization;
1744 }
1745 }
1746 scf = 0;
1747
1748// // GaussianShell is the actual orbital functions it seems ...
1749// //ExEnv::out0() << "There are the following Gaussian Shells: " << endl;
1750// SCVector3 r;
1751// r.x() = r.y() = r.z() = 10;
1752// ExEnv::out0() << "We get the following value at " << r << "." << endl;
1753// Ref<Integral> intgrl = Integral::get_default_integral();
1754// GaussianBasisSet::ValueData vdat(wfn->basis(), integral);
1755// ExEnv::out0() << "Value at (10,10,10) is " << EvaluateDensity(r, intgrl, vdat, wfn) << endl;
1756// boost::function<double (SCVector3 &r)> evaluator =
1757// boost::bind(&EvaluateDensity, _1, boost::ref(intgrl), boost::ref(vdat), boost::ref(wfn));
1758// ExEnv::out0() << "Check against values at " << r << "." << endl;
1759// int nbasis = wfn->basis()->nbasis();
1760// double *b_val = new double[nbasis];
1761// wfn->basis()->values(r, &vdat, b_val);
1762// for (int i=0; i<nbasis; i++) {
1763// //ExEnv::out0() << "Shell nr. " << nr << ": ";
1764// ExEnv::out0() << "Value at (10,10,10) is " << b_val[i] << endl;
1765// }
1766// // perform test integration of density
1767// double delta = 1.;
1768// double sum = 0.;
1769// for (r.x() = -10. ; r.x() < 10.; r.x() += delta)
1770// for (r.y() = -10. ; r.y() < 10.; r.y() += delta)
1771// for (r.z() = -10. ; r.z() < 10.; r.z() += delta) {
1772// wfn->basis()->values(r, &vdat, b_val);
1773// for (int i=0; i<nbasis; i++)
1774// sum += wfn->ao_density()->get_element(i,i)*b_val[i];
1775// }
1776// sum /= pow(20/delta,3);
1777// ExEnv::out0() << "Sum over domain [0:20]^3 with " << delta << " delta is " << sum << "." << endl;
1778// delete[] b_val;
1779 }
1780
1781 delete[] molname;
1782 SCFormIO::set_default_basename(0);
1783
1784 renderer = 0;
1785 molfreq = 0;
1786 molhess = 0;
1787 opt = 0;
1788 mole = 0;
1789 integral = 0;
1790 debugger = 0;
1791 thread = 0;
1792 tim = 0;
1793 keyval = 0;
1794 parsedkv = 0;
1795 memory = 0;
1796 clean_up();
1797
1798#if defined(HAVE_TIME) && defined(HAVE_CTIME)
1799 time_t t;
1800 time(&t);
1801 const char *tstr = ctime(&t);
1802#endif
1803 if (!tstr) {
1804 tstr = "UNKNOWN";
1805 }
1806 ExEnv::out0() << endl
1807 << indent << scprintf("End Time: %s", tstr) << endl;
1808}
1809
1810// static values object
1811OptionValues values;
1812
1813#ifdef HAVE_JOBMARKET
1814FragmentResult::ptr MPQCJob::Work()
1815{
1816 char mpqc[] = "mpqc" ;
1817 char **argv = new char*[1];
1818 argv[0] = &mpqc[0];
1819 int argc = 1;
1820// init();
1821//
1822// ExEnv::init(argc, argv);
1823//
1824// // parse commandline options
1825// GetLongOpt options;
1826// int optind = ParseOptions(options, argc, argv);
1827// const char *output = 0;
1828// ostream *outstream = 0;
1829// ComputeOptions(options, output, outstream);
1830// OptionValues values;
1831// parseRemainderOptions(options, values, argc, argv);
1832//
1833// // get the basename for output files
1834// char filename_template[] = "mpqc_temp_XXXXXX";
1835// output = mktemp(filename_template);
1836// setOutputBaseName(NULL, output);
1837
1838 // now comes the actual work
1839 int nfilebase = (int) inputfile.length();
1840 char *in_char_array = new char[nfilebase + 1];
1841 strncpy(in_char_array, inputfile.c_str(), nfilebase);
1842 in_char_array[nfilebase] = '\0';
1843 const char *input = 0;
1844 const char *generic_input = 0;
1845 Ref<MessageGrp> grp = MessageGrp::get_default_messagegrp();
1846 // create unique, temporary name and check whether it exists
1847 const char *output = NULL;
1848 std::ifstream test;
1849 do {
1850 char filename_template[] = "mpqc_temp_XXXXXX.in";
1851 output = mktemp(filename_template);
1852 test.open(output);
1853 } while (test.good());
1854 // put info how to sample the density into MPQCData
1855 MPQCData data(grid);
1856// now call work horse
1857 mainFunction(grp, values, output, input, generic_input, in_char_array, argc, argv, data);
1858// delete[] in_char_array;
1859
1860// if (output != 0) {
1861// ExEnv::set_out(&cout);
1862// delete outstream;
1863// }
1864// delete[] argv;
1865//
1866 // place into returnstream
1867 std::stringstream returnstream;
1868 boost::archive::text_oarchive oa(returnstream);
1869 oa << data;
1870
1871 FragmentResult::ptr s( new FragmentResult(getId(), returnstream.str()) );
1872 return s;
1873}
1874#endif
1875
1876// we need to explicitly instantiate the serialization functions as
1877// its is only serialized through its base class FragmentJob
1878BOOST_CLASS_EXPORT_IMPLEMENT(MPQCJob)
1879
1880int
1881try_main(int argc, char *argv[])
1882{
1883 init();
1884
1885 ExEnv::init(argc, argv);
1886
1887 // parse commandline options
1888 GetLongOpt options;
1889 int optind = ParseOptions(options, argc, argv);
1890 const char *output = 0;
1891 ostream *outstream = 0;
1892 ComputeOptions(options, output, outstream);
1893 parseRemainderOptions(options, values, argc, argv);
1894
1895 // get input file names, either object-oriented or generic
1896 const char *object_input = 0;
1897 const char *generic_input = 0;
1898 getInputFileNames(object_input, generic_input, options, optind, argc, argv);
1899 const char *input = 0;
1900 if (object_input) input = object_input;
1901 if (generic_input) input = generic_input;
1902
1903 // get the message group. first try the commandline and environment
1904 Ref<MessageGrp> grp;
1905 getMessageGroup(grp, argc, argv);
1906
1907 // check if we got option "-n"
1908 int exitflag = 0;
1909#ifdef HAVE_JOBMARKET
1910 if (options.retrieve("n")) {
1911 /// create new argc, argv and call by splitting with tokenizer
1912 std::string networkstring(options.retrieve("n"));
1913 typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
1914 boost::char_separator<char> sep(" ");
1915 tokenizer tok(networkstring, sep);
1916 // simple count because tokenizer has now size()
1917 int argc_network = 0;
1918 for(tokenizer::iterator beg=tok.begin(); beg!=tok.end();++beg)
1919 ++argc_network;
1920 // argv[0] is program name
1921 char **argv_network = new char*[argc_network+1];
1922 argv_network[0] = new char[5];
1923 strcpy(argv_network[0], "mpqc");
1924 // then we place each token as a new argument
1925 argc_network = 1;
1926 for(tokenizer::iterator beg=tok.begin(); beg!=tok.end();++beg){
1927 const size_t strlength = (*beg).length();
1928 const char *strarray = beg->c_str();
1929 //std::cout << "Token " << argc_network << " is " << strarray << ", length " << strlength << endl;
1930 argv_network[argc_network] = new char[strlength+1];
1931 strcpy(argv_network[argc_network], strarray);
1932 argv_network[argc_network][strlength] = '\0';
1933 for (size_t index = 0; index < strlength; ++index)
1934 if (argv_network[argc_network][index] == '+')
1935 argv_network[argc_network][index] = '-';
1936 ++argc_network;
1937 }
1938 /// and start listening for MPQCJobs
1939 exitflag = poolworker_main(argc_network, argv_network);
1940 /// remove the artifical [argv,argv] again
1941 for (int i=0;i<argc_network;++i)
1942 delete[] argv_network[i];
1943 delete[] argv_network;
1944 } else
1945#endif
1946 {
1947 // if not, work on the command line input
1948 char *in_char_array = 0;
1949#ifdef HAVE_MPQCDATA
1950 MPQCData data;
1951 mainFunction(grp, values, output, input, generic_input, in_char_array, argc, argv, data);
1952#else
1953 mainFunction(grp, values, output, input, generic_input, in_char_array, argc, argv);
1954#endif
1955 }
1956
1957 if (output != 0) {
1958 ExEnv::set_out(&cout);
1959 delete outstream;
1960 }
1961
1962 grp = 0;
1963 final_clean_up();
1964
1965 return exitflag;
1966}
1967
1968
1969double EvaluateDensity(SCVector3 &r, Ref<Integral> &intgrl, GaussianBasisSet::ValueData &vdat, Ref<Wavefunction> &wfn)
1970{
1971 ExEnv::out0() << "We get the following values at " << r << "." << endl;
1972 int nbasis = wfn->basis()->nbasis();
1973 double *b_val = new double[nbasis];
1974 wfn->basis()->values(r, &vdat, b_val);
1975 double sum=0.;
1976 for (int i=0; i<nbasis; i++)
1977 sum += b_val[i];
1978 delete[] b_val;
1979 return sum;
1980}
1981
1982int
1983main(int argc, char *argv[])
1984{
1985 try {
1986 try_main(argc, argv);
1987 }
1988 catch (SCException &e) {
1989 cout << argv[0] << ": ERROR: SC EXCEPTION RAISED:" << endl
1990 << e.what()
1991 << endl;
1992 clean_up();
1993 throw;
1994 }
1995 catch (bad_alloc &e) {
1996 cout << argv[0] << ": ERROR: MEMORY ALLOCATION FAILED:" << endl
1997 << e.what()
1998 << endl;
1999 clean_up();
2000 throw;
2001 }
2002 catch (exception &e) {
2003 cout << argv[0] << ": ERROR: EXCEPTION RAISED:" << endl
2004 << e.what()
2005 << endl;
2006 clean_up();
2007 throw;
2008 }
2009 catch (...) {
2010 cout << argv[0] << ": ERROR: UNKNOWN EXCEPTION RAISED" << endl;
2011 clean_up();
2012 throw;
2013 }
2014 return 0;
2015}
2016
2017/////////////////////////////////////////////////////////////////////////////
2018
2019// Local Variables:
2020// mode: c++
2021// c-file-style: "ETS"
2022// End:
Note: See TracBrowser for help on using the repository browser.