Created
August 6, 2019 10:51
-
-
Save DomiDre/1b3c1724161c5bc21ae94c87fe1a4317 to your computer and use it in GitHub Desktop.
A short rust script to execute a fit using the rusfun crate
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use ndarray::{array, Array1}; | |
use rusfun::{curve_fit, func1d, size_distribution}; | |
use std::fs::File; | |
use std::io::{BufRead, BufReader, Result}; | |
fn main() { | |
// read data | |
let (x, y, sy) = read_column_file("./gaussianData.xye").unwrap_or_else(|err| { | |
eprintln!("Error reading data file: {}", err); | |
std::process::exit(1); | |
}); | |
// define initial parameters | |
let p = array![20.0, 3.0, 0.2, 0.0]; | |
let model = size_distribution::gaussian; | |
let model_function = func1d::Func1D::new(&p, &x, model); | |
// fit data | |
let t0 = std::time::Instant::now(); | |
let mut minimizer = curve_fit::Minimizer::init(&model_function, &y, &sy, 1.0); | |
minimizer.minimize(10 * p.len()); | |
println!("Execution time: {} microsecs", t0.elapsed().as_micros()); | |
minimizer.report(); | |
} | |
fn read_column_file(filename: &str) -> Result<(Array1<f64>, Array1<f64>, Array1<f64>)> { | |
let mut x: Vec<f64> = Vec::new(); | |
let mut y: Vec<f64> = Vec::new(); | |
let mut sy: Vec<f64> = Vec::new(); | |
let reader = BufReader::new(File::open(filename).expect("Cannot open file")); | |
for line in reader.lines() { | |
let unwrapped_line = line.unwrap(); | |
if unwrapped_line.starts_with('#') { | |
continue | |
} | |
let splitted_line = unwrapped_line.split_whitespace(); | |
for (i, number) in splitted_line.enumerate() { | |
match i { | |
0 => x.push(number.parse().unwrap()), | |
1 => y.push(number.parse().unwrap()), | |
2 => sy.push(number.parse().unwrap()), | |
_ => {} | |
} | |
} | |
} | |
let x = Array1::from_vec(x); | |
let y = Array1::from_vec(y); | |
let sy = Array1::from_vec(sy); | |
Ok((x, y, sy)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment