pwdata 0.5.9.dev0__py3-none-any.whl → 0.5.9.dev2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of pwdata might be problematic. Click here for more details.

pwdata/castepdata.py ADDED
@@ -0,0 +1,408 @@
1
+ """Parse CASTEP output files (.castep / .geom / .md) into pwdata Image objects.
2
+
3
+ Supported formats:
4
+ - castep/scf : single-point / geometry-optimisation ``<seed>.castep`` output,
5
+ one Image per converged ionic step (1 for a single-point run)
6
+ - castep/geom : ``<seed>.geom`` geometry-optimisation trajectory, one Image
7
+ per optimisation step
8
+ - castep/md : ``<seed>.md`` AIMD trajectory, one Image per MD step
9
+
10
+ Conventions:
11
+ - ``.castep`` values are natively in eV / Angstrom / GPa. Both the modern
12
+ markers (``Final energy, E = ...``, ``Cartesian components of stress
13
+ tensor (GPa)``) and the older CASTEP <= 6.x / Materials Studio markers
14
+ (``Final energy = ...``, ``Cartesian components (GPa)``) are recognised.
15
+ - One Image is emitted per step that carries an energy AND a complete force
16
+ table (older versions print per-iteration energies several times during
17
+ the cut-off convergence sweep but forces only for the final structure, so
18
+ energy-only intermediates are not emitted); a pending energy-only step is
19
+ emitted at end of file as a structural salvage image. Positions are taken
20
+ from the last ``Cell Contents`` table (older versions print it once).
21
+ - ``.geom`` and ``.md`` values are in atomic units (Hartree / Bohr); both the
22
+ classic tag layout (``<-- E``, ``<-- h``, ``<-- R``, ``<-- F``, ``<-- S``)
23
+ and the restructured layout of newer CASTEP versions (``BEGIN header`` /
24
+ ``END header`` block followed by blank-line separated frames carrying the
25
+ same tags) are handled by the same parser.
26
+ - CASTEP positions in ``.geom``/``.md`` are Cartesian; ``.castep`` fractional
27
+ coordinates are stored as fractional (``image.cartesian=False``).
28
+ - CASTEP prints stress with positive = compression; the virial is stored as
29
+ ``virial = stress[GPa] * volume[A^3] / 160.21766208`` with no sign flip,
30
+ consistent with the CP2K path (``pwdata.utils.constant.gpa2ev``).
31
+ - Velocities, temperatures and pressures are skipped (``Image`` has no fields
32
+ for them).
33
+ """
34
+ import os
35
+ import glob
36
+ import re
37
+ import numpy as np
38
+ from collections import Counter
39
+ from tqdm import tqdm
40
+ from pwdata.image import Image
41
+ from pwdata.calculators.const import ELEMENTTABLE
42
+ from pwdata.utils.format_change import to_numpy_array, to_integer, to_float
43
+ from pwdata.utils.constant import HARTREE2EV, BOHR2ANG, HARTREE2EV_PER_BOHR2ANG, HARTREE_PER_BOHR3_TO_GPA, gpa2ev
44
+
45
+ NUMBER_PATTERN = re.compile(r"[-+]?\d+(?:\.\d+)?(?:[eE][-+]?\d+)?")
46
+ TAG_PATTERN = re.compile(r"<--\s*([A-Za-z]+)")
47
+ # tags carried by .geom/.md frames; anything else (e.g. '<-- c' constraint
48
+ # rows, '<-- T/P' scalars, '<-- V' velocities) is ignored
49
+ TRAJ_TAGS = ["E", "h", "S", "R", "F"]
50
+
51
+
52
+ def species_to_element(species):
53
+ """Map a CASTEP species label ('H', 'Fe_1', 'O2-', 'Fe:Fe_1') to its atomic number."""
54
+ label = species.split(':')[0] if ':' in species else species
55
+ if label in ELEMENTTABLE:
56
+ return ELEMENTTABLE[label]
57
+ stripped = label.rstrip('0123456789_+-')
58
+ if stripped in ELEMENTTABLE:
59
+ return ELEMENTTABLE[stripped]
60
+ stripped = stripped.capitalize()
61
+ if stripped in ELEMENTTABLE:
62
+ return ELEMENTTABLE[stripped]
63
+ raise ValueError("Cannot map CASTEP species label %r to an element" % species)
64
+
65
+
66
+ def resolve_castep_file(file_path, ext):
67
+ """Return the CASTEP file path; file_path may be the file itself or a directory."""
68
+ if os.path.isfile(file_path):
69
+ return file_path
70
+ if os.path.isdir(file_path):
71
+ matches = sorted(glob.glob(os.path.join(file_path, "*" + ext)))
72
+ if len(matches) == 0:
73
+ raise FileNotFoundError("No *{} file found in {}".format(ext, file_path))
74
+ if len(matches) > 1:
75
+ raise ValueError("Multiple *{} files found in {}, please specify the file directly".format(ext, file_path))
76
+ return matches[0]
77
+ raise FileNotFoundError("No such file or directory: {}".format(file_path))
78
+
79
+
80
+ def looks_like_castep_traj(file_path, n_probe=50):
81
+ """Cheap content sniff: does the file carry '<--' data tags or a CASTEP header?
82
+
83
+ Used to keep foreign files with a CASTEP-like extension (e.g. markdown
84
+ *.md files) out of directory searches and format inference.
85
+ """
86
+ try:
87
+ with open(file_path, 'r') as f:
88
+ for i, line in enumerate(f):
89
+ if i > n_probe:
90
+ break
91
+ if TAG_PATTERN.search(line) or "END header" in line or "BEGIN header" in line:
92
+ return True
93
+ except OSError:
94
+ return False
95
+ return False
96
+
97
+
98
+ def _fill_atom_info(image, species_list):
99
+ """Set atom_type/atom_type_num/atom_types_image/atomic_energy on an Image."""
100
+ atom_types_image = [species_to_element(species) for species in species_list]
101
+ image.atom_nums = to_integer(len(atom_types_image))
102
+ image.atom_types_image = to_numpy_array(atom_types_image)
103
+ counter = Counter(atom_types_image)
104
+ image.atom_type = to_numpy_array(list(counter.keys()))
105
+ image.atom_type_num = to_numpy_array(list(counter.values()))
106
+ # If Atomic-Energy is not in the file, calculate it from the Ep
107
+ if image.atomic_energy is None and image.Ep is not None and image.atom_type_num is not None:
108
+ atomic_energy, _, _, _ = np.linalg.lstsq([image.atom_type_num], np.array([image.Ep]), rcond=1e-3)
109
+ atomic_energy = np.repeat(atomic_energy, image.atom_type_num)
110
+ image.atomic_energy = to_numpy_array(atomic_energy.tolist())
111
+
112
+
113
+ def _parse_atom_row(line):
114
+ """Parse a '<-- R/F' style row 'H 1 0.0 0.0 0.0 <-- R' into (species, [x, y, z])."""
115
+ fields = line.split()
116
+ species = fields[0]
117
+ try:
118
+ int(fields[1])
119
+ xyz = [float(_) for _ in fields[2:5]]
120
+ except (ValueError, IndexError):
121
+ numbers = NUMBER_PATTERN.findall(line)
122
+ xyz = [float(_) for _ in numbers[-3:]]
123
+ return species, xyz
124
+
125
+
126
+ def _frame_to_image(frame, iteration):
127
+ """Convert one parsed .geom/.md frame (tag -> rows) into an Image, or None if unusable.
128
+
129
+ Frames with missing/incomplete force blocks are dropped with a warning:
130
+ training data always requires forces.
131
+ """
132
+ if not frame["R"] or not frame["h"]:
133
+ return None
134
+ if not frame["F"] or len(frame["F"]) != len(frame["R"]):
135
+ print("Warning: iteration {} has a missing/incomplete force block, the frame is skipped".format(iteration))
136
+ return None
137
+ species_list = [row[0] for row in frame["R"]]
138
+ positions = np.array([row[1] for row in frame["R"]]) * BOHR2ANG
139
+ lattice = np.array(frame["h"][:3]) * BOHR2ANG
140
+ image = Image(lattice=lattice, position=positions, pbc=np.array([1, 1, 1]), iteration=iteration)
141
+ image.cartesian = True
142
+ image.force = to_numpy_array(np.array([row[1] for row in frame["F"]]) * HARTREE2EV_PER_BOHR2ANG)
143
+ if frame["E"]:
144
+ energies = frame["E"][0]
145
+ image.Ep = to_float(energies[0] * HARTREE2EV)
146
+ if len(energies) >= 3:
147
+ image.Ek = to_float(energies[2] * HARTREE2EV)
148
+ if len(frame["S"]) >= 3:
149
+ stress_gpa = np.array(frame["S"][:3]) * HARTREE_PER_BOHR3_TO_GPA
150
+ volume = np.abs(np.linalg.det(lattice))
151
+ image.virial = to_numpy_array(gpa2ev(stress_gpa, volume))
152
+ _fill_atom_info(image, species_list)
153
+ return image
154
+
155
+
156
+ def _parse_trajectory_frames(file_path):
157
+ """Parse a classic or restructured .geom/.md file into a list of frame dicts.
158
+
159
+ Frames are blank-line separated blocks (restructured layout) carrying
160
+ '<-- tag' labelled lines; a new '<-- E' line also starts a new frame so
161
+ files without blank-line separators still parse. Lines before the
162
+ 'END header' marker are skipped when the header block is present.
163
+ """
164
+ frames = []
165
+ current = None
166
+ with open(file_path, 'r') as f:
167
+ # skip the optional 'BEGIN/END header' block; files without one are
168
+ # parsed from the beginning
169
+ header_found = False
170
+ for i, line in enumerate(f):
171
+ if "END header" in line:
172
+ header_found = True
173
+ break
174
+ if i > 50:
175
+ break
176
+ if not header_found:
177
+ f.seek(0)
178
+ for line in tqdm(f, desc="Reading %s" % os.path.basename(file_path)):
179
+ stripped = line.strip()
180
+ if stripped == "":
181
+ if current is not None and current["R"]:
182
+ frames.append(current)
183
+ current = None
184
+ continue
185
+ match = TAG_PATTERN.search(line)
186
+ if match is None:
187
+ continue # bare lines: time value (md) / step counter (geom)
188
+ tag = match.group(1)
189
+ if tag not in TRAJ_TAGS:
190
+ continue # '<-- c' constraint rows, '<-- T/P/V' rows etc.
191
+ if tag == "E" and current is not None and current["E"]:
192
+ if current["R"]:
193
+ frames.append(current)
194
+ current = None
195
+ if current is None:
196
+ current = {tag_key: [] for tag_key in TRAJ_TAGS}
197
+ if tag in ("R", "F"):
198
+ species, xyz = _parse_atom_row(line)
199
+ current[tag].append((species, xyz))
200
+ else:
201
+ numbers = NUMBER_PATTERN.findall(line)
202
+ current[tag].append([float(_) for _ in numbers])
203
+ if current is not None and current["R"]:
204
+ frames.append(current)
205
+ return frames
206
+
207
+
208
+ class _CASTEPTrajectory(object):
209
+ """Shared implementation of the .geom and .md trajectory parsers."""
210
+
211
+ def __init__(self, traj_file, ext):
212
+ self.image_list: list[Image] = []
213
+ self.traj_file = resolve_castep_file(traj_file, ext)
214
+ frames = _parse_trajectory_frames(self.traj_file)
215
+ for iteration, frame in enumerate(frames):
216
+ image = _frame_to_image(frame, iteration)
217
+ if image is not None:
218
+ self.image_list.append(image)
219
+ assert len(self.image_list) > 0, "No system loaded!"
220
+ for image in self.image_list:
221
+ image.image_nums = len(self.image_list)
222
+ print("Load data %s successfully! \t\t\t\t Image nums: %d" % (self.traj_file, len(self.image_list)))
223
+
224
+ def get(self):
225
+ return self.image_list
226
+
227
+
228
+ class CASTEPGEOM(_CASTEPTrajectory):
229
+ """Parse a <seed>.geom geometry-optimisation trajectory (one Image per step)."""
230
+
231
+ def __init__(self, geom_file):
232
+ super(CASTEPGEOM, self).__init__(geom_file, ".geom")
233
+
234
+
235
+ class CASTEPMD(_CASTEPTrajectory):
236
+ """Parse a <seed>.md AIMD trajectory (one Image per MD step)."""
237
+
238
+ def __init__(self, md_file):
239
+ super(CASTEPMD, self).__init__(md_file, ".md")
240
+
241
+
242
+ class CASTEPSCF(object):
243
+ """Parse a <seed>.castep output file (single-point or geometry-optimisation).
244
+
245
+ One Image is created per converged ionic step; the lattice, species and
246
+ fractional positions are carried forward between steps because CASTEP may
247
+ print them only once in highly symmetric runs. Images of steps whose SCF
248
+ did not converge are skipped.
249
+ """
250
+
251
+ def __init__(self, castep_file):
252
+ self.image_list: list[Image] = []
253
+ self.castep_file = resolve_castep_file(castep_file, ".castep")
254
+ self.load_castep_file()
255
+ assert len(self.image_list) > 0, "No system loaded!"
256
+ for image in self.image_list:
257
+ image.image_nums = len(self.image_list)
258
+ print("Load data %s successfully! \t\t\t\t Image nums: %d" % (self.castep_file, len(self.image_list)))
259
+
260
+ def get(self):
261
+ return self.image_list
262
+
263
+ def _finalize(self, lattice, species_list, frac_positions, cur_energy,
264
+ cur_forces, cur_stress, cur_unconverged, cur_iteration):
265
+ """Build an Image from the current ionic step's carried state."""
266
+ if cur_energy is None or species_list is None or cur_unconverged:
267
+ return None
268
+ image = Image(lattice=lattice, position=frac_positions,
269
+ pbc=np.array([1, 1, 1]), iteration=cur_iteration)
270
+ image.cartesian = False
271
+ image.Ep = to_float(cur_energy)
272
+ if cur_forces is not None:
273
+ image.force = to_numpy_array(cur_forces)
274
+ if cur_stress is not None and lattice is not None:
275
+ volume = np.abs(np.linalg.det(lattice))
276
+ image.virial = to_numpy_array(gpa2ev(cur_stress, volume))
277
+ _fill_atom_info(image, species_list)
278
+ self.image_list.append(image)
279
+ return image
280
+
281
+ def load_castep_file(self):
282
+ with open(self.castep_file, 'r') as rf:
283
+ castep_contents = rf.readlines()
284
+
285
+ lattice = None
286
+ species_list = None
287
+ frac_positions = None
288
+ cur_energy = None
289
+ cur_forces = None
290
+ cur_stress = None
291
+ # cur_unconverged refers to the step being accumulated; next_unconverged
292
+ # is set by 'SCF not converged' lines which occur during the SCF loop
293
+ # of the FOLLOWING step (after this step's forces), so it must not be
294
+ # applied to the pending step
295
+ cur_unconverged = False
296
+ next_unconverged = False
297
+ cur_iteration = 0
298
+
299
+ def finalize_pending():
300
+ nonlocal cur_energy, cur_forces, cur_stress, cur_unconverged
301
+ self._finalize(lattice, species_list, frac_positions, cur_energy,
302
+ cur_forces, cur_stress, cur_unconverged, cur_iteration)
303
+ cur_energy = None
304
+ cur_forces = None
305
+ cur_stress = None
306
+ cur_unconverged = False
307
+
308
+ for idx, line in tqdm(enumerate(castep_contents), total=len(castep_contents), desc="Processing data"):
309
+ if "SCF not converged" in line:
310
+ next_unconverged = True
311
+ elif "starting iteration" in line:
312
+ match = re.search(r"starting iteration\s+(\d+)", line)
313
+ if match is not None:
314
+ cur_iteration = int(match.group(1))
315
+ elif "Real Lattice(A)" in line:
316
+ # next lines carry the real-space lattice in Angstrom
317
+ rows = []
318
+ j = idx + 1
319
+ while j < len(castep_contents) and len(rows) < 3 and j <= idx + 10:
320
+ numbers = NUMBER_PATTERN.findall(castep_contents[j])
321
+ if len(numbers) >= 3:
322
+ rows.append([float(_) for _ in numbers[:3]])
323
+ j += 1
324
+ if len(rows) == 3:
325
+ lattice = np.array(rows)
326
+ elif "Cell Contents" in line:
327
+ # bordered table: x Element Count u v w x ; take rows
328
+ # between the 'xxxx' borders, skipping header/separator rows
329
+ rows = []
330
+ j = idx + 1
331
+ in_table = False
332
+ while j < len(castep_contents) and j <= idx + 300:
333
+ jline = castep_contents[j]
334
+ if "xxxx" in jline:
335
+ if in_table:
336
+ break
337
+ in_table = True
338
+ elif in_table and rows and jline.strip() == "":
339
+ # blank line closes the table when the closing border
340
+ # is absent; the table itself never contains blanks
341
+ break
342
+ elif in_table:
343
+ fields = jline.split()
344
+ if len(fields) >= 5:
345
+ if fields[0] == 'x':
346
+ species, pos_fields = fields[1], fields[3:6]
347
+ else:
348
+ species, pos_fields = fields[0], fields[2:5]
349
+ try:
350
+ pos = [float(_) for _ in pos_fields]
351
+ rows.append((species, pos))
352
+ except ValueError:
353
+ pass # header / separator rows
354
+ j += 1
355
+ if rows:
356
+ species_list = [row[0] for row in rows]
357
+ frac_positions = np.array([row[1] for row in rows])
358
+ elif "Final energy" in line:
359
+ # covers both the modern 'Final energy, E = ...' and the old
360
+ # CASTEP <= 6.x 'Final energy = ...'; a pending step is only
361
+ # emitted once it carries an energy AND a complete force table
362
+ if cur_energy is not None and cur_forces is not None:
363
+ finalize_pending()
364
+ cur_unconverged = next_unconverged
365
+ next_unconverged = False
366
+ numbers = NUMBER_PATTERN.findall(line)
367
+ cur_energy = float(numbers[0]) if numbers else None
368
+ cur_forces = None
369
+ cur_stress = None
370
+ elif "Cartesian components (eV/A)" in line and species_list is not None:
371
+ # one row per atom: 'spec idx fx fy fz'; force rows carry an
372
+ # integer atom index as the second field, which distinguishes
373
+ # them from neighbouring tables (e.g. stress rows); the scan is
374
+ # bounded so a truncated block cannot swallow later sections
375
+ target = len(species_list)
376
+ forces = []
377
+ j = idx + 1
378
+ while j < len(castep_contents) and len(forces) < target and j <= idx + target + 20:
379
+ jline = castep_contents[j]
380
+ fields = jline.replace('*', ' ').split()
381
+ try:
382
+ int(fields[1])
383
+ except (ValueError, IndexError):
384
+ j += 1
385
+ continue # decoration / header / other-section rows
386
+ numbers = NUMBER_PATTERN.findall(jline)
387
+ if len(numbers) >= 3:
388
+ forces.append([float(_) for _ in numbers[-3:]])
389
+ j += 1
390
+ if len(forces) == target:
391
+ cur_forces = np.array(forces)
392
+ elif "Cartesian components" in line and "(GPa)" in line:
393
+ # covers both the modern 'Cartesian components of stress tensor
394
+ # (GPa)' and the old CASTEP <= 6.x 'Cartesian components (GPa)'
395
+ # 3 rows, each carrying the 3 stress components after the axis label
396
+ stress_rows = []
397
+ j = idx + 1
398
+ while j < len(castep_contents) and len(stress_rows) < 3 and j <= idx + 8:
399
+ numbers = NUMBER_PATTERN.findall(castep_contents[j])
400
+ if len(numbers) >= 3:
401
+ stress_rows.append([float(_) for _ in numbers[-3:]])
402
+ j += 1
403
+ if len(stress_rows) == 3:
404
+ cur_stress = np.array(stress_rows)
405
+ if cur_energy is not None and cur_forces is not None:
406
+ finalize_pending() # stress table closes the step
407
+ if cur_energy is not None:
408
+ finalize_pending() # salvage an energy-only step at end of file
pwdata/check_envs.py CHANGED
@@ -29,7 +29,7 @@ def cmd_infos():
29
29
  info += "\tYou can also use 'pwdata convert_config -h' to obtain a more detailed parameter list\n\n"
