smart_arrays_lmfit 2.0.6 copy "smart_arrays_lmfit: ^2.0.6" to clipboard
smart_arrays_lmfit: ^2.0.6 copied to clipboard

outdated

Fits (x, y) data given as arrays to a specified model function using the Levenberg-Marquardt algorithm.

example/example.dart

// Copyright (c) 2019, Dr. Bruno Guigas. All rights reserved. Use of this source
// code is governed by a BSD-style license that can be found in the LICENSE file.
import 'package:smart_arrays_lmfit/smart_arrays_lmfit.dart';
import 'dart:math' as math;

/// Demonstrates fitting data to a Gaussian.
main() async {
  // Define the "fit model" to which a data array should be fitted: a Gaussian
  double fitFunctionGAUSS(double x, List<double> params) {
    // amplitude, center, width, y offset:
    double a = params[0], c = params[1], w = params[2], y0 = params[3];
    final FGAUSS = 4 * math.log(2); // normalization constant
    return y0 + a * math.exp(-FGAUSS * ((x - c) / w) * ((x - c) / w));
  }

  // Compute "experimental data" to be fitted to a Gaussian:
  // We compute an exact Gaussian, then add some random noise to it.
  final int NPOINTS = 50;
  double a = 100, c = 25, w = 10, y0 = 20;
  final List<double> GAUSS_PARS = [a, c, w, y0];
  List<double> xvals = List(NPOINTS), yvals = List(NPOINTS);
  math.Random rand = math.Random();
  for (int i = 0; i < NPOINTS; i++) {
    double x = i.toDouble();
    xvals[i] = x;
    yvals[i] = fitFunctionGAUSS(x, GAUSS_PARS);
    double noise = (2 * rand.nextDouble() - 1.0) * yvals[i] * 0.005;
    yvals[i] += noise;
  }

  // initial parameters for the fit, derived from the exact parameters
  final List<double> INITIAL_PARS = [a * 0.8, c * 0.9, w * 1.2, y0];

  // use these fitting options
  Map<String, List<String>> fitOptions = {
    LMfit.FIT_OPT_TOLERANCE: ["1e-10"],
    LMfit.PARAM_DELTA_CONVERGE: ["0.0001"],
    LMfit.MAX_ITERATIONS: ["200"],
    LMfit.PAR_INFO: [null, null, null, "y0 fixed null null"]
  };

  // start fitting the "experimental data" to a Gaussian
  LMfit lm = LMfit();
  Map<String, List<String>> fitResult =
      await lm.lmfit(fitFunctionGAUSS, xvals, yvals, INITIAL_PARS, fitOptions);

  // print the fitting result
  print("exact Gaussian params=${GAUSS_PARS}");
  print("inital params=${fitResult[LMfit.INITIAL_PARAMS]}");
  print("fitted params=${fitResult[LMfit.PARAMS]}");
  print("iterations=${fitResult[LMfit.ITERATIONS][0]}");
  print("stop reason=${fitResult[LMfit.STOP_REASON][0]}");
  print("time [milliseconds]=${fitResult[LMfit.TIME][0]}");
  print("chi squared=${fitResult[LMfit.CHI2][0]}");
}
1
likes
0
points
17
downloads

Publisher

verified publisherhiveright.tech

Weekly Downloads

Fits (x, y) data given as arrays to a specified model function using the Levenberg-Marquardt algorithm.

Homepage

License

unknown (license)

Dependencies

build_runner, build_web_compilers, pedantic, smart_arrays_numerics

More

Packages that depend on smart_arrays_lmfit