Nanny7 commited on
Commit
d2f237b
·
1 Parent(s): 3d4922f

Fix cube file parsing to follow standard format specification

Browse files
Files changed (2) hide show
  1. app.py +26 -30
  2. force_rebuild.txt +1 -1
app.py CHANGED
@@ -11,41 +11,37 @@ def parse_cube_file(cube_file):
11
  if len(lines) < 6:
12
  raise ValueError("Cube file too short")
13
 
14
- # Find the line with natoms (should be the third line or so)
15
- for i, line in enumerate(lines):
16
- parts = line.split()
17
- if len(parts) >= 4:
18
- try:
19
- natoms = int(float(parts[0])) # Try to parse as int, allowing for float strings
20
- if natoms > 0:
21
- break
22
- except ValueError:
23
- continue
24
- else:
25
- raise ValueError("Could not find natoms in cube file")
26
-
27
- # Now i is the line with natoms
28
- origin = np.array([float(x) for x in lines[i].split()[1:4]])
29
 
30
- # Skip atom lines
31
- grid_start = i + 1 + natoms
32
- if grid_start >= len(lines):
33
- raise ValueError("Cube file malformed")
34
 
35
- grid_line = lines[grid_start]
36
- nx = int(grid_line.split()[0])
37
- dx = float(grid_line.split()[1])
 
38
 
39
- grid_line = lines[grid_start + 1]
40
- ny = int(grid_line.split()[1])
41
- dy = float(grid_line.split()[2])
 
42
 
43
- grid_line = lines[grid_start + 2]
44
- nz = int(grid_line.split()[2])
45
- dz = float(grid_line.split()[3])
 
46
 
47
- # Read data
48
- data_start = grid_start + 3
49
  data = []
50
  for line in lines[data_start:]:
51
  data.extend([float(x) for x in line.split()])
 
11
  if len(lines) < 6:
12
  raise ValueError("Cube file too short")
13
 
14
+ # Standard cube format:
15
+ # Line 0-1: comments
16
+ # Line 2: natoms, origin_x, origin_y, origin_z
17
+ # Line 3: nx, voxel_x, 0, 0
18
+ # Line 4: ny, 0, voxel_y, 0
19
+ # Line 5: nz, 0, 0, voxel_z
20
+ # Lines 6 to 6+natoms-1: atom data
21
+ # Remaining lines: volumetric data
 
 
 
 
 
 
 
22
 
23
+ # Parse line 2 (natoms and origin)
24
+ parts = lines[2].split()
25
+ natoms = abs(int(float(parts[0]))) # abs() handles negative natoms (sometimes used)
26
+ origin = np.array([float(parts[1]), float(parts[2]), float(parts[3])])
27
 
28
+ # Parse line 3 (nx and voxel spacing)
29
+ parts = lines[3].split()
30
+ nx = abs(int(float(parts[0])))
31
+ dx = float(parts[1])
32
 
33
+ # Parse line 4 (ny and voxel spacing)
34
+ parts = lines[4].split()
35
+ ny = abs(int(float(parts[0])))
36
+ dy = float(parts[2])
37
 
38
+ # Parse line 5 (nz and voxel spacing)
39
+ parts = lines[5].split()
40
+ nz = abs(int(float(parts[0])))
41
+ dz = float(parts[3])
42
 
43
+ # Data starts after atom lines
44
+ data_start = 6 + natoms
45
  data = []
46
  for line in lines[data_start:]:
47
  data.extend([float(x) for x in line.split()])
force_rebuild.txt CHANGED
@@ -1,2 +1,2 @@
1
  # Force rebuild
2
- 2025-11-08 v6
 
1
  # Force rebuild
2
+ 2025-11-08 v7