-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcastep_tools.py
More file actions
3366 lines (2793 loc) · 111 KB
/
castep_tools.py
File metadata and controls
3366 lines (2793 loc) · 111 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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Data preparation for ML analysis of STM MTRX data
This file contains functions for preparing data
for training and prediction.
@author: Steven R. Schofield
Created May 2025
"""
# ============================================================================
#region Module dependencies
# --- stdlib ---
import os
import sys
import re
import time
import math
import warnings
from pathlib import Path
from shutil import which
from collections import defaultdict
from typing import List, Union, Tuple, Any
# --- third-party ---
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from ase import Atoms
from ase.calculators.castep import Castep
from ase.mep import NEBTools # updated per ASE 3.23+
import nglview as nv # pip install nglview
from IPython.display import display, Image as StaticImage
# --- CASTEP specific ---
# make sure ‘readts’ (Utilities/readts/) is on PYTHONPATH
from readts import TSFile
# ------------------------------------------------------------
# CASTEP binary configuration & sanity check
# ------------------------------------------------------------
# Default path (override via env var if you like)
#DEFAULT_CASTEP = "/usr/local/bin/castep"
DEFAULT_CASTEP = "/usr/local/CASTEP-24.1/bin/darwin_arm64_gfortran10--serial/castep.serial"
# Pick up user’s CASTEP_COMMAND or fall back
castep_cmd = os.environ.get("CASTEP_COMMAND", DEFAULT_CASTEP)
# Check it exists and is executable, or find it on PATH
if not Path(castep_cmd).is_file() and which(castep_cmd) is None:
warnings.warn(
f"CASTEP binary not found at '{castep_cmd}'.\n"
"Please install CASTEP or set the CASTEP_COMMAND environment variable\n"
"to the full path of your castep executable.",
stacklevel=2
)
else:
# export so ASE picks it up
os.environ["CASTEP_COMMAND"] = castep_cmd
# # ------------------------------------------------------------
# # Instantiate your default calculator
# # ------------------------------------------------------------
# calc = Castep(label="myjob", command=castep_cmd)
#endregion Module dependencies
# ============================================================================
# ============================================================================
#region Basic file io and handling
def find_all_files_by_extension(root_dir, extension=".castep"):
"""
Recursively finds all files with the given extension under the specified directory.
Parameters:
root_dir (str or Path): Directory to search from.
extension (str): File extension to match, including the dot (e.g. ".castep", ".xyz").
Returns:
List[Path]: List of matching Path objects.
"""
root = Path(root_dir)
if not extension.startswith("."):
extension = "." + extension
file_list = list(root.rglob(f"*{extension}"))
file_list = sort_file_list(file_list)
return file_list
#def load_atoms_from_castep(path, filename):
def read_positions_frac(path, filename):
"""
Read both the 'positions_frac' and 'lattice_cart' blocks
from a CASTEP-style text file.
Returns
-------
positions_frac : np.ndarray, shape (N,4), dtype=object
Rows of [element_label, x, y, z].
lattice_cart : np.ndarray, shape (3,3), dtype=float
The three Cartesian lattice vectors (in Å).
"""
filepath = os.path.join(path, filename)
positions = []
lattice = []
inside_pos = False
inside_lat = False
with open(filepath, 'r') as f:
for line in f:
s = line.strip()
# detect start of one of our blocks
if not (inside_pos or inside_lat):
if s.startswith('%BLOCK'):
if 'positions_frac' in s:
inside_pos = True
elif 'lattice_cart' in s:
inside_lat = True
continue
# parse positions_frac block
if inside_pos:
if s.startswith('%ENDBLOCK') and 'positions_frac' in s:
inside_pos = False
continue
if s:
parts = s.split()
elem = parts[0]
x, y, z = map(float, parts[1:4])
positions.append([elem, x, y, z])
continue
# parse lattice_cart block
if inside_lat:
# skip the "ANG" line
if s.upper() == 'ANG':
continue
if s.startswith('%ENDBLOCK') and 'lattice_cart' in s:
inside_lat = False
continue
if s:
vec = list(map(float, s.split()))
lattice.append(vec)
continue
positions_frac = np.array(positions, dtype=object)
lattice_cart = np.array(lattice, dtype=float)
return positions_frac, lattice_cart
def read_param_file(path, filename):
"""
Read a key : value file at os.path.join(path, filename) and return a dict with:
- keys normalized to lowercase with underscores
- values converted to int, float, or bool when possible
- all other values kept as stripped strings
Skips blank lines, lines starting with '#' or '!'.
"""
full_path = os.path.join(path, filename)
if not os.path.isfile(full_path):
raise FileNotFoundError(f"No such file: '{full_path}'")
params = {}
with open(full_path, 'r') as f:
for line in f:
line = line.strip()
# skip blank lines or comments
if not line or line.startswith('#') or line.startswith('!'):
continue
if ':' not in line:
continue
raw_key, raw_val = line.split(':', 1)
# normalize key
key = raw_key.strip().lower().replace(' ', '_').replace('-', '_')
val_str = raw_val.strip()
# boolean?
val_low = val_str.lower()
if val_low in ('true', 'false'):
params[key] = (val_low == 'true')
continue
# int or float?
try:
if val_str.isdigit():
params[key] = int(val_str)
else:
params[key] = float(val_str)
continue
except ValueError:
pass
# fallback: keep string
params[key] = val_str
return params
def read_k_points(path, filename):
"""
Read a file at os.path.join(path, filename), look for a line like:
KPOINTS_MP_GRID : 3 1 2
or
KPOINT_MP_GRID : 3 1 2
(case‐insensitive on the key), skipping blank lines and lines that start
with '#' or '!'. Returns the tuple (3, 1, 2).
"""
full_path = os.path.join(path, filename)
if not os.path.isfile(full_path):
raise FileNotFoundError(f"No such file: '{full_path}'")
with open(full_path, 'r') as f:
for line in f:
raw = line.strip()
if not raw or raw.startswith('#') or raw.startswith('!'):
continue
# strip off any inline comments
content = raw.split('#', 1)[0].split('!', 1)[0].strip()
if not content:
continue
key, sep, rest = content.partition(':')
key_lower = key.strip().lower()
if sep and key_lower in ('kpoint_mp_grid', 'kpoints_mp_grid'):
parts = rest.strip().split()
if len(parts) >= 3:
try:
return tuple(int(x) for x in parts[:3])
except ValueError:
raise ValueError(f"Could not parse integers from '{rest.strip()}'")
else:
raise ValueError(f"Found {key.strip()} but not 3 values: '{rest.strip()}'")
raise ValueError("No valid 'kpoint(s)_mp_grid : a b c' line found in file")
def read_positions_frac_from_template(
path=".",
filename="filename",
lattice_cart_bulk=np.array([
[3.8641976, 0.0, 0.0],
[0.0, 7.7283952, 0.0],
[0.0, 0.0, 5.4648012]
]),
positions_frac_bulk = np.array([
['Si', 0.0000000000, 0.7500000000, 0.7500000000],
['Si', 0.0000000000, 0.2500000000, 0.7500000000],
['Si', 0.5000000000, 0.7500000000, 0.5000000000],
['Si', 0.5000000000, 0.2500000000, 0.5000000000],
['Si', 0.5000000000, 0.5000000000, 0.2500000000],
['Si', 0.5000000000, 0.0000000000, 0.2500000000],
['Si', 0.0000000000, 0.5000000000, 0.0000000000],
['Si', 0.0000000000, 0.0000000000, 0.0000000000]
], dtype=object),
template_unit_cell_dims = np.array([1,1,2]),
sort_order=['z', 'y', 'x', 'atom']
):
"""
Read positions in fractional coordinates from a template file.
"""
# Load the template file and make sure it is sorted
positions_frac_surf, lattice_cart_surf = read_positions_frac(path, filename)
positions_frac_surf = sort_positions_frac(positions_frac_surf, order=sort_order)
# Convert template to cartesian coordinates
positions_cart_surf = frac_to_cart(lattice_cart_surf,positions_frac_surf)
# Calculate the number of atoms in the surface unit cell to take from the template
number_of_atoms_surf = positions_frac_bulk.shape[0] * template_unit_cell_dims[2]
# Select the correct number of atoms from the template
positions_cart_surf = positions_cart_surf[:number_of_atoms_surf,:]
# Adjust the lattice vectors for the surface unit cell (multiply the z-dimension)
lattice_cart_surf = lattice_cart_bulk.copy()
lattice_cart_surf[-1, :] *= template_unit_cell_dims[2] # Adjust the z-dimension
# Remove the z-offset from the fractional coordinates
positions_cart_surf = remove_z_offset(positions_cart_surf)
# Convert the selected positions back to fractional coordinates
positions_frac_surf = cart_to_frac(lattice_cart_surf, positions_cart_surf)
return positions_frac_surf, lattice_cart_surf
def delete_all_files_in_cwd(force: bool = False):
cwd = Path('.').resolve()
files = [f for f in cwd.iterdir() if f.is_file()]
if not files:
print(f"No files found in {cwd}. Nothing to delete.")
return
# If not forcing, show and prompt
if not force:
print(f"Found {len(files)} file(s) in {cwd}:")
for f in files:
print(f" • {f.name}")
confirm = input("Delete ALL these files? [y/N]: ").strip().lower()
if confirm != 'y':
print("Aborted. No files were deleted.")
return
# Proceed with deletion (forced or user-confirmed)
deleted = 0
for entry in files:
try:
entry.unlink()
deleted += 1
except Exception as e:
print(f"Error deleting {entry.name}: {e}")
print(f"Done. {deleted} file(s) deleted.")
def sort_file_list(file_list):
"""
Sort a list of Path objects naturally by filename.
Parameters:
file_list (List[Path]): List of Path objects to sort.
Returns:
List[Path]: Sorted list of Path objects.
"""
# Define a natural sort key
def natural_key(path):
parts = re.split(r'(\d+)', path.name)
return [int(text) if text.isdigit() else text.lower() for text in parts]
if not file_list:
return []
# Ensure all items are Path objects
if not all(isinstance(f, Path) for f in file_list):
raise ValueError("All items in file_list must be Path objects.")
# Sort using the natural key
return sorted(file_list, key=natural_key)
#endregion Basic file io and handling
# ============================================================================
# ============================================================================
#region Get information from .castep files
def get_warnings(castep_path, verbose=True):
"""
Extracts WARNING blocks from a .castep file and returns them as text.
Parameters:
castep_path (str or Path): Path to the .castep file.
verbose (bool): If True, include full blocks until the next blank line.
If False, include only the matching WARNING line.
Returns:
str: The formatted warning output (or a 'no warnings' message).
"""
path = Path(castep_path)
filename = path.name
parent_path = path.parent
full_path = parent_path / filename
with open(castep_path, 'r') as f:
lines = f.readlines()
output_lines = []
in_warning = False
current_warning = []
any_warning_found = False
for i, line in enumerate(lines):
if "warning" in line.lower():
if not any_warning_found:
output_lines.append(f"\n===== WARNINGS in: {filename} =====")
output_lines.append(f" full path: {full_path}\n")
any_warning_found = True
if not verbose:
output_lines.append(f"Line {i+1}: {line.strip()}")
continue
# Verbose mode: start a new block
if current_warning:
# flush previous block
output_lines.append("".join(current_warning).rstrip())
output_lines.append("-" * 40)
in_warning = True
current_warning = [line]
elif in_warning:
if line.strip() == "":
# end of block
output_lines.append("".join(current_warning).rstrip())
output_lines.append("-" * 40)
in_warning = False
current_warning = []
else:
current_warning.append(line)
# flush if file ended while still in a warning block
if in_warning and current_warning and verbose:
output_lines.append("".join(current_warning).rstrip())
output_lines.append("-" * 40)
if not any_warning_found:
output_lines.append(f"No warnings found in: {filename}")
output_lines.append(f" full path: {full_path}")
return "\n".join(output_lines)
def get_convergence_iterations(path, filename):
"""
Searches for a convergence line in the given file and returns the number of iterations.
If convergence is not reached, returns a message with the last completed iteration.
Parameters:
- path: directory containing the file
- filename: name of the file to search
Returns:
- int: number of iterations if convergence line is found
- str: message "Not converged. Last completed iteration = X." if no convergence line is present
"""
# Construct full file path
file_path = os.path.join(path, filename)
# Patterns for convergence and iteration lines
convergence_pattern = re.compile(r'Convergence achieved in\s+(\d+)\s+iterations')
iteration_pattern = re.compile(r'Iteration:\s+(\d+)')
max_iter = 0
try:
with open(file_path, 'r') as file:
for line in file:
# Check for convergence
conv_match = convergence_pattern.search(line)
if conv_match:
return int(conv_match.group(1))
# Track the highest iteration seen
iter_match = iteration_pattern.search(line)
if iter_match:
num = int(iter_match.group(1))
if num > max_iter:
max_iter = num
except FileNotFoundError:
# Notify caller that the file was not found
raise
# If convergence wasn't found, report status
if max_iter > 0:
return f"Not converged. Last completed iteration = {max_iter}."
else:
return "Not converged."
def get_calculation_parameters(castep_path):
"""
Extracts key calculation parameters from a CASTEP .castep file.
Returns a dictionary of parameters and values (as floats, ints, or strings),
including MP grid size, k-point offset, and number of k-points.
"""
keys_of_interest = {
'plane wave basis set cut-off',
'finite basis set correction',
'number of electrons',
'net charge of system',
'net spin of system',
'number of up spins',
'number of down spins',
'treating system as spin-polarized',
'number of bands',
'total energy / atom convergence tol.',
'eigen-energy convergence tolerance',
'max force / atom convergence tol.',
'convergence tolerance window',
'smearing scheme',
'smearing width',
'Fermi energy convergence tolerance',
'periodic dipole correction'
}
results = {}
with open(castep_path, 'r') as f:
for line in f:
# Handle normal key:value pairs
for key in keys_of_interest:
if key in line:
parts = line.split(":", 1)
if len(parts) < 2:
continue
value = parts[1].strip()
try:
results[key] = float(value)
except ValueError:
try:
results[key] = int(value)
except ValueError:
results[key] = value
break # avoid matching multiple keys per line
# MP grid size
if "MP grid size for SCF calculation is" in line:
match = re.findall(r'\d+', line)
if len(match) == 3:
kx = int(match[0])
ky = int(match[1])
kz = int(match[2])
results['k_points_mp_grid'] = (kx,ky,kz)
# Offset
if "with an offset of" in line:
match = re.findall(r'[-+]?\d*\.\d+', line)
if len(match) == 3:
results['k_offset'] = tuple(float(x) for x in match)
# Number of k-points
if "Number of kpoints used" in line:
match = re.search(r'=\s*(\d+)', line)
if match:
results['n_kpoints'] = int(match.group(1))
return results
def get_LBFGS_energies(castep_path):
"""
Extracts iteration numbers and enthalpy values from LBFGS optimization steps.
Returns a list of tuples: (iteration_number, enthalpy_in_eV)
Matches lines like:
LBFGS: finished iteration 0 with enthalpy= -8.36353629E+003 eV
"""
results = []
pattern = re.compile(
r'LBFGS: finished iteration\s+(\d+)\s+with enthalpy=\s*([-+]?\d*\.\d+E[+-]?\d+|\d+)'
)
with open(castep_path, 'r') as f:
for line in f:
match = pattern.search(line)
if match:
iteration = int(match.group(1))
enthalpy = float(match.group(2))
results.append((iteration, enthalpy))
return results
def get_LBFGS_final_enthalpy(castep_path):
"""
Extracts the final enthalpy value from a line like:
'LBFGS: Final Enthalpy = -8.36355887E+003 eV'
Returns:
float or str: Final enthalpy value in eV, or "err" if not found or ambiguous.
"""
pattern = re.compile(r'LBFGS: Final Enthalpy\s*=\s*([-+]?\d+(?:\.\d*)?(?:[eE][+-]?\d+))')
matches = []
try:
with open(castep_path, 'r') as f:
for line in f:
match = pattern.search(line)
if match:
matches.append(float(match.group(1)))
if len(matches) != 1:
return float('nan') # or return None
return matches[0]
except Exception as e:
return float('nan') # or return None
def get_calc_time_and_peak_memory(castep_path):
"""
Extracts the calculation time and peak memory use (with their units) from a .castep output file.
Looks for lines like:
Calculation time = 4935.16 s
Peak Memory Use = 142424116 kB
Returns:
tuple: (calc_time_val, calc_time_unit, peak_mem_val, peak_mem_unit)
Each value is a float (or NaN if missing/ambiguous).
Each unit is the exact string found (or '' if missing/ambiguous).
"""
# regex to capture number and unit
time_pat = re.compile(
r'Calculation time\s*=\s*([-+]?\d+(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*([a-zA-Z%]+)'
)
mem_pat = re.compile(
r'Peak Memory Use\s*=\s*([-+]?\d+(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*([a-zA-Z%]+)',
re.IGNORECASE
)
times = []
mems = []
try:
with open(castep_path, 'r') as f:
for line in f:
tm = time_pat.search(line)
if tm:
val = float(tm.group(1))
unit = tm.group(2)
times.append((val, unit))
mm = mem_pat.search(line)
if mm:
val = float(mm.group(1))
unit = mm.group(2)
mems.append((val, unit))
# Validate that exactly one match was found for each
if len(times) == 1:
calc_time_val, calc_time_unit = times[0]
else:
calc_time_val, calc_time_unit = float('nan'), ''
if len(mems) == 1:
peak_mem_val, peak_mem_unit = mems[0]
else:
peak_mem_val, peak_mem_unit = float('nan'), ''
return calc_time_val, calc_time_unit, peak_mem_val, peak_mem_unit
except Exception:
# On any error, return NaNs and empty units
return float('nan'), '', float('nan'), ''
def get_lattice_parameters(castep_path):
"""
Parse a CASTEP output file and extract, for each 'Unit Cell' block:
- real_lattice: a 3×3 list of floats
- a, b, c: lattice lengths (floats)
- alpha, beta, gamma: cell angles in degrees (floats)
Returns:
List[dict] of the form:
[
{
'real_lattice': [[r11, r12, r13],
[r21, r22, r23],
[r31, r32, r33]],
'a': ...,
'b': ...,
'c': ...,
'alpha': ...,
'beta': ...,
'gamma': ...,
},
...
]
"""
def is_float(s):
try:
float(s)
return True
except ValueError:
return False
results = []
with open(castep_path, 'r') as f:
lines = f.readlines()
i = 0
while i < len(lines):
# Look for the "Unit Cell" heading
if 'Unit Cell' in lines[i]:
# Advance to where the numeric lattice lines start
j = i + 1
# skip until we hit a line that looks like six floats
while j < len(lines):
parts = lines[j].split()
if len(parts) >= 6 and all(is_float(p) for p in parts[:3]):
break
j += 1
if j >= len(lines) - 2:
break
# Read the 3×3 real lattice matrix
real = []
for k in range(j, j + 3):
parts = lines[k].split()
real.append([float(parts[0]), float(parts[1]), float(parts[2])])
# Now find the lattice-parameters block (a, b, c and α, β, γ)
# It always appears as three lines starting with "a =", "b =", "c ="
# somewhere after our matrix, so scan forward a bit
a = b = c = alpha = beta = gamma = None
for k in range(j + 3, min(j + 20, len(lines))):
if re.search(r'^\s*a\s*=', lines[k]):
# Expect three lines: a, b, c
for offset, (param, angle) in enumerate(
[('a','alpha'), ('b','beta'), ('c','gamma')]
):
line = lines[k + offset]
# split on '=' then on whitespace
left, right = line.split('=', 1)
# right now like " 3.866591 alpha = 60.000000"
vals = right.replace('=',' ').split()
length = float(vals[0])
angle_val = float(vals[-1])
if param == 'a':
a, alpha = length, angle_val
elif param == 'b':
b, beta = length, angle_val
else:
c, gamma = length, angle_val
break
# Save and advance
results.append({
'unit_cell': real,
'a': a, 'b': b, 'c': c,
'alpha': alpha, 'beta': beta, 'gamma': gamma,
})
i = j + 3
else:
i += 1
return results
def get_final_lattice_parameters(castep_path):
"""
Parse a CASTEP output file and extract the *final* optimized cell,
i.e. the first 'Unit Cell' block occurring after the
'LBFGS: Final Configuration:' marker.
Returns:
dict with keys:
- 'real_lattice': 3×3 list of floats
- 'a', 'b', 'c': floats
- 'alpha', 'beta', 'gamma': floats
Raises:
RuntimeError if no final configuration or no Unit Cell block is found.
"""
def is_float(s):
try:
float(s)
return True
except ValueError:
return False
with open(castep_path, 'r') as f:
lines = f.readlines()
# 1) Find the line index of the final‐configuration marker
try:
start = next(i for i, L in enumerate(lines)
if 'LBFGS: Final Configuration:' in L)
except StopIteration:
raise RuntimeError("No 'LBFGS: Final Configuration:' found in file")
# 2) From there, find the next 'Unit Cell' header
i = start + 1
while i < len(lines) and 'Unit Cell' not in lines[i]:
i += 1
if i >= len(lines):
raise RuntimeError("No Unit Cell block after final configuration")
# 3) Skip forward to the numeric lattice rows
j = i + 1
while j < len(lines):
parts = lines[j].split()
if len(parts) >= 3 and all(is_float(p) for p in parts[:3]):
break
j += 1
if j + 2 >= len(lines):
raise RuntimeError("Incomplete lattice matrix after Unit Cell")
# 4) Read the 3×3 real‐lattice matrix
real = []
for k in range(j, j + 3):
p = lines[k].split()
real.append([float(p[0]), float(p[1]), float(p[2])])
# 5) Find a, b, c and α, β, γ in the following ~20 lines
a = b = c = alpha = beta = gamma = None
for k in range(j + 3, min(j + 20, len(lines))):
if re.match(r'\s*a\s*=', lines[k]):
# Expect three lines: a, b, c
for offset, (param, angle) in enumerate(
[('a','alpha'), ('b','beta'), ('c','gamma')]
):
line = lines[k + offset]
_, right = line.split('=', 1)
vals = right.replace('=',' ').split()
length = float(vals[0])
angle_val = float(vals[-1])
if param == 'a':
a, alpha = length, angle_val
elif param == 'b':
b, beta = length, angle_val
else:
c, gamma = length, angle_val
break
if None in (a, b, c, alpha, beta, gamma):
raise RuntimeError("Failed to parse lattice parameters a/b/c/α/β/γ")
unit_cell = real
return unit_cell, a, b, c, alpha, beta, gamma
def get_lattice_parameters(castep_path, a0=3.8668346, vac=15.0):
ax, ay, az = 'err', 'err', 'err'
nx, ny, nz = 'err', 'err', 'err'
with open(castep_path, 'r') as f:
lines = f.readlines()
for i in range(len(lines) - 1, 0, -1):
if "Lattice parameters" in lines[i]:
# Should be followed by 3 lines like: a = 5.43 alpha = 90.0
a_line = lines[i+1].strip().split()
b_line = lines[i+2].strip().split()
c_line = lines[i+3].strip().split()
ax = float(a_line[2])
alpha = float(a_line[5])
ay = float(b_line[2])
beta = float(b_line[5])
az = float(c_line[2])
gamma = float(c_line[5])
try:
nx_temp = ax / a0
ny_temp = ay / a0
nz_temp = (az - vac) / (a0 * np.sqrt(2) / 4 )
# Check each dimension separately for integer status after rounding to 6 decimal places
nx = round(nx_temp) if round(nx_temp, 6).is_integer() else 'err'
ny = round(ny_temp) if round(ny_temp, 6).is_integer() else 'err'
nz = round(nz_temp) if round(nz_temp, 6).is_integer() else 'err'
except Exception as e:
ax, ay, az = 'err', 'err', 'err'
nx, ny, nz = 'err', 'err', 'err'
return {'ax': ax, 'ay': ay, 'az': az, 'nx': nx, 'ny': ny, 'nz': nz, 'alpha': alpha, 'beta': beta, 'gamma': gamma}
def get_final_fractional_positions(castep_path):
"""
Extracts the final fractional positions from the LBFGS: Final Configuration block
in a CASTEP .castep file, by looking for the specific border line
'x----...----x' after the headers, then reading subsequent 'x ... x' lines.
"""
lines = Path(castep_path).read_text().splitlines()
frac_positions = []
in_lbfgs = False
start_parsing = False
for line in lines:
# 1) Enter LBFGS block
if not in_lbfgs and "LBFGS: Final Configuration" in line:
in_lbfgs = True
continue
if not in_lbfgs:
continue
# 2) Look for the dashed border after column headings:
# must start (after whitespace) with 'x-' and end with '-x'
if not start_parsing:
if re.match(r'^\s*x-+x\s*$', line):
start_parsing = True
continue
# 3) Once parsing, stop on blank or non-x lines
if not line.strip() or not line.lstrip().startswith('x'):
break
# 4) Strip off the 'x' borders and whitespace
entry = line.strip().strip('x').strip()
parts = entry.split()
# Expect at least 5 fields: Element, Number, u, v, w
if len(parts) < 5:
continue
symbol = parts[0]
try:
u, v, w = map(float, parts[2:5])
except ValueError:
continue
frac_positions.append((symbol, u, v, w))
return frac_positions
def fractional_coords_from_castep(castep_path):
# 1. extract fractional positions and lattice
fracs = get_final_fractional_positions(castep_path) # returns [(symbol,u,v,w),…]
lat = get_lattice_parameters(castep_path) # {'a':…, 'b':…, 'c':…, …}
# 2. clean up symbols and build lists
symbols = [s.split(':')[0] for s, u, v, w in fracs] # drop any “:D” suffix
scaled_positions = [(u, v, w) for s, u, v, w in fracs]
# 3. assemble cell matrix (orthogonal example)
a, b, c = lat['ax'], lat['ay'], lat['az']
cell = [[a, 0, 0],
[0, b, 0],
[0, 0, c]]
# 4. build the Atoms object
atoms = Atoms(symbols=symbols,
scaled_positions=scaled_positions,
cell=cell,
pbc=True)
return atoms
#endregion Get information from .castep files
# ============================================================================
# ============================================================================
#region Plotting and visualization functions
def print_filename(castep_path):
"""
Prints a clear heading with filename and full path.
"""
path = Path(castep_path)
filename = path.name
parent_path = path.parent
full_path = parent_path / filename
# Build a consistent-width header
header_text = f" FILE: {filename} "
path_text = f" PATH: {full_path} "
width = max(len(header_text), len(path_text)) + 4
print("\n" + "=" * width)
print(header_text.center(width))
print(path_text.center(width))
print("=" * width + "\n")
def plot_energy_vs_iteration(data, ylabel="Energy (eV)", title="Energy Convergence", figsize=(6, 4)):
if not data:
print("No data to plot.")
return
iterations, energies = zip(*data)
fig, ax = plt.subplots(figsize=figsize)
ax.plot(iterations, energies, marker='o', linestyle='-')
ax.set_xlabel("Iteration")
ax.set_ylabel(ylabel)
ax.set_title(title)
ax.grid(True)
# ――― key line ―――
ax.ticklabel_format(style='plain', axis='y', useOffset=False)
plt.tight_layout()
plt.show()
def view_structure(atoms,show_structure=True):
view = nv.show_ase(atoms,scale=0.01, aspectRatio=1.)
view.camera = 'orthographic'
view.center()
view.control.spin([0, 0, 1], math.pi/2) # Rotate 90° about z-axis
view.control.spin([0, 1, 0], math.pi/2) # Rotate 90° about z-axis
view.control.zoom(0.5)
if show_structure:
display(view)
return
else:
return view