Hi,
I am trying to write a molecular dynamics simulation. I use vectors for position and other
variables representing the particle model type.
In order to visualize the positions I have to export the data to a file specially to a vtk format.
Similar to this
vtk DataFile Version 3.0
'Time: 0.140000 s'
ASCII
DATASET UNSTRUCTURED_GRID
POINTS 1000 FLOAT
0.001000 0.001000 0.0
0.007072 0.001115 0.0
0.009918 0.001752 0.0
0.013555 0.001456 0.0
0.016900 0.001530 0.0
0.023293 0.001219 0.0
0.028694 0.001030 0.0
0.031127 0.002262 0.0
Well I have tried few ways, But I am unable to get it working. I need probably
simplest way to write a vector to file, or an int to a file, then I will loop
in my vector and write it in a specified manner.
Thank you.
1 Like
Can you share some code of what you have tried?
Here is the sample code.
use std::io::Write;
use std::io::prelude::*;
use std::fs::File;
fn main() {
let data = vec![1., 2., 3.];
let mut f = File::create("output.vtk").expect("Unable to create file");
for i in &data{
f.write_all((*i)).expect("Unable to write data");
}
}
what's the issue with it?
Are you trying to write the data as binary or ASCII? The file you showed in the original post is ASCII but here you’re writing raw byte representation.
1 Like
I think @vitalyd has a point here. As it is you're trying to write the bytes in your vector to the file, while in the sample you've shown formatting has been applied (thing printf
) to turn those numbers into ascii characters people can read. Have you had a look at the write!()
macro?
fn main() {
let data = vec![1., 2., 3.];
let mut f = File::create("output.vtk").expect("Unable to create file");
for i in &data{
write!(f, "{} {} {}", x, y, z);
}
}
You'll probably also want to package each particle up into its own struct so you aren't implicitly depending on indices into a Vec<f32>
to know what goes where.
struct Particle {
x: f32,
y: f32,
z: f32,
}
let data = vec![
Particle { x: 1.0, y: 2.0, z: 3.0},
];
let mut f = File::create("output.vtk")?
for thing in &data {
write!(f, "{} {} {}", thing.x, thing.y, thing.z)?;
}
2 Likes