spintronics 0.3.0

Pure Rust library for simulating spin dynamics, spin current generation, and conversion phenomena in magnetic and topological materials
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
//! OOMMF Vector Field (OVF) Format Support
//!
//! This module implements reading and writing of OVF files, the standard
//! format used by OOMMF (Object Oriented MicroMagnetic Framework) and
//! other micromagnetic simulation tools.
//!
//! ## OVF Format Specification
//!
//! OVF files can be in text or binary format and contain:
//! - Header with metadata (mesh dimensions, units, etc.)
//! - Vector field data (typically magnetization)
//!
//! ## Supported Versions
//! - OVF 1.0 (text and binary)
//! - OVF 2.0 (text and binary)
//!
//! ## References
//! - OOMMF User's Guide: <https://math.nist.gov/oommf/>
//! - OVF Format Specification: <https://math.nist.gov/oommf/doc/userguide20a3/userguide/OVF_2.0_format.html>

use std::fs::File;
use std::io::{BufRead, BufReader, BufWriter, Write};
use std::path::Path;

use crate::vector3::Vector3;

/// OVF file format version and encoding
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum OvfFormat {
    /// OVF 1.0 text format
    Text1_0,
    /// OVF 2.0 text format
    Text2_0,
    /// OVF 1.0 binary format (4-byte floats)
    Binary4_1_0,
    /// OVF 2.0 binary format (4-byte floats)
    Binary4_2_0,
    /// OVF 2.0 binary format (8-byte doubles)
    Binary8_2_0,
}

/// OVF data structure
#[derive(Debug, Clone)]
pub struct OvfData {
    /// Title/description
    pub title: String,

    /// Mesh dimensions (nx, ny, nz)
    pub mesh_size: (usize, usize, usize),

    /// Physical mesh dimensions in meters (xsize, ysize, zsize)
    pub mesh_physical_size: (f64, f64, f64),

    /// Cell size in meters (dx, dy, dz)
    pub cell_size: (f64, f64, f64),

    /// Value dimension (3 for vector field)
    pub value_dim: usize,

    /// Value units (e.g., "A/m" for magnetization)
    pub value_units: String,

    /// Value labels (e.g., ["m_x", "m_y", "m_z"])
    pub value_labels: Vec<String>,

    /// Vector field data (flattened: [v0_x, v0_y, v0_z, v1_x, v1_y, v1_z, ...])
    pub data: Vec<Vector3<f64>>,
}

impl OvfData {
    /// Create new OVF data structure
    pub fn new(nx: usize, ny: usize, nz: usize, xsize: f64, ysize: f64, zsize: f64) -> Self {
        let mesh_size = (nx, ny, nz);
        let mesh_physical_size = (xsize, ysize, zsize);
        let cell_size = (xsize / nx as f64, ysize / ny as f64, zsize / nz as f64);

        Self {
            title: "Magnetization field".to_string(),
            mesh_size,
            mesh_physical_size,
            cell_size,
            value_dim: 3,
            value_units: "A/m".to_string(),
            value_labels: vec!["m_x".to_string(), "m_y".to_string(), "m_z".to_string()],
            data: vec![Vector3::new(0.0, 0.0, 0.0); nx * ny * nz],
        }
    }

    /// Set vector at position (i, j, k)
    pub fn set_vector(&mut self, i: usize, j: usize, k: usize, v: Vector3<f64>) {
        let (nx, ny, _nz) = self.mesh_size;
        let idx = i + j * nx + k * nx * ny;
        if idx < self.data.len() {
            self.data[idx] = v;
        }
    }

    /// Get vector at position (i, j, k)
    pub fn get_vector(&self, i: usize, j: usize, k: usize) -> Option<Vector3<f64>> {
        let (nx, ny, _nz) = self.mesh_size;
        let idx = i + j * nx + k * nx * ny;
        self.data.get(idx).copied()
    }
}

/// OVF file writer
pub struct OvfWriter {
    format: OvfFormat,
}

impl OvfWriter {
    /// Create new OVF writer with specified format
    pub fn new(format: OvfFormat) -> Self {
        Self { format }
    }

    /// Write OVF data to file
    pub fn write<P: AsRef<Path>>(&self, path: P, data: &OvfData) -> std::io::Result<()> {
        match self.format {
            OvfFormat::Text2_0 => self.write_text_2_0(path, data),
            OvfFormat::Text1_0 => self.write_text_1_0(path, data),
            _ => Err(std::io::Error::new(
                std::io::ErrorKind::Unsupported,
                "Binary OVF format not yet implemented",
            )),
        }
    }

    /// Write OVF 2.0 text format
    fn write_text_2_0<P: AsRef<Path>>(&self, path: P, data: &OvfData) -> std::io::Result<()> {
        let file = File::create(path)?;
        let mut writer = BufWriter::new(file);

        // Write header
        writeln!(writer, "# OOMMF OVF 2.0")?;
        writeln!(writer, "#")?;
        writeln!(writer, "# Segment count: 1")?;
        writeln!(writer, "#")?;
        writeln!(writer, "# Begin: Segment")?;
        writeln!(writer, "# Begin: Header")?;
        writeln!(writer, "#")?;
        writeln!(writer, "# Title: {}", data.title)?;
        writeln!(writer, "# Desc: Magnetization field data")?;
        writeln!(writer, "#")?;
        writeln!(writer, "# meshtype: rectangular")?;
        writeln!(writer, "# meshunit: m")?;
        writeln!(writer, "#")?;

        let (nx, ny, nz) = data.mesh_size;
        writeln!(writer, "# xnodes: {}", nx)?;
        writeln!(writer, "# ynodes: {}", ny)?;
        writeln!(writer, "# znodes: {}", nz)?;
        writeln!(writer, "#")?;

        let (xsize, ysize, zsize) = data.mesh_physical_size;
        writeln!(writer, "# xmin: 0")?;
        writeln!(writer, "# ymin: 0")?;
        writeln!(writer, "# zmin: 0")?;
        writeln!(writer, "# xmax: {}", xsize)?;
        writeln!(writer, "# ymax: {}", ysize)?;
        writeln!(writer, "# zmax: {}", zsize)?;
        writeln!(writer, "#")?;

        writeln!(writer, "# valuedim: {}", data.value_dim)?;
        writeln!(
            writer,
            "# valuelabels: {} {} {}",
            data.value_labels[0], data.value_labels[1], data.value_labels[2]
        )?;
        writeln!(
            writer,
            "# valueunits: {} {} {}",
            data.value_units, data.value_units, data.value_units
        )?;
        writeln!(writer, "#")?;
        writeln!(writer, "# End: Header")?;
        writeln!(writer, "#")?;
        writeln!(writer, "# Begin: Data Text")?;

        // Write data
        for v in &data.data {
            writeln!(writer, " {:.17e}  {:.17e}  {:.17e}", v.x, v.y, v.z)?;
        }

        writeln!(writer, "# End: Data Text")?;
        writeln!(writer, "# End: Segment")?;

        Ok(())
    }

    /// Write OVF 1.0 text format
    fn write_text_1_0<P: AsRef<Path>>(&self, path: P, data: &OvfData) -> std::io::Result<()> {
        let file = File::create(path)?;
        let mut writer = BufWriter::new(file);

        // OVF 1.0 header
        writeln!(writer, "# OOMMF: rectangular mesh v1.0")?;
        writeln!(writer, "# Segment count: 1")?;
        writeln!(writer, "# Begin: Segment")?;
        writeln!(writer, "# Begin: Header")?;
        writeln!(writer, "# Title: {}", data.title)?;
        writeln!(writer, "# Desc: Magnetization field data")?;

        let (nx, ny, nz) = data.mesh_size;
        let (dx, dy, dz) = data.cell_size;

        writeln!(writer, "# meshunit: m")?;
        writeln!(writer, "# meshtype: rectangular")?;
        writeln!(writer, "# xbase: {}", dx / 2.0)?;
        writeln!(writer, "# ybase: {}", dy / 2.0)?;
        writeln!(writer, "# zbase: {}", dz / 2.0)?;
        writeln!(writer, "# xstepsize: {}", dx)?;
        writeln!(writer, "# ystepsize: {}", dy)?;
        writeln!(writer, "# zstepsize: {}", dz)?;
        writeln!(writer, "# xnodes: {}", nx)?;
        writeln!(writer, "# ynodes: {}", ny)?;
        writeln!(writer, "# znodes: {}", nz)?;
        writeln!(writer, "# xmin: 0")?;
        writeln!(writer, "# ymin: 0")?;
        writeln!(writer, "# zmin: 0")?;
        writeln!(writer, "# xmax: {}", data.mesh_physical_size.0)?;
        writeln!(writer, "# ymax: {}", data.mesh_physical_size.1)?;
        writeln!(writer, "# zmax: {}", data.mesh_physical_size.2)?;
        writeln!(writer, "# valuedim: {}", data.value_dim)?;
        writeln!(writer, "# valuelabels: m_x m_y m_z")?;
        writeln!(writer, "# valueunits: A/m A/m A/m")?;
        writeln!(writer, "# End: Header")?;
        writeln!(writer, "# Begin: data text")?;

        // Write data
        for v in &data.data {
            writeln!(writer, "{:.17e} {:.17e} {:.17e}", v.x, v.y, v.z)?;
        }

        writeln!(writer, "# End: data text")?;
        writeln!(writer, "# End: Segment")?;

        Ok(())
    }
}

/// OVF file reader
pub struct OvfReader;

impl OvfReader {
    /// Read OVF file
    pub fn read<P: AsRef<Path>>(path: P) -> std::io::Result<OvfData> {
        let file = File::open(path)?;
        let reader = BufReader::new(file);

        let mut lines = reader.lines();
        let first_line = lines
            .next()
            .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::InvalidData, "Empty file"))??;

        if first_line.starts_with("# OOMMF OVF 2.0") {
            Self::read_ovf_2_0(lines)
        } else if first_line.starts_with("# OOMMF: rectangular mesh v1.0") {
            Self::read_ovf_1_0(lines)
        } else {
            Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "Unknown OVF format",
            ))
        }
    }

    /// Read OVF 2.0 format
    fn read_ovf_2_0<I>(lines: I) -> std::io::Result<OvfData>
    where
        I: Iterator<Item = std::io::Result<String>>,
    {
        let mut title = String::new();
        let mut nx = 0;
        let mut ny = 0;
        let mut nz = 0;
        let mut xmax = 0.0;
        let mut ymax = 0.0;
        let mut zmax = 0.0;
        let mut value_dim = 3;
        let mut in_data_section = false;
        let mut data = Vec::new();

        for line in lines {
            let line = line?;
            let line = line.trim();

            if line.starts_with("# Title:") {
                if let Some(rest) = line.strip_prefix("# Title:") {
                    title = rest.trim().to_string();
                }
            } else if line.starts_with("# xnodes:") {
                nx = line
                    .strip_prefix("# xnodes:")
                    .unwrap_or("")
                    .trim()
                    .parse()
                    .unwrap_or(0);
            } else if line.starts_with("# ynodes:") {
                ny = line
                    .strip_prefix("# ynodes:")
                    .unwrap_or("")
                    .trim()
                    .parse()
                    .unwrap_or(0);
            } else if line.starts_with("# znodes:") {
                nz = line
                    .strip_prefix("# znodes:")
                    .unwrap_or("")
                    .trim()
                    .parse()
                    .unwrap_or(0);
            } else if line.starts_with("# xmax:") {
                xmax = line
                    .strip_prefix("# xmax:")
                    .unwrap_or("")
                    .trim()
                    .parse()
                    .unwrap_or(0.0);
            } else if line.starts_with("# ymax:") {
                ymax = line
                    .strip_prefix("# ymax:")
                    .unwrap_or("")
                    .trim()
                    .parse()
                    .unwrap_or(0.0);
            } else if line.starts_with("# zmax:") {
                zmax = line
                    .strip_prefix("# zmax:")
                    .unwrap_or("")
                    .trim()
                    .parse()
                    .unwrap_or(0.0);
            } else if line.starts_with("# valuedim:") {
                value_dim = line
                    .strip_prefix("# valuedim:")
                    .unwrap_or("")
                    .trim()
                    .parse()
                    .unwrap_or(3);
            } else if line.starts_with("# Begin: Data Text") {
                in_data_section = true;
            } else if line.starts_with("# End: Data Text") {
                break;
            } else if in_data_section && !line.starts_with('#') && !line.is_empty() {
                let parts: Vec<&str> = line.split_whitespace().collect();
                if parts.len() >= 3 {
                    let x: f64 = parts[0].parse().unwrap_or(0.0);
                    let y: f64 = parts[1].parse().unwrap_or(0.0);
                    let z: f64 = parts[2].parse().unwrap_or(0.0);
                    data.push(Vector3::new(x, y, z));
                }
            }
        }

        let mut ovf_data = OvfData::new(nx, ny, nz, xmax, ymax, zmax);
        ovf_data.title = title;
        ovf_data.value_dim = value_dim;
        ovf_data.data = data;

        Ok(ovf_data)
    }

    /// Read OVF 1.0 format
    fn read_ovf_1_0<I>(lines: I) -> std::io::Result<OvfData>
    where
        I: Iterator<Item = std::io::Result<String>>,
    {
        let mut title = String::new();
        let mut nx = 0;
        let mut ny = 0;
        let mut nz = 0;
        let mut xmax = 0.0;
        let mut ymax = 0.0;
        let mut zmax = 0.0;
        let mut in_data_section = false;
        let mut data = Vec::new();

        for line in lines {
            let line = line?;
            let line = line.trim();

            if line.starts_with("# Title:") {
                if let Some(rest) = line.strip_prefix("# Title:") {
                    title = rest.trim().to_string();
                }
            } else if line.starts_with("# xnodes:") {
                nx = line
                    .strip_prefix("# xnodes:")
                    .unwrap_or("")
                    .trim()
                    .parse()
                    .unwrap_or(0);
            } else if line.starts_with("# ynodes:") {
                ny = line
                    .strip_prefix("# ynodes:")
                    .unwrap_or("")
                    .trim()
                    .parse()
                    .unwrap_or(0);
            } else if line.starts_with("# znodes:") {
                nz = line
                    .strip_prefix("# znodes:")
                    .unwrap_or("")
                    .trim()
                    .parse()
                    .unwrap_or(0);
            } else if line.starts_with("# xmax:") {
                xmax = line
                    .strip_prefix("# xmax:")
                    .unwrap_or("")
                    .trim()
                    .parse()
                    .unwrap_or(0.0);
            } else if line.starts_with("# ymax:") {
                ymax = line
                    .strip_prefix("# ymax:")
                    .unwrap_or("")
                    .trim()
                    .parse()
                    .unwrap_or(0.0);
            } else if line.starts_with("# zmax:") {
                zmax = line
                    .strip_prefix("# zmax:")
                    .unwrap_or("")
                    .trim()
                    .parse()
                    .unwrap_or(0.0);
            } else if line.starts_with("# Begin: data text") {
                in_data_section = true;
            } else if line.starts_with("# End: data text") {
                break;
            } else if in_data_section && !line.starts_with('#') && !line.is_empty() {
                let parts: Vec<&str> = line.split_whitespace().collect();
                if parts.len() >= 3 {
                    let x: f64 = parts[0].parse().unwrap_or(0.0);
                    let y: f64 = parts[1].parse().unwrap_or(0.0);
                    let z: f64 = parts[2].parse().unwrap_or(0.0);
                    data.push(Vector3::new(x, y, z));
                }
            }
        }

        let mut ovf_data = OvfData::new(nx, ny, nz, xmax, ymax, zmax);
        ovf_data.title = title;
        ovf_data.data = data;

        Ok(ovf_data)
    }
}

#[cfg(test)]
mod tests {
    use std::f64::consts::PI;

    use super::*;

    #[test]
    fn test_ovf_data_creation() {
        let ovf = OvfData::new(10, 10, 1, 1e-6, 1e-6, 1e-9);

        assert_eq!(ovf.mesh_size, (10, 10, 1));
        assert_eq!(ovf.data.len(), 100);
        assert_eq!(ovf.value_dim, 3);
    }

    #[test]
    fn test_ovf_set_get_vector() {
        let mut ovf = OvfData::new(5, 5, 1, 5e-7, 5e-7, 1e-9);

        let v = Vector3::new(1.0, 0.0, 0.0);
        ovf.set_vector(2, 3, 0, v);

        let retrieved = ovf
            .get_vector(2, 3, 0)
            .expect("vector at (2,3,0) should exist");
        assert_eq!(retrieved.x, 1.0);
        assert_eq!(retrieved.y, 0.0);
        assert_eq!(retrieved.z, 0.0);
    }

    #[test]
    fn test_ovf_write_read_2_0() {
        let mut ovf = OvfData::new(3, 3, 1, 3e-9, 3e-9, 1e-9);
        ovf.title = "Test data".to_string();

        // Set some test vectors
        for i in 0..3 {
            for j in 0..3 {
                let angle = (i + j) as f64 * PI / 4.0;
                let v = Vector3::new(angle.cos(), angle.sin(), 0.0);
                ovf.set_vector(i, j, 0, v);
            }
        }

        // Write to file
        let writer = OvfWriter::new(OvfFormat::Text2_0);
        let path = "/tmp/test_ovf_2_0.ovf";
        writer
            .write(path, &ovf)
            .expect("OVF 2.0 write should succeed");

        // Read back
        let ovf_read = OvfReader::read(path).expect("OVF 2.0 read should succeed");

        assert_eq!(ovf_read.mesh_size, (3, 3, 1));
        assert_eq!(ovf_read.data.len(), 9);
        assert_eq!(ovf_read.title, "Test data");
    }

    #[test]
    fn test_ovf_write_1_0() {
        let mut ovf = OvfData::new(2, 2, 1, 2e-9, 2e-9, 1e-9);
        ovf.title = "OVF 1.0 test".to_string();

        ovf.set_vector(0, 0, 0, Vector3::new(1.0, 0.0, 0.0));
        ovf.set_vector(1, 1, 0, Vector3::new(0.0, 1.0, 0.0));

        let writer = OvfWriter::new(OvfFormat::Text1_0);
        let path = "/tmp/test_ovf_1_0.ovf";
        writer
            .write(path, &ovf)
            .expect("OVF 1.0 write should succeed");

        let ovf_read = OvfReader::read(path).expect("OVF 1.0 read should succeed");
        assert_eq!(ovf_read.mesh_size, (2, 2, 1));
    }
}