phosph-rs 0.4.0

Simple, pretty, multiplatform molecular viewer for chemists.
Documentation
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
use bevy::prelude::*;
use std::error::Error;
use std::fmt;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::Path;

/// Represents a 3D volumetric grid of scalar values
#[derive(Debug, Clone, Resource)]
pub struct VolumetricData {
    /// Grid dimensions (number of voxels in x, y, z)
    pub dimensions: UVec3,

    /// Origin point of the grid in world space (Angstroms)
    pub origin: Vec3,

    /// Voxel spacing vectors (defines grid orientation and spacing)
    /// Each vector represents the step in x, y, z direction respectively
    pub voxel_vectors: [Vec3; 3],

    /// Flat array of scalar values (density, orbital, potential, etc.)
    /// Stored in x-major order: data[x + y*nx + z*nx*ny]
    pub values: Vec<f32>,

    /// Number of atoms in the file (for reference)
    pub n_atoms: usize,

    /// Atomic numbers of atoms
    pub atom_numbers: Vec<u32>,

    /// Atomic positions in Angstroms
    pub atom_positions: Vec<Vec3>,

    /// Optional: atomic charges (from cube file)
    pub atom_charges: Vec<f32>,

    /// Metadata from the cube file
    pub comment_lines: [String; 2],
}

#[derive(Debug)]
pub enum CubeError {
    Io(std::io::Error),
    Parse(String),
    InvalidFormat(String),
}

impl fmt::Display for CubeError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            CubeError::Io(e) => write!(f, "IO error: {}", e),
            CubeError::Parse(s) => write!(f, "Parse error: {}", s),
            CubeError::InvalidFormat(s) => write!(f, "Invalid format: {}", s),
        }
    }
}

impl Error for CubeError {}

impl From<std::io::Error> for CubeError {
    fn from(err: std::io::Error) -> CubeError {
        CubeError::Io(err)
    }
}

impl VolumetricData {
    /// Get the value at a specific voxel coordinate
    #[inline]
    pub fn get_voxel(&self, x: usize, y: usize, z: usize) -> Option<f32> {
        if x >= self.dimensions.x as usize
            || y >= self.dimensions.y as usize
            || z >= self.dimensions.z as usize
        {
            return None;
        }

        let idx = x
            + y * (self.dimensions.x as usize)
            + z * (self.dimensions.x as usize) * (self.dimensions.y as usize);
        self.values.get(idx).copied()
    }

    /// Get the value at a specific voxel coordinate (unchecked)
    #[inline]
    pub fn get_voxel_unchecked(&self, x: usize, y: usize, z: usize) -> f32 {
        let idx = x
            + y * (self.dimensions.x as usize)
            + z * (self.dimensions.x as usize) * (self.dimensions.y as usize);
        self.values[idx]
    }

    /// Set the value at a specific voxel coordinate
    #[inline]
    pub fn set_voxel(&mut self, x: usize, y: usize, z: usize, value: f32) -> bool {
        if x >= self.dimensions.x as usize
            || y >= self.dimensions.y as usize
            || z >= self.dimensions.z as usize
        {
            return false;
        }

        let idx = x
            + y * (self.dimensions.x as usize)
            + z * (self.dimensions.x as usize) * (self.dimensions.y as usize);
        if let Some(v) = self.values.get_mut(idx) {
            *v = value;
            true
        } else {
            false
        }
    }

    /// Convert voxel coordinates to world position
    #[inline]
    pub fn voxel_to_world(&self, x: usize, y: usize, z: usize) -> Vec3 {
        self.origin
            + self.voxel_vectors[0] * x as f32
            + self.voxel_vectors[1] * y as f32
            + self.voxel_vectors[2] * z as f32
    }

    /// Convert world position to voxel coordinates (returns fractional coordinates)
    pub fn world_to_voxel(&self, pos: Vec3) -> Vec3 {
        let relative = pos - self.origin;

        // Build a 3x3 matrix whose columns are the voxel step vectors in world space.
        // This allows handling rotated / skewed grids correctly by solving A * voxel = relative.
        let a = Mat3::from_cols(
            self.voxel_vectors[0],
            self.voxel_vectors[1],
            self.voxel_vectors[2],
        );

        // In this Bevy version `Mat3::inverse()` returns a Mat3 (not an Option).
        // Use the inverse directly. If the matrix is degenerate the result will
        // be whatever the inverse computes (fallback behavior is intentionally
        // simple to avoid panics); keep a safe axis-aligned fallback available if needed.
        let inv = a.inverse();
        inv * relative
    }

    /// Trilinear interpolation of value at a world position
    pub fn sample_trilinear(&self, pos: Vec3) -> Option<f32> {
        let voxel_pos = self.world_to_voxel(pos);

        // Get the integer voxel coordinates
        let x0 = voxel_pos.x.floor() as i32;
        let y0 = voxel_pos.y.floor() as i32;
        let z0 = voxel_pos.z.floor() as i32;

        // Check bounds
        if x0 < 0
            || y0 < 0
            || z0 < 0
            || x0 >= (self.dimensions.x - 1) as i32
            || y0 >= (self.dimensions.y - 1) as i32
            || z0 >= (self.dimensions.z - 1) as i32
        {
            return None;
        }

        let x0 = x0 as usize;
        let y0 = y0 as usize;
        let z0 = z0 as usize;
        let x1 = x0 + 1;
        let y1 = y0 + 1;
        let z1 = z0 + 1;

        // Fractional parts
        let fx = voxel_pos.x.fract();
        let fy = voxel_pos.y.fract();
        let fz = voxel_pos.z.fract();

        // Get the 8 corner values
        let v000 = self.get_voxel_unchecked(x0, y0, z0);
        let v100 = self.get_voxel_unchecked(x1, y0, z0);
        let v010 = self.get_voxel_unchecked(x0, y1, z0);
        let v110 = self.get_voxel_unchecked(x1, y1, z0);
        let v001 = self.get_voxel_unchecked(x0, y0, z1);
        let v101 = self.get_voxel_unchecked(x1, y0, z1);
        let v011 = self.get_voxel_unchecked(x0, y1, z1);
        let v111 = self.get_voxel_unchecked(x1, y1, z1);

        // Trilinear interpolation
        let v00 = v000 * (1.0 - fx) + v100 * fx;
        let v01 = v001 * (1.0 - fx) + v101 * fx;
        let v10 = v010 * (1.0 - fx) + v110 * fx;
        let v11 = v011 * (1.0 - fx) + v111 * fx;

        let v0 = v00 * (1.0 - fy) + v10 * fy;
        let v1 = v01 * (1.0 - fy) + v11 * fy;

        Some(v0 * (1.0 - fz) + v1 * fz)
    }

    /// Get min and max values in the grid
    pub fn value_range(&self) -> (f32, f32) {
        let mut min = f32::INFINITY;
        let mut max = f32::NEG_INFINITY;

        for &value in &self.values {
            if value < min {
                min = value;
            }
            if value > max {
                max = value;
            }
        }

        (min, max)
    }

    /// Get the total grid size in world units
    pub fn grid_size(&self) -> Vec3 {
        Vec3::new(
            self.voxel_vectors[0].length() * self.dimensions.x as f32,
            self.voxel_vectors[1].length() * self.dimensions.y as f32,
            self.voxel_vectors[2].length() * self.dimensions.z as f32,
        )
    }
}

/// Parse a Gaussian cube file
///
/// Cube file format:
/// Line 1: Comment line
/// Line 2: Comment line
/// Line 3: N_atoms Ox Oy Oz (number of atoms, origin coordinates in Bohr)
/// Line 4: N1 v1x v1y v1z (number of voxels and vector for x-axis in Bohr)
/// Line 5: N2 v2x v2y v2z (number of voxels and vector for y-axis in Bohr)
/// Line 6: N3 v3x v3y v3z (number of voxels and vector for z-axis in Bohr)
/// Next N_atoms lines: Atomic_number charge x y z (atom data in Bohr)
/// Remaining lines: Volumetric data (in row-major order)
pub fn parse_cube_file<P: AsRef<Path>>(path: P) -> Result<VolumetricData, CubeError> {
    let file = File::open(path)?;
    let mut reader = BufReader::new(file);
    let mut line = String::new();

    // Bohr to Angstrom conversion factor
    const BOHR_TO_ANGSTROM: f32 = 0.529177;

    // Read comment lines
    reader.read_line(&mut line)?;
    let comment1 = line.trim().to_string();
    line.clear();

    reader.read_line(&mut line)?;
    let comment2 = line.trim().to_string();
    line.clear();

    // Parse atom count and origin
    reader.read_line(&mut line)?;
    let parts: Vec<&str> = line.split_whitespace().collect();
    if parts.len() < 4 {
        return Err(CubeError::InvalidFormat(
            "Invalid atom count line".to_string(),
        ));
    }

    let n_atoms = parts[0]
        .parse::<i32>()
        .map_err(|e| CubeError::Parse(format!("Failed to parse atom count: {}", e)))?;

    // Handle negative atom count (indicates atomic charges are present)
    let _has_charges = n_atoms < 0;
    let n_atoms = n_atoms.abs() as usize;

    let origin = Vec3::new(
        parts[3]
            .parse::<f32>()
            .map_err(|e| CubeError::Parse(format!("Failed to parse origin x: {}", e)))?
            * BOHR_TO_ANGSTROM,
        parts[2]
            .parse::<f32>()
            .map_err(|e| CubeError::Parse(format!("Failed to parse origin y: {}", e)))?
            * BOHR_TO_ANGSTROM,
        parts[1]
            .parse::<f32>()
            .map_err(|e| CubeError::Parse(format!("Failed to parse origin z: {}", e)))?
            * BOHR_TO_ANGSTROM,
    );
    line.clear();

    // Parse voxel dimensions and vectors
    let mut dimensions = UVec3::ZERO;
    let mut voxel_vectors = [Vec3::ZERO; 3];

    for i in 0..3 {
        reader.read_line(&mut line)?;
        let parts: Vec<&str> = line.split_whitespace().collect();
        if parts.len() < 4 {
            return Err(CubeError::InvalidFormat(format!(
                "Invalid voxel vector line {}",
                i
            )));
        }

        let n = parts[0]
            .parse::<u32>()
            .map_err(|e| CubeError::Parse(format!("Failed to parse voxel count: {}", e)))?;

        dimensions[i] = n;

        voxel_vectors[i] =
            Vec3::new(
                parts[3].parse::<f32>().map_err(|e| {
                    CubeError::Parse(format!("Failed to parse voxel vector: {}", e))
                })? * BOHR_TO_ANGSTROM,
                parts[2].parse::<f32>().map_err(|e| {
                    CubeError::Parse(format!("Failed to parse voxel vector: {}", e))
                })? * BOHR_TO_ANGSTROM,
                parts[1].parse::<f32>().map_err(|e| {
                    CubeError::Parse(format!("Failed to parse voxel vector: {}", e))
                })? * BOHR_TO_ANGSTROM,
            );
        line.clear();
    }

    // Parse atom data
    let mut atom_numbers = Vec::with_capacity(n_atoms);
    let mut atom_positions = Vec::with_capacity(n_atoms);
    let mut atom_charges = Vec::with_capacity(n_atoms);

    for _ in 0..n_atoms {
        reader.read_line(&mut line)?;
        let parts: Vec<&str> = line.split_whitespace().collect();
        if parts.len() < 5 {
            return Err(CubeError::InvalidFormat("Invalid atom line".to_string()));
        }

        let atomic_number = parts[0]
            .parse::<u32>()
            .map_err(|e| CubeError::Parse(format!("Failed to parse atomic number: {}", e)))?;

        let charge = parts[1]
            .parse::<f32>()
            .map_err(|e| CubeError::Parse(format!("Failed to parse charge: {}", e)))?;

        let position = Vec3::new(
            parts[2]
                .parse::<f32>()
                .map_err(|e| CubeError::Parse(format!("Failed to parse atom x: {}", e)))?
                * BOHR_TO_ANGSTROM,
            parts[3]
                .parse::<f32>()
                .map_err(|e| CubeError::Parse(format!("Failed to parse atom y: {}", e)))?
                * BOHR_TO_ANGSTROM,
            parts[4]
                .parse::<f32>()
                .map_err(|e| CubeError::Parse(format!("Failed to parse atom z: {}", e)))?
                * BOHR_TO_ANGSTROM,
        );

        atom_numbers.push(atomic_number);
        atom_charges.push(charge);
        atom_positions.push(position);
        line.clear();
    }

    // Parse volumetric data
    let total_voxels = (dimensions.x * dimensions.y * dimensions.z) as usize;
    let mut values = Vec::with_capacity(total_voxels);

    // Heuristic: ORCA may insert a stray "charge mult" line here (two integers, no decimals).
    // Peek the next line and skip it if it looks like that.
    let mut peek_line = String::new();
    let bytes_read = reader.read_line(&mut peek_line)?;
    if bytes_read > 0 {
        let tokens: Vec<&str> = peek_line.split_whitespace().collect();
        let looks_like_orca_charge_mult = tokens.len() == 2
            && tokens
                .iter()
                .all(|t| t.parse::<i32>().is_ok() && !t.contains('.'));
        if !looks_like_orca_charge_mult {
            // Treat this as the first volumetric data line
            for value_str in tokens {
                if values.len() >= total_voxels {
                    break;
                }
                if let Ok(v) = value_str.parse::<f32>() {
                    values.push(v);
                } else {
                    // ignore non-numeric tokens
                }
            }
        } // else: skip the peeked line
        peek_line.clear();
    }

    // Read remaining lines until we have the expected number of voxel values
    for line_result in reader.lines() {
        if values.len() >= total_voxels {
            break;
        }
        let line = line_result?;
        for value_str in line.split_whitespace() {
            if values.len() >= total_voxels {
                break;
            }
            if let Ok(v) = value_str.parse::<f32>() {
                values.push(v);
            } else {
                // ignore any non-numeric tokens that may appear
            }
        }
    }

    if values.len() < total_voxels {
        return Err(CubeError::InvalidFormat(format!(
            "Expected {} values, got {}",
            total_voxels,
            values.len()
        )));
    }

    if values.len() > total_voxels {
        // Defensive: if somehow there are extra parsed numeric tokens, truncate and warn.
        let extra = values.len() - total_voxels;
        values.truncate(total_voxels);
        eprintln!(
            "Warning: cube file contained {} extra numeric value(s); truncating to {} voxels",
            extra, total_voxels
        );
    }

    Ok(VolumetricData {
        dimensions,
        origin,
        voxel_vectors,
        values,
        n_atoms,
        atom_numbers,
        atom_positions,
        atom_charges,
        comment_lines: [comment1, comment2],
    })
}

/// Component to mark entities that should render volumetric data as isosurfaces
#[derive(Component)]
pub struct VolumetricRenderer {
    /// Isovalue for marching cubes
    pub isovalue: f32,

    /// Color used for positive density values (linear RGB as Vec3)
    pub positive_color: Vec3,

    /// Color used for negative density values (linear RGB as Vec3)
    pub negative_color: Vec3,

    /// Whether to use smooth normal averaging (true) or flat per-triangle normals (false)
    pub smooth_normals: bool,
}

impl Default for VolumetricRenderer {
    fn default() -> Self {
        Self {
            isovalue: 0.02,
            // Warm/orange for positive values (linear RGB)
            positive_color: Vec3::new(1.0, 0.5, 0.0),
            // Cool/blue for negative values (linear RGB)
            negative_color: Vec3::new(0.2, 0.6, 1.0),
            // Default to smooth normals
            smooth_normals: false,
        }
    }
}

/// System to load cube files from command line arguments
fn load_cube_files(mut commands: Commands) {
    let args: Vec<String> = std::env::args().collect();

    for path in args.iter().skip(1) {
        if path.ends_with(".cube") {
            match parse_cube_file(path) {
                Ok(data) => {
                    println!("Loaded cube file: {}", path);
                    println!(
                        "  Dimensions: {} x {} x {}",
                        data.dimensions.x, data.dimensions.y, data.dimensions.z
                    );
                    println!("  Origin: {:?}", data.origin);
                    println!("  Atoms: {}", data.n_atoms);

                    let (min, max) = data.value_range();
                    println!("  Value range: {} to {}", min, max);

                    // Insert as resource for other systems to use
                    commands.insert_resource(data);
                }
                Err(e) => {
                    eprintln!("Failed to load cube file {}: {}", path, e);
                }
            }
        }
    }
}

pub struct CubePlugin;

impl Plugin for CubePlugin {
    fn build(&self, app: &mut App) {
        app.add_systems(Startup, load_cube_files);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_voxel_indexing() {
        let data = VolumetricData {
            dimensions: UVec3::new(10, 10, 10),
            origin: Vec3::ZERO,
            voxel_vectors: [Vec3::X, Vec3::Y, Vec3::Z],
            values: vec![0.0; 1000],
            n_atoms: 0,
            atom_numbers: vec![],
            atom_positions: vec![],
            atom_charges: vec![],
            comment_lines: ["test".to_string(), "test".to_string()],
        };

        assert_eq!(data.get_voxel(0, 0, 0), Some(0.0));
        assert_eq!(data.get_voxel(9, 9, 9), Some(0.0));
        assert_eq!(data.get_voxel(10, 0, 0), None);
    }

    #[test]
    fn test_voxel_to_world() {
        let data = VolumetricData {
            dimensions: UVec3::new(10, 10, 10),
            origin: Vec3::new(1.0, 2.0, 3.0),
            voxel_vectors: [Vec3::X * 0.5, Vec3::Y * 0.5, Vec3::Z * 0.5],
            values: vec![0.0; 1000],
            n_atoms: 0,
            atom_numbers: vec![],
            atom_positions: vec![],
            atom_charges: vec![],
            comment_lines: ["test".to_string(), "test".to_string()],
        };

        let world_pos = data.voxel_to_world(2, 4, 6);
        assert_eq!(world_pos, Vec3::new(2.0, 4.0, 6.0));
    }
}