Skip to content

Instantly share code, notes, and snippets.

@mjhong0708
Created December 20, 2023 15:25
Show Gist options
  • Save mjhong0708/43c48d98bd9d889dd8fbc2cbc1022b40 to your computer and use it in GitHub Desktop.
Save mjhong0708/43c48d98bd9d889dd8fbc2cbc1022b40 to your computer and use it in GitHub Desktop.
Print E0 energy value from VASP calculations
package main
import (
"bufio"
"fmt"
"os"
"path/filepath"
"regexp"
)
func main() {
args := os.Args[1:]
// Check for help argument
if len(args) > 0 && (args[0] == "-h" || args[0] == "--help") {
printHelp()
return
}
// If no directory is provided, use the current directory
if len(args) == 0 {
args = append(args, ".")
}
for _, dir := range args {
e0, err := readEnergy(dir)
if err != nil {
fmt.Printf("%s is not a VASP calculation\n", dir)
} else {
fmt.Printf("%s: E0 = %f eV\n", dir, e0)
}
}
}
func printHelp() {
fmt.Println("e0 - Read E0 values from OSZICAR files in given directories.")
fmt.Println("Usage: e0 [DIRECTORY]...")
fmt.Println("If no directory is given, the current working directory is used.")
}
func readEnergy(calcDir string) (float64, error) {
filePath := filepath.Join(calcDir, "OSZICAR")
file, err := os.Open(filePath)
if err != nil {
return 0, err
}
defer file.Close()
var lastMatch string
scanner := bufio.NewScanner(file)
re := regexp.MustCompile(`E0\s*=\s*([-\d\.E\+]+)`)
for scanner.Scan() {
line := scanner.Text()
if re.MatchString(line) {
lastMatch = re.FindStringSubmatch(line)[1]
}
}
if lastMatch == "" {
return 0, fmt.Errorf("%s: E0 value not found", calcDir)
}
var e0 float64
fmt.Sscanf(lastMatch, "%f", &e0)
return e0, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment