Skip to content

Instantly share code, notes, and snippets.

@DomiDre
Created August 6, 2019 12:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DomiDre/88949d95790169fb2eec6a1a98688a67 to your computer and use it in GitHub Desktop.
Save DomiDre/88949d95790169fb2eec6a1a98688a67 to your computer and use it in GitHub Desktop.
Fit of a Gaussian model to data using the ml-levenberg-marquardt package
var LM = require('ml-levenberg-marquardt');
var fs = require('fs');
function gaussianFunction([A, mu, sigma, c]) {
return (x) => A * Math.exp(-0.5*((x-mu)/sigma)**2) + c;
}
fs.readFile('../gaussianData.xye', 'utf8', async function(err, data) {
if (err) throw err;
const lines = String(data).split('\n');
// initialize empty lists for the columns
const x = [];
const y = [];
const sy = [];
// check lines for first non-empty line that's not a comment and see
// if it has 2 or 3 columns
let has_three_cols = false;
for (let line of lines) {
const trimmed_line = line.trim();
// ignore comments
if (trimmed_line.startsWith('#')) continue
// ignore empty lines
if (trimmed_line.length > 0) {
const splitted_line = trimmed_line.split(/\s+/);
has_three_cols = splitted_line.length >= 3;
break;
}
}
for (let line of lines) {
const trimmed_line = line.trim();
// ignore comments
if (trimmed_line.startsWith('#')) continue
// split line at white-spaces or tabs
const splitted_line = trimmed_line.split(/\s+/)
if (splitted_line.length >= 2) {
x.push(Number(splitted_line[0]));
y.push(Number(splitted_line[1]));
if (has_three_cols) {
if (splitted_line.length >= 3) {
sy.push(Number(splitted_line[2]));
} else {
throw "File identified as 3 column file has one line with only 2 columns"
}
}
}
}
fitData(x,y,sy)
});
function fitData(x,y,sy) {
let data = {
x: x,
y: y
};
let initialValues = [
20, 3, 0.2, 0
];
const options = {
damping: 1.5,
initialValues: initialValues,
gradientDifference: 10e-2,
maxIterations: 100,
errorTolerance: 10e-3
};
t0 = process.hrtime();
let fittedParams = LM(data, gaussianFunction, options);
t1 = process.hrtime();
console.log((t1[0]-t0[0])*1000 + (t1[1] - t0[1])/1e6, " ms");
console.log(fittedParams);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment