private void stopamo(float[] pb) { int i, j; covar = new float[0, 0]; float[,] alpha = new float[0, 0]; float alamda; chisq = 0; f = new DerivFunction(f0); if (f is DerivFunction) { ((DerivFunction)f).fast = false; } for (i = 0, j = 0; i < f.p.Length; i++) { if (ip0[i]) { f.p[i] = pb[j++]; } } alamda = -1; mrqmin(ip0, ref covar, ref alpha, ref chisq, ref alamda); alamda = 0; mrqmin(ip0, ref covar, ref alpha, ref chisq, ref alamda); ip0 = null; p0 = null; ptry = null; }
public PointN FindMin(double eps) { int dimensionsCount = x0.Coordinates.Count; int k = 0; double ak = 0.0; PointN xk = x0; while (true) { VectorN gradFxk = Gradient.Calculate(funcND, xk); // Градиент все время прыгает во все стороны, а xk все наращивается Log.Add(String.Format("Grad(F({0, -23})) = {1, -25}", xk, gradFxk)); if (gradFxk.Length <= eps) { return(xk); } Function1D func1D = (double alpha) => { return(funcND(xk - gradFxk * alpha)); }; // TODO alpha >= 0 ak = OneDimensionalMinimization.FindMin(func1D, ak, eps); // TODO негибкая стратегия выбора eps Log.Add(String.Format("ak = {0}", ak)); xk = xk - gradFxk * ak; k++; Log.Add("==================Next Iteration===================="); } }
//Конструктор protected OneDimMethod(Function1D f, Function1D df, double eps, string name, int maxIterations = 50) { Name = name; F = f; Df = df; Eps = eps; MaxIterations = maxIterations; }
private void cosClick(object sender, System.EventArgs e) { Function1D cos = new Function1D(); cos.source = "return cos(x);"; cos.Compile(true); cos.Color = Color.Red; cos.lineWidth = 2; cos.lineStyle = DashStyle.Dash; graph.Model.Items.Add(cos); graph.Invalidate(); }
// Это хорошая идея - выносить параметры вроде eps сюда // Можно добавить список строк List<String> // И выводить в него информацию по алгоритму // Затем, в output мы берем его и выводим на экран (по желанию) public PointNMathNet FindMin(double eps) { int k = 0; PointNMathNet xk = x0; // x(k) PointNMathNet xk_1 = x0; // x(k-1) Matrix <double> Hk = H0.Clone(); // Квазиньютоновская матрицы double ak = 0.0; // Вспомогательные вектора VectorNMathNet sk = VectorNMathNet.Build.Dense(n); VectorNMathNet yk = VectorNMathNet.Build.Dense(n); while (true) { VectorNMathNet gradient = Gradient.Calculate(funcND, xk); Log.Add(String.Format("Grad(F(\n{0, -23})) = \n{1, -25}", xk, gradient)); // TODO: некрасивый вывод if (gradient.L2Norm() <= eps) // градиент слишком мал, максимум очень близко { return(xk); } if (k != 0) { sk = xk - xk_1; //Log.Add(String.Format("sk:\n{0}", sk)); Matrix <double> m_sk = sk.ToColumnMatrix(); Matrix <double> m_sk_t = m_sk.Transpose(); yk = Gradient.Calculate(funcND, xk) - Gradient.Calculate(funcND, xk_1); // TODO Один из членов этого вектора становится слишком мал (или Hk или M_yk_t) //Log.Add(String.Format("yk:\n{0}", yk)); Matrix <double> m_yk = yk.ToColumnMatrix(); Matrix <double> m_yk_t = m_yk.Transpose(); Hk = Hk - ((Hk * m_yk * m_yk_t * Hk) / (m_yk_t * Hk * m_yk)[0, 0]) + ((m_sk * m_sk_t)[0, 0] / (m_yk_t * m_sk)[0, 0]); Log.Add(String.Format("Hk:\n{0}", Hk)); } VectorNMathNet pk = -Hk * gradient; Function1D func1D = (double alpha) => { return(funcND((xk + pk * alpha))); }; ak = OneDimensionalMinimization.FindMin(func1D, ak, eps); Log.Add(String.Format("ak = {0}", ak)); // Инкремент xk_1 = xk; xk = xk + ak * pk; k++; Log.Add("==================Next Iteration===================="); } }
private void MarquardtStart() { chisq = 0; oldchisq = -1e10F; alamda = -1; NEval = 0; if (f0.p.Length > 0 && f0.dfdp.Length == 0) { f = new DerivFunction(f0); } else { f = f0; } ThreadPool.QueueUserWorkItem(new WaitCallback(MarquardtThread)); //Do(); }
public float[] RK4(Function1D func, float initial, float dx, int N) { float[] sol = new float[N]; sol[0] = initial; for (int i = 0; i < N - 1; i++) { float k1 = dx * func(sol[i]); float k2 = dx * func(sol[i] + 0.5f * k1); float k3 = dx * func(sol[i] + 0.5f * k2); float k4 = dx * func(sol[i] + k3); sol[i + 1] = sol[i] + (k1 + 2 * k2 + 2 * k3 + k4) / 6; } return(sol); }
private void gaussClick(object sender, System.EventArgs e) { Function1D gauss = new Function1D(); //Here the source accesses the array p, an array of function parameters. //When you compile the item, the size of p is automatically set to the //highest element referred to in the source. gauss.source = "double arg = (x-p[0])/p[1]; return p[2]*exp(-arg*arg);"; gauss.Compile(true); gauss.p[0] = 1; gauss.p[1] = 1; gauss.p[2] = 4; graph.Model.Items.Add(gauss); graph.Invalidate(); }
private void sinClick(object sender, System.EventArgs e) { Function1D sin = new Function1D(); //The source represents the body of the following function: //double[] p, dfdp; //double f(double x) { // ... //} sin.source = "return sin(x);"; sin.Compile(true); sin.Color = Color.Blue; sin.lineWidth = 2; graph.Model.Items.Add(sin); graph.Invalidate(); }
private void NelderMeadStart(bool T0) { const int TFAC = 3; chisq = 0; f = f0; if (T0) { T = 0; } else { T = data.Length * TFAC; } NEval = 0; ThreadPool.QueueUserWorkItem(new WaitCallback(NelderMeadThread)); //Do(); }
public DerivFunction(Function1D f) { code = f.code; p = f.p; if (f.dfdp.Length == f.p.Length) { dfdp = f.dfdp; fast = true; this.f = f.f; } else { dfdp = new SmallData(); fast = true; dfdp.Length = p.Length; this.f = new Code(F); } }
public Paul(Function1D f, Function1D df, double eps = 1e-6, int maxIterations = 50) : base(f, df, eps, "Метод ПАУЛА", maxIterations) { }
public Fit(DataItem data, Function1D f, bool[] fitp) { Data = data; f0 = f; this.fitp = (bool[])fitp.Clone(); }
public Fit(DataItem data, Function1D f) { Data = data; Function = f; }
public Extrapolation(Function1D f, double eps = 1e-6, int maxIteratons = 50) : base(f, null, eps, "Метод ЭКСТРАПОЛЯЦИИ", maxIteratons) { }
//Конструктор public Fibonacci1(Function1D f, double eps = 1e-6, int maxIteratons = 50) : base(f, null, eps, "Метод ФИБОНАЧЧИ-1", maxIteratons) { }
public Dichotomy(Function1D f, double eps = 1e-6, int maxIterations = 50) : base(f, null, eps, "Метод ДИХТОМИИ", maxIterations) { }
public BoostedDavidon(Function1D f, Function1D df, double eps = 1e-6, int maxIterations = 50) : base(f, df, eps, "Метод ДАВИДОНА", maxIterations) { }
public Dsk(Function1D f, double eps = 1e-6, int maxIterations = 50) : base(f, null, eps, "Метод ДСК", maxIterations) { }
public Bolzano(Function1D f, Function1D df, double eps = 1e-6, int maxIterations = 50) : base(f, df, eps, "Метод БОЛЬЦАНО", maxIterations) { }
/// <summary> /// Обязательно нужен df2!!! /// </summary> /// <param name="f">функция</param> /// <param name="df">первая производная</param> /// <param name="d2f">вторая производная</param> /// <param name="eps">точность</param> /// <param name="maxIterations">кол-во итераций</param> // ReSharper disable once InconsistentNaming public Newton(Function1D f, Function1D df, Function1D d2f, double eps = 1e-6, int maxIterations = 50) : base(f, df, eps, "Метод НЬЮТОНА", maxIterations) { D2F = d2f; }
public GoldenRatio2(Function1D f, double eps = 1e-6, int maxIterations = 50) : base(f, null, eps, "Метод ЗОЛОТОГО СЕЧЕНИЯ-2", maxIterations) { }
public void ResetPar() { bool fitpok = true; lock (this) { GraphModel model = graph.Model; string name; int i; name = (string)function.Text; f = null; for (i = 0; i < model.Items.Count; i++) { if ((model.Items[i].name == name) && (model.Items[i] is Function1D) && (((Function1D)model.Items[i]).Fitable())) { f = (Function1D)model.Items[i]; } } name = (string)data.Text; dataItem = null; for (i = 0; i < model.Items.Count; i++) { if ((model.Items[i].name == name) && (model.Items[i] is DataItem)) { dataItem = (DataItem)model.Items[i]; } } if (f != null) { if (f != oldf || f.Modified) { if (f != oldf) { fitp = new bool[f.p.Length]; for (i = 0; i < f.p.Length; i++) { fitp[i] = true; } } grid.ColumnsCount = 4; grid.RowsCount = f.p.Length + 1; grid[0, 0] = new SourceGrid2.Cells.Real.ColumnHeader("n"); grid[0, 1] = new SourceGrid2.Cells.Real.ColumnHeader("fit"); grid[0, 2] = new SourceGrid2.Cells.Real.ColumnHeader("p[n]"); grid[0, 3] = new SourceGrid2.Cells.Real.ColumnHeader("±Δp[n]"); for (i = 0; i < f.p.Length; i++) { grid[i + 1, 0] = new SourceGrid2.Cells.Real.RowHeader(i.ToString()); grid[i + 1, 1] = new SourceGrid2.Cells.Real.CheckBox(fitp[i]); grid[i + 1, 2] = new SourceGrid2.Cells.Real.Cell(f.p[i], typeof(double)); if (covar == null) { grid[i + 1, 3] = new SourceGrid2.Cells.Real.Cell("", typeof(string)); } else { grid[i + 1, 3] = new SourceGrid2.Cells.Real.Cell(Math.Sqrt(covar[i, i]), typeof(double)); } grid[i + 1, 3].DataModel.EnableEdit = false; } covar = null; } plength = f.p.Length; } if (f == null) { grid.RowsCount = 4; grid.ColumnsCount = 1; grid[0, 0] = new SourceGrid2.Cells.Real.ColumnHeader("n"); grid[0, 1] = new SourceGrid2.Cells.Real.ColumnHeader("fit"); grid[0, 2] = new SourceGrid2.Cells.Real.ColumnHeader("p[n]"); grid[0, 3] = new SourceGrid2.Cells.Real.ColumnHeader("±Δp[n]"); } grid.AutoSize(); oldf = f; Q.Text = ""; chisq.Text = ""; covariance.Enabled = covar != null; fitpok = false; for (i = 0; i < fitp.Length; i++) { if (fitp[i]) { fitpok = true; } } start.Enabled = (f != null && data != null && fitpok); neval.Text = ""; } }