-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqplot
More file actions
executable file
·323 lines (270 loc) · 9.52 KB
/
qplot
File metadata and controls
executable file
·323 lines (270 loc) · 9.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.13"
# dependencies = [
# "matplotlib",
# "numpy",
# "scipy",
# "pyqt6"
# ]
# ///
import argparse
import sys
import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import make_interp_spline
from scipy.constants import calorie, kilo, N_A, physical_constants
from mylib.parsers import OrcaParser
hartree, _, _ = physical_constants["Hartree energy"]
plt.rcParams.update({"text.usetex": True, "font.size": 18})
def plot_irc(files):
"""Plot IRC data from one or more files."""
for file_path in files:
try:
with open(file_path, "r") as f:
lines = f.readlines()
except FileNotFoundError:
print(f"Error: File not found at {file_path}", file=sys.stderr)
continue
start = 0
end = 0
for i, line in enumerate(lines):
if "IRC PATH SUMMARY" in line:
start = i + 5
if "SUGGESTED CITATIONS FOR THIS RUN" in line:
end = i - 3
if "Timings for individual modules" in line and end == 0:
end = i - 2
if start == 0 or end == 0:
print(
f"Warning: IRC path summary not found in {file_path}", file=sys.stderr
)
continue
data = lines[start:end]
y = []
counter = 0
ts = -1
for line in data:
parts = line.strip().split()
if not parts:
continue
if "TS" in line:
ts = counter
try:
y.append(float(parts[2]))
counter += 1
except (ValueError, IndexError):
print(
f"Warning: Could not parse line in {file_path}: {line.strip()}",
file=sys.stderr,
)
continue
if not y:
print(
f"Warning: No data points found for IRC in {file_path}", file=sys.stderr
)
continue
y = [j - min(y) for j in y]
x = range(1, len(y) + 1)
xy_spline = make_interp_spline(x, y)
xsmooth = np.linspace(min(x), max(x), 500)
ysmooth = xy_spline(xsmooth)
(line,) = plt.plot(xsmooth, ysmooth, "-.", label=file_path)
plt.plot(x, y, "o", color=line.get_color())
if ts != -1:
plt.plot(x[ts], y[ts], "o", color="red")
plt.xlabel("IRC Point")
plt.ylabel("Relative Energy (kcal/mol)")
plt.title("IRC Profile")
plt.legend()
plt.grid(True)
plt.show()
def plot_neb(files, show_all_iterations):
"""Plot NEB data from one or more files."""
for file_path in files:
try:
with open(file_path, "r") as f:
lines = f.readlines()
except FileNotFoundError:
print(f"Error: File not found at {file_path}", file=sys.stderr)
continue
all_images = []
all_interps = []
image = []
interp = []
mode = None
for line in lines:
line = line.strip()
if not line:
continue
fields = line.split()
if fields[0] == "Iteration:":
if image:
all_images.append(np.array(image))
all_interps.append(np.array(interp))
image = []
interp = []
mode = None
elif fields[0] == "Images:":
mode = "images"
elif fields[0] == "Interp.:":
mode = "interps"
else:
try:
if mode == "images":
image.append([float(entry) for entry in fields])
elif mode == "interps":
interp.append([float(entry) for entry in fields])
except ValueError:
print(
f"Warning: Could not parse line in {file_path}: {line.strip()}",
file=sys.stderr,
)
if image:
all_images.append(np.array(image))
all_interps.append(np.array(interp))
if not all_images:
print(f"Warning: No NEB data found in {file_path}", file=sys.stderr)
continue
images = np.array(all_images)
interps = np.array(all_interps)
i_max = images[-1, :, 2].argmax()
forward_barrier = images[-1, i_max, 2] - images[-1, 0, 2]
backward_barrier = images[-1, i_max, 2] - images[-1, -1, 2]
print(f"--- Results for {file_path} ---")
print(
f"Barrier is at the {i_max + 1}th image (out of {len(images[-1, :, 2])})."
)
print(
f"Forward barrier : {forward_barrier:6.4f} Eh "
f"({forward_barrier * hartree * N_A / kilo:5.1f} kJ/mol, "
f"{forward_barrier * hartree * N_A / (kilo * calorie):5.1f} kcal/mol)"
)
print(
f"Backward barrier: {backward_barrier:6.4f} Eh "
f"({backward_barrier * hartree * N_A / kilo:5.1f} kJ/mol, "
f"{backward_barrier * hartree * N_A / (kilo * calorie):5.1f} kcal/mol)"
)
print("-" * (20 + len(file_path)))
if show_all_iterations:
min_energy = np.min(images[:, :, 2])
else:
min_energy = np.min(images[-1, :, 2])
if show_all_iterations:
for i in range(len(images) - 1):
plt.plot(images[i, :, 1], images[i, :, 2] - min_energy, "ok")
plt.plot(
interps[i, :, 1],
interps[i, :, 2] - min_energy,
"--",
label=f"{file_path} iter {i+1}",
)
(line,) = plt.plot(
interps[-1, :, 1],
interps[-1, :, 2] - min_energy,
"--",
label=f"{file_path} (final)",
)
plt.plot(
images[-1, :, 1], images[-1, :, 2] - min_energy, "o", color=line.get_color()
)
plt.xlabel("Distance (Bohr)")
plt.ylabel("Energy (Eh)")
plt.title("NEB Profile")
plt.legend()
plt.grid(True)
plt.show()
def plot_scan(files, relative):
"""Plot scan data from one or more files."""
reference = 0
for file_path in files:
try:
with open(file_path, "r") as f:
lines = f.readlines()
except FileNotFoundError:
print(f"Error: File not found at {file_path}", file=sys.stderr)
continue
x, y = OrcaParser(lines).parse_relaxed_scan()
if x[-1] < x[0]:
x.reverse()
y.reverse()
if relative:
y = [(j - min(y)) * hartree * N_A / (kilo * calorie) for j in y]
else:
if reference == 0:
reference = min(y)
y = [(j - reference) * hartree * N_A / (kilo * calorie) for j in y]
xy_spline = make_interp_spline(x, y)
xsmooth = np.linspace(min(x), max(x), 500)
ysmooth = xy_spline(xsmooth)
(line,) = plt.plot(xsmooth, ysmooth, "-.", label=file_path)
plt.plot(x, y, "o", color=line.get_color())
plt.xlabel("Coordinate")
plt.ylabel("Relative Energy (kcal/mol)")
plt.title("Scan Profile")
plt.legend()
plt.grid(True)
plt.show()
def plot_stdin(data_lines):
"""Plot data from stdin."""
y = []
for line in data_lines:
try:
y.append(float(line.strip()))
except ValueError:
print(
f"Warning: Could not parse line from stdin as a float: '{line.strip()}'",
file=sys.stderr,
)
continue
if not y:
print("Warning: No data points found from stdin", file=sys.stderr)
return
y = [(i - min(y)) * 627.5 for i in y]
x = range(1, len(y) + 1)
# Using spline interpolation for a smooth curve, like in other functions
# make_interp_spline needs at least k+1 points, default k=3
if len(y) > 3:
xy_spline = make_interp_spline(x, y)
xsmooth = np.linspace(min(x), max(x), 500)
ysmooth = xy_spline(xsmooth)
(line,) = plt.plot(xsmooth, ysmooth, "-.", label="stdin")
else:
(line,) = plt.plot(x, y, "-.", label="stdin")
plt.plot(x, y, "o", color=line.get_color())
plt.xlabel("Index")
plt.ylabel("Value")
plt.title("Data from stdin")
plt.legend()
plt.grid(True)
plt.show()
def main() -> None:
"""Main function."""
if not sys.stdin.isatty():
plot_stdin(sys.stdin.readlines())
return
parser = argparse.ArgumentParser(description="Plot data from one or more files.")
parser.add_argument("files", nargs="+", help="One or more files to plot.")
parser.add_argument("--irc", action="store_true", help="Plot IRC data.")
parser.add_argument("--scan", action="store_true", help="Plot scan data.")
parser.add_argument("--neb", action="store_true", help="Plot NEB data.")
parser.add_argument(
"-a", "--all", action="store_true", help="For NEB, plot all iterations."
)
parser.add_argument(
"-r",
"--relative",
action="store_true",
help="deactivate relative energy plotting",
)
args = parser.parse_args()
if not (args.irc or args.scan or args.neb):
parser.error("No plot type specified. Please use --irc, --scan, or --neb.")
if args.irc:
plot_irc(args.files)
if args.neb:
plot_neb(args.files, args.all)
if args.scan:
plot_scan(args.files, args.relative)
if __name__ == "__main__":
main()