import 'dart:math';

import 'package:surface_tension_calculator/scripts/rk4.dart';

/// ========== FINDING OPTIMAL PARAMETERS USING MINIMZATION ==========
List<double> optimizeParameters(
  List<double> posEdgePoints,
  List<double> negEdgePoints,
  double aGuessRadCurv,
  double bGuessShapeFact,
  double xGuess,
  double tGuessAngle,
) {
  var rk4PosTable = makeRK4Table(posEdgePoints);
  var rk4NegTable = makeRK4Table(negEdgePoints);

  double msd(List<double> args) {
    double aRadCurv = args[0];
    double bShapeFact = args[1];
    double x = args[2];
    double tAngle = args[3];

    rk4PosTable[0][3] = x;
    rk4PosTable[0][4] = tAngle;
    rk4NegTable[0][3] = x;
    rk4NegTable[0][4] = tAngle;
    double fTotalDiffSquared =
        bashforthAdamsRK4(rk4PosTable, aRadCurv, bShapeFact, 1.0) +
        bashforthAdamsRK4(rk4NegTable, aRadCurv, bShapeFact, -1.0);

    return sqrt(
      fTotalDiffSquared / (posEdgePoints.length + negEdgePoints.length),
    );
  }

  var optResult = minimize(msd, [
    aGuessRadCurv,
    bGuessShapeFact,
    xGuess,
    tGuessAngle,
  ]);
  if (optResult.success) {
    print("minimization success");
    return [optResult.fun.toDouble()] + optResult.x;
  } else {
    return [9999999, 0, 0, 0, 0];
  }
}
