private Vector3 GetDirectionOnSimplex2(Simplex simplex) { Vector3 simplexAB = simplex.Support [1].s - simplex.Support [0].s; Vector3 simplexAO = simplex.Support [0].s * - 1.0; return Vector3.Cross( Vector3.Cross(simplexAB, simplexAO), simplexAB); }
private void buttonNext_Click(object sender, EventArgs e) { //для запоминания типа шага if (simplextable.ResponseCheck() == 1) { type_of_step.Add(false); } else { type_of_step.Add(true); } try { //выбран ли опорный элемент simplextable.ButtonPressedOrNot(dataGridView3); //смена местами переменной + буферизация simplextable.ChangeOfVisualizationVariables(dataGridView3); // Буферизируем визуализацию колонок simplextable.BufferingVariablevisualizationForDeleteColumns(dataGridView3); // Буферизируем визуализацию строк simplextable.BufferingVariablevisualizationForDeleteRows(dataGridView3); //буферизация элементов таблицы simplextable.BufferingSimplexTableValues_ForArtifical(); //удаляем подсвеченные simplextable.delete_green_grids(dataGridView3); //вычисление согласно выбранному опорному элементу simplextable.CalculateSimplexTable(simplextable.row_of_the_support_element, simplextable.column_of_the_support_element); // обновление данных ячеек таблицы if (Radical_or_Decimal) { addGridParam_for_simplex_elements(simplextable.simplex_elements, dataGridView3); } else { addGridParam_for_simplex_elements(simplextable.simplex_elements_with_radicals, dataGridView3); } // Если искусственный базис ещё не пришёл в ноль if (!ArtificalBasixGoToNull) { // создаём новую симплекс таблицу для дальнейшей работы if (Radical_or_Decimal) { simplextable1 = new Simplex(simplextable); } else { simplextable1 = new Simplex(simplextable); } } if (!ArtificalBasixGoToNull) { switch (simplextable1.ArtificialResponseCheck(variable_visualization, dataGridView3)) { case 1: step++; if (!ArtificalBasixGoToNull) { // Удаляем столбцы с искусственными переменными. simplextable.DeleteArtificalBasix(dataGridView3); // Считываем ограничения заного if (Radical_or_Decimal) { ogr = new List <List <double> >(); read_grids(dataGridView3, ogr); simplextable.simplex_elements = ogr; // удаляем строку с нулями из элементов симплекс таблицы simplextable.simplex_elements.RemoveAt(simplextable.simplex_elements.Count - 1); // удаляем последнюю строку с нулями из датаГрид dataGridView3.Rows.RemoveAt(dataGridView3.Rows.Count - 1); // отображаем новые данные addGridParam_for_simplex_elements(simplextable.simplex_elements, dataGridView3); } else { ogr_with_radicals = new List <List <Fractions> >(); read_grids(dataGridView3, ogr_with_radicals); simplextable.simplex_elements_with_radicals = ogr_with_radicals; // удаляем строку с нулями из элементов симплекс таблицы simplextable.simplex_elements_with_radicals.RemoveAt(simplextable.simplex_elements_with_radicals.Count - 1); // удаляем последнюю строку с нулями из датаГрид dataGridView3.Rows.RemoveAt(dataGridView3.Rows.Count - 1); // отображаем новые данные addGridParam_for_simplex_elements(simplextable.simplex_elements_with_radicals, dataGridView3); } // Высчитываем последнюю строку simplextable.CalculateCelRow(dataGridView3); } ArtificalBasixGoToNull = true; switch (simplextable.ResponseCheck()) { case 0: //выбор опорного simplextable.SelectionOfTheSupportElement(dataGridView3); label1.Text = "Симплекс таблица"; step_1++; break; case 1: // Подставляем ответ if (MinMax == 0) { if (Radical_or_Decimal) { label_answer.Text = "Ответ :" + simplextable.Response(); } else { label_answer.Text = "Ответ :" + simplextable.Responce_for_radicals().Reduction(); } } else { if (Radical_or_Decimal) { label_answer.Text = "Ответ: " + simplextable.Response() * (-1); } else { label_answer.Text = "Ответ :" + simplextable.Responce_for_radicals().Reduction() * (-1); } } // Выводим точку X* if (corner_dot_was_added == false) { corner_dot_was_added = true; //добавляем точку addGridParam(simplextable.ResponseDot(dataGridView3), dataGridViewCornerDot); } groupBoxCornerDot.Visible = true; label_answer.Visible = true; buttonNext.Enabled = false; step_1++; break; case -1: label1.Text = "Линейная форма не ограничена на множестве планов задачи."; buttonNext.Enabled = false; MessageBox.Show("Линейная форма не ограничена на множестве планов задачи.", ""); step_1++; break; } break; case 0: if (simplextable.ResponseCheck() == 1) { // Если симплекс таблица решена step++; if (MinMax == 0) { if (Radical_or_Decimal) { label_answer.Text = "Ответ :" + simplextable.Response(); } else { label_answer.Text = "Ответ :" + simplextable.Responce_for_radicals().Reduction(); } } else { if (Radical_or_Decimal) { label_answer.Text = "Ответ: " + simplextable.Response() * (-1); } else { label_answer.Text = "Ответ :" + simplextable.Responce_for_radicals().Reduction() * (-1); } } // Выводим точку X* if (corner_dot_was_added == false) { corner_dot_was_added = true; //добавляем точку addGridParam(simplextable.ResponseDot(dataGridView3), dataGridViewCornerDot); } groupBoxCornerDot.Visible = true; label_answer.Visible = true; buttonNext.Enabled = false; step_1++; } else { step++; label1.Text = "Метод искусственного базиса. Выбор опорного элемента."; //выбор опорного simplextable.SelectionOfTheSupportElement(dataGridView3); } break; case -1: MessageBox.Show("Решения нет"); break; } } // Симплекс метод else { switch (simplextable.ResponseCheck()) { case 0: //выбор опорного simplextable.SelectionOfTheSupportElement(dataGridView3); label1.Text = "Симплекс таблица"; step_1++; break; case 1: // Подставляем ответ if (MinMax == 0) { if (Radical_or_Decimal) { label_answer.Text = "Ответ :" + simplextable.Response(); } else { label_answer.Text = "Ответ :" + simplextable.Responce_for_radicals().Reduction(); } } else { if (Radical_or_Decimal) { label_answer.Text = "Ответ: " + simplextable.Response() * (-1); } else { label_answer.Text = "Ответ :" + simplextable.Responce_for_radicals().Reduction() * (-1); } } // Выводим точку X* if (corner_dot_was_added == false) { corner_dot_was_added = true; //добавляем addGridParam(simplextable.ResponseDot(dataGridView3), dataGridViewCornerDot); } groupBoxCornerDot.Visible = true; label_answer.Visible = true; buttonNext.Enabled = false; step_1++; break; case -1: label1.Text = "Линейная форма не ограничена на множестве планов задачи."; MessageBox.Show("Линейная форма не ограничена на множестве планов задачи.", ""); buttonNext.Enabled = false; step_1++; break; } } } catch (Exception d) { MessageBox.Show(d.Message); } }
public static string eqModelSVI( [ExcelArgument(Description = "id of option to be constructed ")] string ObjectId, [ExcelArgument(Description = "ATM forward ")] double forward, [ExcelArgument(Description = "expiry (years of fraction ")] double tenor, [ExcelArgument(Description = "Strikes ")] double[] strikes, [ExcelArgument(Description = "implied vols ")] double[] volatilities, [ExcelArgument(Description = "initial parameters ")] double[] initials, [ExcelArgument(Description = "trigger ")] object trigger) { if (ExcelUtil.CallFromWizard()) { return(""); } string callerAddress = ""; callerAddress = ExcelUtil.getActiveCellAddress(); try { if (strikes.Length != volatilities.Length) { throw new Exception("SABR input lengths don't match."); } if (initials.Length != 5) { throw new Exception("SVI has five parameters."); } int[] idx = volatilities.Select((v, Index) => new { V = v, idx = Index }) .Where(x => x.V == 0) .Select(x => x.idx) .ToArray(); QlArray xx = new QlArray((uint)strikes.Length - (uint)idx.Length); QlArray yy = new QlArray((uint)volatilities.Length - (uint)idx.Length); for (uint i = 0, j = 0; i < strikes.Length; i++) { if (volatilities[i] == 0) // empty { continue; } xx.set(j, strikes[i]); yy.set(j, volatilities[i]); j++; } EndCriteria endcriteria = new EndCriteria(100000, 100, 1e-8, 1e-8, 1e-8); OptimizationMethod opmodel = new Simplex(0.01); // alpha: ATM Vol, beta: CEV param, rho: underlying/vol correlation, nu: vol of vol SVIInterpolation svi = new SVIInterpolation(xx, yy, tenor, forward, initials[0], initials[1], initials[2], initials[3], initials[4], endcriteria, opmodel, true); double err = 0; err = svi.update(); // Store the option and return its id string id = "MODEL@" + ObjectId; OHRepository.Instance.storeObject(id, svi, callerAddress); id += "#" + (String)DateTime.Now.ToString(@"HH:mm:ss"); return(id); } catch (Exception e) { ExcelUtil.logError(callerAddress, System.Reflection.MethodInfo.GetCurrentMethod().Name.ToString(), e.Message); return(e.Message); } }
public KopernicusSimplexWrapper(PQSMod_VertexPlanet.SimplexWrapper copyFrom) : base(copyFrom) { simplex = copyFrom.simplex; }
public void PrepareToExecute(Simplex simplex) { #region Preechimento das variáveis necessárias numeroVariaveis = simplex.Variaveis.Value; numeroRestricoes = simplex.Restricoes.Value; qtdColunas = (numeroVariaveis + numeroRestricoes) + 1; funcaoObjetiva = new decimal[qtdColunas]; matrizNumerica = new decimal[numeroRestricoes, qtdColunas]; Var = new string[numeroRestricoes + qtdColunas]; #endregion #region Montar vetor da função objetivo for (int i = 0; i < qtdColunas; i++) { if (i < numeroVariaveis) { funcaoObjetiva[i] = (simplex.Minimizar ? simplex.objectiveVector[i] : -simplex.objectiveVector[i]); } else { funcaoObjetiva[i] = 0; } } #endregion #region Montar matriz de acordo com valores preenchidos for (int i = 0, k = 0; i < numeroRestricoes; i++) { for (int j = 0; j < numeroVariaveis + 1; j++) { if (j == numeroVariaveis) { j = (numeroVariaveis + numeroRestricoes); } matrizNumerica[i, j] = simplex.Matriz[k]; k++; } } for (int i = 0; i < numeroRestricoes; i++) { matrizNumerica[i, numeroVariaveis + i] = 1; } #endregion #region Montar vetor com Elementos da operação for (int i = 0, j = 1, k = 1; i < (numeroRestricoes + qtdColunas); i++) { if (j > numeroRestricoes) { j = 1; } if (i < numeroRestricoes) { Var[i] = "F" + j; j++; } else if (i < qtdColunas - 1) { Var[i] = "X" + k; k++; } else if (i < (numeroRestricoes + qtdColunas - 1)) { Var[i] = "F" + j; j++; } else { Var[i] = "B"; } } #endregion ElementosOriginais = (string[])Var.Clone(); quadroSimplex = new QuadroSimplex(Var, matrizNumerica, funcaoObjetiva); quadroSimplexOriginal = quadroSimplex.Clone(quadroSimplex); }
public void SetupBiomeNoise(int RandomSeed) { TemperatureNoise = new Simplex(RandomSeed+1); HumidityNoise = new Simplex(RandomSeed); }
/// <summary> /// used for generating veins of resources /// </summary> /// <param name="offset">use to create unique deposit zones</param> /// <param name="p">use to tweak how much is generated</param> public bool HasDeposit(double offset, double p) { Tuple <double, double, double> xyz = Program.LatLong2Spherical(y * Math.PI, x * Math.PI); return(p < Simplex.OctaveNoise(xyz.Item1 + offset, xyz.Item2 + offset, xyz.Item3 + offset, 0, octaves)); }
public override void OnSetup() { //AddSimplexNoise simplex1 = new Simplex(seed, octaves, persistence, frequency); //SmoothHeightMap simplex2 = new Simplex(smoothSeed, smoothOctaves, smoothPersistence, smoothFrequency); #region setSmoothDeformity if (smoothDeformity == 0) { if (deformity < 500) { smoothDeformity = 20; } if (deformity > 500 && deformity < 2000) { smoothDeformity = 200; } if (deformity > 2000 && deformity < 4000) { smoothDeformity = 400; } if (deformity > 4000 && deformity < 8000) { smoothDeformity = deformity / 10; } if (deformity > 8000) { smoothDeformity = deformity; } } #endregion #region setSmoothValues if (sphere.radius < 500000) { smoothOctaves = 2; smoothFrequency = 50; } if (sphere.radius > 50000 && sphere.radius < 100000) { smoothOctaves = 6; smoothFrequency = 70; } if (sphere.radius > 100000 && sphere.radius < 200000) { smoothOctaves = 12; smoothFrequency = 200; } if (sphere.radius > 200000) { smoothOctaves = 24; smoothFrequency = 400; } #endregion if (heightMap == null) { throw new ArgumentNullException(nameof(heightMap)); } if (colorMap == null) { throw new ArgumentNullException(nameof(colorMap)); } if (scaleDeformityByRadius) { heightDeformity = sphere.radius * heightmapDeformity; } if (!scaleDeformityByRadius) { heightDeformity = heightmapDeformity; } }
public World() { this.noisemodule = new Simplex(); this.p = new SharpNoise.Models.Plane(noisemodule); }
public override void OnVertexBuildHeight(PQS.VertexBuildData data) { switch (indexer) { case Indexer.Billow: bill1 = new Billow(frequency, lacunarity, persistence, Convert.ToInt32(octaves), seed, mode); if (onlyOnOcean) { if (data.vertHeight < internalRadius) { if (bill1.GetValue(data.directionFromCenter) > cutoff) { data.vertHeight += deformity + offset; } } } if (!onlyOnOcean) { if (bill1.GetValue(data.directionFromCenter) > cutoff) { data.vertHeight += deformity + offset; } } if (addNoise) { var Simp2 = new Simplex(seed, octaves, persistence, frequency); if (bill1.GetValue(data.directionFromCenter) > cutoff) { data.vertHeight = Simp2.noise(data.directionFromCenter) * noiseDeformity; } } break; case Indexer.Perlin: perl1 = new Perlin(frequency, lacunarity, persistence, Convert.ToInt32(octaves), seed, mode); if (onlyOnOcean) { if (data.vertHeight < internalRadius) { if (perl1.GetValue(data.directionFromCenter) > cutoff) { data.vertHeight += deformity + offset; } } } if (!onlyOnOcean) { if (perl1.GetValue(data.directionFromCenter) > cutoff) { data.vertHeight += deformity + offset; } } if (addNoise) { var Simp2 = new Simplex(seed, octaves, persistence, frequency); if (perl1.GetValue(data.directionFromCenter) > cutoff) { data.vertHeight = Simp2.noise(data.directionFromCenter) * noiseDeformity; } } break; case Indexer.RiggedMultifractal: rig1 = new RiggedMultifractal(frequency, lacunarity, Convert.ToInt32(octaves), seed, mode); if (onlyOnOcean) { if (data.vertHeight < internalRadius) { if (rig1.GetValue(data.directionFromCenter) > cutoff) { data.vertHeight += deformity + offset; } } } if (!onlyOnOcean) { if (rig1.GetValue(data.directionFromCenter) > cutoff) { data.vertHeight += deformity + offset; } } if (addNoise) { var Simp2 = new Simplex(seed, octaves, persistence, frequency); if (rig1.GetValue(data.directionFromCenter) > cutoff) { data.vertHeight = Simp2.noise(data.directionFromCenter) * noiseDeformity; } } break; case Indexer.Simplex: simp1 = new Simplex(seed, octaves, persistence, frequency); if (onlyOnOcean) { if (data.vertHeight < internalRadius) { if (simp1.noise(data.directionFromCenter) > cutoff) { data.vertHeight += deformity + offset; } } } if (!onlyOnOcean) { if (simp1.noise(data.directionFromCenter) > cutoff) { data.vertHeight += deformity + offset; } } if (addNoise) { var Simp2 = new Simplex(seed, octaves, persistence, frequency); if (simp1.noise(data.directionFromCenter) > cutoff) { data.vertHeight = Simp2.noise(data.directionFromCenter) * noiseDeformity; } } break; } }
private Double @value(Double xin, Double yin, Double zin) { F3 = 0.333333333333333; s = (xin + yin + zin) * F3; i = fastfloor(xin + s); j = fastfloor(yin + s); k = fastfloor(zin + s); G3 = 0.166666666666667; t = (i + j + k) * G3; X0 = i - t; Y0 = j - t; Z0 = k - t; x0 = xin - X0; y0 = yin - Y0; z0 = zin - Z0; if (x0 >= y0) { if (y0 >= z0) { i1 = 1; j1 = 0; k1 = 0; i2 = 1; j2 = 1; k2 = 0; } else if (x0 < z0) { i1 = 0; j1 = 0; k1 = 1; i2 = 1; j2 = 0; k2 = 1; } else { i1 = 1; j1 = 0; k1 = 0; i2 = 1; j2 = 0; k2 = 1; } } else if (y0 < z0) { i1 = 0; j1 = 0; k1 = 1; i2 = 0; j2 = 1; k2 = 1; } else if (x0 >= z0) { i1 = 0; j1 = 1; k1 = 0; i2 = 1; j2 = 1; k2 = 0; } else { i1 = 0; j1 = 1; k1 = 0; i2 = 0; j2 = 1; k2 = 1; } x1 = x0 - i1 + G3; y1 = y0 - j1 + G3; z1 = z0 - k1 + G3; x2 = x0 - i2 + 2 * G3; y2 = y0 - j2 + 2 * G3; z2 = z0 - k2 + 2 * G3; x3 = x0 - 1 + 3 * G3; y3 = y0 - 1 + 3 * G3; z3 = z0 - 1 + 3 * G3; ii = i & 255; jj = j & 255; kk = k & 255; gi0 = perm[ii + perm[jj + perm[kk]]] % 12; gi1 = perm[ii + i1 + perm[jj + j1 + perm[kk + k1]]] % 12; gi2 = perm[ii + i2 + perm[jj + j2 + perm[kk + k2]]] % 12; gi3 = perm[ii + 1 + perm[jj + 1 + perm[kk + 1]]] % 12; t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0; if (t0 >= 0) { Simplex simplex = this; simplex.t0 = simplex.t0 * t0; n0 = t0 * t0 * dot(grad3[gi0], x0, y0, z0); } else { n0 = 0; } t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1; if (t1 >= 0) { Simplex simplex1 = this; simplex1.t1 = simplex1.t1 * t1; n1 = t1 * t1 * dot(grad3[gi1], x1, y1, z1); } else { n1 = 0; } t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2; if (t2 >= 0) { Simplex simplex2 = this; simplex2.t2 = simplex2.t2 * t2; n2 = t2 * t2 * dot(grad3[gi2], x2, y2, z2); } else { n2 = 0; } t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3; if (t3 >= 0) { Simplex simplex3 = this; simplex3.t3 = simplex3.t3 * t3; n3 = t3 * t3 * dot(grad3[gi3], x3, y3, z3); } else { n3 = 0; } return(32 * (n0 + n1 + n2 + n3)); }
public void RunApplication(IModelFactory dotNetModelFactory) { if (dotNetModelFactory != null) { // Tell OpenDA what model factory to use ModelFactory.InsertModelFactory(dotNetModelFactory); } // run the openda application ApplicationRunnerSingleThreaded applicationRunner; try { applicationRunner = new ApplicationRunnerSingleThreaded(); applicationRunner.initialize(new java.io.File(odaDirectoryName), odaFileName); applicationRunner.runSingleThreaded(); } catch (Exception e) { String message = "Error running OpenDA application.\nDetailed error message: " + e.Message; ModelFactory.AppendLogMessage(message); Console.WriteLine(message); return; } if (true) // TODO: applicationRunner.getStatus()== ApplicationRunnerJ2N.Status.FINISHED // DONE) { // get a reference to the model instance selected by the algorithm as optimal IAlgorithm algorithm = applicationRunner.getAlgorithm(); IStochModelInstance calibratedStochModel; if (algorithm is Dud) { Dud dud = ((Dud)algorithm); calibratedStochModel = dud.getBestEstimate(); } else if (algorithm is SparseDud) { SparseDud sparseDud = ((SparseDud)algorithm); calibratedStochModel = sparseDud.getBestEstimate(); } else if (algorithm is Powell) { Powell powell = ((Powell)algorithm); calibratedStochModel = powell.getBestEstimate(); } else if (algorithm is Simplex) { Simplex simplex = ((Simplex)algorithm); calibratedStochModel = simplex.getBestEstimate(); } else if (algorithm is AbstractSequentialAlgorithm) { AbstractSequentialAlgorithm asAlgorithm = ((AbstractSequentialAlgorithm)algorithm); calibratedStochModel = asAlgorithm.getMainModel(); if (calibratedStochModel == null) { Console.WriteLine("No main model set by ensemble algorithm"); return; } } else { Console.WriteLine("Unknown Algoritm type: " + algorithm.GetType()); return; } // Get the model instance out of the stochModel->java2dotnet->modelInstance layers if (calibratedStochModel is BBStochModelInstance) { org.openda.interfaces.IModelInstance modelInstance = ((BBStochModelInstance)calibratedStochModel).getModel(); if (modelInstance is ModelInstanceN2J) { ResultingModelInstance = ((ModelInstanceN2J)modelInstance).getDotNetModelInstance(); } else { string message = "Unknown java 2 dotnet model instance type: " + modelInstance.GetType(); ModelFactory.AppendLogMessage(message); Console.WriteLine(message); } } else { string message = "Unknown Stoch model instance type: " + calibratedStochModel.GetType(); ModelFactory.AppendLogMessage(message); Console.WriteLine(message); } } }
public Vector solve(IFunction f, double precision) { Simplex smpl = Simplex.getRegularSimplex(x); double alpha = 1.0; double beta = 0.5; double gamma = 2.0; bool flag = false; double f_h, f_g, f_l, f_r, f_e, f_s, tempD; Vector x_h = new Vector(x.Size), x_g = new Vector(x.Size), x_l = new Vector(x.Size), x_r = new Vector(x.Size), x_e = new Vector(x.Size), x_s = new Vector(x.Size), x_c = new Vector(x.Size), tempV = new Vector(x.Size); double[] fValues = new double[smpl.Size]; for (int i = 0; i < smpl.Size; i++) { fValues[i] = f.value(smpl[i]); // Вычисление значений функции на начальном симплексе } while (!QuitCase(smpl, precision)) // Проверка на условие выхода { // Шаг 1. Сортировка Sort(smpl, fValues); x_h = smpl[smpl.Size - 1]; f_h = fValues[smpl.Size - 1]; x_g = smpl[smpl.Size - 2]; f_g = fValues[smpl.Size - 2]; x_l = smpl[0]; f_l = fValues[0]; if (Double.IsInfinity(f_l)) { for (int i = 0; i < x.Size; i++) { x_l[i] = (x_l[i] < 0) ? Double.NegativeInfinity : (x_l[i] == 0) ? 0 : Double.PositiveInfinity; } return(x_l); } // Шаг 2. Вычисление центра тяжести симплекса for (int i = 0; i < x_c.Size; i++) // начальный вектор (0,0,...,0) { x_c[i] = 0; } for (int i = 0; i < x_c.Size; i++) { x_c += smpl[i]; } x_c = x_c / x_c.Size; // 3Шаг . Отражение x_r = x_c * (1 + alpha) - x_h * alpha; f_r = f.value(x_r); // Шаг 4. if (f_r <= f_l) { // Шаг 4a. x_e = x_c * (1 - gamma) + x_r * gamma; f_e = f.value(x_e); if (f_e < f_l) { smpl[smpl.Size - 1] = x_e; fValues[smpl.Size - 1] = f_e; } else { smpl[smpl.Size - 1] = x_r; fValues[smpl.Size - 1] = f_r; } } if ((f_l < f_r) && (f_r <= f_g)) { // Шаг 4.b smpl[smpl.Size - 1] = x_r; fValues[smpl.Size - 1] = f_r; } flag = false; if ((f_h >= f_r) && (f_r > f_g)) { // Шаг 4c. flag = true; tempD = f_h; tempV = x_h; smpl[smpl.Size - 1] = x_r; fValues[smpl.Size - 1] = f_r; x_r = tempV; f_r = tempD; } // Шаг 4d. if (f_r > f_h) { flag = true; } if (flag) { // Шаг 5. Сжатие x_s = x_h * beta + x_c * (1 - beta); f_s = f.value(x_s); if (f_s < f_h) { // 6. tempD = f_h; tempV = x_h; smpl[smpl.Size - 1] = x_s; fValues[smpl.Size - 1] = f_s; x_s = tempV; f_s = tempD; } else { // Шаг 7. Глобальное сжатие for (int i = 0; i < smpl.Size; i++) { smpl[i] = x_l + (smpl[i] - x_l) / 2; } } } } return(x_l); }
private Simplex MainStep() { Simplex smp = new Simplex(); MathFunction fnc = FuncStep(); var limits = LimitsStep(); smp.SetFunction(fnc); foreach (var x in limits) smp.AddLimit(x); return smp; }
public override void Decorate(ChunkColumn column, Biome biome, float[] thresholdMap, int x, int y, int z, bool surface, bool isBelowMaxHeight) { try { var currentTemperature = biome.Temperature; if (y > 64) { int distanceToSeaLevel = y - 64; currentTemperature = biome.Temperature - (0.00166667f * distanceToSeaLevel); } int rx = column.x * 16 + x; int rz = column.z * 16 + z; bool generated = false; if (surface && y >= OverworldGenerator.WaterLevel) { var noise = Simplex.Noise(rx, rz, biome.Downfall, 0.5, true); if (x >= 3 && x <= 13 && z >= 3 && z <= 13) { Structure tree = null; if (biome.Downfall <= 0f && biome.Temperature >= 2f) { if (GetRandom(32) == 16) { var randValue = GetRandom(18); if (randValue >= 0 && randValue <= 2) //3 tall cactus { tree = new CactusStructure(3); } else if (randValue > 2 && randValue <= 5) // 2 tall cactus { tree = new CactusStructure(2); } else if (randValue > 5 && randValue <= 11) // 1 tall cactus { tree = new CactusStructure(1); } } } if (tree == null && biome.Downfall >= 0 && (noise > ((1f - biome.Downfall) /* + 0.5*/) + (y / 512f))) { if (currentTemperature >= 1f && biome.Downfall >= 0.2f) { if (GetRandom(8) == 4) { tree = new LargeJungleTree(); } else { tree = new SmallJungleTree(); } } /* else if (currentTemperature >= 0.7F && biome.Downfall >= 0.2f) * { * tree = new OakTree(true); * }*/ else if (currentTemperature >= 0.7F && biome.Downfall < 0.2f) { tree = new AcaciaTree(); } else if (currentTemperature > 0.25f && biome.Downfall > 0f) { if (biome.Name.Contains("Birch") || GetRandom(16) == 8) { tree = new BirchTree(); } else { tree = new OakTree(); } } else if (currentTemperature <= 0.25f && biome.Downfall > 0f) { tree = new PineTree(); } } if (tree != null) { if (y + 1 < 254) { tree.Create(column, x, y + 1, z); } generated = true; } } if (!generated) { if (noise > 0.5) //Threshold 1 { /*if (currentTemperature > 0.3f && currentTemperature < 1.5f && biome.Downfall >= 0.85f) * { * column.SetBlock(x, y + 1, z, 18); //Leaves * column.SetMetadata(x, y + 1, z, 3); //Jungle Leaves * } * else*/ if (currentTemperature > 0.3f && currentTemperature < 1.5f && biome.Downfall > 0) { var blockBeneath = column.GetBlock(x, y, z); var sugarPosibility = GetRandom(18); if (/*sugarPosibility <= 11*/ noise > 0.75f && (blockBeneath == 3 || blockBeneath == 2 || blockBeneath == 12) && IsValidSugarCaneLocation(column, x, y, z)) { int height = 1; if (sugarPosibility <= 2) { height = 3; } else if (sugarPosibility <= 5) { height = 2; } //var growth = Rnd.Next(0x1, 0x15); for (int mY = y + 1; mY < y + 1 + height; mY++) { column.SetBlock(x, mY, z, 83); //SugarCane if (mY == y + 1 + height) { column.SetMetadata(x, mY, z, (byte)Rnd.Next(0, 15)); } else { column.SetMetadata(x, mY, z, 0); } } } else if (noise > 0.8 && blockBeneath == 3 || blockBeneath == 2) //If above 0.8, we generate flowers :) { if (Simplex.Noise(rx, rz, 0.5f, 0.5f, true) > 0.5) { column.SetBlock(x, y + 1, z, 38); //Poppy column.SetMetadata(x, y + 1, z, (byte)GetRandom(8)); } else { column.SetBlock(x, y + 1, z, 37); //Dandelion } } else if (blockBeneath == 3 || blockBeneath == 2) { column.SetBlock(x, y + 1, z, 31); //Grass column.SetMetadata(x, y + 1, z, 1); } } } } } } catch (Exception e) { } }
public OverworldNoise(int seed) { generatorSettings = new OverworldTerrainSettings() { Seed = seed }; generator = new OverworldTerrainGenerator(generatorSettings); generatorModule = generator.CreateModule(); cavePerlin = new Simplex { Frequency = 1.14, Lacunarity = 2.0, OctaveCount = 2, Persistence = 1.53 }; coalNoise = new Multiply { Source0 = new Checkerboard(), Source1 = new Perlin { Frequency = 1.14, Lacunarity = 2.222, Seed = generatorSettings.Seed } }; BiomeNoise = new Turbulence() { Frequency = 43.25, Power = 0.01, Roughness = 6, Seed = generatorSettings.Seed + 100, Source0 = new Add() { Source0 = new Clamp() { UpperBound = 2, LowerBound = -0.1, Source0 = new Billow() { Seed = generatorSettings.Seed + 101, Frequency = 43.25, Lacunarity = generatorSettings.ContinentLacunarity, OctaveCount = 1, Quality = NoiseQuality.Fast, } }, Source1 = new Clamp() { UpperBound = 0.1, LowerBound = -2, Source0 = new Invert() { Source0 = new Billow() { Seed = generatorSettings.Seed + 102, Frequency = 43.25, Lacunarity = generatorSettings.ContinentLacunarity, OctaveCount = 1, Quality = NoiseQuality.Fast, } } } } }; BiomeHumidity = new Turbulence() { Frequency = 47.25, Power = 0.01, Roughness = 6, Seed = generatorSettings.Seed + 103, Source0 = new Add() { Source0 = new Clamp() { UpperBound = 2, LowerBound = -0.1, Source0 = new Billow() { Seed = generatorSettings.Seed + 104, Frequency = 47.25, Lacunarity = generatorSettings.ContinentLacunarity, OctaveCount = 1, Quality = NoiseQuality.Fast, } }, Source1 = new Clamp() { UpperBound = 0.1, LowerBound = -2, Source0 = new Invert() { Source0 = new Billow() { Seed = generatorSettings.Seed + 105, Frequency = 47.25, Lacunarity = generatorSettings.ContinentLacunarity, OctaveCount = 1, Quality = NoiseQuality.Fast, } } } } }; }
private IEnumerator<YieldInstruction> GenerateAllMaps() { double doing = -1d; foreach (ConfigNode body in cfg.GetNode("ore").nodes) { CelestialBody planet = null; if (KRESUtils.TryParseCelestialBody(body.name, out planet) && relevantBodies.Contains(planet)) { currentResource = string.Empty; doing++; currentBody = planet.name; DefaultBody defaultBody = DefaultLibrary.GetSelectedDefault().GetBody(planet.bodyName); if (!Directory.Exists(Path.Combine(texturePath, body.name))) { Debug.LogWarning("[KRES]: Created texture folder for " + body.name); Directory.CreateDirectory(Path.Combine(texturePath, body.name)); } string path = Path.Combine(texturePath, body.name); double current = -1d; double res = (1d / body.GetNodes("KRES_DATA").Count()); foreach (ConfigNode resource in body.GetNodes("KRES_DATA")) { current++; amountComplete = (doing + (current * res)) / max; string resourceName = string.Empty; if (!resource.TryGetValue("name", ref resourceName)) { Debug.LogWarning("[KRES]: Nameless resource for " + body.name); continue; } currentResource = resourceName; yield return null; DefaultResource defaultResource = defaultBody.GetResourceOfType(resourceName, "ore"); Color colour = ResourceInfoLibrary.Instance.GetResource(resourceName).Colour; if (colour.a == 0) { Debug.LogWarning("[KRES]: Invalid colour for node " + resourceName + " for " + body.name); continue; } if (defaultResource.Density == 0 || defaultResource.Octaves == 0 || defaultResource.Persistence == 0 || defaultResource.Frequency == 0) { Debug.LogWarning("[KRES]: Invalid values for node " + resourceName + "for " + body.name); continue; } //Map generation Simplex simplex = new Simplex(defaultResource.Seed, defaultResource.Octaves, defaultResource.Persistence, defaultResource.Frequency); Texture2D map = new Texture2D(1440, 720, TextureFormat.ARGB32, false); var timer = System.Diagnostics.Stopwatch.StartNew(); for (int x = 0; x < 1440; x++) { double lon = 90d - (x / 4d); for (int y = 0; y < 720; y++) { double lat = (y / 4d) - 90d; //Takes too much time to process ~50s per texture, will have to do on scanning. /* if (!double.IsInfinity(defaultResource.MinAltitude) || !double.IsInfinity(defaultResource.MaxAltitude)) { double alt = planet.TerrainAltitude(lat, lon); if (alt > defaultResource.MaxAltitude || alt < defaultResource.MinAltitude) { map.SetPixel(x, y, KRESUtils.BlankColour); continue; } } */ if (defaultResource.Biomes.Length > 0 || defaultResource.ExcludedBiomes.Length > 0) { string biome = planet.GetBiome(lat, lon); if ((defaultResource.Biomes.Length > 0 && !defaultResource.Biomes.Contains(biome)) || (defaultResource.ExcludedBiomes.Length > 0 && defaultResource.ExcludedBiomes.Contains(biome))) { map.SetPixel(x, y, KRESUtils.BlankColour); continue; } } Vector3d position = KRESUtils.SphericalToCartesian(10d, x / 4d, y / 4d); double density = simplex.noiseNormalized(position) - 1d + defaultResource.Density; if (density > 0) { float a = Mathf.Lerp(0.2f, 1f, (float)(density / defaultResource.Density)) * colour.a; if (a > 0.8f) { a = 0.8f; } map.SetPixel(x, y, new Color(colour.r, colour.g, colour.b, a)); } else { map.SetPixel(x, y, KRESUtils.BlankColour); } } if (x % 360 == 0) { yield return null; } } map.Apply(); //Save texture File.WriteAllBytes(Path.Combine(path, resourceName + ".png"), map.EncodeToPNG()); Destroy(map); timer.Stop(); print(String.Format("[KRES]: Texture for {0} on {1} created in {2}ms", resourceName, currentBody, timer.ElapsedMilliseconds)); } } } amountComplete = 1d; }
/// <summary> /// Initializes the base mod /// </summary> public override void OnSetup() { simplex = new Simplex(seed, octaves, persistence, frequency); }
public SimplexLoader() { simplex = new Simplex(0, 1, 1, 1); }
public float Generate1D(float x) { return(Simplex.Generate(x)); }
static void Test() { File.WriteAllLines("output.txt", Simplex.Test().Select(x => x.ToString())); Exit(); }
public float Generate2D(float x, float y) { return(Simplex.Generate(x, y)); }
internal static unsafe DistanceHit ColliderDistance(PhysicsTransform transformA, ref DistanceProxy proxyA, ref DistanceProxy proxyB) { var simplex = new Simplex(); simplex.Reset(transformA, proxyA, proxyB); var inverseRotationA = math.transpose(transformA.Rotation); var vertices = &simplex.Vertex1; Simplex.VertexIndexTriple saveA; Simplex.VertexIndexTriple saveB; var iteration = 0; while (iteration < PhysicsSettings.Constants.MaxGJKInterations) { // Copy simplex so we can identify duplicates. var saveCount = simplex.Count; for (var i = 0; i < saveCount; ++i) { saveA.Index[i] = vertices[i].IndexA; saveB.Index[i] = vertices[i].IndexB; } switch (saveCount) { case 1: break; case 2: simplex.Solve2(); break; case 3: simplex.Solve3(); break; default: SafetyChecks.ThrowInvalidOperationException("Simplex has invalid count."); return(default); } // If we have 3 points, then the origin is in the corresponding triangle. if (simplex.Count == 3) { break; } // Get search direction. var direction = simplex.GetSearchDirection(); // Ensure the search direction is numerically fit. if (math.lengthsq(direction) < float.Epsilon * float.Epsilon) { // The origin is probably contained by a line segment // or triangle. Thus the shapes are overlapped. // We can't return zero here even though there may be overlap. // In case the simplex is a point, segment, or triangle it is difficult // to determine if the origin is contained in the CSO or very close to it. break; } // Compute a tentative new simplex vertex using support points. var vertex = vertices + simplex.Count; vertex->IndexA = proxyA.GetSupport(PhysicsMath.mul(inverseRotationA, -direction)); vertex->SupportA = PhysicsMath.mul(transformA, proxyA.Vertices[vertex->IndexA]); vertex->IndexB = proxyB.GetSupport(direction); vertex->SupportB = proxyB.Vertices[vertex->IndexB]; vertex->W = vertex->SupportB - vertex->SupportA; // Iteration count is equated to the number of support point calls. ++iteration; // Check for duplicate support points. This is the main termination criteria. var duplicate = false; for (var i = 0; i < saveCount; ++i) { if (vertex->IndexA == saveA.Index[i] && vertex->IndexB == saveB.Index[i]) { duplicate = true; break; } } // If we found a duplicate support point we must exit to avoid cycling. if (duplicate) { break; } // New vertex is okay and needed. simplex.Count++; } // Prepare result. var pointA = float2.zero; var pointB = float2.zero; simplex.GetWitnessPoints(ref pointA, ref pointB); var distance = math.distance(pointA, pointB); var radiusA = proxyA.ConvexRadius; var radiusB = proxyB.ConvexRadius; if (distance > (radiusA + radiusB) && distance > float.Epsilon) { // Shapes not overlapped. // Move the witness points to the outer surface. distance -= radiusA + radiusB; var normal = math.normalize(pointB - pointA); pointA += radiusA * normal; pointB -= radiusB * normal; } else { // Shapes are overlapped. // Move the witness points to the middle. pointA = pointB = 0.5f * (pointA + pointB); distance = 0f; } return(new DistanceHit { PointA = pointA, PointB = pointB, Fraction = distance }); }
public float Generate3D(float x, float y, float z) { return(Simplex.Generate(x, y, z)); }
/// <summary> /// Выполнение. /// </summary> private void Implementation() { if (Radical_or_Decimal) { //создаём сиплекс-таблицу simplextable = new Simplex(number_of_basix, number_of_free_variables, ogr, cel_function, false, Radical_or_Decimal); //отрисовываем симплекс таблицу simplextable.DrawSimplexTable(ogr, dataGridView3); } else { //создаём сиплекс-таблицу simplextable = new Simplex(number_of_basix, number_of_free_variables, ogr_with_radicals, cel_function_with_radicals, false, Radical_or_Decimal); //отрисовываем симплекс таблицу simplextable.DrawSimplexTable(ogr_with_radicals, dataGridView3); } if (simplextable.ResponseCheck() == 1) { // tabControl1.TabPages[0].Text = "Холостой шаг: Метод искусственного базиса. Выбор опорного элемента."; //холостой шаг //simplextable.IdleStep(); } else { // tabControl1.TabPages[0].Text = "Шаг " + step + ": Метод искусственного базиса. Выбор опорного элемента."; //выбор опорного simplextable.SelectionRandomSupportElement(); } // Делаем пока таблица искус базиса не вышла в ноль while (ArtificalBasixGoToNull == false) { //смена местами переменной + буферизация simplextable.ChangeOfVisualizationVariables(dataGridView3); //вычисление согласно выбранному опорному элементу simplextable.CalculateSimplexTable(simplextable.row_of_the_support_element, simplextable.column_of_the_support_element); // обновление данных ячеек таблицы if (Radical_or_Decimal) { addGridParam_for_simplex_elements(simplextable.simplex_elements, dataGridView3); } else { addGridParam_for_simplex_elements(simplextable.simplex_elements_with_radicals, dataGridView3); } switch (simplextable.ArtificialResponseCheck(variable_visualization, dataGridView3)) { case 1: //MessageBox.Show("Таблица пришла в ноль!"); if (!ArtificalBasixGoToNull) { // Удаляем столбцы с искусственными переменными. simplextable.DeleteArtificalBasix(dataGridView3); // Считываем ограничения заного if (Radical_or_Decimal) { ogr = new List <List <double> >(); read_grids(dataGridView3, ogr); simplextable.simplex_elements = ogr; // удаляем строку с нулями из элементов симплекс таблицы simplextable.simplex_elements.RemoveAt(simplextable.simplex_elements.Count - 1); // удаляем последнюю строку с нулями из датаГрид dataGridView3.Rows.RemoveAt(dataGridView3.Rows.Count - 1); // отображаем новые данные addGridParam_for_simplex_elements(simplextable.simplex_elements, dataGridView3); } else { ogr_with_radicals = new List <List <Fractions> >(); read_grids(dataGridView3, ogr_with_radicals); simplextable.simplex_elements_with_radicals = ogr_with_radicals; // удаляем строку с нулями из элементов симплекс таблицы simplextable.simplex_elements_with_radicals.RemoveAt(simplextable.simplex_elements_with_radicals.Count - 1); // удаляем последнюю строку с нулями из датаГрид dataGridView3.Rows.RemoveAt(dataGridView3.Rows.Count - 1); // отображаем новые данные addGridParam_for_simplex_elements(simplextable.simplex_elements_with_radicals, dataGridView3); } // Высчитываем последнюю строку simplextable.CalculateCelRow(dataGridView3); } ArtificalBasixGoToNull = true; // Если ответ готов сразу же switch (simplextable.ResponseCheck()) { case 0: //выбор опорного simplextable.SelectionRandomSupportElement(); break; case 1: if (MinMax == 0) { if (Radical_or_Decimal) { label_answer.Text = "Ответ :" + simplextable.Response(); } else { label_answer.Text = "Ответ :" + simplextable.Responce_for_radicals().Reduction(); } } else { if (Radical_or_Decimal) { label_answer.Text = "Ответ: " + simplextable.Response() * (-1); } else { label_answer.Text = "Ответ :" + simplextable.Responce_for_radicals().Reduction() * (-1); } } // Выводим точку X* if (corner_dot_was_added == false) { corner_dot_was_added = true; //добавляем точку addGridParam(simplextable.ResponseDot(dataGridView3), dataGridViewCornerDot); } break; case -1: // tabControl1.TabPages[0].Text = "Линейная форма не ограничена сверху на множествен планов задачи."; MessageBox.Show("Линейная форма не ограничена сверху на множествен планов задачи", ""); break; } break; case 0: if (simplextable.ResponseCheck() == 1) { // Если симплекс таблица решена if (MinMax == 0) { if (Radical_or_Decimal) { label_answer.Text = "Ответ :" + simplextable.Response(); } else { label_answer.Text = "Ответ :" + simplextable.Responce_for_radicals().Reduction(); } } else { if (Radical_or_Decimal) { label_answer.Text = "Ответ: " + simplextable.Response() * (-1); } else { label_answer.Text = "Ответ :" + simplextable.Responce_for_radicals().Reduction() * (-1); } } // Выводим точку X* if (corner_dot_was_added == false) { corner_dot_was_added = true; //добавляем точку addGridParam(simplextable.ResponseDot(dataGridView3), dataGridViewCornerDot); } } else { // tabControl1.TabPages[0].Text = "Шаг " + step + ": Метод искусственного базиса. Выбор опорного элемента."; //выбор опорного simplextable.SelectionRandomSupportElement(); } break; case -1: // MessageBox.Show("Решения не имеет"); break; } } // Переходим к симплекс таблице, если она не имеет решения или пока ещё не решена, и решаем её до тех пор while (simplextable.ResponseCheck() != 1 && simplextable.ResponseCheck() != -1) { //смена местами переменной + буферизация simplextable.ChangeOfVisualizationVariables(dataGridView3); //вычисление согласно выбранному опорному элементу simplextable.CalculateSimplexTable(simplextable.row_of_the_support_element, simplextable.column_of_the_support_element); // обновление данных ячеек таблицы if (Radical_or_Decimal) { addGridParam_for_simplex_elements(simplextable.simplex_elements, dataGridView3); } else { addGridParam_for_simplex_elements(simplextable.simplex_elements_with_radicals, dataGridView3); } switch (simplextable.ResponseCheck()) { case 0: //выбор опорного simplextable.SelectionRandomSupportElement(); break; case 1: // Подставляем ответ if (MinMax == 0) { if (Radical_or_Decimal) { label_answer.Text = "Ответ :" + simplextable.Response(); } else { label_answer.Text = "Ответ :" + simplextable.Responce_for_radicals().Reduction(); } } else { if (Radical_or_Decimal) { label_answer.Text = "Ответ: " + simplextable.Response() * (-1); } else { label_answer.Text = "Ответ :" + simplextable.Responce_for_radicals().Reduction() * (-1); } } // Выводим точку X* if (corner_dot_was_added == false) { corner_dot_was_added = true; //добавляем точку addGridParam(simplextable.ResponseDot(dataGridView3), dataGridViewCornerDot); } break; case -1: // tabControl1.TabPages[0].Text = "Линейная форма не ограничена сверху на множествен планов задачи."; MessageBox.Show("Линейная форма не ограничена сверху на множествен планов задачи.", ""); break; } } }
public static void Example1() { TestModels.IModel modelFactory = TestModels.ModelFactory.Model2B(); XmlFilePath structureFile = modelFactory.Model(); DelimitedFilePath dataFile = modelFactory.Data(); // Read in the model and the data. XElement model = XElement.Load(structureFile) .DefineAttributeData(dataFile); // Create the objective function. double ObjectiveFunction(double[] x) { XElement localModel = new XElement(model); localModel.SetConsumerPrices(x) .ShockProducerPrices() .CalculateMarketShares() .CalculateMarketEquilibrium(); return(ObjectiveFunctionFactory.SumOfSquares(localModel)); } // Set up the simplex solver. Simplex simplex = new Simplex( objectiveFunction: ObjectiveFunction, lowerBound: 0, upperBound: 10, //dimensions: model.DescendantsAndSelf().Count(), dimensions: model.DescendantsAndSelf().Count(x => !x.HasElements), iterations: 50000, seed: 0, textWriter: Console.Out ); // Find the minimum solution. Solution solution = simplex.Minimize(); // Apply the final solution model.SetConsumerPrices(solution.Vector) .ShockProducerPrices() .CalculateMarketShares() .CalculateMarketEquilibrium(); // Print the results PrintResults(model, solution); //// Set up the swarm solver. //PSO.Swarm swarm = // new PSO.Swarm( // objectiveFunction: x => objectiveFunction(x), // lowerBound: 0, // upperBound: 5, // dimensions: model.DescendantsAndSelf().Count(x => !x.HasElements), // iterations: 25000, // particles: model.DescendantsAndSelf().Count(x => !x.HasElements) * 2, // seed: 0, // textWriter: Console.Out // ); //// Find the minimum solution. //Solution solution = PSO.MinimizeSwarmExtensions.Minimize(swarm); //// Apply the final solution //model.SetConsumerPrices(solution.Vector) // .ShockProducerPrices() // .CalculateMarketShares() // .CalculateMarketEquilibrium(); //// Print the results //PrintResults(model, solution); }
bool CheckCollision() { Simplex simplex = new Simplex(); Vector3 direction1 = Vector3.Normalize(((E + F + G + H) / 4.0f) - ((A + B + C + D) / 4.0f)); //C2 - C1 simplex.support(0, this, direction1); Vector3 direction2 = -direction1; //Opposite of direction 1 simplex.support(1, this, direction2); //(ab×ao)×ab Vector3 direction3 = Vector3.Cross(simplex.getPoint(1) - simplex.getPoint(0), Vector3.Cross(simplex.getPoint(1) - simplex.getPoint(0), simplex.getPoint(0) - new Vector3(0.0f, 0.0f, 0.0f))); simplex.support(2, this, direction3); //N1 = ab×ac //N2 = -N1 Vector3 N1 = Vector3.Cross(simplex.getPoint(1) - simplex.getPoint(0), simplex.getPoint(2) - simplex.getPoint(0)); Vector3 N2 = -N1; Vector3 T = (simplex.getPoint(0) + simplex.getPoint(1) + simplex.getPoint(2)) / 3; float T1 = Vector3.Dot(T, N1); Vector3 direction4; if (T1 < 0.0f) { direction4 = N1; } else { direction4 = N2; } simplex.support(3, this, direction4); Matrix4x4 Matrix1 = new Matrix4x4(); Matrix1.SetRow(0, new Vector4(simplex.getPoint(0).x, simplex.getPoint(0).y, simplex.getPoint(0).z, 1)); Matrix1.SetRow(1, new Vector4(simplex.getPoint(1).x, simplex.getPoint(1).y, simplex.getPoint(1).z, 1)); Matrix1.SetRow(2, new Vector4(simplex.getPoint(2).x, simplex.getPoint(2).y, simplex.getPoint(2).z, 1)); Matrix1.SetRow(3, new Vector4(simplex.getPoint(3).x, simplex.getPoint(3).y, simplex.getPoint(3).z, 1)); float D0 = Matrix1.determinant; Matrix4x4 Matrix2 = new Matrix4x4(); Matrix2.SetRow(0, new Vector4(0, 0, 0, 1)); Matrix2.SetRow(1, new Vector4(simplex.getPoint(1).x, simplex.getPoint(1).y, simplex.getPoint(1).z, 1)); Matrix2.SetRow(2, new Vector4(simplex.getPoint(2).x, simplex.getPoint(2).y, simplex.getPoint(2).z, 1)); Matrix2.SetRow(3, new Vector4(simplex.getPoint(3).x, simplex.getPoint(3).y, simplex.getPoint(3).z, 1)); float D1 = Matrix2.determinant; Matrix4x4 Matrix3 = new Matrix4x4(); Matrix3.SetRow(0, new Vector4(simplex.getPoint(0).x, simplex.getPoint(0).y, simplex.getPoint(0).z, 1)); Matrix3.SetRow(1, new Vector4(0, 0, 0, 1)); Matrix3.SetRow(2, new Vector4(simplex.getPoint(2).x, simplex.getPoint(2).y, simplex.getPoint(2).z, 1)); Matrix3.SetRow(3, new Vector4(simplex.getPoint(3).x, simplex.getPoint(3).y, simplex.getPoint(3).z, 1)); float D2 = Matrix3.determinant; Matrix4x4 Matrix4 = new Matrix4x4(); Matrix4.SetRow(0, new Vector4(simplex.getPoint(0).x, simplex.getPoint(0).y, simplex.getPoint(0).z, 1)); Matrix4.SetRow(1, new Vector4(simplex.getPoint(1).x, simplex.getPoint(1).y, simplex.getPoint(1).z, 1)); Matrix4.SetRow(2, new Vector4(0, 0, 0, 1)); Matrix4.SetRow(3, new Vector4(simplex.getPoint(3).x, simplex.getPoint(3).y, simplex.getPoint(3).z, 1)); float D3 = Matrix4.determinant; Matrix4x4 Matrix5 = new Matrix4x4(); Matrix5.SetRow(0, new Vector4(simplex.getPoint(0).x, simplex.getPoint(0).y, simplex.getPoint(0).z, 1)); Matrix5.SetRow(1, new Vector4(simplex.getPoint(1).x, simplex.getPoint(1).y, simplex.getPoint(1).z, 1)); Matrix5.SetRow(2, new Vector4(simplex.getPoint(2).x, simplex.getPoint(2).y, simplex.getPoint(2).z, 1)); Matrix5.SetRow(3, new Vector4(0, 0, 0, 1)); float D4 = Matrix5.determinant; float D0Sign = Mathf.Sign(D0); if (Mathf.Sign(D1) == D0Sign && Mathf.Sign(D2) == D0Sign && Mathf.Sign(D3) == D0Sign && Mathf.Sign(D4) == D0Sign) { Debug.Log("Tetrahedron is colliding!"); isColliding = true; } else { isColliding = false; } return(isColliding); }
/// <summary> /// This generates a honeycomb by reflecting in 4 mirrors of the fundamental simplex. /// This "new" method is now old. /// </summary> public static void OneHoneycombNew(HoneycombDef imageData) { int p = imageData.P; int q = imageData.Q; int r = imageData.R; double thickness = 0.05; double thicknessSpherical = Spherical2D.s2eNorm(thickness); double thicknessHyperbolic = R3.Math.DonHatch.h2eNorm(thickness); double threshold = 1; H3.Cell.Edge[] edges = null; H3.Cell[] cellsToHighlight = null; Sphere[] simplex = null; Vector3D vertex = new Vector3D(); Geometry g = Util.GetGeometry(p, q, r); if (g == Geometry.Spherical) { thickness = thicknessSpherical /*.07 for 333*/ /* 0.05for 433*/ /*.025 for 533,335*/; threshold = 10000; simplex = SimplexCalcs.MirrorsSpherical(p, q, r); vertex = SimplexCalcs.VertexSpherical(p, q, r); // Ugly special casing for 333, since it has a vertex project to infinity. if (p == 3 && q == 3 && r == 3) { SpecialCase333(); } } else if (g == Geometry.Euclidean) { thickness = thickness / 2; threshold = 1 /*20*/; //SimplexCalcs.CalcEScale(); simplex = SimplexCalcs.MirrorsEuclidean(); Vector3D[] verts = SimplexCalcs.VertsEuclidean(); vertex = verts[2]; } else { thickness = thicknessHyperbolic; threshold = 0.01; simplex = SimplexCalcs.Mirrors(p, q, r); Vector3D[] verts = SimplexCalcs.VertsBall(p, q, r); vertex = verts[2]; //Vector3D[] simplexVerts = SimplexCalcs.VertsBall( p, q, r ); //H3.Cell.Edge edge = new H3.Cell.Edge( simplexVerts[2], simplexVerts[3] ); //H3.Cell.Edge edge = SimplexCalcs.HoneycombEdgeBall( p, q, r ); //H3.Cell.Edge[] startingEdges = new H3.Cell.Edge[] { edge }; //H3.Cell.Edge[] edges = Recurse.CalcEdgesSmart2( simplex, startingEdges ); // Vertex Centered. bool vertexCentered = false; if (vertexCentered) { Vector3D v = SimplexCalcs.VertexPointBall(p, q, r); v = H3Models.BallToUHS(v); double scale = 1.0 / v.Abs(); edges = edges.Select(e => { Vector3D start = H3Models.UHSToBall(H3Models.BallToUHS(e.Start) * scale); Vector3D end = H3Models.UHSToBall(H3Models.BallToUHS(e.End) * scale); return(new H3.Cell.Edge(start, end)); }).ToArray(); } // Code to show endpoints of 535 /*using( StreamWriter sw = File.CreateText( "535_points.pov" ) ) * { * HashSet<Vector3D> verts = new HashSet<Vector3D>(); * foreach( H3.Cell.Edge e in edges ) * { * verts.Add( Sterographic.SphereToPlane( e.Start ) ); * verts.Add( Sterographic.SphereToPlane( e.End ) ); * } * * foreach( Vector3D vert in verts ) * if( !Infinity.IsInfinite( vert ) ) * sw.WriteLine( PovRay.Sphere( new Sphere() { Center = vert, Radius = 0.01 } ) ); * }*/ } // Recurse bool dual = false; { H3.Cell.Edge[] startingEdges = null; if (dual) { startingEdges = new H3.Cell.Edge[] { SimplexCalcs.DualEdgeBall(simplex) } } ; else { //startingEdges = new H3.Cell.Edge[] { SimplexCalcs.HoneycombEdgeBall( simplex, vertex ) }; Vector3D[] verts = SimplexCalcs.VertsEuclidean(); Vector3D v1 = verts[0] + 2 * verts[2]; // adjacent cube center Vector3D corner = verts[3]; startingEdges = new H3.Cell.Edge[] { new H3.Cell.Edge(v1, corner) }; } edges = Recurse.CalcEdges(simplex, startingEdges, new Recurse.Settings() { G = g, Threshold = threshold }); edges = edges.Where(e => { int sum = e.Depths.Count(d => d == 0); return(true); }).ToArray(); //CullHalfOfEdges( ref edges ); // No need to cull edges in spherical case. // This was just to generate some images for 350-cell paper. //edges = Cull120Cell( edges ); Simplex tet = new Simplex(); tet.Facets = simplex; if (dual) { H3.Cell.Edge[] oneDualCell = edges.Where(e => e.Depths[2] == 0).ToArray(); simplex = simplex.Skip(1).ToArray(); edges = Recurse.CalcEdges(simplex, oneDualCell, new Recurse.Settings() { G = g, Threshold = threshold }); int[] polyMirrors = new int[] { 0, 1, 3 }; H3.Cell startingCell = HoneycombGen.PolyhedronToHighlight(g, polyMirrors, tet, new Vector3D()); cellsToHighlight = Recurse.CalcCells(simplex, new H3.Cell[] { startingCell }); //cellsToHighlight = new H3.Cell[] { startingCell }; //cellsToHighlight = cellsToHighlight.Skip( 7 ).ToArray(); } else { int[] polyMirrors = new int[] { 1, 2, 3 }; H3.Cell startingCell = HoneycombGen.PolyhedronToHighlight(g, polyMirrors, tet, vertex); //cellsToHighlight = Recurse.CalcCells( simplex, new H3.Cell[] { startingCell } ); cellsToHighlight = new H3.Cell[] { startingCell }; } // Include just one cell? bool includeOne = false; if (includeOne) { edges = edges.Where(e => e.Depths[0] == 0).ToArray(); //cellsToHighlight = cellsToHighlight.Where( c => c.Depths[0] == 0 ).ToArray(); } } // Rotate bool rotate = false; if (rotate) { CompoundOfFive24Cells(ref edges); } // Write the file bool pov = true; if (pov) { string filename = string.Format("{0}{1}{2}.pov", p, q, r); PovRay.WriteEdges(new PovRay.Parameters() { AngularThickness = thickness }, g, edges, filename, append: false); //File.Delete( filename ); //PovRay.AppendFacets( cellsToHighlight, filename ); HashSet <Vector3D> verts = new HashSet <Vector3D>(); foreach (H3.Cell.Edge e in edges) { verts.Add(e.Start); verts.Add(e.End); } /*foreach( Vector3D v in verts ) * { * Vector3D t = v; * t.Normalize(); * t *= 0.9; * System.Diagnostics.Trace.WriteLine( string.Format( "light_source {{ <{0},{1},{2}> White*.2 }}", t.X, t.Y, t.Z ) ); * }*/ /* * // Include the standard pov stuff, so we can batch this. * string fileName = imageData.FormatFilename( string.Empty ); * using( StreamWriter sw = File.CreateText( fileName + ".pov" ) ) * { * sw.WriteLine( "#include \"C:\\Users\\hrn\\Documents\\roice\\povray\\paper\\H3.pov\"" ); * } * * bool dummy = true; // Doesn't matter for Pov-Ray, just Shapeways meshes. * H3.SaveToFile( fileName, edges, dummy, append: true ); */ } else { if (g == Geometry.Spherical) { edges = edges.Where(e => e.Start.Valid() && e.End.Valid() && !Infinity.IsInfinite(e.Start) && !Infinity.IsInfinite(e.End)).ToArray(); S3.EdgesToStl(edges); } else { throw new System.NotImplementedException(); } } }
public void Generate(IList <VERTEX> input, bool assignIds = true, bool checkInput = false) { Clear(); Buffer = new ObjectBuffer <VERTEX>(Dimension); int inputCount = input.Count; if (inputCount < Dimension + 1) { return; } Buffer.AddInput(input, assignIds, checkInput); InitConvexHull(); // Expand the convex hull and faces. while (Buffer.UnprocessedFaces.First != null) { SimplexWrap <VERTEX> currentFace = Buffer.UnprocessedFaces.First; Buffer.CurrentVertex = currentFace.FurthestVertex; UpdateCenter(); // The affected faces get tagged TagAffectedFaces(currentFace); // Create the cone from the currentVertex and the affected faces horizon. if (!Buffer.SingularVertices.Contains(Buffer.CurrentVertex) && CreateCone()) { CommitCone(); } else { HandleSingular(); } // Need to reset the tags int count = Buffer.AffectedFaceBuffer.Count; for (int i = 0; i < count; i++) { Buffer.AffectedFaceBuffer[i].Tag = 0; } } for (int i = 0; i < Buffer.ConvexSimplexs.Count; i++) { SimplexWrap <VERTEX> wrap = Buffer.ConvexSimplexs[i]; wrap.Tag = i; Simplexs.Add(new Simplex <VERTEX>(Dimension)); } for (int i = 0; i < Buffer.ConvexSimplexs.Count; i++) { SimplexWrap <VERTEX> wrap = Buffer.ConvexSimplexs[i]; Simplex <VERTEX> simplex = Simplexs[i]; simplex.IsNormalFlipped = wrap.IsNormalFlipped; simplex.Offset = wrap.Offset; for (int j = 0; j < Dimension; j++) { simplex.Normal[j] = wrap.Normal[j]; simplex.Vertices[j] = wrap.Vertices[j]; if (wrap.AdjacentFaces[j] != null) { simplex.Adjacent[j] = Simplexs[wrap.AdjacentFaces[j].Tag]; } else { simplex.Adjacent[j] = null; } } simplex.CalculateCentroid(); } Buffer.Clear(); Buffer = null; }
private void Implementation() { if (Radical_or_Decimal) { //Прямой ход метода Гаусса для приведения к треугольному виду. StepsSolve.Gauss(ogr, CornerDot); //Выражение базисных переменных и приведение к диагональному виду. StepsSolve.HoistingMatrix(ogr, number_of_basix); // Обновляем данные на таблице //Обновление визуализации переменных. if (CornerDot) { addGridParam(ogr, dataGridView3, variable_visualization); } else { addGridParam(ogr, dataGridView3); } //создаём сиплекс-таблицу simplextable = new Simplex(number_of_basix, number_of_free_variables, ogr, cel_function, true, Radical_or_Decimal); DrawSimplexTable(ogr); } else { //Прямой ход метода Гаусса для приведения к треугольному виду. StepsSolve.Gauss(ogr_with_radicals, CornerDot); //Выражение базисных переменных и приведение к диагональному виду. StepsSolve.HoistingMatrix(ogr_with_radicals, number_of_basix); //Обновление визуализации переменных. if (CornerDot) { addGridParam(ogr_with_radicals, dataGridView3, variable_visualization); } else { addGridParam(ogr_with_radicals, dataGridView3); } //создаём сиплекс-таблицу simplextable = new Simplex(number_of_basix, number_of_free_variables, ogr_with_radicals, cel_function_with_radicals, true, Radical_or_Decimal); DrawSimplexTable(ogr_with_radicals); } int responce; int step = 1; while (true) { if ((responce = simplextable.ResponseCheck()) == 0) { //выбор любого опорного simplextable.SelectionRandomSupportElement(); //меняем местами переменные simplextable.ChangeOfVisualWithoutBuffer(dataGridView3); // высчитывание по опорному simplextable.CalculateSimplexTable(simplextable.row_of_the_support_element, simplextable.column_of_the_support_element); // обновление данных симплекс таблицы if (Radical_or_Decimal) { addGridParam_for_simplex_elements(simplextable.simplex_elements, dataGridView3); } else { addGridParam_for_simplex_elements(simplextable.simplex_elements_with_radicals, dataGridView3); } step++; } else if (responce == 1) { if (MinMax == 0) { if (Radical_or_Decimal) { label_answer.Text = "Ответ :" + simplextable.Response(); } else { label_answer.Text = "Ответ :" + simplextable.Responce_for_radicals().Reduction(); } } else { if (Radical_or_Decimal) { label_answer.Text = "Ответ: " + simplextable.Response() * (-1); } else { label_answer.Text = "Ответ :" + simplextable.Responce_for_radicals().Reduction() * (-1); } } // Выводим точку X* if (corner_dot_was_added == false) { corner_dot_was_added = true; //добавляем точку addGridParam(ResponseDot(), dataGridViewCornerDot); } break; } else if (responce == -1) { MessageBox.Show("Задача не разрешима"); // tabControl1.TabPages[0].Text = "Задача не разрешима!"; break; } } }
private void buttonBack_Click(object sender, EventArgs e) { if (step == 1) { bool Cancel = true; const string message = "Закрыть?"; const string caption = ""; var result = MessageBox.Show(message, caption, MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.Yes) { Cancel = false; } if (!Cancel) { this.Close(); } } else { if (step_1 == 1) { // Достаём из буфера визуализацию variable_visualization = simplextable.GetOutTheBufferVariablevisualizationForDeleteColumns(); basix_variable_visualization = simplextable.GetOutTheBufferVariablevisualizationForDeleteRows(); simplextable = new Simplex(simplextable1); if (Radical_or_Decimal) { addGridParam_for_simplex_elements(simplextable.buffer_simplex_elements[simplextable.buffer_simplex_elements.Count - 1], dataGridView3, variable_visualization, basix_variable_visualization); } else { addGridParam_for_simplex_elements(simplextable.buffer_simplex_elements_for_radicals[simplextable.buffer_simplex_elements_for_radicals.Count - 1], dataGridView3, variable_visualization, basix_variable_visualization); } // достаём из буффера симлпекс элементы simplextable.GetOutOfTheBufferSimplex_ForArtifical(); step--; step_1--; label1.Text = "Метод искусственного базиса. Выбор опорного элемента."; //меняем местами переменные обратно simplextable.ChangeOfVisualizationVariables_GetOutTheBuffer(dataGridView3); simplextable.SelectionOfTheSupportElement(dataGridView3); ArtificalBasixGoToNull = false; buttonNext.Enabled = true; return; } else if (step_1 > 1) { buttonNext.Enabled = true; label_answer.Visible = false; groupBoxCornerDot.Visible = false; //убираем кнопки simplextable.delete_green_grids(dataGridView3); //меняем местами переменные обратно simplextable.ChangeOfVisualizationVariables_GetOutTheBuffer(dataGridView3); //выводим данные из буфера simplextable.GetOutOfTheBufferSimplex_ForArtifical(); //отрисовываем if (Radical_or_Decimal) { addGridParam_for_simplex_elements(simplextable.simplex_elements, dataGridView3); } else { addGridParam_for_simplex_elements(simplextable.simplex_elements_with_radicals, dataGridView3); } step_1--; label1.Text = "Метод искусственного базиса. Выбор опорного элемента."; simplextable.SelectionOfTheSupportElement(dataGridView3); // очищаем буфер на один шаг simplextable.buffer_delete_artifical_columns.RemoveAt(simplextable.buffer_delete_artifical_columns.Count - 1); simplextable.buffer_delete_artifical_rows.RemoveAt(simplextable.buffer_delete_artifical_rows.Count - 1); return; } //убираем кнопки simplextable.delete_green_grids(dataGridView3); //меняем местами переменные обратно simplextable.ChangeOfVisualizationVariables_GetOutTheBuffer(dataGridView3); //выводим данные из буфера simplextable.GetOutOfTheBufferSimplex_ForArtifical(); //отрисовываем if (Radical_or_Decimal) { addGridParam_for_simplex_elements(simplextable.simplex_elements, dataGridView3); } else { addGridParam_for_simplex_elements(simplextable.simplex_elements_with_radicals, dataGridView3); } step--; label1.Text = "Метод искусственного базиса. Выбор опорного элемента"; simplextable.SelectionOfTheSupportElement(dataGridView3); } }
internal static global::System.Runtime.InteropServices.HandleRef getCPtr(Simplex obj) { return((obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr); }
/// <summary> /// Запуск программы симплекса. /// </summary> public static void Main() => Simplex.UI();
public static void SimplexSeed(long seed) => Simplex = new Simplex(seed);
/// <summary> /// Ritorna la distanza se distanza 0.0f allora vi è intersezione o compenetrazione tra gli oggetti, /// se distanza 0.0 allora i due oggetti non collidono /// </summary> /// <returns>The GJK algorithm.</returns> /// <param name="shape1">Shape1.</param> /// <param name="shape2">Shape2.</param> /// <param name="cp">Cp.</param> /// <param name="isIntersection">If set to <c>true</c> is itersection.</param> private double ExecuteGJKAlgorithm( SimulationObject shape1, SimulationObject shape2, int geometryIndexA, int geometryIndexB, ref Vector3 collisionNormal, ref CollisionPoint cp, ref List<SupportTriangle> triangles, ref Vector3 centroid, ref bool isIntersection) { double minDistance = double.MaxValue; int minTriangleIndex = -1; var result = new EngineCollisionPoint(); var oldDirection = new Vector3(); var simplex = new Simplex(); //Primo punto del simplex simplex.Support.Add(GetFarthestPoint(shape1, shape2)); //Secondo punto del simplex Vector3 direction = Vector3.Normalize(simplex.Support[0].s * -1.0); if (!simplex.AddSupport(Helper.GetMinkowskiFarthestPoint(shape1, shape2, geometryIndexA, geometryIndexB, direction))) return -1.0; //Terzo punto del simplex direction = Vector3.Normalize(GetDirectionOnSimplex2(simplex)); if(!simplex.AddSupport(Helper.GetMinkowskiFarthestPoint(shape1, shape2, geometryIndexA, geometryIndexB, direction))) return -1.0; //Quarto punto del simplex direction = Vector3.Normalize(GeometryUtilities.CalculateNormal( simplex.Support[0].s, simplex.Support[1].s, simplex.Support[2].s)); if (!simplex.AddSupport(Helper.GetMinkowskiFarthestPoint(shape1, shape2, geometryIndexA, geometryIndexB, direction))) simplex.AddSupport(Helper.GetMinkowskiFarthestPoint(shape1, shape2, geometryIndexA, geometryIndexB, -1.0 * direction)); //Costruisco il poliedro centroid = Helper.SetStartTriangle( ref triangles, simplex.Support.ToArray()); //Verifico che l'origine sia contenuta nel poliedro if (Helper.IsInConvexPoly(origin, triangles)) { isIntersection = true; return -1.0; } Vector3 triangleDistance = GetMinDistance(ref triangles, origin, ref minTriangleIndex); result.SetDist(triangleDistance); result.SetNormal(Vector3.Normalize(triangleDistance)); Helper.GetVertexFromMinkowsky(triangles[minTriangleIndex], shape1, shape2, ref result); minDistance = triangleDistance.Length(); for (int i = 0; i < MaxIterations; i++) { direction = -1.0 * triangleDistance.Normalize(); if (Vector3.Length(direction) < constTolerance) { direction = origin - centroid; } if (direction == oldDirection) break; oldDirection = direction; if (!simplex.AddSupport(Helper.GetMinkowskiFarthestPoint(shape1, shape2, geometryIndexA, geometryIndexB, direction))) { for (int j = 0; j < triangles.Count; j++) { direction = triangles[j].normal; if (!simplex.AddSupport(Helper.GetMinkowskiFarthestPoint(shape1, shape2, geometryIndexA, geometryIndexB, direction))) { if (simplex.AddSupport(Helper.GetMinkowskiFarthestPoint(shape1, shape2, geometryIndexA, geometryIndexB, -1.0 * direction))) break; continue; } break; } } triangles = Helper.AddPointToConvexPolygon(triangles, simplex.Support[simplex.Support.Count - 1], centroid); //Verifico che l'origine sia contenuta nel poliedro if (Helper.IsInConvexPoly(origin, triangles)) { isIntersection = true; return -1.0; } triangleDistance = GetMinDistance(ref triangles, origin, ref minTriangleIndex); double mod = triangleDistance.Length(); if (mod < minDistance) { result.SetDist(triangleDistance); result.SetNormal(Vector3.Normalize(triangleDistance)); Helper.GetVertexFromMinkowsky(triangles[minTriangleIndex], shape1, shape2, ref result); minDistance = mod; } } collisionNormal = -1.0 * result.normal; cp = new CollisionPoint( result.a, result.b, collisionNormal); return minDistance; }
public Planet() { Noise = new Simplex(); }
internal static global::System.Runtime.InteropServices.HandleRef getCPtr(Simplex obj) { return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr; }
private void ShowView() { string state = Session["state"] as string; Simplex simplex; switch (state) { case "phase3nextstep": this.field = (SimplexField) Session["field"]; simplex = new Simplex(this.field); simplex.NextStep(); this.field = simplex.Field; this.DrawField(); this.MultiView1.SetActiveView(this.View3); Session["field"] = this.field; if (simplex.isComplete()) { this.nextButton.Enabled = false; } break; case "phase3refresh": this.field = (SimplexField) Session["field"]; this.DrawField(); this.MultiView1.SetActiveView(this.View3); break; case "phase3": this.GenerateField(); simplex = new Simplex(this.field); simplex.SetPivotElement(); this.field = simplex.Field; this.DrawField(); this.MultiView1.SetActiveView(this.View3); break; case "phase2": this.MultiView1.SetActiveView(this.View2); break; case "start": case null: default: Application["state"] = "start"; this.MultiView1.SetActiveView(this.View1); break; } }