/// <summary> /// Gets the section geometrical properties. /// </summary> /// <returns>An array containing geometrical properties of section</returns> /// <remarks> /// This is the order of returned array: [Iz,Iy,J,A,Ay,Az] /// Note: Ay and Az are spotted as same value as A (e.g. Ay = A and Az = A) /// </remarks> public double[] GetSectionGeometricalProperties() { var lastPoint = this.points[this.points.Count - 1]; if (lastPoint != points[0]) { throw new InvalidOperationException("First point and last point ot PolygonYz should put on each other"); } double a = 0.0, iz = 0.0, iy = 0.0, ixy = 0.0; var x = new double[this.points.Count]; var y = new double[this.points.Count]; for (int i = 0; i < points.Count; i++) { x[i] = points[i].Y; y[i] = points[i].Z; } var l = points.Count - 1; var ai = 0.0; for (var i = 0; i < l; i++) { ai = x[i] * y[i + 1] - x[i + 1] * y[i]; a += ai; iy += (y[i] * y[i] + y[i] * y[i + 1] + y[i + 1] * y[i + 1]) * ai; iz += (x[i] * x[i] + x[i] * x[i + 1] + x[i + 1] * x[i + 1]) * ai; ixy += (x[i] * y[i + 1] + 2 * x[i] * y[i] + 2 * x[i + 1] * y[i + 1] + x[i + 1] * y[i]) * ai; } a = a * 0.5; iz = iz * 1 / 12.0; iy = iy * 1 / 12.0; ixy = ixy * 1 / 24.0; var j = iy + iz; //not sure which one is correct j = ix + iy or j = ixy :)! var buf = new double[] { iz, iy, j, a, a, a }; if (a < 0) { for (var i = 0; i < 6; i++) { buf[i] = -buf[i]; } } Debug.Assert(buf.All(i => i >= 0)); return(buf); }
public static bool IsEquilateral(double side1, double side2, double side3) { if (!IsTriangleValid(side1, side2, side3)) { return(false); } double[] sides = new double[3] { side1, side2, side3 }; return(sides.All(x => x == side1) ? true : false); }
public void SubCTest_double() { foreach (int length in new[] { 24, 128 }) { double[] a = new double[length]; double[] y = new double[length]; Vectors.Set(length, 0, a, 0); Mathematics.SubC(length, a, 0, 1, y, 0); Assert.IsTrue(y.All(x => x == -1)); Vectors.Set(length, double.NegativeInfinity, a, 0); Mathematics.SubC(length, a, 0, 1, y, 0); Assert.IsTrue(y.All(x => double.IsNegativeInfinity(x))); Vectors.Set(length, double.PositiveInfinity, a, 0); Mathematics.SubC(length, a, 0, 1, y, 0); Assert.IsTrue(y.All(x => double.IsPositiveInfinity(x))); Vectors.Set(length, double.MinValue, a, 0); Mathematics.SubC(length, a, 0, 1, y, 0); Assert.IsTrue(y.All(x => x == double.MinValue)); Vectors.Set(length, double.MaxValue, a, 0); Mathematics.SubC(length, a, 0, 1, y, 0); Assert.IsTrue(y.All(x => x == double.MaxValue)); Vectors.Set(length, double.NaN, a, 0); Mathematics.SubC(length, a, 0, 1, y, 0); Assert.IsTrue(y.All(x => double.IsNaN(x))); } }
public double LineSalience(int n, string line) { var counter = new CodegramCounter(); var identifiersGrams = counter.IdentifierSequences(n, line).ToList(); var wordGrams = counter.WordSequences(n, line).ToList(); var words = counter.AllWords(line).Select(w => w.ToLower()).ToList(); var identifiers = counter.AllIdentifiers(line).Select(ident => ident.ToLower()).ToList(); var sumIdentifierGrams = 0.0; var sumWordGrams = 0.0; var sumWords = 0.0; var sumIdentifiers = 0.0; foreach (var word in words) { sumWords += (ReadCommands.LookupWordFrequency(Connection, Cache, word) + 1) / (double)WordCount; } foreach (var ident in identifiers) { sumIdentifiers += (ReadCommands.LookupIdentifierFrequency(Connection, Cache, ident) + 1) / (double)IdentifierCount; } foreach (var wordGram in wordGrams) { sumWordGrams += (SequenceWordFrequency(wordGram) + 1) / (double)WordSequenceCount; } foreach (var identGram in identifiersGrams) { sumIdentifierGrams += (SequenceIdentifierFrequency(identGram) + 1) / (double)IdentifierSequenceCount; } var vals = new double[] { sumWords, sumIdentifiers, sumWordGrams, sumIdentifierGrams }; if (vals.All(v => v == 0.0)) { return(0.0); } var multiplier = 1.0; if (words.Count == 1 && identifiers.Count == 1) { //Console.Write(line); multiplier = 0.01; } var salience = (vals.Where(s => s > 0.0).Min() / vals.Max()) * multiplier; return(salience); //return sumIdentifierGrams / IdentifierCount; }
public void NextDouble_ReturnsValuesBetween0And1() { // Arrange var randomValues = new double[Iterations]; var rng = new SecureRandomNumberGenerator(); // Action for (var i = 0; i < Iterations; i++) { randomValues[i] = rng.NextDouble(); } // Assert Assert.IsTrue(randomValues.All(x => x >= 0 && x < 1)); }
public void No_Arg_All_Values_Are_Between_Zero_And_MaxValue() { var doubles = new double[Assertion.Amount]; for (var i = 0; i < Assertion.Amount; i++) { doubles[i] = DoubleProvider.Double(); } doubles.AssertNotAllValuesAreTheSame(); Assert.True( doubles.All(x => x >= 0 && x < double.MaxValue), "doubles.All(x => x >= 0 && x < double.MaxValue)" ); }
public void MoreComplexTasks() { var Results = new double[100]; var TestObject = new TaskQueue <int>(4, x => { Results[x] = 2 * F(1); return(true); }); for (var x = 0; x < 100; ++x) { Assert.True(TestObject.Enqueue(x)); } while (!TestObject.IsComplete) { Thread.Sleep(100); } Assert.True(Results.All(x => System.Math.Abs(x - 3.14159d) < EPSILON)); }
public void Inclusive_Min_Arg() { var doubles = new double[Assertion.Amount]; const double arg = 100; for (var i = 0; i < Assertion.Amount; i++) { doubles[i] = DoubleProvider.Double(arg, arg); } Assert.True( doubles.All(x => x == arg), "doubles.All(x => x == arg)" ); }
public void All_Values_Are_Between_Zero_And_Max() { var doubles = new double[Assertion.Amount]; const double max = 200; for (var i = 0; i < Assertion.Amount; i++) { doubles[i] = DoubleProvider.Double(max); } doubles.AssertNotAllValuesAreTheSame(); Assert.True( doubles.All(x => x >= 0 && x < max), "doubles.All(x => x >= 0 && x < max)" ); }
/// <summary> /// Gets the section geometrical properties. /// </summary> /// <returns>An array containing geometrical properties of section</returns> /// <remarks> /// This is the order of returned array: [Iz,Iy,J,A,Ay,Az] /// Note: Ay and Az are spotted as same value as A (e.g. Ay = A and Az = A) /// </remarks> public static double[] GetSectionGeometricalProperties(PointYZ[] pts) { var lastPoint = pts.Last(); if (lastPoint != pts[0]) { throw new InvalidOperationException("First point and last point ot PolygonYz should put on each other"); } double a = 0.0, iz = 0.0, iy = 0.0, iyz = 0.0; var l = pts.Length - 1; var ai = 0.0; for (var i = 0; i < l; i++) { ai = pts[i].Y * pts[i + 1].Z - pts[i + 1].Y * pts[i].Z; a += ai; iy += (pts[i].Z * pts[i].Z + pts[i].Z * pts[i + 1].Z + pts[i + 1].Z * pts[i + 1].Z) * ai; iz += (pts[i].Y * pts[i].Y + pts[i].Y * pts[i + 1].Y + pts[i + 1].Y * pts[i + 1].Y) * ai; iyz += (pts[i].Y * pts[i + 1].Z + 2 * pts[i].Y * pts[i].Z + 2 * pts[i + 1].Y * pts[i + 1].Z + pts[i + 1].Y * pts[i].Z) * ai; } a = a * 0.5; iz = iz * 1 / 12.0; iy = iy * 1 / 12.0; iyz = iyz * 1 / 24.0; var j = iy + iz; //not sure which one is correct j = ix + iy or j = ixy :)! var buf = new double[] { iy, iz, j, a, a, a }; if (a < 0) { for (var i = 0; i < 6; i++) { buf[i] = -buf[i]; } } Debug.Assert(buf.All(i => i >= 0)); return(buf); }
public double SimulateUntilMatch() { double iteration = 0; double[] intersectsAt = new double[] { -1, -1, -1 }; while (true) { foreach (var body in _bodies) { body.Interact(_bodies.Except(new[] { body })); } foreach (var body in _bodies) { body.ApplyVelocity(); } iteration++; if (intersectsAt[0] == -1 && _bodies.All(x => x.Velocity.X == 0)) { intersectsAt[0] = iteration; } if (intersectsAt[1] == -1 && _bodies.All(x => x.Velocity.Y == 0)) { intersectsAt[1] = iteration; } if (intersectsAt[2] == -1 && _bodies.All(x => x.Velocity.Z == 0)) { intersectsAt[2] = iteration; } if (intersectsAt.All(time => time > -1)) { break; } } var leastCommonMultiple = LCM(intersectsAt[0], LCM(intersectsAt[1], intersectsAt[2])) * 2; return(leastCommonMultiple); }
public void Exclusive_Max_Arg() { var doubles = new double[Assertion.Amount]; const double max = 100; const double min = max - MaxSupportedPrecision; for (var i = 0; i < Assertion.Amount; i++) { doubles[i] = DoubleProvider.Double(min, max); } doubles.AssertNotAllValuesAreTheSame(); Assert.True( doubles.All(x => x < max), "doubles.All(x => x < max)" ); }
public void TestArrayFastFill() { var testArray = new double[TestSize]; var stopwatch = new Stopwatch(); stopwatch.Start(); for (int n = 0; n < 10; n++) { testArray.FastFill(4.123456); } stopwatch.Stop(); Debug.WriteLine("Time taken:" + stopwatch.Elapsed); Assert.IsTrue(testArray.All(value => value == 4.123456)); }
public void NextDouble_WithSeed_ReturnsAlwaysTheSameValue() { // Arrange var randomValues = new double[Iterations]; var seed = new System.Random().Next(); // Action for (var i = 0; i < Iterations; i++) { var rng = new DefaultRandomNumberGenerator(seed); randomValues[i] = rng.NextDouble(); var a = randomValues[i]; Console.WriteLine(randomValues[i]); } // Assert Assert.IsTrue(randomValues.All(x => x == randomValues[0])); }
public bool checkSolve(List <double> lst, double E) { double[] errors = new double[n]; for (int i = 0; i < n; i++) { double sum = 0; for (int j = 0; j < n; j++) { sum += matrix[i][j] * lst[j]; } errors[i] = sum - matrix[i][n]; } if (errors.All(t => t < E)) { return(true); } return(false); }
public NaiveBayesClassifier(DataSample[] samples, int classes, ColumnDataType[] columnDataTypes) { _classes = classes; _distribution = new IDistribution[classes, columnDataTypes.Length]; _classesProbablityDistribution = new CategoricalDistribution( samples.Select(item => item.ClassId).ToArray(), classes); var splitDataPerClass = SplitDataPerClass(samples, _classes, columnDataTypes.Length); var groups = GetClassGroups(samples, _classes); for (int index = 0; index < columnDataTypes.Length; index++) { //var values = GetDataPerClass(samples, _classes, index); Double[][] values = new double[classes][]; for (int classIndex = 0; classIndex < classes; classIndex++) { values[classIndex] = splitDataPerClass[index, classIndex]; } //var values = splitDataPerClass[index,_] if (values.All(item => item == null)) { continue; } for (int classIndex = 0; classIndex < classes; classIndex++) { var itemsOnClass = values[classIndex] ?? new double[0]; if (!columnDataTypes[index].IsDiscrete) { _distribution[classIndex, index] = new GaussianDistribution(itemsOnClass); } else { _distribution[classIndex, index] = new CategoricalDistribution(itemsOnClass.Select(Convert.ToInt32).ToArray(), columnDataTypes[index].NumberOfCategories, groups[classIndex]); } } } }
private void RandomizeWeights(Layer[] layers) { // setting 1 weight value for input layer neurons var inputWeights = new double[Layers[1].Neurons.Length]; inputWeights.All(w => { w = 1; return(true); }); Layers.First().Neurons.All(n => { n.SetWeights(inputWeights); return(true); }); var random = new Random(); for (var i = 1; i < layers.Length; i++) { for (var y = 0; y < layers[i].Neurons.Length; y++) { var weights = new double[layers[i - 1].Neurons.Length]; weights.All(w => { w = random.NextDouble(); return(true); }); layers[i].Neurons[y].SetWeights(weights); } } }
private double[] Backpropagation(double[] expected, double[] inputSignals) { Run(inputSignals); var error = new double[OutputSignals.Length]; for (var i = 0; i < error.Length; i++) { error[i] = OutputSignals[i] - expected[i]; Layers.Last().Neurons[i].Learn(error[i], LearningRate); } for (var y = Layers.Length - 2; y > 0; y--) { var layer = Layers[y]; var forwardLayer = Layers[y + 1]; for (var i = 0; i < layer.Neurons.Length; i++) { var neuron = layer.Neurons[i]; for (var k = 0; k < forwardLayer.Neurons.Length; k++) { var forwardNeuron = forwardLayer.Neurons[k]; var neuronError = forwardNeuron.Weights[i] * forwardNeuron.Delta; neuron.Learn(neuronError, LearningRate); } } } // returning square of error var result = new double[error.Length]; result.All(r => { r *= r; return(true); }); return(result); }
public void Solve() { var __ = sc.Integer(); for (int _ = 1; _ <= __; _++) { var n = sc.Integer(); var V = sc.Double(); var X = sc.Double(); var r = new double[n]; var c = new double[n]; for (int i = 0; i < n; i++) { r[i] = sc.Double(); c[i] = sc.Double(); } if (n == 1) { if (c[0] == X) { IO.Printer.Out.WriteLine("Case #{0}: {1:0.000000000000}", _, V / r[0]); } else { IO.Printer.Out.WriteLine("Case #{0}: IMPOSSIBLE", _); } } else if (n == 2) { if (c.All(x => x > X) || c.All(x => x < X)) { IO.Printer.Out.WriteLine("Case #{0}: IMPOSSIBLE", _); } else if (c[0] == X && c[1] == X) { var ans = V / (r[0] + r[1]); IO.Printer.Out.WriteLine("Case #{0}: {1:0.000000000000}", _, ans); } else if (c[0] == X) { var ans = V / (r[0]); IO.Printer.Out.WriteLine("Case #{0}: {1:0.000000000000}", _, ans); } else if (c[1] == X) { var ans = V / (r[1]); IO.Printer.Out.WriteLine("Case #{0}: {1:0.000000000000}", _, ans); } else { var v0 = Math.Abs(V * (X - c[1]) / (c[1] - c[0])); var v1 = V - v0; var ans = Math.Max(v0 / r[0], v1 / r[1]); IO.Printer.Out.WriteLine("Case #{0}: {1:0.000000000000}", _, ans); } } else { IO.Printer.Out.WriteLine("Case #{0}: OTAKU", _); } //IO.Printer.Out.WriteLine("Case #{0}: {1}", _); } }
static int[] GetGauss(double[][] slae) { int w = slae[0].Length; int h = slae.Length; double[] dAns = new double[w]; int[] iAns = new int[w]; double divCoef = 1; for (int k = 0; k < Math.Min(w - 1, h); k++) // Проход по диагонали { int l = k; // while (l + 1 < h && slae[l][k] == 0) // { l++; // Выведение наверх строчки } if (l != k) // с ненулевым начальным элементом { // var temp = slae[k]; // slae[k] = slae[l]; // slae[l] = temp; // } // if (slae[k][k] != 1) // { // var pivot = slae[k][k]; // for (int j = k; j < w; j++) // Делаем начальный элемент равным единице, { slae[k][j] /= pivot; // проходя по строке и деля её на него } divCoef *= pivot; } for (int i = k + 1; i < h; i++) // Проход по столбцам для обнуления { if (slae[i][k] != 0) // нижнего треугольника { double m = slae[i][k] / slae[k][k]; for (int j = k; j < w; j++) // Обнуление k столбца ниже k строки { slae[i][j] -= m * slae[k][j]; // (проход по строкам) } divCoef *= slae[k][k]; } } } for (int k = Math.Min(w - 2, h - 1); k >= 0; k--) // Проход по диагонали снизу вверх для // создания единичной матрицы в левой части { for (int i = k - 1; i >= 0; i--) // Проход по столбцам для обнуления строки над 1 { if (slae[i][k] != 0) { double m = slae[i][k] / slae[k][k]; // Обнуление k столбца выше k строки for (int j = k; j < w; j += w - k - 1) // (проход по строкам) { slae[i][j] -= m * slae[k][j]; } divCoef *= slae[k][k]; } } } dAns[w - 1] = 1; for (int i = 0; i < w - 1; i++) { dAns[i] = -slae[i][w - 1]; } if (dAns.All(i => i % 1 == 0)) { for (int j = 0; j < w; j++) { iAns[j] = (int)dAns[j]; } } else { for (int j = 0; j < w; j++) { dAns[j] = dAns[j] * Math.Abs(divCoef); iAns[j] = (int)Math.Round(dAns[j]); } int gcd = GCD(iAns); for (int i = 0; i < w; i++) { iAns[i] /= gcd; } } return(iAns); }
public void OptimizeParallelInsertsForDifferentGroups() { var tests = new ListOfTuples <string, string, bool> // Format: // 1. Records to insert (Grouping1-Grouping2) to entity MultipleGroups, with parallel requests. // 2. Expected generated codes (Code1-Code2) for each record. // 3. Whether the inserts should be executed in parallel. { { "A-B, A-B", "1-1, 2-2", false }, // Same Grouping1 and Grouping2: codes should be generated sequentially. { "A-B, A-C", "1-1, 2-1", false }, // Same Grouping1: Code1 should be generated sequentially. { "A-B, C-B", "1-1, 1-2", false }, // Same Grouping2: Code2 should be generated sequentially. { "A-B, C-D", "1-1, 1-1", true }, { "A-B, B-A", "1-1, 1-1", true }, }; var results = new ListOfTuples <string, string, bool>(); var report = new List <string>(); const int testPause = 100; const int retries = 4; foreach (var test in tests) { for (int retry = 0; retry < retries; retry++) { var items = test.Item1.Split(',').Select(item => item.Trim()).Select(item => item.Split('-')) .Select(item => new TestAutoCode.MultipleGroups { Grouping1 = item[0], Grouping2 = item[1] }) .ToArray(); var insertDurations = new double[items.Length]; var parallelInsertRequests = items.Select((item, x) => (Action <Common.ExecutionContext>) (context => { var sw = Stopwatch.StartNew(); context.Repository.TestAutoCode.MultipleGroups.Insert(item); insertDurations[x] = sw.Elapsed.TotalMilliseconds; Thread.Sleep(testPause); })) .ToArray(); var exceptions = ExecuteParallel(parallelInsertRequests, context => context.Repository.TestAutoCode.MultipleGroups.Insert(new TestAutoCode.MultipleGroups { }), context => Assert.AreEqual(1, context.Repository.TestAutoCode.MultipleGroups.Query().Count(), $"({test.Item1}) Test initialization failed.")); Assert.IsTrue(exceptions.All(e => e == null), $"({test.Item1}) Test initialization threw exception. See the test output for details"); // Check the generated codes: string generatedCodes; using (var container = new RhetosTestContainer(false)) { var repository = container.Resolve <Common.DomRepository>(); generatedCodes = TestUtility.DumpSorted( repository.TestAutoCode.MultipleGroups.Load(items.Select(item => item.ID)), x => $"{x.Code1}-{x.Code2}"); } // Check if the inserts were executed in parallel: bool startedImmediately = insertDurations.Any(t => t < testPause); bool executedInParallel = insertDurations.All(t => t < testPause); // It the parallelism check did not pass, try again to reduce false negatives when the test machine is under load. if (!startedImmediately || executedInParallel != test.Item3) { Console.WriteLine("Retry"); continue; } Assert.IsTrue(startedImmediately, $"({test.Item1}) At lease one item should be inserted without waiting. The test machine was probably under load during the parallelism test."); report.Add($"Test '{test.Item1}' insert durations: '{TestUtility.Dump(insertDurations)}'."); results.Add(test.Item1, generatedCodes, executedInParallel); break; } } Assert.AreEqual( string.Concat(tests.Select(test => $"{test.Item1} => {test.Item2} {(test.Item3 ? "parallel" : "sequential")}\r\n")), string.Concat(results.Select(test => $"{test.Item1} => {test.Item2} {(test.Item3 ? "parallel" : "sequential")}\r\n")), "Report: " + string.Concat(report.Select(line => "\r\n" + line))); }
public bool PriceOut() { for (int j = 0; j < B_1.GetLength(0); j++) { double answer2 = 0; for (int k = 0; k < B_1.GetLength(1); k++) { answer2 = answer2 + cB[k] * B_1[j, k]; } cBB_1[j] = answer2; } double[,] nBV = new double[iN.Length, A.GetLength(1)]; nBV = GetNBVArray(); double[] answers = new double[iN.Length]; for (int j = 0; j < nBV.GetLength(0); j++) { double answer = 0; double tempanswer = 0; for (int k = 0; k < nBV.GetLength(1); k++) { tempanswer = tempanswer + cBB_1[k] * nBV[j, k]; } answer = answer + tempanswer; answers[j] = answer; } double[] tempNBVObjetiveCoeficientsPositions = new double[iN.Length]; for (int i = 0; i < tempNBVObjetiveCoeficientsPositions.Length; i++) { tempNBVObjetiveCoeficientsPositions[i] = iN[i]; } for (int i = 0; i < answers.Length; i++) { answers[i] = answers[i] - c[int.Parse(tempNBVObjetiveCoeficientsPositions[i].ToString())]; } bool allNonNegative = false; bool allNegative = false; if (lpType == "max") { allNonNegative = answers.All(x => x >= 0); allNegative = false; } else { allNegative = answers.All(x => x <= 0); allNonNegative = false; } if ((allNonNegative == true && allNegative == false) || (allNegative == true && allNonNegative == false)) { for (int j = 0; j < B_1.GetLength(0); j++) { double answer3 = 0; for (int k = 0; k < B_1.GetLength(1); k++) { answer3 = answer3 + b[k + 1] * B_1[k, j]; } newRHS[j] = answer3; } return(true); } else { double tempFind = answers.Min(); int position = 0; int tempNBVPosition = 0; for (int i = 0; i < answers.Length; i++) { if (answers[i] == tempFind) { position = iN[i]; tempNBVPosition = i; } } int tempNBVToBVNumber = position; //To compute the column in the current table double[] tempcolum = new double[nBV.GetLength(0)]; for (int j = 0; j < B_1.GetLength(0); j++) { double answer3 = 0; for (int k = 0; k < B_1.GetLength(1); k++) { answer3 = answer3 + A[position, k] * B_1[k, j]; } tempcolum[j] = answer3; } //To compute the RHS of the current table double[] tempRHS = new double[nBV.GetLength(0)]; for (int j = 0; j < B_1.GetLength(0); j++) { double answer3 = 0; for (int k = 0; k < B_1.GetLength(1); k++) { answer3 = answer3 + b[k + 1] * B_1[k, j]; } tempRHS[j] = answer3; } for (int i = 0; i < newRHS.Length; i++) { newRHS[i] = tempRHS[i]; } //Ratio test double[] ratios = new double[tempRHS.Length]; for (int i = 0; i < tempRHS.Length; i++) { ratios[i] = tempRHS[i] / tempcolum[i]; } //Finding the smallest ratio double temp = 0; for (int i = 0; i < ratios.Length; i++) { for (int j = 0; j < ratios.Length - 1; j++) { if (ratios[j] > ratios[j + 1]) { if (ratios[j + 1] > 0) { temp = ratios[j + 1]; } } else { if (ratios[j] > 0) { temp = ratios[j]; } } } } for (int i = 0; i < ratios.Length; i++) { if (ratios[i] == temp) { position = i; } } int tempBVToNBVposition = position; int tempBVToNBV = 0; for (int i = 0; i < iB.Length; i++) { if (i == tempBVToNBVposition) { tempBVToNBV = iB[i]; } } //Used to define the new basic and non basic variables iB[tempBVToNBVposition] = tempNBVToBVNumber; iN[tempNBVPosition] = tempBVToNBV; for (int i = 0; i < iB.Length; i++) { cB[i] = c[iB[i]]; } //Calculate the new values of the column using product form double[] tempColumn = new double[tempcolum.Length]; double piviotValue = tempcolum[position]; for (int i = 0; i < tempColumn.Length; i++) { if (i == position) { tempColumn[i] = 1 / tempcolum[i]; } else { tempColumn[i] = tempcolum[i] / piviotValue; tempColumn[i] = tempColumn[i] * -1; } } double[,] elementaryMatrix = new double[I.GetLength(0), I.GetLength(1)]; for (int i = 0; i < I.GetLength(0); i++) { for (int j = 0; j < I.GetLength(1); j++) { elementaryMatrix[i, j] = I[i, j]; } } double[,] tempB_1 = new double[B_1.GetLength(0), B_1.GetLength(1)]; //Creating the elementary matrix for (int i = 0; i < tempColumn.Length; i++) { elementaryMatrix[position, i] = tempColumn[i]; } tempB_1 = multiplyarr(elementaryMatrix, B_1); B_1 = tempB_1; return(PriceOut()); } }
/// <summary> /// Применение метода широкополосного сигнала /// Извлечение данных из графического файла /// </summary> /// <param name="bbsOptions">Параметры алгоритма включая графический файл с внедрёнными данными</param> /// <returns>Извлечённые данные</returns> public static string Unpack(BbsOptions bbsOptions) { Debug.WriteLine(bbsOptions.ToString()); var key = bbsOptions.Key; var expandSize = bbsOptions.ExpandSize; var codeSize = bbsOptions.EccCodeSize; var dataSize = bbsOptions.EccDataSize; var filterStep = bbsOptions.FilterStep; var eccIndex = bbsOptions.EccIndex; var mixerIndex = bbsOptions.MixerIndex; var gammaIndex = bbsOptions.GammaIndex; var archiverIndex = bbsOptions.ArchiverIndex; var zipperIndex = bbsOptions.ZipperIndex; double alpha = bbsOptions.Alpha; double betta = 0; var dhtMode = bbsOptions.DhtMode; var autoAlpha = bbsOptions.AutoAlpha; var maximumGamma = bbsOptions.MaximumGamma; var extractBarcode = bbsOptions.ExtractBarcode; var bitmap = bbsOptions.InputBitmap; if (extractBarcode) { using (var barcode = new Barcode(bitmap.Bitmap)) { // Извлечение параметров из внедрённого в изображение баркода // и использование этих извлечённых параметров для используемых алгоритмов barcode.Decode(); archiverIndex = barcode.ArchiverIndex; eccIndex = barcode.EccIndex; mixerIndex = barcode.MixerIndex; gammaIndex = barcode.GammaIndex; // ints expandSize = barcode.ExpandSize; codeSize = barcode.EccCodeSize; dataSize = barcode.EccDataSize; // bools dhtMode = barcode.DhtMode; autoAlpha = barcode.AutoAlpha; maximumGamma = barcode.MaximumGamma; // strings key = barcode.Key; Debug.WriteLine(barcode.ToString()); } } using (var builder = new BlurBuilder(filterStep)) bbsOptions.MedianBitmap = new CvBitmap(bitmap, builder); var median = bbsOptions.MedianBitmap; var length = bitmap.Length; var index = new int[length]; var colors = new double[length]; var medianColors = new double[length]; var data = new byte[length / expandSize / BitsPerByte]; using (var builder = new Mixer(mixerIndex, key)) builder.GetInts(index); var gamma = new byte[maximumGamma ? ((length + BitsPerByte - 1) / BitsPerByte) : ((expandSize + BitsPerByte - 1) / BitsPerByte)]; using (var builder = new Gamma(gammaIndex, key)) builder.GetBytes(gamma); var bitmapDataContainer = dhtMode ? new HartleyOfBitmap(bitmap) : (IDataContainer)bitmap; bitmapDataContainer.Select(index, colors); var medianDataContainer = dhtMode ? new HartleyOfBitmap(median) : (IDataContainer)median; medianDataContainer.Select(index, medianColors); Debug.Assert(dhtMode || colors.All(x => x >= 0)); Debug.Assert(dhtMode || medianColors.All(x => x >= 0)); // Рассчёт весов пикселей var middle = medianColors.Average(); var weight = medianColors.Select(x => F / (F + Math.Abs(x - middle))).ToArray(); var average = weight.Average(); weight = weight.Select(x => x / average).ToArray(); var delta = colors.Zip(medianColors, (x, y) => (x - y)).Zip(weight, (x, y) => x * y).ToArray(); if (autoAlpha) { // Вычисление параметров из характеристик полученных данных var e1 = delta.Average(x => x); var e2 = delta.Average(x => x * x); betta = e1; bbsOptions.Alpha = (int)Math.Ceiling(alpha = Math.Sqrt(e2 - e1 * e1)); Debug.WriteLine("alpha = {0} betta = {1}", alpha, betta); } using (var bbSignals = new BbSignals(expandSize, maximumGamma)) bbSignals.Extract(delta, data, gamma, alpha, betta); Debug.WriteLine(string.Join("", data.Select(x => x.ToString("X02")))); // В дополнение к самому методу широкополосного сигнала данные могут быть сжаты алгоритмом компрессии данных, // добавлены коды исправления ошибок, последовательности бит могут размещаться в изображении не последовательно, а в // соответствии с выбранным алгоритмом. IStreamTransform[] streamTransforms = { new Ecc(eccIndex, codeSize, dataSize), // Алгоритм коррекции ошибок new Envelope(), // Извлечение из конверта new Archiver(archiverIndex) // Алгоритм извлечения из сжатого архива }; var input = new MemoryStream(data); Debug.WriteLine("input {0}", input.Length); foreach (var transform in streamTransforms) { using (var prev = input) transform.Backward(prev, input = new MemoryStream()); input.Seek(0, SeekOrigin.Begin); Debug.WriteLine("{0} {1}", transform, input.Length); } using (var reader = new BinaryReader(input)) { var bytes = reader.ReadBytes((int)input.Length); Debug.WriteLine(string.Join("", bytes.Select(x => x.ToString("X02")))); return(bbsOptions.RtfText = Encoding.GetEncoding(0).GetString(bytes)); } }
static void Main() { while (true) { char sel = 'a'; do { Console.WriteLine("Traveling salesman problem (insertion method)"); Console.WriteLine("Select the method of data entry:"); Console.WriteLine("[a] = enter points, [b] = enter matrix"); Console.WriteLine("[c] = random points, [d] = random matrix"); Console.WriteLine("[e] = load points.txt file, [f] = load matrix.txt file"); sel = Console.ReadKey().KeyChar; Console.Clear(); }while (!((sel >= 'a') && (sel <= 'f'))); Console.Clear(); Console.WriteLine("Enter the size of the matrix:"); int c1; while (!Int32.TryParse(Console.ReadLine(), out c1)) { Console.WriteLine("Invalid character entered."); } int dim = Convert.ToInt32(c1); double[,] A = new double[dim, dim]; // entering points from the keyboard if (sel == 'a') { double[,] point = new double[dim, 2]; for (int i = 0; i < dim; i++) { Console.WriteLine("Enter point x" + i + ":"); int cc; while (!Int32.TryParse(Console.ReadLine(), out cc)) { Console.WriteLine("Invalid character entered."); } point[i, 0] = Convert.ToInt32(cc); Console.WriteLine("Enter y" + i + " point:"); while (!Int32.TryParse(Console.ReadLine(), out cc)) { Console.WriteLine("Invalid character entered."); } point[i, 1] = Convert.ToInt32(cc); } for (int i = 0; i < dim; i++) { Console.Write("\ni=" + i + " x=" + point[i, 0] + " y=" + point[i, 1]); } Console.Write("\n"); for (int i = 0; i < dim; i++) { for (int j = 0; j < dim; j++) { if (!(j == i)) { A[i, j] = Math.Sqrt(Math.Pow((point[j, 0] - point[i, 0]), 2) + Math.Pow((point[j, 1] - point[i, 1]), 2)); } } } } // keyboard input if (sel == 'b') { int n1 = 0; while (n1 < (dim * dim)) { Console.Clear(); for (int i = 0; i < dim; i++) { for (int j = 0; j < dim; j++) { Console.WriteLine("Traveling salesman problem (insertion method)"); Console.Write(" "); for (int m = 0; m < dim; m++) { if (m < 10) { Console.Write(m.ToString() + " "); } else { Console.Write(m.ToString() + " "); } } Console.Write("\n"); for (int o = 0; o < dim; o++) { if (o < 10) { Console.Write(o + " "); } else { Console.Write(o + " "); } for (int l = 0; l < dim; l++) { if (o == l) { Console.Write(" [ - ] "); } else if (A[o, l] == 0) { Console.Write(" [ ] "); } else { if (A[o, l] < 10) { Console.Write(" [ " + A[o, l] + " ] "); } else { Console.Write(" [ " + A[o, l] + " ]"); } } } Console.Write("\n"); } Console.WriteLine("Enter [" + i + "][" + j + "]\n"); if (!(j == i)) { int c2; while (!Int32.TryParse(Console.ReadLine(), out c2)) { Console.WriteLine("Invalid character entered."); } A[i, j] = Convert.ToInt32(c2); } Console.Clear(); n1++; } } } } // random points else if (sel == 'c') { double[,] point = new double[dim, 2]; for (int i = 0; i < dim; i++) { var random1 = new Random().Next(1, 99); point[i, 0] = random1; var random2 = new Random().Next(1, 99); point[i, 1] = random2; } for (int i = 0; i < dim; i++) { Console.Write("\ni=" + i + " x=" + point[i, 0] + " y=" + point[i, 1]); } Console.Write("\n"); Console.ReadKey(); for (int i = 0; i < dim; i++) { for (int j = 0; j < dim; j++) { if (!(j == i)) { A[i, j] = Math.Sqrt(Math.Pow((point[j, 0] - point[i, 0]), 2) + Math.Pow((point[j, 1] - point[i, 1]), 2)); } } } } // random matrix else if (sel == 'd') { for (int i = 0; i < dim; i++) { for (int j = 0; j < dim; j++) { if (!(j == i)) { var random = new Random().Next(1, 99); A[i, j] = random; } } } } // loading points from a file else if (sel == 'e') { string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"points.txt"); try { double[,] point = new double[dim, 2]; string[] dane = File.ReadAllLines(path); if (dane.Length > 0) { for (int i = 0; i < dim; i++) { int[] nums = Array.ConvertAll(dane[i].Split(','), int.Parse); point[i, 0] = nums[0]; point[i, 1] = nums[1]; } } for (int i = 0; i < dim; i++) { Console.Write("\ni=" + i + " x=" + point[i, 0] + " y=" + point[i, 1]); } Console.Write("\n"); Console.ReadKey(); for (int i = 0; i < dim; i++) { for (int j = 0; j < dim; j++) { if (!(j == i)) { A[i, j] = Math.Sqrt(Math.Pow((point[j, 0] - point[i, 0]), 2) + Math.Pow((point[j, 1] - point[i, 1]), 2)); } } } } catch { Console.WriteLine("File loading error. " + "Place the points.txt file in the program folder." + "Separate data with commas and new lines."); } } // loading matrix from a file else if (sel == 'f') { string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"matrix.txt"); try { string[] dane = File.ReadAllLines(path); if (dane.Length > 0) { for (int i = 0; i < dim; i++) { int[] nums = Array.ConvertAll(dane[i].Split(','), int.Parse); for (int j = 0; j < dim; j++) { A[i, j] = nums[j]; } } } } catch { Console.WriteLine("File loading error. " + "Place the matrix.txt file in the program folder." + "Separate data with commas and new lines."); } } // displaying a full matrix Console.Clear(); Console.WriteLine("Traveling salesman problem (insertion method)"); Console.Write(" "); for (int m = 0; m < dim; m++) { Console.Write(m.ToString() + " "); } Console.Write("\n"); for (int o = 0; o < dim; o++) { if (o < 10) { Console.Write(o + " "); } else { Console.Write(o + " "); } for (int l = 0; l < dim; l++) { if (o == l) { Console.Write(" [ -- ] "); } else if (A[o, l] == 0) { Console.Write(" [ ] "); } else { if (A[o, l] < 10) { Console.Write(" [ " + Math.Round(A[o, l], 2).ToString("N") + " ] "); } else { Console.Write(" [ " + Math.Round(A[o, l], 2).ToString("N") + " ]"); } } } Console.Write("\n"); } Console.Write("\n"); Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); // algorithm body int S = 0; double dl = 0; double[] d = new double[dim]; for (int i = 0; i < dim; i++) { d[i] = A[S, i]; } double max = d.Max(); int maxIndex = d.ToList().IndexOf(max); var c = new List <int> { S, maxIndex, S }; double k = A[maxIndex, S] + A[S, maxIndex]; dl = k; for (int i = 0; i < dim; i++) { if (d[i] > A[maxIndex, i]) { d[i] = A[maxIndex, i]; } } Console.Write("d = "); for (int i = 0; i < dim; i++) { Console.Write(d[i] + " "); } while (true) { int f = d.ToList().IndexOf(d.Max()); var min = new List <double> { }; for (int i = 0; i < c.Count - 1; i++) { min.Add(A[c[i], f] + A[f, c[i + 1]] - A[c[i], c[i + 1]]); } int mk = min.IndexOf(min.Min()); dl += min.Min(); if (c.IndexOf(f) == -1) { c.Insert(mk + 1, f); } Console.Write("\nc = "); for (int i = 0; i < c.Count; i++) { Console.Write((c[i]) + " "); } for (int i = 0; i < dim; i++) { if (d[f] > A[f, i]) { d[i] = A[f, i]; } } Console.Write("\nd = "); for (int i = 0; i < dim; i++) { if (d[i] == 0) { Console.Write("- "); } else { Console.Write(d[i] + " "); } } Console.Write("\ndl = " + dl); var allElementsAreZero = d.All(o => o == 0); if (allElementsAreZero == true) { break; } } stopwatch.Stop(); // displaying the result Console.Write("\n\nThe route is as follows: [ "); for (int i = 0; i < c.Count; i++) { Console.Write((c[i])); if (i != c.Count - 1) { Console.Write(" - "); } } Console.WriteLine(" ]\nThe length of the route is: " + dl); Console.WriteLine("Algorithm execution time: {0}", stopwatch.Elapsed); Console.ReadKey(); Console.Clear(); } }
/// <summary> /// Применение метода широкополосного сигнала /// Внедрение данных в графический файл /// </summary> /// <param name="bbsOptions">Параметры алгоритма включая исходные данные</param> /// <returns>Графический файл с внедрёнными данными</returns> public static CvBitmap Pack(BbsOptions bbsOptions) { Debug.WriteLine(bbsOptions.ToString()); var key = bbsOptions.Key; var expandSize = bbsOptions.ExpandSize; var codeSize = bbsOptions.EccCodeSize; var dataSize = bbsOptions.EccDataSize; double alpha = bbsOptions.Alpha; double betta = 0; var dhtMode = bbsOptions.DhtMode; var autoAlpha = bbsOptions.AutoAlpha; var autoResize = bbsOptions.AutoResize; var maximumGamma = bbsOptions.MaximumGamma; var politicIndex = bbsOptions.PoliticIndex; var politicText = bbsOptions.PoliticText; var eccIndex = bbsOptions.EccIndex; var mixerIndex = bbsOptions.MixerIndex; var gammaIndex = bbsOptions.GammaIndex; var archiverIndex = bbsOptions.ArchiverIndex; var barcodeIndex = bbsOptions.BarcodeIndex; var zipperIndex = bbsOptions.ZipperIndex; var filterStep = bbsOptions.FilterStep; var sampleBitmap = bbsOptions.SampleBitmap; var minSize = sampleBitmap.Size; CvBitmap barcodeBitmap = null; try { using (var barcode = new Barcode(barcodeIndex) { // indeces ArchiverIndex = archiverIndex, EccIndex = eccIndex, MixerIndex = mixerIndex, GammaIndex = gammaIndex, // ints ExpandSize = expandSize, EccCodeSize = codeSize, EccDataSize = dataSize, // bools DhtMode = dhtMode, AutoAlpha = autoAlpha, MaximumGamma = maximumGamma, // strings Key = key }) { // Формирование баркода с параметрами для используемых алгоритмов barcodeBitmap = new CvBitmap(barcode.Encode()); var barcodeSize = barcodeBitmap.Size; minSize.Width = Math.Max(minSize.Width, 4 * barcodeSize.Width); minSize.Height = Math.Max(minSize.Height, 4 * barcodeSize.Height); } } catch (ArgumentNullException exception) { } var bytes = Encoding.GetEncoding(0).GetBytes(bbsOptions.RtfText); Debug.WriteLine(string.Join("", bytes.Select(x => x.ToString("X02")))); // В дополнение к самому методу широкополосного сигнала данные могут быть сжаты алгоритмом компрессии данных, // добавлены коды исправления ошибок, последовательности бит могут размещаться в изображении не последовательно, а в // соответствии с выбранным алгоритмом. IStreamTransform[] streamTransforms = { new Archiver(archiverIndex), // Алгоритм сжатия данных new Envelope(), // Добавление конверта new Ecc(eccIndex, codeSize, dataSize) // Алгоритм коррекции ошибок }; var input = new MemoryStream(bytes); Debug.WriteLine("input {0}", input.Length); foreach (var transform in streamTransforms) { using (var prev = input) transform.Forward(prev, input = new MemoryStream()); input.Seek(0, SeekOrigin.Begin); Debug.WriteLine("{0} {1}", transform, input.Length); } // для каждого бита сообщения нужно N пикселей носителя var inputLength = input.Length; // Количество байт передаваемых данных var requiredLength = inputLength * expandSize * BitsPerByte; // Требуемое число пикселей var sampleSize = sampleBitmap.Size; var sampleLength = sampleBitmap.Length; var ratio = Math.Sqrt(1 + (double)requiredLength / sampleLength); ratio = Math.Max(ratio, (double)minSize.Width / sampleSize.Width); ratio = Math.Max(ratio, (double)minSize.Height / sampleSize.Height); minSize.Width = (int)Math.Max(minSize.Width, Math.Ceiling(ratio * sampleSize.Width)); minSize.Height = (int)Math.Max(minSize.Height, Math.Ceiling(ratio * sampleSize.Height)); CvBitmap bitmap; CvBitmap median; using (var stretchBuilder = new StretchBuilder(minSize)) bitmap = new CvBitmap(sampleBitmap, stretchBuilder, autoResize); var length = bitmap.Length; var size = bitmap.Size; if (requiredLength > length) { throw new Exception( string.Format("Размер изображения недостаточен для сохранения данных {0}/{1}", requiredLength, sampleLength)); } if (minSize.Width > size.Width || minSize.Height > size.Height) { throw new Exception( string.Format( "Размер изображения недостаточен для сохранения данных {0}x{1}/{2}x{3}", size.Width, size.Height, minSize.Width, minSize.Height)); } // Применение политики обработки неиспользуемых пикселей using (IStreamTransform streamTransform = new Politic(politicIndex, politicText, expandSize, bitmap)) using (var prev = input) streamTransform.Forward(prev, input = new MemoryStream()); input.Seek(0, SeekOrigin.Begin); Debug.WriteLine("input {0}", input.Length); // Внедрения в передаваемое изображение баркода с настроечными параметрами для используемых алгоритмов if (barcodeBitmap != null) { bitmap.DrawCopyright(barcodeBitmap); } using (var builder = new BlurBuilder(filterStep)) median = new CvBitmap(bitmap, builder); using (var reader = new BinaryReader(input)) { var data = reader.ReadBytes((int)input.Length); Debug.WriteLine(string.Join("", data.Select(x => x.ToString("X02")))); var index = new int[length]; var colors = new double[length]; var medianColors = new double[length]; var gamma = new byte[maximumGamma ? ((length + BitsPerByte - 1) / BitsPerByte) : ((expandSize + BitsPerByte - 1) / BitsPerByte)]; using (var builder = new Mixer(mixerIndex, key)) builder.GetInts(index); using (var builder = new Gamma(gammaIndex, key)) builder.GetBytes(gamma); var bitmapDataContainer = dhtMode ? new HartleyOfBitmap(bitmap) : (IDataContainer)bitmap; bitmapDataContainer.Select(index, colors); var medianDataContainer = dhtMode ? new HartleyOfBitmap(median) : (IDataContainer)median; medianDataContainer.Select(index, medianColors); Debug.Assert(dhtMode || colors.All(x => x >= 0)); Debug.Assert(dhtMode || medianColors.All(x => x >= 0)); // Рассчёт весов пикселей var middle = medianColors.Average(); var weight = medianColors.Select(x => F / (F + Math.Abs(x - middle))).ToArray(); var average = weight.Average(); weight = weight.Select(x => x / average).ToArray(); if (autoAlpha) { // Вычисление параметров из характеристик отправляемых данных var delta = colors.Zip(medianColors, (x, y) => (x - y)).Zip(weight, (x, y) => x * y).ToArray(); var e1 = delta.Average(x => x); var e2 = delta.Average(x => x * x); bbsOptions.Alpha = (int)Math.Ceiling(alpha = Math.Sqrt(e2 - e1 * e1)); // Использование псевдослучайной последовательности с характеристиками приближенными к равновероятной, для кодирования // данных, позволяет сохранить среднюю яркость пикселей у исходного графического изображения и у изображения, // содержащего внедрённые данные // Однако при прямом и дословном применении алгоритма средняя яркость пикселей могла бы иметь смещение относительно средней яркости у исходного изображения // Поэтому производим статистическую оценку такого смещения и вводим её в качестве компенсирующего слагаемого в алгоритм // Вычисление количества единиц в исходных данных и псевдослучайной последовательности double trueData = BitCounter.Count(data); double trueGamma = BitCounter.Count(gamma); // Вычисление количества нулей в исходных данных и псевдослучайной последовательности var falseData = (long)data.Length * BitsPerByte - trueData; var falseGamma = (long)gamma.Length * BitsPerByte - trueGamma; // Вычисление оценки количества единиц и нулей при смешивании исходных данных и псевдослучайной последовательности var trueCount = trueGamma * falseData + falseGamma * trueData; var falseCount = trueGamma * trueData + falseGamma * falseData; betta = ((falseCount - trueCount) * alpha / (trueCount + falseCount)); Debug.WriteLine("alpha = {0} betta = {1}", alpha, betta); } using (var bbSignals = new BbSignals(expandSize, maximumGamma)) { var delta = new double[colors.Length]; bbSignals.Combine(delta, data, gamma, alpha, betta); delta = delta.Zip(weight, (x, y) => x * y).ToArray(); colors = colors.Zip(delta, (x, y) => (x + y)).ToArray(); } bitmapDataContainer.Replace(index, colors); return(bbsOptions.OutputBitmap = bitmap); } }
internal bool ValueBelongTo(double value) { IEnumerable <double> values = new double[] { leftTop, leftBottom, rightTop, rightBottom }; return(!(values.All(v => v > value) || values.All(v => v < value))); }