30
30
 
31
31
  info += "convert_configs or cvt_configs:\n"
32
- info += "\tExtract various trajectory files(movement of PWmat, outcar of Vasp, lammps/dump of Lammps, cp2k-mdfile of CP2K) or data sets (deepmd/npy, deepmd/raw, extxyz, meta aselmdb) into pwmlff/npy or extxyz format, the command example:\n"
32
+ info += "\tExtract various trajectory files(movement of PWmat, outcar of Vasp, lammps/dump of Lammps, cp2k-md file of CP2K, castep/geom/md of CASTEP) or data sets (deepmd/npy, deepmd/raw, extxyz, meta aselmdb) into pwmlff/npy or extxyz format, the command example:\n"
33
33
  info += "\tpwdata convert_images -i input_file1 input_file2 ... input_filen -f input_file_format -n output_format_name -o output_format\n\n"
34
34
 
35
35
  info += "count or count_configs:\n"
@@ -49,6 +49,9 @@ def cmd_infos():
49
49
  info += "| LAMMPS | dump | True | False | 'lammps/dump' |\n"
50
50
  info += "| CP2K | stdout, xyz, pdb | True | True | 'cp2k/md' |\n"
51
51
  info += "| CP2K | stdout | False | True | 'cp2k/scf' |\n"
52
+ info += "| CASTEP | <seed>.geom | True | True | 'castep/geom' |\n"
53
+ info += "| CASTEP | <seed>.md | True | True | 'castep/md' |\n"
54
+ info += "| CASTEP | <seed>.castep | True | True | 'castep/scf' |\n"
52
55
  info += "| PWMLFF | \*.npy | True | True | 'pwmlff/npy' |\n"
53
56
  info += "| DeepMD (read) | \*.npy, \*.raw | True | True | 'deepmd/npy', 'deepmd/raw' |\n"
54
57
  info += "| \* (extended xyz) | \*.xyz | True | True | 'extxyz' |\n"
pwdata/config.py CHANGED
@@ -13,6 +13,7 @@ from pwdata.atomconfig import CONFIG
13
13
  from pwdata.dump import DUMP
14
14
  from pwdata.lammpsdata import LMP
15
15
  from pwdata.cp2kdata import CP2KMD, CP2KSCF
16
+ from pwdata.castepdata import CASTEPSCF, CASTEPGEOM, CASTEPMD, looks_like_castep_traj
16
17
  from pwdata.deepmd import DPNPY, DPRAW
17
18
  from pwdata.pwmlff import PWNPY
18
19
  from pwdata.movement_saver import save_to_movement
@@ -56,6 +57,12 @@ class Save_Data(object):
56
57
  self.image_data = CP2KMD(data_path)
57
58
  elif format.lower() == 'cp2k/scf':
58
59
  self.image_data = CP2KSCF(data_path)
60
+ elif format.lower() == 'castep/scf':
61
+ self.image_data = CASTEPSCF(data_path)
62
+ elif format.lower() == 'castep/geom':
63
+ self.image_data = CASTEPGEOM(data_path)
64
+ elif format.lower() == 'castep/md':
65
+ self.image_data = CASTEPMD(data_path)
59
66
  elif format.lower() == 'deepmd/npy':
60
67
  self.image_data = DPNPY(data_path)
61
68
  elif format.lower() == 'deepmd/raw':
@@ -192,6 +199,12 @@ class Config(object):
192
199
  image = CP2KMD(data_path).image_list[index]
193
200
  elif format.lower() == 'cp2k/scf':
194
201
  image = CP2KSCF(data_path).image_list
202
+ elif format.lower() == 'castep/scf':
203
+ image = CASTEPSCF(data_path).image_list[index]
204
+ elif format.lower() == 'castep/geom':
205
+ image = CASTEPGEOM(data_path).image_list[index]
206
+ elif format.lower() == 'castep/md':
207
+ image = CASTEPMD(data_path).image_list[index]
195
208
  elif format.lower() == 'deepmd/npy':
196
209
  image = DPNPY(data_path).image_list[index]
197
210
  elif format.lower() == 'deepmd/raw':
@@ -292,7 +305,26 @@ def string2index(string: str) -> Union[int, slice, str]:
292
305
  i += (3 - len(i)) * [None]
293
306
  return slice(*i)
294
307
 
295
- def infer_format(data_path: str, pbc = None, atom_names = None, index = ':', **kwargs):
308
+ def infer_format(data_path: str, pbc = None, atom_names = None, index = ':', **kwargs):
309
+ # CASTEP output files are probed by extension first, so the parsers never
310
+ # run on foreign files and foreign probing never runs on CASTEP files;
311
+ # .md/.geom files must pass a cheap content sniff so markdown files etc.
312
+ # are not parsed at all
313
+ if isinstance(data_path, str) and os.path.isfile(data_path):
314
+ lower = data_path.lower()
315
+ if lower.endswith('.castep') or \
316
+ ((lower.endswith('.geom') or lower.endswith('.md')) and looks_like_castep_traj(data_path)):
317
+ try:
318
+ if lower.endswith('.castep'):
319
+ image = CASTEPSCF(data_path).image_list[index]
320
+ return image, FORMAT.castep_scf
321
+ if lower.endswith('.geom'):
322
+ image = CASTEPGEOM(data_path).image_list[index]
323
+ return image, FORMAT.castep_geom
324
+ image = CASTEPMD(data_path).image_list[index]
325
+ return image, FORMAT.castep_md
326
+ except Exception as e:
327
+ pass
296
328
  try:
297
329
  image = MOVEMENT(data_path).image_list[index]
298
330
  return image, FORMAT.pwmat_movement
pwdata/convert_files.py CHANGED
@@ -8,6 +8,7 @@ from pwdata.build.supercells import make_supercell
8
8
  from pwdata.pertub.perturbation import perturb_structure
9
9
  from pwdata.pertub.scale import scale_cell
10
10
  from pwdata.utils.constant import FORMAT, ELEMENTTABLE, get_atomic_name_from_number
11
+ from pwdata.castepdata import looks_like_castep_traj
11
12
  from pwdata.image import Image
12
13
  from collections import Counter
13
14
  from ase.build import general_surface
@@ -24,7 +25,7 @@ def do_convert_config(input_file:str,
24
25
  direct:bool = True): # True: save as fractional coordinates, False for cartesian coordinates
25
26
  image = Config(data_path=input_file, format=input_format, atom_names=atom_types)
26
27
  if output_format is None:
27
- output_format = FORMAT.pwmat_config if image.format == FORMAT.cp2k_scf else image.format
28
+ output_format = FORMAT.pwmat_config if image.format in [FORMAT.cp2k_scf, FORMAT.castep_scf] else image.format
28
29
  if savename is None:
29
30
  savename = FORMAT.get_filename_by_format(output_format)
