5 # Created by Toshi Nagata on 2009/11/22.
6 # Copyright 2009 Toshi Nagata. All rights reserved.
8 # This program is free software; you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation version 2 of the License.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
34 # Import nbo log. The argument is either an array of Strings
36 def import_nbo_log(lines)
38 getline = lambda { lines.gets }
40 getline = lambda { lines.shift }
43 while (ln = getline.call) != nil
44 if ln =~ /done with NBO analysis/
47 if ln =~ /NATURAL POPULATIONS: Natural atomic orbital occupancies/
53 while (ln = getline.call) != nil
58 # Double blank lines indicates the end of the table
63 next unless ln =~ /^ *(\d+) *([A-Za-z]+) *(\d+) *([a-z]+) +([A-Za-z]+)\( *(\d+)([a-z]+)\)/
66 atom_label = $2 + $3.to_s
70 vals = $~.post_match.split.map { |e| e.to_f }
71 # atom_index, type, pn+label, occupancy[, energy]
72 nbo["nao"].push([atom_label, type, pn + label] + vals)
74 elsif ln =~ / NATURAL BOND ORBITALS \(Summary\):/
77 while (ln = getline.call) != nil
78 break if ln =~ /Total Lewis/
83 # Double blank lines indicates the end of the table
87 if ln =~ /^\s*(\d+)\. *([A-Za-z]+\*?) *\( *(\d+)\) *([A-Za-z]+) *(\d+)(- *([A-Za-z]+) *(\d+))? *(\d\.\d+)/
91 atom_label = $4 + ($5.to_i - 1).to_s
93 atom_label += "-" + $7 + ($8.to_i - 1).to_s
96 nbo["nbo"].push([orb_kind + "_" + orb_idx, atom_label, occ])
99 elsif ln =~ /([A-Z]+)s in the ([A-Z]+) basis:/ || ln =~ /([A-Z]+) Fock matrix:/
106 key = src + "/" + dst
114 while (ln = getline.call) != nil
116 # Blank line: end of one block
119 # Double blank lines indicates the end of the table
131 lab = $~.pre_match.strip
132 a = ([$~[0]] + $~.post_match.split).map { |e| e.to_f }
134 lab =~ /^[0-9]+\. *(.*)$/
137 (elements[idx] ||= []).concat(a)
140 nbo[key] = LAMatrix.new(elements).transpose!
141 key2 = (src == "F" ? dst : src) + "_L"
149 # Convert NAO based matrix into AO based matrix
150 @nbo.keys.each { |key|
151 if key[0..3] == "NAO/"
152 key2 = "AO/" + key[4..-1]
153 @nbo[key2] = @nbo["AO/NAO"] * @nbo[key]
160 def Molecule.read_gamess_basis_sets(fname)
161 # $gamess_basis = Hash.new unless $gamess_basis
162 $gamess_ecp = Hash.new unless $gamess_ecp
163 # $gamess_basis_desc = Hash.new unless $gamess_basis_desc
164 # $gamess_basis_keys = [] unless $gamess_basis_keys
165 basename = File.basename(fname, ".*")
168 File.open(fname, "r") { |fp|
170 if s =~ /^\s*!\s*/ && descname == nil
171 # Get the descriptive name from the first comment line
172 s = Regexp.last_match.post_match
174 descname = Regexp.last_match.pre_match
176 descname = (s.split)[0]
178 $gamess_basis_desc[basename] = descname
181 ss, bas = (s.split)[0..1] # Tokens delimited by whitespaces
182 next if ss == nil || ss == ""
184 # Read the ECP section
185 ecp = $gamess_ecp[basename]
188 $gamess_ecp[basename] = ecp
190 keys << basename unless keys.include?(basename)
193 ary = s.split # (PNAME, PTYPE, IZCORE, LMAX+1)
194 elem = ary[0].match(/\w{1,2}/).to_a[0] # ary[0] should begin with an element name
195 ap = Parameter.builtin.elements.find { |p| p.name.casecmp(elem) == 0 }
196 raise MolbyError, "the ECP definition does not begin with an element name: #{s}" if !ap
199 (0..Integer(ary[3])).each {
201 raise MolbyError, "the ECP definition ends unexpectedly at line #{ln} for: #{s}" if !s
203 ary = s.split # (NGPOT, comment)
205 (1..Integer(ary[0])).each {
207 raise MolbyError, "the ECP definition ends unexpectedly at line #{ln} for: #{s}" if !s
212 ecp[ap.index] = ecpdef
215 # Comments or other unrecognizable lines
217 elsif (ap = Parameter.builtin.elements.find { |p| p.name.casecmp(ss) == 0 || p.fullname.casecmp(ss) == 0 })
218 # Valid basis definition
219 if bas == nil || bas =~ /\W/
222 basis = $gamess_basis[bas]
225 $gamess_basis[bas] = basis
227 keys << bas unless keys.include?(bas)
229 while (s = fp.gets) && s =~ /\S/
232 basis[ap.index] = basdef
234 raise MolbyError, "ss is not a valid element symbol or name: #{s}"
238 unless $gamess_basis_keys.include?(basename)
239 $gamess_basis_keys.push(basename)
243 # Execute GAMESS (inferior copy of rungms script)
244 # inpname is the input file
245 # mol (optional) is the molecule from which the GAMESS input was built.
246 # If mol is specified and RUNTYP=OPTIMIZE, then the intermediate structures are
247 # displayed real-time.
248 def Molecule.execute_gamess(inpname, mol = nil)
249 gmsname = get_global_settings("gamess.executable_path")
253 cygwin_version = false # For windows: old cygwin version
256 if gmsname == nil || !File.exist?(gmsname)
257 gmsname = Dialog.open_panel("Please locate the GAMESS executable")
258 exit if gmsname == nil
260 gmsbase = File.basename(gmsname)
261 gmsdir = File.dirname(gmsname)
262 if gmsbase =~ /gamess\.(.*)\.(exe|x)$/i
267 error_message_box(gmsbase + " does not look like a GAMESS executable!")
272 # mol = Molecule.open(inpname)
274 # error_message_box("Cannot open #{inpname} as GAMESS input")
279 inpbase = File.basename(inpname)
280 inpdir = File.dirname(inpname)
281 inpbody = inpbase.sub(/\.inp$/, "")
282 logbase = inpbody + ".log"
284 set_global_settings("gamess.executable_path", gmsname)
286 ncpus = get_global_settings("gamess.ncpus").to_i
291 # Prepare the scratch directory
293 scrdir = create_temp_dir("gamess", inpbody)
295 error_message_box($!.to_s)
298 # scrdir = $home_directory + "/Molby/gamess"
300 # mkdir_recursive(scrdir)
302 # error_message_box("Cannot create directory #{scrdir}: " + $!.to_s)
306 # scrdir = scrdir + "/" + inpbody + "." + $$.to_s + ".0"
308 # while File.exist?(scrdir)
309 # scrdir = scrdir.sub(".#{n}", ".#{n + 1}")
314 if $platform == "win"
316 scrdir.gsub!("/", sep)
317 gmsdir.gsub!("/", sep)
322 # Old (obsolete) cygwin version, using ddikick
323 if $platform == "win"
325 cygwin_version = true
329 # Get the host name etc.
330 hostname = backquote("hostname").chomp
331 if $platform == "win"
332 s = backquote("cmd.exe /c dir \"#{scrdir}\"")
333 freebytes = s.split("\n").pop.match(/([0-9,]+)[^0-9]*$/).to_a[1]
335 freebytes = (freebytes.gsub(",","").to_i / 1024).to_s + " Kbytes"
337 freebytes = "(unknown)"
339 uname = backquote("cmd.exe /c ver").to_s.gsub("\n", "")
341 freebytes = `df -k "#{scrdir}"`
342 uname = `uname`.chomp
345 # Redirect standard output to the log file
346 logname = scrdir + sep + logbase
347 fpout = File.open(logname, "w")
349 # The cygwin version uses LF as the eol character
352 fpout.print "----- GAMESS execution script -----\n"
353 fpout.print "This job is running on host #{hostname}\n"
354 fpout.print "under operating system #{uname} at #{Time.now.to_s}\n"
355 fpout.print "Available scratch disk space (Kbyte units) at beginning of the job is\n"
356 fpout.print freebytes + "\n"
358 # Copy the input file
359 scrprefix = scrdir + sep + inpbody
360 if $platform == "win"
365 filecopy(inpname, scrprefix + ".F05")
366 File.open("#{scrdir}/.in_use", "w") { |fp| }
368 # Prepare environmental variables
369 auxdir = "#{gmsdir}#{sep}auxdata"
370 ENV["ERICFMT"] = "#{auxdir}#{sep}ericfmt.dat"
371 ENV["MCPPATH"] = "#{auxdir}#{sep}MCP"
372 ENV["BASPATH"] = "#{auxdir}#{sep}BASES"
373 ENV["QUANPOL"] = "#{auxdir}#{sep}QUANPOL"
374 ENV["EXTBAS"] = "/dev/null"
375 ENV["IRCDATA"] = "#{scrbody}.irc"
376 ENV["RESTART"] = "#{scrbody}.rst"
377 ENV["TRAJECT"] = "#{scrbody}.trj"
378 ENV["PUNCH"] = "#{scrbody}.dat"
379 ENV["INPUT"] = "#{scrbody}.F05"
380 ENV["AOINTS"] = "#{scrbody}.F08"
381 ENV["MOINTS"] = "#{scrbody}.F09"
382 ENV["DICTNRY"] = "#{scrbody}.F10"
383 ENV["DRTFILE"] = "#{scrbody}.F11"
384 ENV["CIVECTR"] = "#{scrbody}.F12"
385 ENV["CASINTS"] = "#{scrbody}.F13"
386 ENV["CIINTS"] = "#{scrbody}.F14"
387 ENV["WORK15"] = "#{scrbody}.F15"
388 ENV["WORK16"] = "#{scrbody}.F16"
389 ENV["CSFSAVE"] = "#{scrbody}.F17"
390 ENV["FOCKDER"] = "#{scrbody}.F18"
391 ENV["WORK19"] = "#{scrbody}.F19"
392 ENV["DASORT"] = "#{scrbody}.F20"
393 ENV["DFTINTS"] = "#{scrbody}.F21"
394 ENV["DFTGRID"] = "#{scrbody}.F22"
395 ENV["JKFILE"] = "#{scrbody}.F23"
396 ENV["ORDINT"] = "#{scrbody}.F24"
397 ENV["EFPIND"] = "#{scrbody}.F25"
398 ENV["PCMDATA"] = "#{scrbody}.F26"
399 ENV["PCMINTS"] = "#{scrbody}.F27"
400 ENV["MLTPL"] = "#{scrbody}.F28"
401 ENV["MLTPLT"] = "#{scrbody}.F29"
402 ENV["DAFL30"] = "#{scrbody}.F30"
403 ENV["SOINTX"] = "#{scrbody}.F31"
404 ENV["SOINTY"] = "#{scrbody}.F32"
405 ENV["SOINTZ"] = "#{scrbody}.F33"
406 ENV["SORESC"] = "#{scrbody}.F34"
407 ENV["SIMEN"] = "#{scrbody}.simen"
408 ENV["SIMCOR"] = "#{scrbody}.simcor"
409 ENV["GCILIST"] = "#{scrbody}.F37"
410 ENV["HESSIAN"] = "#{scrbody}.F38"
411 ENV["SOCCDAT"] = "#{scrbody}.F40"
412 ENV["AABB41"] = "#{scrbody}.F41"
413 ENV["BBAA42"] = "#{scrbody}.F42"
414 ENV["BBBB43"] = "#{scrbody}.F43"
415 ENV["MCQD50"] = "#{scrbody}.F50"
416 ENV["MCQD51"] = "#{scrbody}.F51"
417 ENV["MCQD52"] = "#{scrbody}.F52"
418 ENV["MCQD53"] = "#{scrbody}.F53"
419 ENV["MCQD54"] = "#{scrbody}.F54"
420 ENV["MCQD55"] = "#{scrbody}.F55"
421 ENV["MCQD56"] = "#{scrbody}.F56"
422 ENV["MCQD57"] = "#{scrbody}.F57"
423 ENV["MCQD58"] = "#{scrbody}.F58"
424 ENV["MCQD59"] = "#{scrbody}.F59"
425 ENV["MCQD60"] = "#{scrbody}.F60"
426 ENV["MCQD61"] = "#{scrbody}.F61"
427 ENV["MCQD62"] = "#{scrbody}.F62"
428 ENV["MCQD63"] = "#{scrbody}.F63"
429 ENV["MCQD64"] = "#{scrbody}.F64"
430 ENV["NMRINT1"] = "#{scrbody}.F61"
431 ENV["NMRINT2"] = "#{scrbody}.F62"
432 ENV["NMRINT3"] = "#{scrbody}.F63"
433 ENV["NMRINT4"] = "#{scrbody}.F64"
434 ENV["NMRINT5"] = "#{scrbody}.F65"
435 ENV["NMRINT6"] = "#{scrbody}.F66"
436 ENV["DCPHFH2"] = "#{scrbody}.F67"
437 ENV["DCPHF21"] = "#{scrbody}.F68"
438 ENV["GVVPT"] = "#{scrbody}.F69"
440 # next files are used only during coupled cluster runs, so let's
441 # display the numerous definitions only if they are to be used.
442 # Don't set these variables on windows, where the memory for environmental variables
444 if $platform != "win"
445 ENV["CCREST"] = "#{scrbody}.F70"
446 ENV["CCDIIS"] = "#{scrbody}.F71"
447 ENV["CCINTS"] = "#{scrbody}.F72"
448 ENV["CCT1AMP"] = "#{scrbody}.F73"
449 ENV["CCT2AMP"] = "#{scrbody}.F74"
450 ENV["CCT3AMP"] = "#{scrbody}.F75"
451 ENV["CCVM"] = "#{scrbody}.F76"
452 ENV["CCVE"] = "#{scrbody}.F77"
453 ENV["EOMSTAR"] = "#{scrbody}.F80"
454 ENV["EOMVEC1"] = "#{scrbody}.F81"
455 ENV["EOMVEC2"] = "#{scrbody}.F82"
456 ENV["EOMHC1"] = "#{scrbody}.F83"
457 ENV["EOMHC2"] = "#{scrbody}.F84"
458 ENV["EOMHHHH"] = "#{scrbody}.F85"
459 ENV["EOMPPPP"] = "#{scrbody}.F86"
460 ENV["EOMRAMP"] = "#{scrbody}.F87"
461 ENV["EOMRTMP"] = "#{scrbody}.F88"
462 ENV["EOMDG12"] = "#{scrbody}.F89"
463 ENV["MMPP"] = "#{scrbody}.F90"
464 ENV["MMHPP"] = "#{scrbody}.F91"
465 ENV["MMCIVEC"] = "#{scrbody}.F92"
466 ENV["MMCIVC1"] = "#{scrbody}.F93"
467 ENV["MMCIITR"] = "#{scrbody}.F94"
468 ENV["MMNEXM"] = "#{scrbody}.F95"
469 ENV["MMNEXE"] = "#{scrbody}.F96"
470 ENV["MMNREXM"] = "#{scrbody}.F97"
471 ENV["MMNREXE"] = "#{scrbody}.F98"
474 # next are for TDHFX code, not used by current GAMESS
477 ENV["OLI201"] = "#{scrbody}.F201"
478 ENV["OLI202"] = "#{scrbody}.F202"
479 ENV["OLI203"] = "#{scrbody}.F203"
480 ENV["OLI204"] = "#{scrbody}.F204"
481 ENV["OLI205"] = "#{scrbody}.F205"
482 ENV["OLI206"] = "#{scrbody}.F206"
483 ENV["OLI207"] = "#{scrbody}.F207"
484 ENV["OLI208"] = "#{scrbody}.F208"
485 ENV["OLI209"] = "#{scrbody}.F209"
486 ENV["OLI210"] = "#{scrbody}.F210"
487 ENV["OLI211"] = "#{scrbody}.F211"
488 ENV["OLI212"] = "#{scrbody}.F212"
489 ENV["OLI213"] = "#{scrbody}.F213"
490 ENV["OLI214"] = "#{scrbody}.F214"
491 ENV["OLI215"] = "#{scrbody}.F215"
492 ENV["OLI216"] = "#{scrbody}.F216"
493 ENV["OLI217"] = "#{scrbody}.F217"
494 ENV["OLI218"] = "#{scrbody}.F218"
495 ENV["OLI219"] = "#{scrbody}.F219"
496 ENV["OLI220"] = "#{scrbody}.F220"
497 ENV["OLI221"] = "#{scrbody}.F221"
498 ENV["OLI222"] = "#{scrbody}.F222"
499 ENV["OLI223"] = "#{scrbody}.F223"
500 ENV["OLI224"] = "#{scrbody}.F224"
501 ENV["OLI225"] = "#{scrbody}.F225"
502 ENV["OLI226"] = "#{scrbody}.F226"
503 ENV["OLI227"] = "#{scrbody}.F227"
504 ENV["OLI228"] = "#{scrbody}.F228"
505 ENV["OLI229"] = "#{scrbody}.F229"
506 ENV["OLI230"] = "#{scrbody}.F230"
507 ENV["OLI231"] = "#{scrbody}.F231"
508 ENV["OLI232"] = "#{scrbody}.F232"
509 ENV["OLI233"] = "#{scrbody}.F233"
510 ENV["OLI234"] = "#{scrbody}.F234"
511 ENV["OLI235"] = "#{scrbody}.F235"
512 ENV["OLI236"] = "#{scrbody}.F236"
513 ENV["OLI237"] = "#{scrbody}.F237"
514 ENV["OLI238"] = "#{scrbody}.F238"
515 ENV["OLI239"] = "#{scrbody}.F239"
518 if $platform == "win"
523 # Old (obsolete) cygwin version, using ddikick
524 fpout.print "ddikick will run #{ncpus} compute process\n"
525 ENV["CYGWIN"] = "nodosfilewarning"
527 fpout.print "Microsoft MPI will be running GAMESS on 1 node.\n"
528 fpout.print "The binary kicked off by 'mpiexec' is gamess.#{gmsvers}.exe\n"
529 fpout.print "MS-MPI will run #{ncpus*2} compute process\n"
530 # File containing environmental variables
531 envfil = "#{scrprefix}.GMS.ENV"
532 fp = File.open(envfil, "w")
533 ENV.each { |k, v| fp.print "#{k}=#{v}\n" }
535 # File containing arguments to mpiexec
536 procfil = "#{scrprefix}.processes.mpd"
537 fp = File.open(procfil, "w")
538 fp.print "-env ENVFIL \"#{envfil}\" -wdir \"#{scrdir}\" -n #{ncpus*2} \"#{gmsdir}#{sep}gamess.#{gmsvers}.exe\"\n"
544 fplog = File.open(logname, "r")
552 ne_alpha = ne_beta = 0
557 term_callback = lambda { |m, n|
558 msg = "GAMESS execution on #{inpbase} "
565 msg += "failed with status #{n}."
569 msg += "\n(In directory #{inpdir})"
571 File.delete("#{scrdir}/.in_use")
573 ext_to_keep = [".dat", ".rst", ".trj", ".efp", ".gamma", ".log"]
574 ext_to_keep.each { |ex|
575 if File.exists?("#{scrprefix}#{ex}")
576 filecopy("#{scrprefix}#{ex}", "#{inpdir}#{sep}#{inpbody}#{ex}")
579 Dir.foreach(scrdir) { |file|
580 if file != "." && file != ".." && !ext_to_keep.include?(File.extname(file))
581 File.delete("#{scrdir}#{sep}#{file}")
586 erase_old_logs(scrdir, "latest", 5)
588 error_message_box($!.to_s)
592 if (script = get_global_settings("gamess.postfix_script")) != nil && script != ""
597 message_box(msg, hmsg, :ok, icon)
601 timer_callback = lambda { |m, n|
602 fplog.seek(0, IO::SEEK_END)
606 fplog.seek(size, IO::SEEK_SET)
607 fplog.each_line { |line|
608 if line[-1, 1] == "\n"
609 lines.push(last_line + line)
619 while i < lines.count
621 if line =~ /GEOMETRY SEARCH POINT NSERCH= *(\d+)/
626 elsif line =~ /START OF DRC CALCULATION/
630 elsif line =~ /CONSTRAINED OPTIMIZATION POINT/
633 elsif line =~ /POINT *([0-9]+) *ON THE REACTION PATH/
636 elsif line =~ /ATOMIC BASIS SET/
638 while j < lines.count
640 break if line =~ /TOTAL NUMBER OF BASIS SET/
648 bs_lines.push(lines[ii].chomp)
653 ncomps = mol.sub_load_gamess_log_basis_set(bs_lines, lineno + i)
656 $stderr.write($!.to_s + "\n")
657 $stderr.write($!.backtrace.inspect + "\n")
661 break # Wait until all basis set lines are read
663 elsif line =~ /NUMBER OF OCCUPIED ORBITALS/
671 elsif line =~ /SCFTYP=(\w+)/
673 if ne_alpha > 0 || ne_beta > 0
682 elsif line =~ /^\s*(EIGENVECTORS|MOLECULAR ORBITALS)\s*$/
683 if mo_count == 0 && mol
684 mol.clear_mo_coefficients
685 mol.set_mo_info(:type=>["UHF", "RHF", "ROHF"][rflag], :alpha=>ne_alpha, :beta=>ne_beta)
690 while j < lines.count
692 break if line =~ /\.\.\.\.\.\./ || line =~ /----------------/
696 break # Wait until complete MO info are read
701 mo_lines.push(lines[ii].chomp)
706 mol.sub_load_gamess_log_mo_coefficients(mo_lines, lineno + i, ncomps)
709 $stderr.write($!.to_s + "\n")
710 $stderr.write($!.backtrace.inspect + "\n")
713 elsif line =~ /NSERCH: *([0-9]+)/
717 line =~ /E= +([-.0-9]+)/
719 line =~ /GRAD\. MAX= +([-.0-9]+)/
721 mol.show_text("Search: #{n}\nGradient: #{grad}")
722 # mol.set_property("energy", energy)
725 elsif line =~ /TOTAL ENERGY += *([-.0-9]+)/
727 if mol && search_mode == 2
728 mol.show_text("Point: #{nserch}\nEnergy: #{energy}")
731 elsif line =~ /FINAL .* ENERGY IS +([-.0-9]+) *AFTER/
733 if mol && search_mode == 0
734 mol.set_property("energy", energy)
736 elsif nserch > 0 && line =~ /ddikick\.x/
739 elsif mol && nserch > 0 && (line =~ /COORDINATES OF ALL ATOMS/ || line =~ /COORDINATES \(IN ANGSTROM\) FOR \$DATA GROUP ARE/)
740 # There should be (natoms) lines
741 if line =~ /COORDINATES OF ALL ATOMS/
745 if i + mol.natoms + 1 <= lines.count
747 (i + 1...i + 1 + mol.natoms).each { |j|
748 name, charge, x, y, z = lines[j].split
749 coords.push(Vector3D[x.to_f, y.to_f, z.to_f])
751 mol.create_frame([coords])
752 if search_mode == 1 && energy
753 mol.set_property("energy", energy)
756 last_i = i + mol.natoms
757 i = last_i # Skip the processed lines
759 elsif line =~ /N A T U R A L B O N D O R B I T A L A N A L Y S I S/
762 while j < lines.count
763 break if lines[j] =~ /done with NBO analysis/
767 nbo_lines = lines[i..j]
768 mol.import_nbo_log(nbo_lines) rescue puts "Error: #{$!}, #{$!.backtrace.inspect}"
770 i = last_i # Skip the processed lines
772 break # Wait until NBO is done
781 lines[0..last_i] = nil
789 if (script = get_global_settings("gamess.prefix_script")) != nil && script != ""
793 if $platform == "win"
795 hosts = "localhost " * ncpus
796 cmdline = "cmd.exe /c \"#{gmsdir}/ddikick.exe #{gmsdir}/gamess.#{gmsvers}.exe #{inpbody} -ddi #{ncpus} #{ncpus} #{hosts} -scr #{scrdir} < NUL >>#{logname}"
798 cmdline = "cmd.exe /c \"mpiexec -configfile #{procfil} >>#{logname}"
801 hosts = "localhost " * ncpus
802 cmdline = "/bin/sh -c '#{gmsdir}/ddikick.x #{gmsdir}/gamess.#{gmsvers}.x #{inpbody} -ddi #{ncpus} #{ncpus} #{hosts} -scr #{scrdir} < /dev/null >>#{logname}'"
806 pid = mol.call_subprocess_async(cmdline, term_callback, timer_callback)
808 error_message_box("GAMESS failed to start. Please examine GAMESS installation.")
812 pid = call_subprocess(cmdline, "Running GAMESS")
813 term_callback.call(nil, pid)
819 def export_gamess(fname, hash)
821 def reorder_array(ary, ordered_sub_ary)
822 return (ordered_sub_ary & ary) + (ary - ordered_sub_ary)
827 basename = File.basename(fname, ".*")
829 basename = File.basename(self.name, ".*")
833 icharg = hash["charge"]
835 runtyp = ["ENERGY", "PROP", "OPTIMIZE", "SADPOINT", "IRC"][hash["runtype"].to_i]
836 scftyp = ["RHF", "ROHF", "UHF"][hash["scftype"].to_i]
837 bssname = hash["basis"]
838 bssname2 = hash["secondary_basis"]
839 if hash["use_secondary_basis"].to_i != 0 && bssname2 != bssname
841 element2 = hash["secondary_elements"].split(/[\s,]+/).map { |name| name.capitalize }
846 basis = $gamess_basis[bssname]
847 basis2 = $gamess_basis[bssname2]
849 # Use effective core potentials?
850 ecp = $gamess_ecp[bssname]
851 ecp2 = $gamess_ecp[bssname2]
852 ecp_read = (ecp || ecp2 ? "ECP=READ " : "")
854 # Use only one built-in basis set?
859 gbasis = "PM3 NGAUSS=3"
861 gbasis = "STO NGAUSS=3"
863 gbasis = "N21 NGAUSS=3"
865 gbasis = "N31 NGAUSS=6"
867 gbasis = "N31 NGAUSS=6 NDFUNC=1"
869 gbasis = "N31 NGAUSS=6 NDFUNC=1 NPFUNC=1"
871 gbasis = "N311 NGAUSS=6"
873 gbasis = "N311 NGAUSS=6 NDFUNC=1 NPFUNC=1"
877 # Count non-dummy atoms
880 natoms += 1 if ap.atomic_number != 0
883 # Fill hash with default values
884 h = (hash["CONTRL"] ||= Hash.new)
885 h["COORD"] ||= "UNIQUE"
886 h["EXETYP"] ||= "RUN"
887 h["ICHARG"] ||= (icharg || 0).to_s
889 h["INTTYP"] ||= "HONDO"
892 h["MOLPLT"] ||= ".T."
894 h["MULT"] ||= mult.to_s
895 h["QMTTOL"] ||= "1e-08"
896 h["RUNTYP"] ||= runtyp
897 if (hash["dft"] || 0) != 0 && hash["dfttype"]
898 h["DFTTYP"] ||= hash["dfttype"]
900 if (hash["use_internal"] || 0) != 0 && (hash["runtype"] >= 2 || h["RUNTYP"] == "OPTIMIZE" || h["RUNTYP"] == "SADPOINT" || h["RUNTYP"] == "IRC")
901 nzvar = natoms * 3 - 6 # TODO: 3N-5 for linear molecules
902 h["NZVAR"] ||= nzvar.to_s
906 h["SCFTYP"] ||= scftyp
910 h["UNITS"] ||= "ANGS"
912 h = (hash["SCF"] ||= Hash.new)
913 h["CONV"] ||= "1.0E-06"
914 h["DIRSCF"] ||= ".T."
918 h = (hash["STATPT"] ||= Hash.new)
920 if runtyp == "SADPOINT"
921 h["OPTTOL"] ||= "1.0E-05"
923 h["HSSEND"] ||= ".T."
924 elsif runtyp == "IRC"
925 h["OPTTOL"] ||= "1.0E-05"
927 h["HSSEND"] ||= ".T."
929 h["OPTTOL"] ||= "1.0E-06"
931 if hash["eliminate_freedom"] == 0
932 h["PROJCT"] ||= ".F."
935 h = (hash["SYSTEM"] ||= Hash.new)
937 if runtyp == "SADPOINT" || runtyp == "IRC"
942 h["TIMLIM"] ||= "50000"
944 h = (hash["GUESS"] ||= Hash.new)
945 h["GUESS"] ||= "HUCKEL"
948 h = (hash["BASIS"] ||= Hash.new)
949 h["GBASIS"] ||= gbasis
953 h = (hash["ZMAT"] ||= Hash.new)
959 h = (hash["IRC"] ||= Hash.new)
965 h["OPTTOL"] = "1.0E-05"
968 if (hash["esp"] || 0) != 0
969 h = (hash["ELPOT"] ||= Hash.new)
971 h["OUTPUT"] ||= "PUNCH"
973 h = (hash["PDC"] ||= Hash.new)
974 h["CONSTR"] ||= "NONE"
975 h["PTSEL"] ||= "CONNOLLY"
978 if (hash["include_nbo"] || 0) != 0
979 h = (hash["NBO"] ||= Hash.new)
981 ["nao", "nbo", "nho", "nlmo", "pnao", "pnbo", "pnho", "pnlmo"].each { |nao|
982 if (hash[nao] || 0) != 0
983 s += " f" + nao + " ao" + nao
990 fp = File.open(fname, "wb")
995 fp.print "! GAMESS input\n"
996 fp.print "! Generated by Molby at #{now}\n"
997 fp.print "! Basis set: " + ($gamess_basis_desc[bssname] || "(not specified)") + "\n"
999 fp.print "! [" + element2.join(", ") + "]: " + ($gamess_basis_desc[bssname2] || "(not specified)") + "\n"
1001 ordered = ["CONTRL", "SCF", "STATPT", "SYSTEM", "GUESS", "BASIS", "ZMAT", "ELPOT", "PDC"]
1002 controls = reorder_array(hash.keys.select { |k| k != "key_order" && hash[k].is_a?(Hash) },
1003 hash["key_order"] || ordered)
1006 next if h == nil || h.size == 0 || (h["key_order"] && h.size == 1)
1008 ordered = ["COORD", "EXETYP", "ICHARG", "ICUT", "INTTYP", "ITOL", "MAXIT", "MOLPLT", "MPLEVL",
1009 "MULT", "QMTTOL", "RUNTYP", "SCFTYP", "ECP", "UNITS", "DFTTYP", "NZVAR"]
1011 ordered = ["CONV", "DIRSCF", "FDIFF", "DAMP"]
1013 ordered = ["NSTEP", "OPTTOL", "HESS", "HSSEND"]
1015 ordered = ["MEMDDI", "MWORDS", "TIMLIM"]
1019 ordered = ["GBASIS"]
1021 ordered = ["DLC", "AUTO"]
1023 ordered = ["IEPOT", "OUTPUT", "WHERE"]
1025 ordered = ["CONSTR", "PTSEL"]
1027 ordered = ["SADDLE", "TSENGY", "FORWRD", "NPOINT", "STRIDE", "OPTTOL"]
1031 keys = reorder_array(h.keys, h["key_order"] || ordered)
1033 keys.each_with_index { |kk, i|
1036 fp.printf " $%-6s", k
1040 if v == nil || v == ""
1044 fp.printf " %s=%s", kk, h[kk].to_s
1052 fp.print " $DATA\n#{basename}\nC1 0\n"
1055 next if ap.atomic_number == 0
1056 fp.printf "%-6s %4d %10.6f %10.6f %10.6f\n", ap.name, ap.atomic_number, ap.r.x, ap.r.y, ap.r.z
1057 if use_2nd && element2.include?(ap.element)
1058 secondary[ap.index] = true
1061 # Basis specification followed by a blank line
1062 bas = (secondary[ap.index] ? basis2 : basis)
1064 bas = bas[ap.atomic_number]
1070 puts "Warning: basis set is not defined for atom #{ap.index}, element #{ap.element}"
1079 an = ap.atomic_number
1081 ecpp = (secondary[ap.index] ? ecp2 : ecp)
1082 e = ecp_ary[an] || (ecpp && ecpp[an])
1084 # Cache the PNAME of the $ECP entry and re-use it
1085 ecp_ary[an] ||= (e.split)[0] + "\n"
1087 e = ap.element.upcase + "-ECP NONE\n"
1104 def copy_section_from_gamess_output
1105 if @gamess_output_fname
1106 dir = File.dirname(@gamess_output_fname)
1110 fname = Dialog.open_panel("Select GAMESS Output:", dir, "*.log;*.dat")
1112 fp = open(fname, "rb")
1115 if @gamess_output_fname == fname && @gamess_output_mtime == mtime
1116 # Use the cached value
1117 k = @gamess_output_sections
1122 if ln.start_with?(" $")
1124 if keyword !~ /\$END/
1130 # Cache the information
1131 @gamess_output_fname = fname
1132 @gamess_output_mtime = mtime
1133 @gamess_output_sections = k
1135 keywords = k.keys.sort { |a, b| k[a] <=> k[b] }
1136 h = Dialog.run("Select GAMESS section to copy", "Copy", "Cancel") {
1138 item(:popup, :subitems=>keywords, :tag=>"section"))
1141 fp.seek(k[keywords[h["section"]]])
1145 break if ln =~ /\$END/
1147 export_to_clipboard(s)
1154 def cmd_edit_gamess_input(s)
1156 h = Dialog.run("Edit GAMESS Input", "OK", "Cancel", :resizable=>true) {
1158 item(:textview, :value=>s, :tag=>"edit", :width=>400, :height=>400, :flex=>[0,0,0,0,1,1]),
1159 item(:button, :title=>"Copy Section from GAMESS Output...", :action=>lambda { |it| mol.copy_section_from_gamess_output } ),
1160 :flex=>[0,0,0,0,1,1]
1162 set_min_size(300, 300)
1171 def cmd_create_gamess_input
1176 raise MolbyError, "cannot create GAMESS input; the molecule is empty"
1179 # Descriptive text and internal string for popup menus
1180 # bset_desc = ["PM3", "STO-3G", "3-21G", "6-31G", "6-31G(d)", "6-31G(d,p)", "6-311G", "6-311G(d,p)", "LanL2DZ"]
1181 # bset_internal = ["PM3", "STO3G", "321G", "631G", "631Gd", "631Gdp", "6311G", "6311Gdp", "LanL2DZ"]
1182 bset_desc = $gamess_basis_keys.map { |key| $gamess_basis_desc[key] }
1183 dft_desc = ["B3LYP"]
1184 dft_internal = ["B3LYP"]
1186 defaults = {"scftype"=>0, "runtype"=>0, "use_internal"=>1, "eliminate_freedom"=>1, "charge"=>"0", "mult"=>"1",
1187 "basis"=>4, "use_secondary_basis"=>0, "secondary_elements"=>"",
1188 "secondary_basis"=>8, "esp"=>0, "ncpus"=>"1"}
1190 gamess_input_direct = nil
1192 user_input = Hash.new
1193 ["CONTRL", "SCF", "STATPT", "SYSTEM", "GUESS", "BASIS"].each { |k|
1194 user_input[k] = Hash.new
1196 if ".inp".casecmp(self.name[-4, 4]) == 0
1197 # Read input and analyze commands
1198 fp = open(self.path, "r")
1203 break if "$DATA".casecmp(ln[0, 5]) == 0
1207 key = s[1..-1].upcase
1208 hh = user_input[key] = Hash.new
1209 (user_input["key_order"] ||= []).push(key)
1215 (hh["key_order"] ||= []).push(k)
1221 user_input["charge"] = user_input["CONTRL"]["ICHARG"]
1222 user_input["mult"] = user_input["CONTRL"]["MULT"]
1223 user_input["runtype"] = ["ENERGY", "PROP", "OPTIMIZE"].find_index(user_input["CONTRL"]["RUNTYP"])
1224 user_input["scftype"] = ["RHF", "ROHF", "UHF"].find_index(user_input["CONTRL"]["SCFTYP"])
1225 dft_type = dft_internal.find_index(user_input["CONTRL"]["DFTTYP"])
1227 user_input["dfttype"] = dft_type
1228 user_input["dft"] = 1
1231 user_input["basis"] = "-1"
1232 case user_input["BASIS"]["GBASIS"]
1240 if user_input["NDFUNC"] == "1"
1241 if user_input["NPFUNC"] == "1"
1250 if user_input["NDFUNC"] == "1" && user_input["NPFUNC"] == "1"
1257 user_input["basis"] = $gamess_basis_keys.find_index(bssname).to_s
1259 # puts user_input.inspect
1263 hash = Dialog.run("GAMESS Export") {
1264 def load_basis_set_sub(item)
1265 fname = Dialog.open_panel("Select a file containing GAMESS basis set:")
1267 Molecule.read_gamess_basis_sets(fname)
1268 bset_desc_new = $gamess_basis_keys.map { |key| $gamess_basis_desc[key] }
1269 sel1 = attr("basis", :value)
1270 sel2 = attr("secondary_basis", :value)
1271 set_attr("basis", :subitems=>bset_desc_new)
1272 set_attr("basis", :value=>sel1)
1273 set_attr("secondary_basis", :subitems=>bset_desc_new)
1274 set_attr("secondary_basis", :value=>sel2)
1277 def select_gamess_path(item)
1279 fname = Dialog.open_panel("Locate GAMESS executable:")
1280 return if fname == nil
1281 bname = File.basename(fname)
1282 if bname =~ /gamess\.(.*)\.(exe|x)$/i
1283 set_attr("executable_path", :value=>fname)
1286 error_message_box("\"#{bname}\" does not look like a GAMESS executable! Please try again.")
1290 def set_optional_scripts(item)
1291 h = Dialog.run("GAMESS Optional Scripts") {
1292 s_pre = get_global_settings("gamess.prefix_script")
1293 s_post = get_global_settings("gamess.postfix_script")
1295 item(:text, :title=>"Script to run before GAMESS execution:"),
1296 item(:textview, :width=>400, :height=>200, :value=>s_pre, :tag=>"prefix"),
1297 item(:text, :title=>"Script to run after GAMESS execution:"),
1298 item(:textview, :width=>400, :height=>200, :value=>s_post, :tag=>"postfix"))
1301 set_global_settings("gamess.prefix_script", h["prefix"])
1302 set_global_settings("gamess.postfix_script", h["postfix"])
1305 nbos = ["nao", "nbo", "nho", "nlmo", "pnao", "pnbo", "pnho", "pnlmo"]
1307 item(:text, :title=>"SCF type"),
1308 item(:popup, :subitems=>["RHF", "ROHF", "UHF"], :tag=>"scftype"),
1309 item(:text, :title=>"Run type"),
1310 item(:popup, :subitems=>["Energy", "Property", "Optimize", "Sadpoint", "IRC"], :tag=>"runtype",
1311 :action=>lambda { |it| set_attr("use_internal", :enabled=>(it[:value] >= 2)) } ),
1312 item(:checkbox, :title=>"Use internal coordinates for structure optimization", :tag=>"use_internal"),
1314 item(:checkbox, :title=>"Eliminate translation and rotational degrees of freedom", :tag=>"eliminate_freedom"),
1317 item(:text, :title=>"Charge"),
1318 item(:textfield, :width=>80, :tag=>"charge"),
1319 item(:text, :title=>"Multiplicity"),
1320 item(:textfield, :width=>80, :tag=>"mult"),
1322 item(:checkbox, :title=>"Use DFT", :tag=>"dft",
1323 :action=>lambda { |it| set_attr("dfttype", :enabled=>(it[:value] != 0)) } ),
1325 item(:text, :title=>"DFT type"),
1326 item(:popup, :subitems=>dft_desc, :tag=>"dfttype"),
1331 item(:text, :title=>"Basis set"),
1332 item(:popup, :subitems=>bset_desc + ["(no select)"], :tag=>"basis"),
1336 item(:button, :title=>"Load Basis Set...", :action=>:load_basis_set_sub),
1339 item(:checkbox, :title=>"Use secondary basis set", :tag=>"use_secondary_basis",
1340 :action=>lambda { |it|
1341 flag = (it[:value] != 0)
1342 set_attr("secondary_elements", :enabled=>flag)
1343 set_attr("secondary_basis", :enabled=>flag)
1347 item(:text, :title=>" Elements"),
1348 item(:textfield, :width=>80, :tag=>"secondary_elements"),
1349 item(:text, :title=>"Basis set"),
1350 item(:popup, :subitems=>bset_desc, :tag=>"secondary_basis"),
1355 item(:checkbox, :title=>"Calculate electrostatic potential (ESP)", :tag=>"esp"),
1361 item(:checkbox, :title=>"Include NBO instructions", :tag=>"include_nbo",
1362 :action=>lambda { |it|
1363 flag = (it[:value] != 0)
1364 nbos.each { |nbo| set_attr(nbo, :enabled=>flag) }
1367 item(:checkbox, :title=>"NAO", :tag=>"nao"),
1368 item(:checkbox, :title=>"NBO", :tag=>"nbo"),
1369 item(:checkbox, :title=>"NHO", :tag=>"nho"),
1370 item(:checkbox, :title=>"NLMO", :tag=>"nlmo"),
1371 item(:checkbox, :title=>"PNAO", :tag=>"pnao"),
1372 item(:checkbox, :title=>"PNBO", :tag=>"pnbo"),
1373 item(:checkbox, :title=>"PNHO", :tag=>"pnho"),
1374 item(:checkbox, :title=>"PNLMO", :tag=>"pnlmo"),
1379 item(:checkbox, :title=>"Execute GAMESS on this machine", :tag=>"execute_local",
1380 :action=>lambda { |it|
1381 flag = (it[:value] != 0)
1382 set_attr("executable_path", :enabled=>flag)
1383 set_attr("select_path", :enabled=>flag)
1384 set_attr("ncpus", :enabled=>flag)
1388 item(:text, :title=>" Path"),
1389 item(:textfield, :width=>300, :tag=>"executable_path"),
1393 item(:button, :title=>"Select Path...", :tag=>"select_path", :action=>:select_gamess_path),
1395 item(:button, :title=>"Optional Scripts...", :action=>:set_optional_scripts),
1397 item(:text, :title=>" N of CPUs"),
1398 item(:textfield, :width=>80, :tag=>"ncpus"),
1404 item(:button, :title=>"Edit GAMESS Input and Go", :action=>lambda { |it|
1407 if (tag = it2[:tag]) != nil
1408 h[tag] = it2[:value]
1411 h["basis"] = $gamess_basis_keys[h["basis"]]
1412 h["secondary_basis"] = $gamess_basis_keys[h["secondary_basis"]]
1413 h["dfttype"] = dft_internal[h["dfttype"]]
1414 gamess_input_direct = mol.cmd_edit_gamess_input(mol.export_gamess(nil, h))
1415 if gamess_input_direct
1425 values[tag] = (user_input[tag] || get_global_settings("gamess.#{tag}") || defaults[tag])
1426 if tag == "basis" && values[tag] == "-1"
1427 values[tag] = (bset_desc.count).to_s
1429 it[:value] = values[tag]
1432 set_attr("secondary_elements", :enabled=>(values["use_secondary_basis"] == 1))
1433 set_attr("secondary_basis", :enabled=>(values["use_secondary_basis"] == 1))
1434 set_attr("dfttype", :enabled=>(values["dft"] == 1))
1435 set_attr("use_internal", :enabled=>(values["runtype"] >= 2))
1436 set_attr("executable_path", :enabled=>(values["execute_local"] == 1))
1437 set_attr("select_path", :enabled=>(values["execute_local"] == 1))
1438 set_attr("ncpus", :enabled=>(values["execute_local"] == 1))
1440 set_attr(nao, :enabled=>(values["include_nbo"] == 1))
1443 hash.each_pair { |key, value|
1444 next if key == :status
1445 set_global_settings("gamess.#{key}", value)
1447 if hash[:status] == 0
1448 # Specify basis by internal keys
1449 hash["basis"] = $gamess_basis_keys[hash["basis"]]
1450 hash["secondary_basis"] = $gamess_basis_keys[hash["secondary_basis"]]
1451 hash["dfttype"] = dft_internal[hash["dfttype"]]
1452 basename = (self.path ? File.basename(self.path, ".*") : self.name)
1453 fname = Dialog.save_panel("Export GAMESS input file:", self.dir, basename + ".inp", "GAMESS input file (*.inp)|*.inp|All files|*.*")
1454 return nil if !fname
1455 if gamess_input_direct
1456 # puts "gamess_input_direct = \"#{gamess_input_direct}\""
1457 File.open(fname, "w") { |fp| fp.print(gamess_input_direct) }
1459 export_gamess(fname, hash)
1461 if hash["execute_local"] == 1
1462 Molecule.execute_gamess(fname, self)
1471 grid = default_MO_grid
1475 item(:text, :title=>"This molecule does not contain MO information."))
1481 if mos == nil || mos.length == 0
1484 item(:text, :title=>"Please select MO(s) in the MO Info table."))
1490 item(:text, :title=>"Please specify cube dimensions (in angstrom units):"),
1492 item(:text, :title=>"Origin"),
1493 item(:textfield, :width=>100, :height=>20, :tag=>"originx", :value=>sprintf("%.6f", grid[0].x)),
1494 item(:textfield, :width=>100, :height=>20, :tag=>"originy", :value=>sprintf("%.6f", grid[0].y)),
1495 item(:textfield, :width=>100, :height=>20, :tag=>"originz", :value=>sprintf("%.6f", grid[0].z)),
1496 item(:text, :title=>"Delta"),
1497 item(:textfield, :width=>100, :height=>20, :tag=>"deltax", :value=>sprintf("%.6f", grid[1])),
1498 item(:textfield, :width=>100, :height=>20, :tag=>"deltay", :value=>sprintf("%.6f", grid[2])),
1499 item(:textfield, :width=>100, :height=>20, :tag=>"deltaz", :value=>sprintf("%.6f", grid[3])),
1500 item(:text, :title=>"Step"),
1501 item(:textfield, :width=>100, :height=>20, :tag=>"stepx", :value=>grid[4].to_s),
1502 item(:textfield, :width=>100, :height=>20, :tag=>"stepy", :value=>grid[5].to_s),
1503 item(:textfield, :width=>100, :height=>20, :tag=>"stepz", :value=>grid[6].to_s)))
1505 if hash[:status] == 0
1506 path = self.path || self.name
1507 dir = self.dir || Dir.pwd
1508 origin = Vector3D[hash["originx"], hash["originy"], hash["originz"]]
1515 basename = File.basename(path, ".*")
1517 mo_type = self.mo_type
1519 fname1 = fname2 = nil
1520 alpha = (mo_type != "UHF" ? "" : "alpha ")
1521 a = (mo_type != "UHF" ? "" : "a")
1522 fname1 = Dialog.save_panel("Cube file name for #{alpha}MO #{n}", dir, basename + "_#{n}#{a}.cube", "Gaussian cube file (*.cube)|*.cube")
1523 if (mo_type == "UHF")
1524 fname2 = Dialog.save_panel("Cube file name for beta MO #{n}", dir, basename + "_#{n}b.cube", "Gaussian cube file (*.cube)|*.cube")
1526 filenames.push([n, fname1, fname2])
1528 filenames.each { |pair|
1530 alpha = (mo_type != "UHF" ? "" : "alpha ")
1531 show_progress_panel("Creating cube file for #{alpha}MO #{n}...")
1533 cubegen(pair[1], n, origin, dx, dy, dz, nx, ny, nz, true)
1535 if pair[2] && mo_type == "UHF"
1536 set_progress_message("Creating cube file for beta MO #{n}...")
1537 cubegen(pair[2], n, origin, dx, dy, dz, nx, ny, nz, true, true)
1544 def export_psi4(fname, hash)
1547 fp = File.open(fname, "wb")
1552 fp.print "# Psi4 input\n"
1553 fp.print "# Generated by Molby at #{now}\n"
1554 fp.print "import sys\n"
1555 fp.print "import re\n"
1556 fp.print "base = re.sub('\\.\\w*$', '', sys.argv[1]) # Basename of the input file\n"
1557 fp.print "molecule mol {\n"
1558 charge = Integer(hash["charge"])
1559 mult = Integer(hash["mult"])
1560 if charge != 0 || mult != 1
1561 fp.printf " %d %d\n", charge, mult
1564 fp.printf "%-8s %16.12f %16.12f %16.12f\n", ap.element, ap.x, ap.y, ap.z
1566 use_symmetry = Integer(hash["use_symmetry"])
1567 move_to_com = Integer(hash["move_to_com"])
1568 do_reorient = Integer(hash["do_reorient"])
1573 fp.print "noreorient\n"
1575 if use_symmetry == 0
1576 fp.print "symmetry c1\n"
1578 fp.print "units angstrom\n"
1580 fp.print "set basis #{hash['basis']}\n"
1581 fp.print "set reference #{hash['scftype']}\n"
1582 options = "return_wfn=True"
1584 options += ", dft_functional='#{hash['dfttype']}'"
1586 runtype = hash['runtype'].downcase
1587 fp.print "energy, wfn = #{runtype}('scf', #{options})\n"
1588 fp.print "wfn.write_molden(f'{base}.molden')\n"
1589 if hash['run_junpa'] != 0
1591 fp.print "# Interface for JANPA\n"
1592 fp.print "# cf. https://sourceforge.net/p/janpa/wiki/psi4Examples/\n"
1593 fp.print "d = wfn.Da().to_array()\n"
1594 fp.print "s = wfn.S().to_array()\n"
1595 fp.print "c = wfn.Ca().to_array()\n"
1596 fp.print "occs = c.T.dot(s.dot(d).dot(s).dot(c))\n"
1597 fp.print "molden(wfn, f'{base}.da.molden', density_a = psi4.core.Matrix.from_array(occs))\n"
1611 # inppath is the input file minus extention
1612 # mol is the molecule (may be nil)
1613 def Molecule.execute_janpa(inppath, mol, spherical)
1614 # nbo_desc = # JANPA
1615 janpa_dir = "#{ResourcePath}/JANPA"
1618 cmd1 = "java -jar #{janpa_dir}/molden2molden.jar -NormalizeBF -i #{inppath}.da.molden -o #{inppath}.in.molden >#{inppath}.janpa.log"
1620 cmd1 = "java -jar #{janpa_dir}/molden2molden.jar -frompsi4v1mo -NormalizeBF -cart2pure -i #{inppath}.da.molden -o #{inppath}.in.molden >#{inppath}.janpa.log"
1624 cmd2 = "java -jar #{janpa_dir}/janpa.jar -i #{inppath}.in.molden"
1625 ["nao", "pnao", "aho", "lho", "lpo", "clpo"].each { |type|
1626 if (get_global_settings("psi4.#{type}").to_i != 0)
1627 cmd2 += " -#{type.upcase}_Molden_File #{inppath}.#{type.upcase}.molden"
1630 cmd2 += " >>#{inppath}.janpa.log"
1635 # import JANPA log and molden output
1636 # Files: inppath.japa.log, inppath.{NAO,PNAO,AHO,LHO,LPO,CLPO}.molden
1637 mol.sub_load_janpa_log(inppath)
1640 status = $?.exitstatus
1641 message_box("Execution of #{procname} failed with status #{status}.", "JANPA Failed")
1647 # inpname is the input file
1648 # mol (optional) is the molecule from which the Psi4 input was built.
1649 def Molecule.execute_psi4(inpname, mol = nil)
1651 inpbase = File.basename(inpname)
1652 inpbody = File.basename(inpname, ".*")
1653 inpdir = File.dirname(inpname)
1655 # Set PATH for psi4conda
1656 psi4folder = get_global_settings("psi4.psi4conda_folder")
1657 ncpus = get_global_settings("psi4.ncpus").to_i
1658 orgpath = ENV["PATH"]
1660 if $platform == "win"
1661 ENV["PATH"] = "#{psi4folder};#{psi4folder}\\Library\\mingw-w64\\bin;#{psi4folder}\\Library\\usr\\bin;#{psi4folder}\\Library\\bin;#{psi4folder}\\Scripts;#{psi4folder}\\bin;#{psi4folder}\\condabin;" + ENV["PATH"]
1663 ENV["PATH"] = "#{psi4folder}/bin:#{psi4folder}/condabin:" + ENV["PATH"]
1666 cmdline = "psi4 #{inpbase}"
1668 cmdline += " -n #{ncpus}"
1675 outfile = inpdir + "/" + inpbody + ".out"
1676 if File.exists?(outfile)
1679 outbackfile = inpdir + "/" + inpbody + "~" + (n == 1 ? "" : "{#n}") + ".out"
1680 break if !File.exists?(outbackfile)
1683 File.rename(outfile, outbackfile)
1695 timer_callback = lambda { |m, n|
1698 if timer_count < 10 # Only handle every 1 seconds
1703 if File.exists?(outfile)
1704 fplog = Kernel.open(outfile, "rt")
1710 return true # Skip until outfile is available
1713 fplog.seek(0, IO::SEEK_END)
1714 current_size = fplog.tell
1715 if current_size > last_size
1717 fplog.seek(last_size, IO::SEEK_SET)
1718 fplog.each_line { |line|
1719 if line[-1, 1] == "\n"
1720 lines.push(last_line + line)
1727 last_size = fplog.tell
1730 getline = lambda { if li < lines.length; li += 1; return lines[li - 1]; else return nil; end }
1732 while (line = getline.call)
1733 if line =~ /==> Geometry <==/
1734 # Skip until line containing "------"
1735 while line = getline.call
1736 break if line =~ /------/
1740 # Read atom positions
1741 while line = getline.call
1743 break if line =~ /^\s*$/
1744 tokens = line.split(' ')
1745 vecs.push(Vector3D[Float(tokens[1]), Float(tokens[2]), Float(tokens[3])])
1748 if vecs.length < mol.natoms
1749 break # Log file is incomplete
1751 # Does this geometry differ from the last one?
1752 vecs.length.times { |i|
1753 if (mol.atoms[i].r - vecs[i]).length2 > 1.0e-20
1754 # Create a new frame and break
1756 vecs.length.times { |j|
1757 mol.atoms[j].r = vecs[j]
1764 elsif line =~ /Final Energy: +([-.0-9]+)/
1765 # Energy for this geometry
1767 mol.set_property("energy", energy)
1768 mol.show_text("Frame: #{mol.nframes - 1}\nEnergy: #{energy}")
1769 print("Frame: #{mol.nframes - 1} Energy: #{energy}\n")
1774 elsif line =~ /ROHF/
1778 elsif line =~ /^ *Nalpha *= *(\d+)/
1779 nalpha = Integer($1)
1780 elsif line =~ /^ *Nbeta *= *(\d+)/
1782 elsif line =~ /^ *Spherical Harmonics\?: *(\w+)/
1783 spherical = ($1 == "true")
1787 lines.slice!(0, next_index)
1792 # Some error occurred during callback. Show the message in the console and abort.
1793 $stderr.write("#{e.message}\n")
1794 $stderr.write("#{e.backtrace.inspect}\n")
1799 # Terminate callback
1800 term_callback = lambda { |m, n|
1803 msg = "Psi4 execution of #{inpbase} "
1806 msg += "cannot be started. Please examine Psi4 installation."
1815 msg += "failed with status #{n}."
1819 msg += "\n(In directory #{inpdir})"
1821 ENV["PATH"] = orgpath
1824 message_box(msg, hmsg, :ok, icon)
1827 # Try to load final lines of the logfile
1829 timer_callback.call(m, n)
1830 # Try to load molden file if available
1832 mol.clear_mo_coefficients
1833 mol.set_mo_info(:type => hf_type, :alpha => nalpha, :beta => nbeta)
1834 molden = inpdir + "/" + inpbody +".molden"
1835 if File.exists?(molden)
1836 fp = Kernel.open(molden, "rt")
1837 mol.instance_eval { @lineno = 0 }
1839 # mol.@hf_type should be set before calling sub_load_molden
1840 mol.sub_load_molden(fp)
1843 $stderr.write("#{e.message}\n")
1844 $stderr.write("#{e.backtrace.inspect}\n")
1847 if (get_global_settings("psi4.run_janpa").to_i == 1)
1851 # The child process actually did not start
1852 # Restore the old file if outbackfile is not nil
1853 if outbackfile && !File.exists?(outfile)
1854 File.rename(outbackfile, outfile)
1857 if outbackfile && File.exists?(outbackfile)
1858 File.delete(outbackfile)
1861 Molecule.execute_janpa(inpdir + "/" + inpbody, mol, spherical)
1864 $stderr.write("#{e.message}\n")
1865 $stderr.write("#{e.backtrace.inspect}\n")
1872 pid = mol.call_subprocess_async(cmdline, term_callback, timer_callback)
1874 # This may not happen on OSX or Linux (don't know for MSW)
1875 error_message_box("Psi4 failed to start. Please examine Psi4 installation.")
1879 status = call_subprocess(cmdline, "Running Psi4")
1880 term_callback.call(nil, status)
1885 def cmd_edit_psi4_input(s)
1887 h = Dialog.run("Edit Psi4 Input", "OK", "Cancel", :resizable=>true) {
1889 item(:textview, :value=>s, :tag=>"edit", :width=>400, :height=>400, :flex=>[0,0,0,0,1,1]),
1891 set_min_size(300, 300)
1900 def cmd_create_psi4_input
1905 raise MolbyError, "cannot create Psi4 input; the molecule is empty"
1908 # Basis sets Cf. https://psicode.org/psi4manual/master/basissets_tables.html#apdx-basistables
1909 bset_desc = ["STO-3G", "3-21G", "6-31G", "6-31G(d)", "6-31G(d,p)", "6-311G", "6-311G(d)", "6-311G(d,p)", "LanL2DZ"]
1910 dfttype_desc = ["B3LYP"]
1911 runtype_desc = ["Energy", "Optimize"]
1912 scftype_desc = ["RHF", "ROHF", "UHF"]
1913 nbo_desc = ["nao", "pnao", "aho", "lho", "lpo", "clpo"] # JANPA
1914 user_input = Hash.new
1915 defaults = {"scftype"=>0, "runtype"=>0, "move_to_com"=>0, "do_reorient"=>0,
1916 "use_symmetry"=>0, "charge"=>"0", "mult"=>"1",
1917 "basis"=>1, "use_secondary_basis"=>0, "secondary_elements"=>"",
1918 "secondary_basis"=>8, "esp"=>0, "ncpus"=>"1"}
1919 psi4_input_direct = nil
1921 hash = Dialog.run("Psi4 Export") {
1922 def load_basis_set_sub(item)
1923 fname = Dialog.open_panel("Select a file containing GAMESS basis set:")
1925 Molecule.read_gamess_basis_sets(fname)
1926 bset_desc_new = $gamess_basis_keys.map { |key| $gamess_basis_desc[key] }
1927 sel1 = attr("basis", :value)
1928 sel2 = attr("secondary_basis", :value)
1929 set_attr("basis", :subitems=>bset_desc_new)
1930 set_attr("basis", :value=>sel1)
1931 set_attr("secondary_basis", :subitems=>bset_desc_new)
1932 set_attr("secondary_basis", :value=>sel2)
1935 def select_psi4_folder(item)
1936 # By default, psi4conda is installed in the home directory
1938 fname = Dialog.open_panel("Locate 'psi4conda' Folder:", ENV["HOME"] || ENV["USERPROFILE"], nil, true)
1939 return if fname == nil
1940 bname = File.basename(fname)
1941 if bname == "psi4conda"
1944 h = Dialog.run("", "OK", "Choose Again") {
1946 item(:text, :title=>"The folder does not have the name 'psi4conda'."),
1947 item(:text, :title=>"Do you want to use it anyway?"))
1954 set_attr("psi4conda_folder", :value=>fname)
1958 item(:text, :title=>"SCF type"),
1959 item(:popup, :subitems=>scftype_desc, :tag=>"scftype"),
1960 item(:text, :title=>"Run type"),
1961 item(:popup, :subitems=>runtype_desc, :tag=>"runtype"),
1963 item(:checkbox, :title=>"Detect symmetry", :tag=>"use_symmetry"),
1966 item(:checkbox, :title=>"Move the molecule to the center of mass", :tag=>"move_to_com"),
1969 item(:checkbox, :title=>"Rotate the molecule to the symmetry principle axes", :tag=>"do_reorient"),
1972 item(:text, :title=>"Charge"),
1973 item(:textfield, :width=>80, :tag=>"charge"),
1974 item(:text, :title=>"Multiplicity"),
1975 item(:textfield, :width=>80, :tag=>"mult"),
1977 item(:checkbox, :title=>"Use DFT", :tag=>"dft",
1978 :action=>lambda { |it| set_attr("dfttype", :enabled=>(it[:value] != 0)) } ),
1980 item(:text, :title=>"DFT type"),
1981 item(:popup, :subitems=>dfttype_desc, :tag=>"dfttype"),
1986 item(:text, :title=>"Basis set"),
1987 item(:popup, :subitems=>bset_desc, :tag=>"basis"),
1991 #item(:button, :title=>"Load Basis Set...", :action=>:load_basis_set_sub),
1994 #item(:checkbox, :title=>"Use secondary basis set", :tag=>"use_secondary_basis",
1995 # :action=>lambda { |it|
1996 # flag = (it[:value] != 0)
1997 # set_attr("secondary_elements", :enabled=>flag)
1998 # set_attr("secondary_basis", :enabled=>flag)
2002 #item(:text, :title=>" Elements"),
2003 #item(:textfield, :width=>80, :tag=>"secondary_elements"),
2004 #item(:text, :title=>"Basis set"),
2005 #item(:popup, :subitems=>bset_desc, :tag=>"secondary_basis"),
2010 #item(:checkbox, :title=>"Calculate electrostatic potential (ESP)", :tag=>"esp"),
2016 item(:checkbox, :title=>"Run JANPA after Psi4", :tag=>"run_janpa",
2017 :action=>lambda { |it|
2018 flag = (it[:value] != 0)
2019 nbo_desc.each { |nbo| set_attr(nbo, :enabled=>flag) }
2023 item(:checkbox, :title=>"NAO", :tag=>"nao"),
2024 item(:checkbox, :title=>"PNAO", :tag=>"pnao"),
2025 item(:checkbox, :title=>"AHO", :tag=>"aho"),
2026 item(:checkbox, :title=>"LHO", :tag=>"lho"),
2028 item(:checkbox, :title=>"LPO", :tag=>"lpo"),
2029 item(:checkbox, :title=>"CLPO", :tag=>"clpo"),
2035 item(:checkbox, :title=>"Execute Psi4 on this machine", :tag=>"execute_local",
2036 :action=>lambda { |it|
2037 flag = (it[:value] != 0)
2038 set_attr("psi4conda_folder", :enabled=>flag)
2039 set_attr("select_folder", :enabled=>flag)
2040 set_attr("ncpus", :enabled=>flag)
2044 item(:text, :title=>" Psi4 Folder"),
2045 item(:textfield, :width=>300, :tag=>"psi4conda_folder"),
2049 item(:button, :title=>"Select Folder...", :tag=>"select_folder", :action=>:select_psi4_folder),
2051 # item(:button, :title=>"Optional Scripts...", :action=>:set_optional_scripts),
2053 item(:text, :title=>" N of CPUs"),
2054 item(:textfield, :width=>80, :tag=>"ncpus"),
2060 item(:button, :title=>"Edit Psi4 Input and Go", :action=>lambda { |it|
2063 if (tag = it2[:tag]) != nil
2064 h[tag] = it2[:value]
2067 h["basis"] = bset_desc[h["basis"] || 0]
2068 h["secondary_basis"] = bset_desc[h["secondary_basis"] || 0]
2069 h["dfttype"] = dfttype_desc[h["dfttype"] || 0]
2070 h["runtype"] = runtype_desc[h["runtype"] || 0]
2071 h["scftype"] = scftype_desc[h["scftype"] || 0]
2072 psi4_input_direct = mol.cmd_edit_psi4_input(mol.export_psi4(nil, h))
2073 if psi4_input_direct
2083 values[tag] = (user_input[tag] || get_global_settings("psi4.#{tag}") || defaults[tag])
2085 it[:value] = values[tag]
2089 #set_attr("secondary_elements", :enabled=>(values["use_secondary_basis"] == 1))
2090 #set_attr("secondary_basis", :enabled=>(values["use_secondary_basis"] == 1))
2091 set_attr("dfttype", :enabled=>(values["dft"] == 1))
2092 set_attr("psi4conda_folder", :enabled=>(values["execute_local"] == 1))
2093 set_attr("select_folder", :enabled=>(values["execute_local"] == 1))
2094 set_attr("ncpus", :enabled=>(values["execute_local"] == 1))
2096 # set_attr(nao, :enabled=>(values["include_nbo"] == 1))
2100 hash.each_pair { |key, value|
2101 next if key == :status
2102 set_global_settings("psi4.#{key}", value)
2104 if hash[:status] == 0
2105 # Specify basis by internal keys
2106 hash["basis"] = bset_desc[hash["basis"] || 0]
2107 hash["secondary_basis"] = bset_desc[hash["secondary_basis"] || 0]
2108 hash["dfttype"] = dfttype_desc[hash["dfttype"] || 0]
2109 hash["runtype"] = runtype_desc[hash["runtype"] || 0]
2110 hash["scftype"] = scftype_desc[hash["scftype"] || 0]
2111 basename = (self.path ? File.basename(self.path, ".*") : self.name)
2112 fname = Dialog.save_panel("Export Psi4 input file:", self.dir, basename + ".in", "Psi4 input file (*.in)|*.in|All files|*.*")
2113 return nil if !fname
2114 if psi4_input_direct
2115 File.open(fname, "w") { |fp| fp.print(psi4_input_direct) }
2117 export_psi4(fname, hash)
2119 if hash["execute_local"] == 1
2120 @hf_type = hash["scftype"]
2121 Molecule.execute_psi4(fname, self)
2127 end # End def create_psi4_input
2133 "PM3" => " PM3 0\n",
2134 "STO3G" => " STO 3\n",
2135 "321G" => " N21 3\n",
2136 "631G" => " N31 6\n" }
2137 $gamess_basis_desc = {
2139 "STO3G" => "STO-3G",
2142 $gamess_basis_keys = ["PM3", "STO3G", "321G", "631G"]
2144 ["631Gd", "631Gdp", "631+Gd", "631++Gdp", "6311Gdp", "6311+Gd", "6311++Gdp", "6311++G2d2p", "6311++G3df3pd", "LanL2DZ"].each { |n|
2145 Molecule.read_gamess_basis_sets("basis_sets/#{n}.txt")
2148 register_menu("QChem\tCreate GAMESS Input...",
2149 :cmd_create_gamess_input, :non_empty)
2150 register_menu("QChem\tCreate Psi4 Input...",
2151 :cmd_create_psi4_input, :non_empty)
2152 register_menu("QChem\tCreate MOPAC6 Input...",
2153 :cmd_create_mopac_input, :non_empty) # mopac6.rb
2154 register_menu("QChem\tCreate MO Cube...",
2155 :cmd_create_cube, lambda { |m| m && m.mo_type } )