source: ThirdParty/mpqc_open/src/bin/mpqc/mpqc.cc@ 1c350e

Action_Thermostats Add_AtomRandomPerturbation Add_RotateAroundBondAction Add_SelectAtomByNameAction Adding_Graph_to_ChangeBondActions Adding_MD_integration_tests Adding_StructOpt_integration_tests AutomationFragmentation_failures Candidate_v1.6.0 Candidate_v1.6.1 ChangeBugEmailaddress ChangingTestPorts ChemicalSpaceEvaluator Combining_Subpackages Debian_Package_split Debian_package_split_molecuildergui_only Disabling_MemDebug Docu_Python_wait EmpiricalPotential_contain_HomologyGraph_documentation Enable_parallel_make_install Enhance_userguide Enhanced_StructuralOptimization Enhanced_StructuralOptimization_continued Example_ManyWaysToTranslateAtom Exclude_Hydrogens_annealWithBondGraph FitPartialCharges_GlobalError Fix_ChronosMutex Fix_StatusMsg Fix_StepWorldTime_single_argument Fix_Verbose_Codepatterns ForceAnnealing_goodresults ForceAnnealing_oldresults ForceAnnealing_tocheck ForceAnnealing_with_BondGraph ForceAnnealing_with_BondGraph_continued ForceAnnealing_with_BondGraph_continued_betteresults ForceAnnealing_with_BondGraph_contraction-expansion GeometryObjects Gui_displays_atomic_force_velocity IndependentFragmentGrids_IntegrationTest JobMarket_RobustOnKillsSegFaults JobMarket_StableWorkerPool JobMarket_unresolvable_hostname_fix ODR_violation_mpqc_open PartialCharges_OrthogonalSummation PythonUI_with_named_parameters QtGui_reactivate_TimeChanged_changes Recreated_GuiChecks RotateToPrincipalAxisSystem_UndoRedo StoppableMakroAction Subpackage_levmar Subpackage_vmg ThirdParty_MPQC_rebuilt_buildsystem TremoloParser_IncreasedPrecision TremoloParser_MultipleTimesteps Ubuntu_1604_changes stable
Last change on this file since 1c350e was 1c350e, checked in by Frederik Heber <heber@…>, 8 years ago

Added MPI_Init() call to mpqc's main() when MPI is available but not used as vmg depends on it.

  • Property mode set to 100644
File size: 69.6 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 "Fragmentation/Summation/Containers/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
1184static int getCoreElectrons(const int z)
1185{
1186 int n=0;
1187 if (z > 2) n += 2;
1188 if (z > 10) n += 8;
1189 if (z > 18) n += 8;
1190 if (z > 30) n += 10;
1191 if (z > 36) n += 8;
1192 if (z > 48) n += 10;
1193 if (z > 54) n += 8;
1194 return n;
1195}
1196
1197void init()
1198{
1199 //trash_stack();
1200
1201 int i;
1202 atexit(clean_up);
1203
1204#ifdef HAVE_FEENABLEEXCEPT
1205 // this uses a glibc extension to trap on individual exceptions
1206# ifdef FE_DIVBYZERO
1207 feenableexcept(FE_DIVBYZERO);
1208# endif
1209# ifdef FE_INVALID
1210 feenableexcept(FE_INVALID);
1211# endif
1212# ifdef FE_OVERFLOW
1213 feenableexcept(FE_OVERFLOW);
1214# endif
1215#endif
1216
1217#ifdef HAVE_FEDISABLEEXCEPT
1218 // this uses a glibc extension to not trap on individual exceptions
1219# ifdef FE_UNDERFLOW
1220 fedisableexcept(FE_UNDERFLOW);
1221# endif
1222# ifdef FE_INEXACT
1223 fedisableexcept(FE_INEXACT);
1224# endif
1225#endif
1226
1227#if defined(HAVE_SETRLIMIT)
1228 struct rlimit rlim;
1229 rlim.rlim_cur = 0;
1230 rlim.rlim_max = 0;
1231 setrlimit(RLIMIT_CORE,&rlim);
1232#endif
1233}
1234
1235/** Finds the region index to a given timer region name.
1236 *
1237 * @param nregion number of regions
1238 * @param region_names array with name of each region
1239 * @param name name of desired region
1240 * @return index of desired region in array
1241 */
1242int findTimerRegion(const int &nregion, const char **&region_names, const char *name)
1243{
1244 size_t region=0;
1245 for (;region<nregion;++region) {
1246 //std::cout << "Comparing " << region_names[region] << " and " << name << "." << std::endl;
1247 if (strcmp(region_names[region], name) == 0)
1248 break;
1249 }
1250 if (region == nregion)
1251 region = 0;
1252 return region;
1253}
1254
1255/** Performs the main work to calculate the ground state energies, gradients, etc.
1256 *
1257 * @param grp message group
1258 * @param values temporary value storage for parsed command-line
1259 * @param input input file name
1260 * @param generic_input generic input file name
1261 * @param in_char_array either NULL or contains char array with read input
1262 * @param argc argument count
1263 * @param argv argument array
1264 */
1265void mainFunction(
1266 Ref<MessageGrp> grp,
1267 struct OptionValues &values,
1268 const char *&output,
1269 const char *&input,
1270 const char *&generic_input,
1271 char *&in_char_array,
1272 int argc,
1273 char **argv
1274#ifdef HAVE_MPQCDATA
1275 , MPQCData &data
1276#endif
1277 )
1278{
1279 // get the basename for output files
1280 setOutputBaseName(input, output);
1281
1282 // parse input into keyvalue container
1283 Ref<ParsedKeyVal> parsedkv;
1284 int use_simple_input = 0; // default is object-oriented if in_char_array is given
1285 if (!in_char_array) // obtain from file
1286 parseInputfile(grp, parsedkv, values, input, generic_input, in_char_array, use_simple_input);
1287 parseIntoKeyValue(parsedkv, values, in_char_array, use_simple_input);
1288 delete[] in_char_array;
1289
1290 // prefix parsed values wit "mpqc"
1291 if (values.keyvalue) parsedkv->verbose(1);
1292 Ref<KeyVal> keyval = new PrefixKeyVal(parsedkv.pointer(),"mpqc");
1293
1294 // set up output classes
1295 setupSCFormIO(grp);
1296
1297 // initialize timing for mpqc
1298 Ref<RegionTimer> tim;
1299 initTimings(grp, keyval, tim);
1300
1301 // announce ourselves
1302 makeAnnouncement(tim);
1303
1304 // get the thread group.
1305 Ref<ThreadGrp> thread;
1306 getThreadGroup(keyval, thread, argc, argv);
1307
1308 // get the memory group.
1309 Ref<MemoryGrp> memory;
1310 getMemoryGroup(keyval, memory, argc, argv);
1311
1312 ExEnv::out0() << indent
1313 << "Using " << grp->class_name()
1314 << " for message passing (number of nodes = " << grp->n() << ")." << endl
1315 << indent
1316 << "Using " << thread->class_name()
1317 << " for threading (number of threads = " << thread->nthread() << ")." << endl
1318 << indent
1319 << "Using " << memory->class_name()
1320 << " for distributed shared memory." << endl
1321 << indent
1322 << "Total number of processors = " << grp->n() * thread->nthread() << endl;
1323
1324 // prepare CCA if available
1325 prepareCCA(keyval, values);
1326
1327 // now set up the debugger
1328 Ref<Debugger> debugger;
1329 setupDebugger(keyval, grp, debugger, values);
1330
1331 // now check to see what matrix kit to use
1332 if (keyval->exists("matrixkit"))
1333 SCMatrixKit::set_default_matrixkit(
1334 dynamic_cast<SCMatrixKit*>(
1335 keyval->describedclassvalue("matrixkit").pointer()));
1336
1337 // get the integral factory.
1338 Ref<Integral> integral;
1339 getIntegralFactory(keyval, integral, argc, argv);
1340 ExEnv::out0() << endl << indent
1341 << "Using " << integral->class_name()
1342 << " by default for molecular integrals evaluation" << endl << endl;
1343
1344 // create some filenames for molecule, checkpoint, basename of output
1345 const char *basename = SCFormIO::default_basename();
1346 KeyValValueString molnamedef(basename);
1347 char * molname = keyval->pcharvalue("filename", molnamedef);
1348 if (strcmp(molname, basename))
1349 SCFormIO::set_default_basename(molname);
1350
1351 char * ckptfile = new char[strlen(molname)+6];
1352 sprintf(ckptfile,"%s.ckpt",molname);
1353
1354 KeyValValueString restartfiledef(ckptfile);
1355 char * restartfile = keyval->pcharvalue("restart_file", restartfiledef);
1356
1357 char * wfn_file = keyval->pcharvalue("wfn_file");
1358 if (wfn_file == 0) {
1359 wfn_file = new char[strlen(molname)+6];
1360 sprintf(wfn_file,"%s.wfn",molname);
1361 }
1362 char *mole_ckpt_file = new char[strlen(wfn_file)+1];
1363 sprintf(mole_ckpt_file,"%s",wfn_file);
1364
1365 int savestate = keyval->booleanvalue("savestate",truevalue);
1366
1367 // setup molecular energy and optimization instances
1368 Ref<MolecularEnergy> mole;
1369 Ref<Optimize> opt;
1370
1371 // read in restart file if we do restart
1372 performRestart(keyval, grp, opt, mole, restartfile);
1373
1374 // setup molecule checkpoint file
1375 setMolecularCheckpointFile(keyval, grp, mole, mole_ckpt_file);
1376 delete[] mole_ckpt_file;
1377
1378 int checkpoint = keyval->booleanvalue("checkpoint",truevalue);
1379 if (checkpoint && opt.nonnull()) {
1380 opt->set_checkpoint();
1381 if (grp->me() == 0) opt->set_checkpoint_file(ckptfile);
1382 else opt->set_checkpoint_file(devnull);
1383 }
1384
1385 // see if frequencies are wanted
1386 Ref<MolecularHessian> molhess;
1387 molhess << keyval->describedclassvalue("hess");
1388 Ref<MolecularFrequencies> molfreq;
1389 molfreq << keyval->describedclassvalue("freq");
1390
1391 // check basis set limit
1392 const int check = checkBasisSetLimit(mole, values);
1393 if (check) {
1394 ExEnv::out0() << endl << indent
1395 << "Exiting since the check option is on." << endl;
1396 exit(0);
1397 }
1398
1399 // from now on we time the calculations
1400 if (tim.nonnull()) tim->change("calc");
1401
1402 int do_energy = keyval->booleanvalue("do_energy",truevalue);
1403
1404 int do_grad = keyval->booleanvalue("do_gradient",falsevalue);
1405
1406 int do_opt = keyval->booleanvalue("optimize",truevalue);
1407
1408 int do_pdb = keyval->booleanvalue("write_pdb",falsevalue);
1409
1410 int print_mole = keyval->booleanvalue("print_mole",truevalue);
1411
1412 int print_timings = keyval->booleanvalue("print_timings",truevalue);
1413
1414 // print all current options (keyvalues)
1415 printOptions(keyval, opt, molname, restartfile);
1416
1417 // see if any pictures are desired
1418 Ref<Render> renderer;
1419 renderer << keyval->describedclassvalue("renderer");
1420
1421 // If we have a renderer, then we will read in some more info
1422 // below. Otherwise we can get rid of the keyval's, to eliminate
1423 // superfluous references to objects that we might otherwise be
1424 // able to delete. We cannot read in the remaining rendering
1425 // objects now, since some of their KeyVal CTOR's are heavyweight,
1426 // requiring optimized geometries, etc.
1427 if (renderer.null()) {
1428 if (parsedkv.nonnull()) print_unseen(parsedkv, input);
1429 keyval = 0;
1430 parsedkv = 0;
1431 }
1432
1433 delete[] restartfile;
1434 delete[] ckptfile;
1435
1436 int ready_for_freq = 1;
1437 if (mole.nonnull()) {
1438 if (((do_opt && opt.nonnull()) || do_grad)
1439 && !mole->gradient_implemented()) {
1440 ExEnv::out0() << indent
1441 << "WARNING: optimization or gradient requested but the given"
1442 << endl
1443 << " MolecularEnergy object cannot do gradients."
1444 << endl;
1445 }
1446
1447 if (do_opt && opt.nonnull() && mole->gradient_implemented()) {
1448
1449 ready_for_freq = performEnergyOptimization(opt, mole);
1450
1451 } else if (do_grad && mole->gradient_implemented()) {
1452
1453 performGradientCalculation(mole);
1454
1455 } else if (do_energy && mole->value_implemented()) {
1456 ExEnv::out0() << endl << indent
1457 << scprintf("Value of the MolecularEnergy: %15.10f",
1458 mole->energy())
1459 << endl << endl;
1460 }
1461 }
1462
1463 // stop timing of calculations
1464 if (tim.nonnull()) tim->exit("calc");
1465
1466 // save this before doing the frequency stuff since that obsoletes the
1467 saveState(wfn_file, savestate, opt, grp, mole, molname, ckptfile);
1468
1469 // Frequency calculation.
1470 if (ready_for_freq && molfreq.nonnull()) {
1471 performFrequencyCalculation(mole, molhess, molfreq);
1472 }
1473
1474 if (renderer.nonnull()) {
1475 renderObjects(renderer, keyval, tim, grp);
1476
1477 Ref<MolFreqAnimate> molfreqanim;
1478 molfreqanim << keyval->describedclassvalue("animate_modes");
1479 if (ready_for_freq && molfreq.nonnull()
1480 && molfreqanim.nonnull()) {
1481 if (tim.nonnull()) tim->enter("render");
1482 molfreq->animate(renderer, molfreqanim);
1483 if (tim.nonnull()) tim->exit("render");
1484 }
1485 }
1486
1487 if (mole.nonnull()) {
1488 if (print_mole)
1489 mole->print(ExEnv::out0());
1490
1491 saveToPdb(do_pdb, grp, mole, molname);
1492
1493 }
1494 else {
1495 ExEnv::out0() << "mpqc: The molecular energy object is null" << endl
1496 << " make sure \"mole\" specifies a MolecularEnergy derivative"
1497 << endl;
1498 }
1499 if (parsedkv.nonnull()) print_unseen(parsedkv, input);
1500
1501 // here, we may gather the results
1502 // we start to fill the MPQC_Data object
1503 if (tim.nonnull()) tim->enter("gather");
1504 {
1505 Ref<Wavefunction> wfn;
1506 wfn << mole;
1507// ExEnv::out0() << "The number of atomic orbitals: " << wfn->ao_dimension()->n() << endl;
1508// ExEnv::out0() << "The AO density matrix is ";
1509// wfn->ao_density()->print(ExEnv::out0());
1510// ExEnv::out0() << "The natural density matrix is ";
1511// wfn->natural_density()->print(ExEnv::out0());
1512// ExEnv::out0() << "The Gaussian basis is " << wfn->basis()->name() << endl;
1513// ExEnv::out0() << "The Gaussians sit at the following centers: " << endl;
1514// for (int nr = 0; nr< wfn->basis()->ncenter(); ++nr) {
1515// ExEnv::out0() << nr << " basis function has its center at ";
1516// for (int i=0; i < 3; ++i)
1517// ExEnv::out0() << wfn->basis()->r(nr,i) << "\t";
1518// ExEnv::out0() << endl;
1519// }
1520 // store accuracies
1521 data.accuracy = mole->value_result().actual_accuracy();
1522 data.desired_accuracy = mole->value_result().desired_accuracy();
1523 // print the energy
1524 data.energies.total = wfn->energy();
1525 data.energies.nuclear_repulsion = wfn->nuclear_repulsion_energy();
1526 {
1527 CLHF *clhf = dynamic_cast<CLHF*>(wfn.pointer());
1528 if (clhf != NULL) {
1529 double ex, ec;
1530 clhf->two_body_energy(ec, ex);
1531 data.energies.electron_coulomb = ec;
1532 data.energies.electron_exchange = ex;
1533 clhf = NULL;
1534 } else {
1535 ExEnv::out0() << "INFO: There is no direct CLHF information available." << endl;
1536 data.energies.electron_coulomb = 0.;
1537 data.energies.electron_exchange = 0.;
1538 }
1539 }
1540 SCF *scf = NULL;
1541 {
1542 MBPT2 *mbpt2 = dynamic_cast<MBPT2*>(wfn.pointer());
1543 if (mbpt2 != NULL) {
1544 data.energies.correlation = mbpt2->corr_energy();
1545 scf = mbpt2->ref().pointer();
1546 CLHF *clhf = dynamic_cast<CLHF*>(scf);
1547 if (clhf != NULL) {
1548 double ex, ec;
1549 clhf->two_body_energy(ec, ex);
1550 data.energies.electron_coulomb = ec;
1551 data.energies.electron_exchange = ex;
1552 clhf = NULL;
1553 } else {
1554 ExEnv::out0() << "INFO: There is no reference CLHF information available either." << endl;
1555 data.energies.electron_coulomb = 0.;
1556 data.energies.electron_exchange = 0.;
1557 }
1558 mbpt2 = 0;
1559 } else {
1560 ExEnv::out0() << "INFO: There is no MBPT2 information available." << endl;
1561 data.energies.correlation = 0.;
1562 scf = dynamic_cast<SCF*>(wfn.pointer());
1563 if (scf == NULL)
1564 abort();
1565 }
1566 }
1567 {
1568 // taken from clscf.cc: CLSCF::scf_energy() (but see also Szabo/Ostlund)
1569
1570 RefSymmSCMatrix t = scf->overlap();
1571 RefSymmSCMatrix cl_dens_ = scf->ao_density();
1572
1573 SCFEnergy *eop = new SCFEnergy;
1574 eop->reference();
1575 if (t.dim()->equiv(cl_dens_.dim())) {
1576 Ref<SCElementOp2> op = eop;
1577 t.element_op(op,cl_dens_);
1578 op=0;
1579 }
1580 eop->dereference();
1581
1582 data.energies.overlap = eop->result();
1583
1584 delete eop;
1585 t = 0;
1586 cl_dens_ = 0;
1587 }
1588 {
1589 // taken from Wavefunction::core_hamiltonian()
1590 RefSymmSCMatrix hao(scf->basis()->basisdim(), scf->basis()->matrixkit());
1591 hao.assign(0.0);
1592 Ref<PetiteList> pl = scf->integral()->petite_list();
1593 Ref<SCElementOp> hc =
1594 new OneBodyIntOp(new SymmOneBodyIntIter(scf->integral()->kinetic(), pl));
1595 hao.element_op(hc);
1596 hc=0;
1597
1598 RefSymmSCMatrix h(scf->so_dimension(), scf->basis_matrixkit());
1599 pl->symmetrize(hao,h);
1600
1601 // taken from clscf.cc: CLSCF::scf_energy() (but see also Szabo/Ostlund)
1602 RefSymmSCMatrix cl_dens_ = scf->ao_density();
1603
1604 SCFEnergy *eop = new SCFEnergy;
1605 eop->reference();
1606 if (h.dim()->equiv(cl_dens_.dim())) {
1607 Ref<SCElementOp2> op = eop;
1608 h.element_op(op,cl_dens_);
1609 op=0;
1610 }
1611 eop->dereference();
1612
1613 data.energies.kinetic = 2.*eop->result();
1614
1615 delete eop;
1616 hao = 0;
1617 h = 0;
1618 cl_dens_ = 0;
1619 }
1620 {
1621 // set to potential energy between nuclei and electron charge distribution
1622 RefSymmSCMatrix hao(scf->basis()->basisdim(), scf->basis()->matrixkit());
1623 hao.assign(0.0);
1624 Ref<PetiteList> pl = scf->integral()->petite_list();
1625 Ref<SCElementOp> hc =
1626 new OneBodyIntOp(new SymmOneBodyIntIter(scf->integral()->nuclear(), pl));
1627 hao.element_op(hc);
1628 hc=0;
1629
1630 RefSymmSCMatrix h(scf->so_dimension(), scf->basis_matrixkit());
1631 pl->symmetrize(hao,h);
1632
1633 // taken from clscf.cc: CLSCF::scf_energy() (but see also Szabo/Ostlund)
1634 RefSymmSCMatrix cl_dens_ = scf->ao_density();
1635
1636 SCFEnergy *eop = new SCFEnergy;
1637 eop->reference();
1638 if (h.dim()->equiv(cl_dens_.dim())) {
1639 Ref<SCElementOp2> op = eop;
1640 h.element_op(op,cl_dens_);
1641 op=0;
1642 }
1643 eop->dereference();
1644
1645 data.energies.hcore = 2.*eop->result();
1646
1647 delete eop;
1648 hao = 0;
1649 h = 0;
1650 cl_dens_ = 0;
1651 }
1652 ExEnv::out0() << "total is " << data.energies.total << endl;
1653 ExEnv::out0() << "nuclear_repulsion is " << data.energies.nuclear_repulsion << endl;
1654 ExEnv::out0() << "electron_coulomb is " << data.energies.electron_coulomb << endl;
1655 ExEnv::out0() << "electron_exchange is " << data.energies.electron_exchange << endl;
1656 ExEnv::out0() << "correlation is " << data.energies.correlation << endl;
1657 ExEnv::out0() << "overlap is " << data.energies.overlap << endl;
1658 ExEnv::out0() << "kinetic is " << data.energies.kinetic << endl;
1659 ExEnv::out0() << "hcore is " << data.energies.hcore << endl;
1660 ExEnv::out0() << "sum is " <<
1661 data.energies.nuclear_repulsion
1662 + data.energies.electron_coulomb
1663 + data.energies.electron_exchange
1664 + data.energies.correlation
1665 + data.energies.kinetic
1666 + data.energies.hcore
1667 << endl;
1668
1669 ExEnv::out0() << endl << indent
1670 << scprintf("Value of the MolecularEnergy: %15.10f",
1671 mole->energy())
1672 << endl;
1673 // print the gradient
1674 RefSCVector grad;
1675 if (mole->gradient_result().computed()) {
1676 grad = mole->gradient_result().result_noupdate();
1677 }
1678 // gradient calculation needs to be activated in the configuration
1679 // some methods such as open shell MBPT2 do not allow for gradient calc.
1680// else {
1681// grad = mole->gradient();
1682// }
1683 if (grad.nonnull()) {
1684 data.forces.resize(grad.dim()/3);
1685 for (int j=0;j<grad.dim()/3; ++j) {
1686 data.forces[j].resize(3, 0.);
1687 }
1688 ExEnv::out0() << "Gradient of the MolecularEnergy:" << std::endl;
1689 for (int j=0;j<grad.dim()/3; ++j) {
1690 ExEnv::out0() << "\t";
1691 for (int i=0; i< 3; ++i) {
1692 data.forces[j][i] = grad[3*j+i];
1693 ExEnv::out0() << grad[3*j+i] << "\t";
1694 }
1695 ExEnv::out0() << endl;
1696 }
1697 } else {
1698 ExEnv::out0() << "INFO: There is no gradient information available." << endl;
1699 }
1700 grad = NULL;
1701
1702 {
1703 // eigenvalues (this only works if we have a OneBodyWavefunction, i.e. SCF procedure)
1704 // eigenvalues seem to be invalid for unrestricted SCF calculation
1705 // (see UnrestrictedSCF::eigenvalues() implementation)
1706 UnrestrictedSCF *uscf = dynamic_cast<UnrestrictedSCF*>(wfn.pointer());
1707 if ((scf != NULL) && (uscf == NULL)) {
1708 const double scfernergy = scf->energy();
1709 RefDiagSCMatrix evals = scf->eigenvalues();
1710
1711 ExEnv::out0() << "Eigenvalues:" << endl;
1712 for(int i=0;i<wfn->oso_dimension(); ++i) {
1713 data.energies.eigenvalues.push_back(evals(i));
1714 ExEnv::out0() << i << "th eigenvalue is " << evals(i) << endl;
1715 }
1716 } else {
1717 ExEnv::out0() << "INFO: There is no eigenvalue information available." << endl;
1718 }
1719 }
1720 // we do sample the density only on request
1721 {
1722 // fill positions and charges (NO LONGER converting from bohr radii to angstroem)
1723 const double AtomicLengthToAngstroem = 1.;//0.52917721;
1724 data.positions.reserve(wfn->molecule()->natom());
1725 data.atomicnumbers.reserve(wfn->molecule()->natom());
1726 data.charges.reserve(wfn->molecule()->natom());
1727 for (int iatom=0;iatom < wfn->molecule()->natom(); ++iatom) {
1728 data.atomicnumbers.push_back(wfn->molecule()->Z(iatom));
1729 double charge = wfn->molecule()->Z(iatom);
1730 if (data.DoValenceOnly == MPQCData::DoSampleValenceOnly)
1731 charge -= getCoreElectrons((int)charge);
1732 data.charges.push_back(charge);
1733 std::vector<double> pos(3, 0.);
1734 for (int j=0;j<3;++j)
1735 pos[j] = wfn->molecule()->r(iatom, j)*AtomicLengthToAngstroem;
1736 data.positions.push_back(pos);
1737 }
1738 ExEnv::out0() << "We have "
1739 << data.positions.size() << " positions and "
1740 << data.charges.size() << " charges." << endl;
1741 }
1742 if (data.DoLongrange) {
1743 if (data.sampled_grid.level != 0)
1744 {
1745 // we now need to sample the density on the grid
1746 // 1. get max and min over all basis function positions
1747 assert( scf->basis()->ncenter() > 0 );
1748 SCVector3 bmin( scf->basis()->r(0,0), scf->basis()->r(0,1), scf->basis()->r(0,2) );
1749 SCVector3 bmax( scf->basis()->r(0,0), scf->basis()->r(0,1), scf->basis()->r(0,2) );
1750 for (int nr = 1; nr< scf->basis()->ncenter(); ++nr) {
1751 for (int i=0; i < 3; ++i) {
1752 if (scf->basis()->r(nr,i) < bmin(i))
1753 bmin(i) = scf->basis()->r(nr,i);
1754 if (scf->basis()->r(nr,i) > bmax(i))
1755 bmax(i) = scf->basis()->r(nr,i);
1756 }
1757 }
1758 ExEnv::out0() << "Basis min is at " << bmin << " and max is at " << bmax << endl;
1759
1760 // 2. choose an appropriately large grid
1761 // we have to pay attention to capture the right amount of the exponential decay
1762 // and also to have a power of two size of the grid at best
1763 SCVector3 boundaryV(5.); // boundary extent around compact domain containing basis functions
1764 bmin -= boundaryV;
1765 bmax += boundaryV;
1766 for (size_t i=0;i<3;++i) {
1767 if (bmin(i) < data.sampled_grid.begin[i])
1768 bmin(i) = data.sampled_grid.begin[i];
1769 if (bmax(i) > data.sampled_grid.end[i])
1770 bmax(i) = data.sampled_grid.end[i];
1771 }
1772 // set the non-zero window of the sampled_grid
1773 data.sampled_grid.setWindow(bmin.data(), bmax.data());
1774
1775 // for the moment we always generate a grid of full size
1776 // (NO LONGER converting grid dimensions from angstroem to bohr radii)
1777 const double AtomicLengthToAngstroem = 1.;//0.52917721;
1778 SCVector3 min;
1779 SCVector3 max;
1780 SCVector3 delta;
1781 size_t samplepoints[3];
1782 // due to periodic boundary conditions, we don't need gridpoints-1 here
1783 // TODO: in case of open boundary conditions, we need data on the right
1784 // hand side boundary as well
1785 const int gridpoints = data.sampled_grid.getGridPointsPerAxis();
1786 for (size_t i=0;i<3;++i) {
1787 min(i) = data.sampled_grid.begin_window[i]/AtomicLengthToAngstroem;
1788 max(i) = data.sampled_grid.end_window[i]/AtomicLengthToAngstroem;
1789 delta(i) = data.sampled_grid.getDeltaPerAxis(i)/AtomicLengthToAngstroem;
1790 samplepoints[i] = data.sampled_grid.getWindowGridPointsPerAxis(i);
1791 }
1792 ExEnv::out0() << "Grid starts at " << min
1793 << " and ends at " << max
1794 << " with a delta of " << delta
1795 << " to get "
1796 << samplepoints[0] << ","
1797 << samplepoints[1] << ","
1798 << samplepoints[2] << " samplepoints."
1799 << endl;
1800 assert( data.sampled_grid.sampled_grid.size() == samplepoints[0]*samplepoints[1]*samplepoints[2]);
1801
1802 // 3. sample the atomic density
1803 const double element_volume_conversion =
1804 1./AtomicLengthToAngstroem/AtomicLengthToAngstroem/AtomicLengthToAngstroem;
1805 SCVector3 r = min;
1806
1807 std::set<int> valence_indices;
1808 RefDiagSCMatrix evals = scf->eigenvalues();
1809 if (data.DoValenceOnly == MPQCData::DoSampleValenceOnly) {
1810 // find valence orbitals
1811// std::cout << "All Eigenvalues:" << std::endl;
1812// for(int i=0;i<wfn->oso_dimension(); ++i)
1813// std::cout << i << "th eigenvalue is " << evals(i) << std::endl;
1814 int n_electrons = scf->nelectron();
1815 int n_core_electrons = wfn->molecule()->n_core_electrons();
1816 std::set<double> evals_sorted;
1817 {
1818 int i=0;
1819 double first_positive_ev = std::numeric_limits<double>::max();
1820 for(i=0;i<wfn->oso_dimension(); ++i) {
1821 if (evals(i) < 0.)
1822 evals_sorted.insert(evals(i));
1823 else
1824 first_positive_ev = std::min(first_positive_ev, (double)evals(i));
1825 }
1826 // add the first positive for the distance
1827 evals_sorted.insert(first_positive_ev);
1828 }
1829 std::set<double> evals_distances;
1830 std::set<double>::const_iterator advancer = evals_sorted.begin();
1831 std::set<double>::const_iterator iter = advancer++;
1832 for(;advancer != evals_sorted.end(); ++advancer,++iter)
1833 evals_distances.insert((*advancer)-(*iter));
1834 const double largest_distance = *(evals_distances.rbegin());
1835 ExEnv::out0() << "Largest distance between EV is " << largest_distance << std::endl;
1836 advancer = evals_sorted.begin();
1837 iter = advancer++;
1838 for(;advancer != evals_sorted.begin(); ++advancer,++iter)
1839 if (fabs(fabs((*advancer)-(*iter)) - largest_distance) < 1e-10)
1840 break;
1841 assert( advancer != evals_sorted.begin() );
1842 const double last_core_ev = (*iter);
1843 ExEnv::out0() << "Last core EV might be " << last_core_ev << std::endl;
1844 ExEnv::out0() << "First valence index is " << n_core_electrons/2 << std::endl;
1845 for(int i=n_core_electrons/2;i<wfn->oso_dimension(); ++i)
1846 if (evals(i) > last_core_ev)
1847 valence_indices.insert(i);
1848// {
1849// int i=0;
1850// std::cout << "Valence eigenvalues:" << std::endl;
1851// for (std::set<int>::const_iterator iter = valence_indices.begin();
1852// iter != valence_indices.end(); ++iter)
1853// std::cout << i++ << "th eigenvalue is " << (*iter) << std::endl;
1854// }
1855 } else {
1856 // just insert all indices
1857 for(int i=0;i<wfn->oso_dimension(); ++i)
1858 valence_indices.insert(i);
1859 }
1860
1861 // testing alternative routine from SCF::so_density()
1862 RefSCMatrix oso_vector = scf->oso_eigenvectors();
1863 RefSCMatrix vector = scf->so_to_orthog_so().t() * oso_vector;
1864 oso_vector = 0;
1865 RefSymmSCMatrix occ(scf->oso_dimension(), scf->basis_matrixkit());
1866 occ.assign(0.0);
1867 for (std::set<int>::const_iterator iter = valence_indices.begin();
1868 iter != valence_indices.end(); ++iter) {
1869 const int i = *iter;
1870 occ(i,i) = scf->occupation(i);
1871 ExEnv::out0() << "# " << i << " has ev of " << evals(i) << ", occupied by " << scf->occupation(i) << std::endl;
1872 }
1873 RefSymmSCMatrix d2(scf->so_dimension(), scf->basis_matrixkit());
1874 d2.assign(0.0);
1875 d2.accumulate_transform(vector, occ);
1876
1877 // taken from scf::density()
1878 RefSCMatrix nos
1879 = scf->integral()->petite_list()->evecs_to_AO_basis(scf->natural_orbitals());
1880 RefDiagSCMatrix nd = scf->natural_density();
1881 GaussianBasisSet::ValueData *valdat
1882 = new GaussianBasisSet::ValueData(scf->basis(), scf->integral());
1883 std::vector<double>::iterator griditer = data.sampled_grid.sampled_grid.begin();
1884 const int nbasis = scf->basis()->nbasis();
1885 double *bs_values = new double[nbasis];
1886
1887 // TODO: need to take care when we have periodic boundary conditions.
1888 for (size_t x = 0; x < samplepoints[0]; ++x, r.x() += delta(0)) {
1889 std::cout << "Sampling now for x=" << r.x() << std::endl;
1890 for (size_t y = 0; y < samplepoints[1]; ++y, r.y() += delta(1)) {
1891 for (size_t z = 0; z < samplepoints[2]; ++z, r.z() += delta(2)) {
1892 scf->basis()->values(r,valdat,bs_values);
1893
1894 // loop over natural orbitals adding contributions to elec_density
1895 double elec_density=0.0;
1896 for (int i=0; i<nbasis; ++i) {
1897 double tmp = 0.0;
1898 for (int j=0; j<nbasis; ++j) {
1899 tmp += d2(j,i)*bs_values[j]*bs_values[i];
1900 }
1901 elec_density += tmp;
1902 }
1903 const double dens_at_r = elec_density * element_volume_conversion;
1904 // const double dens_at_r = scf->density(r) * element_volume_conversion;
1905
1906 // if (fabs(dens_at_r) > 1e-4)
1907 // std::cout << "Electron density at " << r << " is " << dens_at_r << std::endl;
1908 if (griditer != data.sampled_grid.sampled_grid.end())
1909 *griditer++ = dens_at_r;
1910 else
1911 std::cerr << "PAST RANGE!" << std::endl;
1912 }
1913 r.z() = min.z();
1914 }
1915 r.y() = min.y();
1916 }
1917 delete[] bs_values;
1918 delete valdat;
1919 assert( griditer == data.sampled_grid.sampled_grid.end());
1920 // normalization of electron charge to equal electron number
1921 {
1922 double integral_value = 0.;
1923 const double volume_element = pow(AtomicLengthToAngstroem,3)*delta(0)*delta(1)*delta(2);
1924 for (std::vector<double>::const_iterator diter = data.sampled_grid.sampled_grid.begin();
1925 diter != data.sampled_grid.sampled_grid.end(); ++diter)
1926 integral_value += *diter;
1927 integral_value *= volume_element;
1928 int n_electrons = scf->nelectron();
1929 if (data.DoValenceOnly == MPQCData::DoSampleValenceOnly)
1930 n_electrons -= wfn->molecule()->n_core_electrons();
1931 const double normalization =
1932 ((integral_value == 0) || (n_electrons == 0)) ?
1933 1. : n_electrons/integral_value;
1934 std::cout << "Created " << data.sampled_grid.sampled_grid.size() << " grid points"
1935 << " with integral value of " << integral_value
1936 << " against " << ((data.DoValenceOnly == MPQCData::DoSampleValenceOnly) ? "n_valence_electrons" : "n_electrons")
1937 << " of " << n_electrons << "." << std::endl;
1938 // with normalization we also get the charge right : -1.
1939 for (std::vector<double>::iterator diter = data.sampled_grid.sampled_grid.begin();
1940 diter != data.sampled_grid.sampled_grid.end(); ++diter)
1941 *diter *= -1.*normalization;
1942 }
1943 }
1944 }
1945 scf = 0;
1946 }
1947 if (tim.nonnull()) tim->exit("gather");
1948
1949 if (print_timings)
1950 if (tim.nonnull()) tim->print(ExEnv::out0());
1951
1952
1953 {
1954 // times obtain from key "mpqc" which should be the first
1955 const int nregion = tim->nregion();
1956 //std::cout << "There are " << nregion << " timed regions." << std::endl;
1957 const char **region_names = new const char*[nregion];
1958 tim->get_region_names(region_names);
1959 // find "gather"
1960 size_t gather_region = findTimerRegion(nregion, region_names, "gather");
1961 size_t mpqc_region = findTimerRegion(nregion, region_names, "mpqc");
1962 delete[] region_names;
1963
1964 // get timings
1965 double *cpu_time = new double[nregion];
1966 double *wall_time = new double[nregion];
1967 double *flops = new double[nregion];
1968 tim->get_cpu_times(cpu_time);
1969 tim->get_wall_times(wall_time);
1970 tim->get_flops(flops);
1971 if (cpu_time != NULL) {
1972 data.times.total_cputime = cpu_time[mpqc_region];
1973 data.times.gather_cputime = cpu_time[gather_region];
1974 }
1975 if (wall_time != NULL) {
1976 data.times.total_walltime = wall_time[mpqc_region];
1977 data.times.gather_walltime = wall_time[gather_region];
1978 }
1979 if (flops != NULL) {
1980 data.times.total_flops = flops[mpqc_region];
1981 data.times.gather_flops = flops[gather_region];
1982 }
1983 delete[] cpu_time;
1984 delete[] wall_time;
1985 delete[] flops;
1986 }
1987
1988 delete[] molname;
1989 SCFormIO::set_default_basename(0);
1990
1991 renderer = 0;
1992 molfreq = 0;
1993 molhess = 0;
1994 opt = 0;
1995 mole = 0;
1996 integral = 0;
1997 debugger = 0;
1998 thread = 0;
1999 tim = 0;
2000 keyval = 0;
2001 parsedkv = 0;
2002 memory = 0;
2003 clean_up();
2004
2005#if defined(HAVE_TIME) && defined(HAVE_CTIME)
2006 time_t t;
2007 time(&t);
2008 const char *tstr = ctime(&t);
2009#endif
2010 if (!tstr) {
2011 tstr = "UNKNOWN";
2012 }
2013 ExEnv::out0() << endl
2014 << indent << scprintf("End Time: %s", tstr) << endl;
2015}
2016
2017// static values object
2018OptionValues values;
2019
2020#ifdef HAVE_JOBMARKET
2021FragmentResult::ptr MPQCJob::Work()
2022{
2023 char mpqc[] = "mpqc" ;
2024 char **argv = new char*[1];
2025 argv[0] = &mpqc[0];
2026 int argc = 1;
2027// init();
2028//
2029// ExEnv::init(argc, argv);
2030//
2031// // parse commandline options
2032// GetLongOpt options;
2033// int optind = ParseOptions(options, argc, argv);
2034// const char *output = 0;
2035// ostream *outstream = 0;
2036// ComputeOptions(options, output, outstream);
2037// OptionValues values;
2038// parseRemainderOptions(options, values, argc, argv);
2039//
2040// // get the basename for output files
2041// char filename_template[] = "mpqc_temp_XXXXXX";
2042// output = mktemp(filename_template);
2043// setOutputBaseName(NULL, output);
2044
2045 // now comes the actual work
2046 int nfilebase = (int) inputfile.length();
2047 char *in_char_array = new char[nfilebase + 1];
2048 strncpy(in_char_array, inputfile.c_str(), nfilebase);
2049 in_char_array[nfilebase] = '\0';
2050 const char *input = 0;
2051 const char *generic_input = 0;
2052 Ref<MessageGrp> grp = MessageGrp::get_default_messagegrp();
2053 // create unique, temporary name and check whether it exists
2054 const char *output = NULL;
2055 char *tempfilename = NULL;
2056 {
2057 std::ifstream test;
2058 do {
2059 if (output != NULL) // free buffer from last round
2060 delete output;
2061 char filename_template[] = "mpqc_temp_XXXXXX\0";
2062 char filename_suffix[] = ".in\0";
2063 tempfilename = (char *) malloc ( (strlen(filename_template)+strlen(filename_suffix)+2)*(sizeof(char)));
2064 strncpy(tempfilename, mktemp(filename_template), strlen(filename_template));
2065 tempfilename[strlen(filename_template)] = '\0';
2066 strncat(tempfilename, filename_suffix, strlen(filename_suffix));
2067 output = tempfilename;
2068 //free(tempfilename); // don't free! output takes over pointer!
2069 test.open(output);
2070 } while (test.good()); // test whether file does not(!) exist
2071 test.close();
2072 }
2073 // put info how to sample the density into MPQCData
2074 MPQCData data(grid);
2075 data.DoLongrange = DoLongrange; // set whether we sample the density
2076 data.DoValenceOnly = DoValenceOnly; // set whether we sample just valence electron and nuclei densities
2077// now call work horse
2078 try {
2079 mainFunction(grp, values, output, input, generic_input, in_char_array, argc, argv, data);
2080 }
2081 catch (SCException &e) {
2082 cout << argv[0] << ": ERROR: SC EXCEPTION RAISED:" << endl
2083 << e.what()
2084 << endl;
2085 clean_up();
2086 }
2087
2088 //delete[] in_char_array; // is deleted in mainFunction()
2089 if (output != 0) {
2090 free(tempfilename);
2091 }
2092 delete[] argv;
2093 grp = NULL;
2094
2095 // place into returnstream
2096 std::stringstream returnstream;
2097 boost::archive::text_oarchive oa(returnstream);
2098 oa << data;
2099
2100 FragmentResult::ptr s( new FragmentResult(getId(), returnstream.str()) );
2101 if (s->exitflag != 0)
2102 cerr << "Job #" << s->getId() << " failed to reach desired accuracy." << endl;
2103
2104 return s;
2105}
2106#endif
2107
2108// we need to explicitly instantiate the serialization functions as
2109// its is only serialized through its base class FragmentJob
2110BOOST_CLASS_EXPORT_IMPLEMENT(MPQCJob)
2111
2112int
2113try_main(int argc, char *argv[])
2114{
2115 init();
2116
2117 ExEnv::init(argc, argv);
2118
2119 // parse commandline options
2120 GetLongOpt options;
2121 int optind = ParseOptions(options, argc, argv);
2122 const char *output = 0;
2123 ostream *outstream = 0;
2124 ComputeOptions(options, output, outstream);
2125 parseRemainderOptions(options, values, argc, argv);
2126
2127 // get input file names, either object-oriented or generic
2128 const char *object_input = 0;
2129 const char *generic_input = 0;
2130 getInputFileNames(object_input, generic_input, options, optind, argc, argv);
2131 const char *input = 0;
2132 if (object_input) input = object_input;
2133 if (generic_input) input = generic_input;
2134
2135 // get the message group. first try the commandline and environment
2136 Ref<MessageGrp> grp;
2137 getMessageGroup(grp, argc, argv);
2138
2139 // check if we got option "-n"
2140 int exitflag = 0;
2141#ifdef HAVE_JOBMARKET
2142 if (options.retrieve("n")) {
2143 /// create new argc, argv and call by splitting with tokenizer
2144 std::string networkstring(options.retrieve("n"));
2145 typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
2146 boost::char_separator<char> sep(" ");
2147 tokenizer tok(networkstring, sep);
2148 // simple count because tokenizer has now size()
2149 int argc_network = 0;
2150 for(tokenizer::iterator beg=tok.begin(); beg!=tok.end();++beg)
2151 ++argc_network;
2152 // argv[0] is program name
2153 char **argv_network = new char*[argc_network+1];
2154 argv_network[0] = new char[5];
2155 strcpy(argv_network[0], "mpqc");
2156 // then we place each token as a new argument
2157 argc_network = 1;
2158 for(tokenizer::iterator beg=tok.begin(); beg!=tok.end();++beg){
2159 const size_t strlength = (*beg).length();
2160 const char *strarray = beg->c_str();
2161 //std::cout << "Token " << argc_network << " is " << strarray << ", length " << strlength << endl;
2162 argv_network[argc_network] = new char[strlength+1];
2163 strcpy(argv_network[argc_network], strarray);
2164 argv_network[argc_network][strlength] = '\0';
2165 for (size_t index = 0; index < strlength; ++index)
2166 if (argv_network[argc_network][index] == '+')
2167 argv_network[argc_network][index] = '-';
2168 ++argc_network;
2169 }
2170 /// and start listening for MPQCJobs
2171 exitflag = poolworker_main(argc_network, argv_network);
2172 /// remove the artifical [argv,argv] again
2173 for (int i=0;i<argc_network;++i)
2174 delete[] argv_network[i];
2175 delete[] argv_network;
2176 } else
2177#endif
2178 {
2179 // if not, work on the command line input
2180 char *in_char_array = 0;
2181#ifdef HAVE_MPQCDATA
2182 MPQCData data;
2183 mainFunction(grp, values, output, input, generic_input, in_char_array, argc, argv, data);
2184#else
2185 mainFunction(grp, values, output, input, generic_input, in_char_array, argc, argv);
2186#endif
2187 }
2188
2189 if (output != 0) {
2190 ExEnv::set_out(&cout);
2191 delete outstream;
2192 }
2193
2194 grp = 0;
2195 final_clean_up();
2196
2197 return exitflag;
2198}
2199
2200
2201double EvaluateDensity(SCVector3 &r, Ref<Integral> &intgrl, GaussianBasisSet::ValueData &vdat, Ref<Wavefunction> &wfn)
2202{
2203 ExEnv::out0() << "We get the following values at " << r << "." << endl;
2204 int nbasis = wfn->basis()->nbasis();
2205 double *b_val = new double[nbasis];
2206 wfn->basis()->values(r, &vdat, b_val);
2207 double sum=0.;
2208 for (int i=0; i<nbasis; i++)
2209 sum += b_val[i];
2210 delete[] b_val;
2211 return sum;
2212}
2213
2214int
2215main(int argc, char *argv[])
2216{
2217#if !defined(DEFAULT_MPI) && !defined(ALWAYS_USE_MPI) && defined(HAVE_MPI)
2218 MPI_Init(&argc, &argv);
2219#endif
2220 size_t exitflag = 0;
2221 try {
2222 exitflag = try_main(argc, argv);
2223 }
2224 catch (SCException &e) {
2225 cout << argv[0] << ": ERROR: SC EXCEPTION RAISED:" << endl
2226 << e.what()
2227 << endl;
2228 clean_up();
2229 throw;
2230 }
2231 catch (bad_alloc &e) {
2232 cout << argv[0] << ": ERROR: MEMORY ALLOCATION FAILED:" << endl
2233 << e.what()
2234 << endl;
2235 clean_up();
2236 throw;
2237 }
2238 catch (exception &e) {
2239 cout << argv[0] << ": ERROR: EXCEPTION RAISED:" << endl
2240 << e.what()
2241 << endl;
2242 clean_up();
2243 throw;
2244 }
2245 catch (...) {
2246 cout << argv[0] << ": ERROR: UNKNOWN EXCEPTION RAISED" << endl;
2247 clean_up();
2248 throw;
2249 }
2250#if !defined(DEFAULT_MPI) && !defined(ALWAYS_USE_MPI) && defined(HAVE_MPI)
2251 // there is an MPI_Finalize() hidden somewhere else
2252// MPI_Finalize();
2253#endif
2254 return exitflag;
2255}
2256
2257/////////////////////////////////////////////////////////////////////////////
2258
2259// Local Variables:
2260// mode: c++
2261// c-file-style: "ETS"
2262// End:
Note: See TracBrowser for help on using the repository browser.