30
31
 
@@ -47,9 +48,9 @@ def do_scale_cell(input_file:str,
47
48
  scale_factor = [scale_factor]
48
49
  image = Config(data_path=input_file, format=input_format, atom_names=atom_types)
49
50
  if output_format is None:
50
- output_format = FORMAT.pwmat_config if image.format == FORMAT.cp2k_scf else image.format
51
+ output_format = FORMAT.pwmat_config if image.format in [FORMAT.cp2k_scf, FORMAT.castep_scf] else image.format
51
52
  if savename is None:
52
- savename = FORMAT.get_filename_by_format(image.format)
53
+ savename = FORMAT.get_filename_by_format(output_format)
53
54
  for idx, factor in enumerate(scale_factor):
54
55
  scaled_structs = scale_cell(image, factor)
55
56
  scaled_structs.to(data_path = os.path.dirname(os.path.abspath(savename)),
@@ -103,16 +104,22 @@ def do_surface(input_file:str,
103
104
  for ii in miller:
104
105
  miller_str += str(ii)
105
106
  tmp_file = f"{prefix_random}-surf-{miller_str}-POSCAR"
107
+ # general_surface expects an ASE Atoms object, convert from pymatgen
108
+ ss_atoms = AseAtomsAdaptor.get_atoms(ss)
109
+ # a vacuum is required, otherwise the slab cell has a zero z-vector and
110
+ # cannot be written; '-v/--vacuum_max' is the vacuum thickness used
111
+ # when '-u/--vacuum_min' is not given
112
+ vacuum = vacuum_min if vacuum_min is not None else vacuum_max
106
113
  # slabgen = SlabGenerator(ss, miller, z_min, 1e-3)
107
114
  if layer_num is not None:
108
115
  slab = general_surface.surface(
109
- ss, indices=miller, vacuum=vacuum_min, layers=layer_num
116
+ ss_atoms, indices=miller, vacuum=vacuum, layers=layer_num
110
117
  )
111
118
  else:
112
119
  # build slab according to z_min value
113
120
  for layer_numb in range(1, max_layer_numb + 1):
114
121
  slab = general_surface.surface(
115
- ss, indices=miller, vacuum=vacuum_min, layers=layer_numb
122
+ ss_atoms, indices=miller, vacuum=vacuum, layers=layer_numb
116
123
  )
117
124
  if slab.cell.lengths()[-1] >= z_min:
118
125
  break
@@ -126,9 +133,9 @@ def do_surface(input_file:str,
126
133
  else:
127
134
  scaled_structs = image
128
135
  if output_format is None:
129
- output_format = FORMAT.pwmat_config if image.format == FORMAT.cp2k_scf else image.format
136
+ output_format = FORMAT.pwmat_config if image.format in [FORMAT.cp2k_scf, FORMAT.castep_scf] else image.format
130
137
  if savename is None:
131
- savename = FORMAT.get_filename_by_format(image.format)
138
+ savename = FORMAT.get_filename_by_format(output_format)
132
139
  data_name = f"surf-{miller}-super-{os.path.basename(savename)}" if supercell_matrix is not None else f"surf-{miller}-{os.path.basename(savename)}"
133
140
  scaled_structs.to(data_path = os.path.dirname(os.path.abspath(savename)),
134
141
  data_name = data_name,
@@ -153,9 +160,9 @@ def do_super_cell(input_file:str,
153
160
  image = Config(data_path=input_file, format=input_format, atom_names=atom_types)
154
161
  scaled_structs = make_supercell(image, supercell_matrix, pbc=pbc, wrap=wrap, tol=tol)
155
162
  if output_format is None:
156
- output_format = FORMAT.pwmat_config if image.format == FORMAT.cp2k_scf else image.format
163
+ output_format = FORMAT.pwmat_config if image.format in [FORMAT.cp2k_scf, FORMAT.castep_scf] else image.format
157
164
  if savename is None:
158
- savename = FORMAT.get_filename_by_format(image.format)
165
+ savename = FORMAT.get_filename_by_format(output_format)
159
166
  scaled_structs.to(data_path = os.path.dirname(os.path.abspath(savename)),
160
167
  data_name = os.path.basename(savename),
161
168
  format = output_format,
@@ -185,7 +192,7 @@ def do_perturb(input_file:str,
185
192
 
186
193
  perturb_files = []
187
194
  if output_format is None:
188
- output_format = FORMAT.pwmat_config if image.format == FORMAT.cp2k_scf else image.format
195
+ output_format = FORMAT.pwmat_config if image.format in [FORMAT.cp2k_scf, FORMAT.castep_scf] else image.format
189
196
  for tmp_perturbed_idx, tmp_pertubed_struct in enumerate(perturbed_structs):
190
197
  tmp_pertubed_struct.to(data_path = save_path,
191
198
  data_name = "{}_{}".format(tmp_perturbed_idx, save_name_prefix),
@@ -277,6 +284,9 @@ def search_images(input_list:list[str], input_format:str = None):
277
284
  data_path[FORMAT.deepmd_npy] = []
278
285
  data_path[FORMAT.deepmd_raw] = []
279
286
  data_path[FORMAT.meta] = []
287
+ data_path[FORMAT.castep_scf] = []
288
+ data_path[FORMAT.castep_geom] = []
289
+ data_path[FORMAT.castep_md] = []
280
290
  data_path[FORMAT.traj] = []
281
291
  for workDir in input_list:
282
292
  workDir = os.path.abspath(workDir)
@@ -286,9 +296,9 @@ def search_images(input_list:list[str], input_format:str = None):
286
296
  if input_format is not None:
287
297
  _data_list = search_by_format(workDir, input_format)
288
298
  if len(_data_list) > 0:
289
- data_path[input_format].extend(search_by_format(workDir, input_format))
299
+ data_path[input_format].extend(_data_list)
290
300
  else:
291
- for _format in [FORMAT.pwmlff_npy, FORMAT.extxyz, FORMAT.deepmd_npy, FORMAT.deepmd_raw, FORMAT.meta]:
301
+ for _format in [FORMAT.pwmlff_npy, FORMAT.extxyz, FORMAT.deepmd_npy, FORMAT.deepmd_raw, FORMAT.meta, FORMAT.castep_scf, FORMAT.castep_geom, FORMAT.castep_md]:
292
302
  _data_list = search_by_format(workDir, _format)
293
303
  if len(_data_list) > 0:
294
304
  data_path[_format].extend(_data_list)
@@ -312,6 +322,9 @@ def search_by_format(workDir, format):
312
322
  data_path[FORMAT.deepmd_npy] = []
313
323
  data_path[FORMAT.deepmd_raw] = []
314
324
  data_path[FORMAT.meta] = []
325
+ data_path[FORMAT.castep_scf] = []
326
+ data_path[FORMAT.castep_geom] = []
327
+ data_path[FORMAT.castep_md] = []
315
328
  if '.xyz' in os.path.basename(workDir):
316
329
  data_path[FORMAT.extxyz].append(workDir)
317
330
  elif '.aselmdb' in os.path.basename(workDir):
@@ -349,7 +362,20 @@ def search_by_format(workDir, format):
349
362
  if '.aselmdb' == ext:
350
363
  data_path[FORMAT.meta].append(os.path.join(root, file))
351
364
  # break
352
-
365
+
366
+ if format in [FORMAT.castep_scf, FORMAT.castep_geom, FORMAT.castep_md]:
367
+ ext = ".castep" if format == FORMAT.castep_scf else (".geom" if format == FORMAT.castep_geom else ".md")
368
+ for root, dirs, files in os.walk(workDir):
369
+ for file in files:
370
+ if not file.endswith(ext):
371
+ continue
372
+ file_path = os.path.join(root, file)
373
+ # '.md' also matches markdown files; keep only files that
374
+ # actually look like CASTEP trajectory output
375
+ if ext != ".castep" and not looks_like_castep_traj(file_path):
376
+ continue
377
+ data_path[format].append(file_path)
378
+
353
379
  return data_path[format]
354
380
 
355
381