Exemplo n.º 1
0
 public void VectorAdd()
 {
     Vector<Point> points = new Vector<Point>();
     points.Add(new Point(2f, 3f));
     Assert.AreEqual(1, points.Count());
     points.Add(new Point(2.4f, 3f));
     points.Add(new Point(2.5f, 3f));
     Assert.AreEqual(3, points.Count());
 }
Exemplo n.º 2
0
 public void ItShouldBeIndexable()
 {
     Vector<byte> testVector = new Vector<byte>();
     testVector.Add(1);
     testVector.Add(0);
     testVector.Add(1);
     int expected = 1;
     int actual = testVector[2];
     Assert.AreEqual(expected, actual);
 }
Exemplo n.º 3
0
 public void ItShouldRemoveElements()
 {
     Vector<byte> testVector = new Vector<byte>();
     testVector.Add(1);
     testVector.Add(0);
     testVector.Add(1);
     testVector.Remove(1);
     int expected = 1;
     int actual = testVector[1];
     Assert.AreEqual(expected, actual);
 }
Exemplo n.º 4
0
 public void ItShouldHoldElements()
 {
     Vector<byte> actual = new Vector<byte>();
     actual.Add(1);
     actual.Add(0);
     actual.Add(1);
     Vector<byte> expected = new Vector<byte>();
     expected.Add(1);
     expected.Add(0);
     expected.Add(1);
     Assert.AreEqual(expected.ToString(), actual.ToString());
 }
Exemplo n.º 5
0
        public void VectorRemove()
        {
            Point pointToRemove = new Point(2.4f, 3f);

            Vector<Point> points = new Vector<Point>();
            points.Add(new Point(2f, 3f));
            points.Add(pointToRemove);
            points.Add(new Point(2.5f, 3f));
            Assert.AreEqual(3, points.Count());
            points.Remove(pointToRemove);
            Assert.AreEqual(2, points.Count());
        }
Exemplo n.º 6
0
        public void VectorPrev()
        {
            Vector<Point> points = new Vector<Point>();
            Point point = new Point(1f, 1.5f);

            points.Add(point);
            points.Add(point);
            Assert.AreEqual(point, points[1]);
            //points.Add(new Point(2f, 3f));
            //points.Add(new Point(2.4f, 3f));
            //points.Add(point);
            //points.Add(new Point(2.5f, 3f));

            //Assert.AreEqual(point, points[3].Prev.Data);
        }
Exemplo n.º 7
0
 protected bool IsInBoundingBox(Vector pt, Vector referencePoint, Vector relativeCenter, Vector size)
 {
     Vector boxCenter = referencePoint.Add(relativeCenter);
     return (boxCenter.X - size.X / 2 < pt.X && pt.X < boxCenter.X + size.X / 2 &&
             boxCenter.Y - size.Y / 2 < pt.Y && pt.Y < boxCenter.Y + size.Y / 2 &&
             boxCenter.Z - size.Z / 2 < pt.Z && pt.Z < boxCenter.Z + size.Z / 2);
 }
Exemplo n.º 8
0
 public void ItShouldBeEnumerable()
 {
     Vector<byte> testVector = new Vector<byte>();
     testVector.Add(1);
     testVector.Add(0);
     testVector.Add(1);
     int counter = 0;
     foreach (byte element in testVector)
     {
         if (element == 1)
             counter++;
     }
     int expected = 2;
     int actual = counter;
     Assert.AreEqual(expected, actual);
 }
Exemplo n.º 9
0
        public void VectorIEnumerable()
        {
            Vector<Point> points = new Vector<Point>();
            points.Add(new Point(2f, 3f));
            points.Add(new Point(2.4f, 3f));
            points.Add(new Point(2.5f, 3f));
            points.RemoveAt(0);

            int countedPoints = 0;
            foreach (Point point in points)
            {
                countedPoints++;
            }

            Assert.AreEqual(2, countedPoints);
        }
Exemplo n.º 10
0
 public static Vector toGrayScaleVector(this Bitmap pic)
 {
     Vector vector = new Vector();
     pic.eachPixel((pixel) => {
         vector.Add(pixel.R * 0.3 + pixel.G * 0.59 + pixel.B * 0.11);
         return 0;
     });
     return vector;
 }
Exemplo n.º 11
0
 public void AddNewObject()
 {
     int[] localData = new int[] { 3, 7, 5, 8 };
     Vector<int> vector = new Vector<int>(localData);
     int obj = 2;
     int[] expectedValue = new int[] { 3, 7, 5, 8, 2, 0, 0, 0 };
     vector.Add(obj);
     CollectionAssert.AreEqual(expectedValue, vector.GetData());
     Assert.AreEqual(5, vector.Count());
 }
Exemplo n.º 12
0
        private Direction GetDirectionForPosition(Vector position, Vector direction)
        {
            Direction resultant = new Direction();
            resultant.Value = GetPositionValue(position);
            resultant.Positions.Add(position);

            for (int i = 1; i < this.sequenceLength; i++)
            {
                Vector newPosition = position.Add(direction, i);
                resultant.Value *= GetPositionValue(newPosition);
                resultant.Positions.Add(newPosition);
            }

            return resultant;
        }
Exemplo n.º 13
0
        public void AddRaiseExceptionIfVectorsHaveDifferenteLengths()
        {
            Vector vector1 = new Vector(new double[] { 1.0, 2.0, 3.0 });
            Vector vector2 = new Vector(new double[] { 4.0, 5.0, 6.0, 7.0 });

            try
            {
                vector1.Add(vector2);
                Assert.Fail();
            }
            catch (Exception ex)
            {
                Assert.IsInstanceOfType(ex, typeof(InvalidOperationException));
                Assert.AreEqual("Vectors have different lengths", ex.Message);
            }
        }
Exemplo n.º 14
0
        private static void Main(String[] args)
        {
            Vector vector = Vector.Zero(3);
            Assert($"{nameof(vector)} is equal to Vector(0, 0, 0)", vector.Equals(new Vector(0, 0, 0)));
            Assert($"{nameof(vector)} is not equal to Vector(1, 1, 0)", !vector.Equals(new Vector(1, 1, 0)));

            Vector vector2 = new Vector(1, 2, 2);
            Assert($"{nameof(vector2)} length should be equal to 3.0", vector2.GetLength() == 3.0);

            Vector vector3 = new Vector(1, 1, 1);
            Vector vector4 = vector2.Add(vector3);
            Assert($"{nameof(vector2)} + {nameof(vector3)} is equal to Vector(2, 3, 3)", vector4.Equals(new Vector(2, 3, 3)));
            Assert($"{nameof(vector2)} + {nameof(vector3)} is equal to Vector(2, 3, 3)", vector4 == new Vector(2, 3, 3));

            Console.ReadKey();
        }
Exemplo n.º 15
0
 public OptionsForm()
 {
     InitializeComponent();
     try
     {
         using (var reader = File.OpenText("math.default"))
         {
             var n = 0;
             var m = new Matrix<decimal>();
             var a = new Matrix<decimal>();
             var b = new Matrix<decimal>();
             var f = new Matrix<decimal>();
             var w = new Matrix<decimal>();
             for (var line = reader.ReadLine(); !string.IsNullOrWhiteSpace(line); line = reader.ReadLine())
             {
                 var arr = line.Split(' ');
                 if (arr[0][0] == 'N')
                 {
                     n = Convert.ToInt32(arr[1]);
                 }
                 else
                 {
                     var x = new Vector<decimal>();
                     for (var i = 1; i < arr.Length; i++) x.Add(Convert.ToDecimal(arr[i]));
                     if (arr[0][0] == 'M') m.Add(x);
                     if (arr[0][0] == 'A') a = new Matrix<decimal> {x};
                     if (arr[0][0] == 'B') b = new Matrix<decimal> {x};
                     if (arr[0][0] == 'F') f.Add(x);
                     if (arr[0][0] == 'W') w.Add(x);
                 }
             }
             numericUpDown1.Value = n;
             _matrixControlM.Value = m;
             _matrixControlA.Value = a;
             _matrixControlB.Value = b;
             _matrixControlF.Value = f;
             _matrixControlW.Value = w;
         }
     }
     catch (Exception ex)
     {
     }
 }
Exemplo n.º 16
0
        public void PerformOperation(object sender, RoutedEventArgs e)
        {
            RadioButton li = sender as RadioButton;

            // Strings used to display results
            String syntaxString, resultType, operationString;

            ///The local variables point1, point2, vector2, etc are defined in each
            ///case block for readability reasons. Each variable is contained within
            ///the scope of each case statement.

            switch (li.Name)
            {   //begin switch
            case "rb1":
            {
                // Translates a Point by a Vector using the overloaded + operator.

                System.Windows.Point point1 = new System.Windows.Point(10, 5);
                Vector vector1 = new Vector(20, 30);
                System.Windows.Point pointResult = new System.Windows.Point();

                pointResult = point1 + vector1;

                // pointResult is equal to (-10,-25)

                // Displaying Results
                syntaxString    = "pointResult = point1 + vector1;";
                resultType      = "Point";
                operationString = "Translating a Point by a Vector";
                ShowResults(pointResult.ToString(), syntaxString, resultType, operationString);
                break;
            }

            case "rb2":
            {
                //<Snippet10>
                // Adds a Vector to a Vector using the overloaded + operator.

                Vector vector1      = new Vector(20, 30);
                Vector vector2      = new Vector(45, 70);
                Vector vectorResult = new Vector();

                // vectorResult is equal to (65,100)
                vectorResult = vector1 + vector2;
                //</Snippet10>

                // Displaying Results
                syntaxString    = "vectorResult = vector1 + vector2;";
                resultType      = "Vector";
                operationString = "Adding a Vector to a Vector";
                ShowResults(vectorResult.ToString(), syntaxString, resultType, operationString);
                break;
            }

            case "rb3":
            {
                // Adds a Vector to a Vector using the static Add method.

                Vector vector1      = new Vector(20, 30);
                Vector vector2      = new Vector(45, 70);
                Vector vectorResult = new Vector();

                vectorResult = Vector.Add(vector1, vector2);

                // vectorResult is equal to (65,100)

                // Displaying Results
                syntaxString    = "vectorResult = Vector.Add(vector1, vector2);";
                resultType      = "Vector";
                operationString = "Adding a Vector to a Vector";
                ShowResults(vectorResult.ToString(), syntaxString, resultType, operationString);
                break;
            }

            case "rb4":
            {
                // Translates a Point by a Vector using the static Add method.

                Vector vector1 = new Vector(20, 30);
                System.Windows.Point point1      = new System.Windows.Point(10, 5);
                System.Windows.Point pointResult = new System.Windows.Point();

                pointResult = Vector.Add(vector1, point1);

                // vectorResult is equal to (30,35)

                // Displaying Results
                syntaxString    = "pointResult = Vector.Add(vector1, point1);";
                resultType      = "Point";
                operationString = "Translating a Point by a Vector";
                ShowResults(pointResult.ToString(), syntaxString, resultType, operationString);
                break;
            }

            case "rb5":
            {
                // Subtracts a Vector from a Vector using the overloaded - operator.

                Vector vector1      = new Vector(20, 30);
                Vector vector2      = new Vector(45, 70);
                Vector vectorResult = new Vector();

                vectorResult = vector1 - vector2;

                // vector Result is equal to (-25, -40)

                // Displaying Results
                syntaxString    = "vectorResult = vector1 - vector2;";
                resultType      = "Vector";
                operationString = "Subtracting a Vector from a Vector";
                ShowResults(vectorResult.ToString(), syntaxString, resultType, operationString);
                break;
            }

            case "rb6":
            {
                // Subtracts a Vector from a Vector using the static Subtract method.

                Vector vector1      = new Vector(20, 30);
                Vector vector2      = new Vector(45, 70);
                Vector vectorResult = new Vector();

                vectorResult = Vector.Subtract(vector1, vector2);

                // vector Result is equal to (-25, -40)

                // Displaying Results
                syntaxString    = "Vector.Subtract(vector1, vector2);";
                resultType      = "Vector";
                operationString = "Subtracting a Vector from a Vector";
                ShowResults(vectorResult.ToString(), syntaxString, resultType, operationString);
                break;
            }

            case "rb7":
            {
                // Multiplies a Vector by a Scalar using the overloaded * operator.

                Vector vector1      = new Vector(20, 30);
                Double scalar1      = 75;
                Vector vectorResult = new Vector();

                vectorResult = vector1 * scalar1;

                // vectorResult is equal to (1500,2250)

                // Displaying Results
                syntaxString    = "vectorResult = vector1 * scalar1;";
                resultType      = "Vector";
                operationString = "Multiplies a Vector by a Scalar";
                ShowResults(vectorResult.ToString(), syntaxString, resultType, operationString);
                break;
            }

            case "rb8":
            {
                // Multiplies a Scalar by a Vector using the overloaded * operator.

                Vector vector1      = new Vector(20, 30);
                Double scalar1      = 75;
                Vector vectorResult = new Vector();

                vectorResult = scalar1 * vector1;

                // vectorResult is equal to (1500,2250)

                // Displaying Results
                syntaxString    = "vectorResult = scalar1 * vector1;";
                resultType      = "Vector";
                operationString = "Multiplies a Scalar by a Vector";
                ShowResults(vectorResult.ToString(), syntaxString, resultType, operationString);
                break;
            }

            case "rb9":
            {
                // Multiplies a Vector by a Vector using the overloaded * operator.

                Vector vector1 = new Vector(20, 30);
                Vector vector2 = new Vector(45, 70);
                Double doubleResult;

                doubleResult = vector1 * vector2;

                // doubleResult is equal to 3000

                // Displaying Results
                syntaxString    = "doubleResult = vector1 * vector2;";
                resultType      = "Double";
                operationString = "Multiplies a Vector by a Vector";
                ShowResults(doubleResult.ToString(), syntaxString, resultType, operationString);
                break;
            }

            case "rb10":
            {
                // Multiplies a Vector by a Matrix using the overloaded * operator.

                Vector vector1      = new Vector(20, 30);
                Matrix matrix1      = new Matrix(40, 50, 60, 70, 80, 90);
                Vector vectorResult = new Vector();

                vectorResult = vector1 * matrix1;

                // vector Result is equal to (2600,3100)

                // Displaying Results
                syntaxString    = "vectorResult = vector1 * matrix1;";
                resultType      = "Vector";
                operationString = "Multiplies a Vector by a Matrix";
                ShowResults(vectorResult.ToString(), syntaxString, resultType, operationString);
                break;
            }

            case "rb11":
            {
                // Multiplies a Vector by a Scalar using the static Multiply method.

                Vector vector1      = new Vector(20, 30);
                Double scalar1      = 75;
                Vector vectorResult = new Vector();

                vectorResult = Vector.Multiply(vector1, scalar1);

                // vectorResult is equal to (1500,2250)

                // Displaying Results
                syntaxString    = "vectorResult = Vector.Multiply(vector1, scalar1);";
                resultType      = "Vector";
                operationString = "Multiplies a Vector by a Scalar";
                ShowResults(vectorResult.ToString(), syntaxString, resultType, operationString);
                break;
            }

            case "rb12":
            {
                // Multiplies a Scalar by a Vector using the static Multiply method.

                Vector vector1      = new Vector(20, 30);
                Double scalar1      = 75;
                Vector vectorResult = new Vector();

                vectorResult = Vector.Multiply(scalar1, vector1);

                // vectorResult is equal to (1500,2250)

                // Displaying Results
                syntaxString    = "vectorResult = Vector.Multiply(scalar1, vector1);";
                resultType      = "Vector";
                operationString = "Multiplies a Scalar by a Vector";
                ShowResults(vectorResult.ToString(), syntaxString, resultType, operationString);
                break;
            }

            case "rb13":
            {
                // Multiplies a Vector by a Vector using the static Multiply method.

                Vector vector1 = new Vector(20, 30);
                Vector vector2 = new Vector(45, 70);
                Double doubleResult;

                doubleResult = Vector.Multiply(vector1, vector2);

                // doubleResult is equal to 3000

                // Displaying Results
                syntaxString    = "DoubleResult = Vector.Multiply(vector1,vector2);";
                resultType      = "Double";
                operationString = "Multiplies a Vector by a Vector";
                ShowResults(doubleResult.ToString(), syntaxString, resultType, operationString);
                break;
            }

            case "rb14":
            {
                // Multiplies a Vector by a Matrix using the static Multiply method.

                Vector vector1      = new Vector(20, 30);
                Matrix matrix1      = new Matrix(40, 50, 60, 70, 80, 90);
                Vector vectorResult = new Vector();

                vectorResult = Vector.Multiply(vector1, matrix1);

                // vector Result is equal to (2600,3100)

                // Displaying Results
                syntaxString    = "vectorResult = Vector.Multiply(vector1,matrix1);";
                resultType      = "Vector";
                operationString = "Multiplies a Vector by a Matrix";
                ShowResults(vectorResult.ToString(), syntaxString, resultType, operationString);
                break;
            }

            case "rb15":
            {
                // Divides a Vector by a Scalar using the overloaded / operator.

                Vector vector1      = new Vector(20, 30);
                Vector vectorResult = new Vector();
                Double scalar1      = 75;

                vectorResult = vector1 / scalar1;

                // vectorResult is approximately equal to (0.26667,0.4)

                // Displaying Results
                syntaxString    = "vectorResult = vector1 / scalar1;";
                resultType      = "Vector";
                operationString = "Dividing a Vector by a Scalar";
                ShowResults(vectorResult.ToString(), syntaxString, resultType, operationString);
                break;
            }

            case "rb16":
            {
                // Divides a Vector by a Double using the static Divide method.

                Vector vector1      = new Vector(20, 30);
                Vector vectorResult = new Vector();
                Double scalar1      = 75;

                vectorResult = Vector.Divide(vector1, scalar1);

                // vectorResult is approximately equal to (0.26667,0.4)

                // Displaying Results
                syntaxString    = "vectorResult = Vector.Divide(vector1, scalar1);";
                resultType      = "Vector";
                operationString = "Dividing a Vector by a Scalar";
                ShowResults(vectorResult.ToString(), syntaxString, resultType, operationString);
                break;
            }

            case "rb17":
            {
                // Gets the hashcode of a Vector structure

                Vector vector1 = new Vector(20, 30);
                int    vectorHashCode;

                vectorHashCode = vector1.GetHashCode();

                // Displaying Results
                syntaxString    = "vectorHashCode = vector1.GetHashCode();";
                resultType      = "int";
                operationString = "Getting the hashcode of a Vector";
                ShowResults(vectorHashCode.ToString(), syntaxString, resultType, operationString);
                break;
            }

            case "rb18":
            {
                // Gets the length of a Vector.

                Vector vector1 = new Vector(20, 30);
                Double length;

                length = vector1.Length;

                // length is approximately equal to 36.0555

                // Displaying Results
                syntaxString    = "length = vector1.Length();";
                resultType      = "Double";
                operationString = "Getting the length of a Vector";
                ShowResults(length.ToString(), syntaxString, resultType, operationString);
                break;
            }

            case "rb19":
            {
                // Gets the square of the length of a Vector.

                Vector vector1 = new Vector(20, 30);
                Double lengthSq;

                lengthSq = vector1.LengthSquared;

                // lengthSq is equal to 1300

                // Displaying Results
                syntaxString    = "lengthSq = vector1.LengthSquared;";
                resultType      = "Double";
                operationString = "Getting the length square of a Vector";
                ShowResults(lengthSq.ToString(), syntaxString, resultType, operationString);
                break;
            }

            case "rb20":
            {
                // Normalizes a Vector using the Normalize method.

                Vector vector1 = new Vector(20, 30);

                vector1.Normalize();

                // vector1 is approximately equal to (0.5547,0.8321)

                // Displaying Results
                syntaxString    = "vector1.Normalize();";
                resultType      = "Vector";
                operationString = "Normalizing a Vector";
                ShowResults(vector1.ToString(), syntaxString, resultType, operationString);
                break;
            }

            case "rb21":
            {
                // Calculates the angle between two Vectors using the static AngleBetween method.

                Vector vector1 = new Vector(20, 30);
                Vector vector2 = new Vector(45, 70);
                Double angleBetween;

                angleBetween = Vector.AngleBetween(vector1, vector2);

                // angleBetween is approximately equal to 0.9548

                // Displaying Results
                syntaxString    = "angleBetween = Vector.AngleBetween(vector1, vector2);";
                resultType      = "Double";
                operationString = "Calculating the angle between two Vectors";
                ShowResults(angleBetween.ToString(), syntaxString, resultType, operationString);
                break;
            }

            case "rb22":
            {
                // Calculates the cross product of two Vectors using the static  CrossProduct method.

                Vector vector1 = new Vector(20, 30);
                Vector vector2 = new Vector(45, 70);
                Double crossProduct;

                crossProduct = Vector.CrossProduct(vector1, vector2);

                // crossProduct is equal to 50

                // Displaying Results
                syntaxString    = "crossProduct = Vector.CrossProduct(vector1,vector2);";
                resultType      = "Double";
                operationString = "Calculating the crossproduct of two Vectors";
                ShowResults(crossProduct.ToString(), syntaxString, resultType, operationString);
                break;
            }

            case "rb23":
            {
                // Calculates the determinant of two Vectors using the static Determinant method.

                Vector vector1 = new Vector(20, 30);
                Vector vector2 = new Vector(45, 70);
                Double determinant;

                determinant = Vector.Determinant(vector1, vector2);

                // determinant is equal to 50

                // Displaying Results
                syntaxString    = "determinant = Vector.Determinant(vector1, vector2);";
                resultType      = "Double";
                operationString = "Calculating the determinant of two Vectors";
                ShowResults(determinant.ToString(), syntaxString, resultType, operationString);
                break;
            }

            case "rb24":
            {
                // Checks if two Vectors are equal using the overloaded equality operator.

                // Declaring vecto1 and initializing x,y values
                Vector vector1 = new Vector(20, 30);

                // Declaring vector2 without initializing x,y values
                Vector vector2 = new Vector();

                // Boolean to hold the result of the comparison
                Boolean areEqual;

                // assigning values to vector2
                vector2.X = 45;
                vector2.Y = 70;

                // Comparing Vectors for equality
                areEqual = (vector1 == vector2);

                // areEqual is False

                // Displaying Results
                syntaxString    = "areEqual = (vector1 == vector2);";
                resultType      = "Boolean";
                operationString = "Checking if two vectors are equal";
                ShowResults(areEqual.ToString(), syntaxString, resultType, operationString);
                break;
            }

            case "rb25":
            {
                // Checks if two Vectors are equal using the static Equals method.

                Vector  vector1 = new Vector(20, 30);
                Vector  vector2 = new Vector(45, 70);
                Boolean areEqual;

                areEqual = Vector.Equals(vector1, vector2);

                // areEqual is False

                // Displaying Results
                syntaxString    = "areEqual = Vector.Equals(vector1, vector2);";
                resultType      = "Boolean";
                operationString = "Checking if two vectors are equal";
                ShowResults(areEqual.ToString(), syntaxString, resultType, operationString);
                break;
            }

            case "rb26":
            {
                // Compares an Object and a Vector for equality using the non-static Equals method.

                Vector  vector1 = new Vector(20, 30);
                Vector  vector2 = new Vector(45, 70);
                Boolean areEqual;

                areEqual = vector1.Equals(vector2);

                // areEqual is False

                // Displaying Results
                syntaxString    = "areEqual = vector1.Equals(vector2);";
                resultType      = "Boolean";
                operationString = "Checking if two vectors are equal";
                ShowResults(areEqual.ToString(), syntaxString, resultType, operationString);
                break;
            }

            case "rb27":
            {
                // Converts a string representation of a vector into a Vector structure

                Vector vectorResult = new Vector();

                vectorResult = Vector.Parse("1,3");

                // vectorResult is equal to (1,3)

                // Displaying Results
                syntaxString    = "vectorResult = Vector.Parse(\"1,3\");";
                resultType      = "Vector";
                operationString = "Converting a string into a Vector";
                ShowResults(vectorResult.ToString(), syntaxString, resultType, operationString);
                break;
            }

            case "rb28":
            {
                // Checks if two Vectors are not equal using the overloaded inequality operator.

                Vector  vector1 = new Vector(20, 30);
                Vector  vector2 = new Vector(45, 70);
                Boolean areNotEqual;

                areNotEqual = (vector1 != vector2);

                // areNotEqual is True

                // Displaying Results
                syntaxString    = "areNotEqual = (vector1 != vector2);";
                resultType      = "Boolean";
                operationString = "Checking if two points are not equal";
                ShowResults(areNotEqual.ToString(), syntaxString, resultType, operationString);
                break;
            }

            case "rb29":
            {
                // Negates a Vector using the Negate method.

                Vector vector1      = new Vector(20, 30);
                Vector vectorResult = new Vector();

                vector1.Negate();

                // vector1 is equal to (-20, -30)

                // Displaying Results
                syntaxString    = "vector1.Negate();";
                resultType      = "void";
                operationString = "Negating a vector";
                ShowResults(vector1.ToString(), syntaxString, resultType, operationString);
                break;
            }

            case "rb30":
            {
                // Negates a Vector using the overloaded unary negation operator.

                Vector vector1      = new Vector(20, 30);
                Vector vectorResult = new Vector();

                vectorResult = -vector1;

                // vectorResult is equal to (-20, -30)

                // Displaying Results
                syntaxString    = "vectorResult = -vector1;";
                resultType      = "Vector";
                operationString = "Negating a vector";
                ShowResults(vectorResult.ToString(), syntaxString, resultType, operationString);
                break;
            }

            case "rb31":
            {
                // Gets a String representation of a Vector structure

                Vector vector1 = new Vector(20, 30);
                String vectorString;

                vectorString = vector1.ToString();

                // vectorString is equal to 10,5

                // Displaying Results
                syntaxString    = "vectorString = vector1.ToString();";
                resultType      = "String";
                operationString = "Getting the string representation of a Vector";
                ShowResults(vectorString.ToString(), syntaxString, resultType, operationString);
                break;
            }

            case "rb32":
            {
                // Explicitly converts a Vector structure into a Size structure
                // Returns a Size.

                Vector vector1            = new Vector(20, 30);
                System.Windows.Size size1 = new System.Windows.Size();

                size1 = (System.Windows.Size)vector1;

                // size1 has a width of 20 and a height of 30

                // Displaying Results
                syntaxString    = "size1 = (Size)vector1;";
                resultType      = "Size";
                operationString = "Expliciting casting a Vector into a Size";
                ShowResults(size1.ToString(), syntaxString, resultType, operationString);
                break;
            }

            case "rb33":
            {
                // Explicitly converts a Vector structure into a Point structure
                // Returns a Point.

                Vector vector1 = new Vector(20, 30);
                System.Windows.Point point1 = new System.Windows.Point();

                point1 = (System.Windows.Point)vector1;

                // point1 is equal to (20, 30)

                // Displaying Results
                syntaxString    = "point1 = (Point)vector1;";
                resultType      = "Point";
                operationString = "Expliciting casting a Vector into a Point";
                ShowResults(point1.ToString(), syntaxString, resultType, operationString);
                break;
            }

            // task example.  this case statement is not referenced from the list of radio buttons
            case "rb40":
            {
                // adds two vectors using Add and +

                Vector vector1 = new Vector(20, 30);
                Vector vector2 = new Vector(45, 70);

                vector1 = vector1 + vector2;
                // vector1 is now equal to (65, 100)

                vector1 = Vector.Add(vector1, vector2);
                // vector1 is now equal to (110, 170)

                // Displaying Results
                syntaxString    = "vectorResult = Vector.Negate(vector1);";
                resultType      = "Vector";
                operationString = "Negating a vector";
                ShowResults(vector1.ToString(), syntaxString, resultType, operationString);
                break;
            }

            default:
                break;
            }   // end switch
        }
Exemplo n.º 17
0
        /// <summary>
        /// Solves the matrix equation Ax = b, where A is the coefficient matrix, b is the
        /// solution vector and x is the unknown vector.
        /// </summary>
        /// <param name="matrix">The coefficient <see cref="Matrix"/>, <c>A</c>.</param>
        /// <param name="input">The solution <see cref="Vector"/>, <c>b</c>.</param>
        /// <param name="result">The result <see cref="Vector"/>, <c>x</c>.</param>
        public void Solve(Matrix matrix, Vector input, Vector result)
        {
            // If we were stopped before, we are no longer
            // We're doing this at the start of the method to ensure
            // that we can use these fields immediately.
            _hasBeenStopped = false;

            // Parameters checks
            if (matrix == null)
            {
                throw new ArgumentNullException("matrix");
            }

            if (matrix.RowCount != matrix.ColumnCount)
            {
                throw new ArgumentException(Resources.ArgumentMatrixSquare, "matrix");
            }

            if (input == null)
            {
                throw new ArgumentNullException("input");
            }

            if (result == null)
            {
                throw new ArgumentNullException("result");
            }

            if (result.Count != input.Count)
            {
                throw new ArgumentException(Resources.ArgumentVectorsSameLength);
            }

            if (input.Count != matrix.RowCount)
            {
                throw Matrix.DimensionsDontMatch<ArgumentException>(input, result);
            }

            // Initialize the solver fields
            // Set the convergence monitor
            if (_iterator == null)
            {
                _iterator = Iterator.CreateDefault();
            }

            if (_preconditioner == null)
            {
                _preconditioner = new UnitPreconditioner();
            }
            
            _preconditioner.Initialize(matrix);
            
            // Compute r_0 = b - Ax_0 for some initial guess x_0
            // In this case we take x_0 = vector
            // This is basically a SAXPY so it could be made a lot faster
            Vector residuals = new DenseVector(matrix.RowCount);
            CalculateTrueResidual(matrix, residuals, result, input);

            // Choose r~ (for example, r~ = r_0)
            var tempResiduals = residuals.Clone();

            // create seven temporary vectors needed to hold temporary
            // coefficients. All vectors are mangled in each iteration.
            // These are defined here to prevent stressing the garbage collector
            Vector vecP = new DenseVector(residuals.Count);
            Vector vecPdash = new DenseVector(residuals.Count);
            Vector nu = new DenseVector(residuals.Count);
            Vector vecS = new DenseVector(residuals.Count);
            Vector vecSdash = new DenseVector(residuals.Count);
            Vector temp = new DenseVector(residuals.Count);
            Vector temp2 = new DenseVector(residuals.Count);

            // create some temporary double variables that are needed
            // to hold values in between iterations
            Complex currentRho = 0;
            Complex alpha = 0;
            Complex omega = 0;

            var iterationNumber = 0;
            while (ShouldContinue(iterationNumber, result, input, residuals))
            {
                // rho_(i-1) = r~^T r_(i-1) // dotproduct r~ and r_(i-1)
                var oldRho = currentRho;
                currentRho = tempResiduals.DotProduct(residuals);

                // if (rho_(i-1) == 0) // METHOD FAILS
                // If rho is only 1 ULP from zero then we fail.
                if (currentRho.Real.AlmostEqual(0, 1) && currentRho.Imaginary.AlmostEqual(0, 1))
                {
                    // Rho-type breakdown
                    throw new Exception("Iterative solver experience a numerical break down");
                }

                if (iterationNumber != 0)
                {
                    // beta_(i-1) = (rho_(i-1)/rho_(i-2))(alpha_(i-1)/omega(i-1))
                    var beta = (currentRho / oldRho) * (alpha / omega);

                    // p_i = r_(i-1) + beta_(i-1)(p_(i-1) - omega_(i-1) * nu_(i-1))
                    nu.Multiply(-omega, temp);
                    vecP.Add(temp, temp2);
                    temp2.CopyTo(vecP);

                    vecP.Multiply(beta, vecP);
                    vecP.Add(residuals, temp2);
                    temp2.CopyTo(vecP);
                }
                else
                {
                    // p_i = r_(i-1)
                    residuals.CopyTo(vecP);
                }

                // SOLVE Mp~ = p_i // M = preconditioner
                _preconditioner.Approximate(vecP, vecPdash);
                
                // nu_i = Ap~
                matrix.Multiply(vecPdash, nu);

                // alpha_i = rho_(i-1)/ (r~^T nu_i) = rho / dotproduct(r~ and nu_i)
                alpha = currentRho * 1 / tempResiduals.DotProduct(nu);

                // s = r_(i-1) - alpha_i nu_i
                nu.Multiply(-alpha, temp);
                residuals.Add(temp, vecS);

                // Check if we're converged. If so then stop. Otherwise continue;
                // Calculate the temporary result. 
                // Be careful not to change any of the temp vectors, except for
                // temp. Others will be used in the calculation later on.
                // x_i = x_(i-1) + alpha_i * p^_i + s^_i
                vecPdash.Multiply(alpha, temp);
                temp.Add(vecSdash, temp2);
                temp2.CopyTo(temp);
                temp.Add(result, temp2);
                temp2.CopyTo(temp);

                // Check convergence and stop if we are converged.
                if (!ShouldContinue(iterationNumber, temp, input, vecS))
                {
                    temp.CopyTo(result);

                    // Calculate the true residual
                    CalculateTrueResidual(matrix, residuals, result, input);

                    // Now recheck the convergence
                    if (!ShouldContinue(iterationNumber, result, input, residuals))
                    {
                        // We're all good now.
                        return;
                    }

                    // Continue the calculation
                    iterationNumber++;
                    continue;
                }

                // SOLVE Ms~ = s
                _preconditioner.Approximate(vecS, vecSdash);

                // temp = As~
                matrix.Multiply(vecSdash, temp);

                // omega_i = temp^T s / temp^T temp
                omega = temp.DotProduct(vecS) / temp.DotProduct(temp);

                // x_i = x_(i-1) + alpha_i p^ + omega_i s^
                temp.Multiply(-omega, residuals);
                residuals.Add(vecS, temp2);
                temp2.CopyTo(residuals);

                vecSdash.Multiply(omega, temp);
                result.Add(temp, temp2);
                temp2.CopyTo(result);

                vecPdash.Multiply(alpha, temp);
                result.Add(temp, temp2);
                temp2.CopyTo(result);

                // for continuation it is necessary that omega_i != 0.0
                // If omega is only 1 ULP from zero then we fail.
                if (omega.Real.AlmostEqual(0, 1) && omega.Imaginary.AlmostEqual(0, 1))
                {
                    // Omega-type breakdown
                    throw new Exception("Iterative solver experience a numerical break down");
                }

                if (!ShouldContinue(iterationNumber, result, input, residuals))
                {
                    // Recalculate the residuals and go round again. This is done to ensure that
                    // we have the proper residuals.
                    // The residual calculation based on omega_i * s can be off by a factor 10. So here
                    // we calculate the real residual (which can be expensive) but we only do it if we're
                    // sufficiently close to the finish.
                    CalculateTrueResidual(matrix, residuals, result, input);
                }

                iterationNumber++;
            }
        }
Exemplo n.º 18
0
 Vector prevCP()
 {
     return(Vector.Add(pos, cPrev));
 }
Exemplo n.º 19
0
        // Improve the random set of points with Lloyd Relaxation.
        private void ImprovePoints()
        {
            // We'd really like to generate "blue noise". Algorithms:
            // 1. Poisson dart throwing: check each new point against all
            //     existing points, and reject it if it's too close.
            // 2. Start with a hexagonal grid and randomly perturb points.
            // 3. Lloyd Relaxation: move each point to the centroid of the
            //     generated Voronoi polygon, then generate Voronoi again.
            // 4. Use force-based layout algorithms to push points away.
            // 5. More at http://www.cs.virginia.edu/~gfx/pubs/antimony/
            // Option 3 is implemented here. If it's run for too many iterations,
            // it will turn into a grid, but convergence is very slow, and we only
            // run it a few times.
            var newPoints = new List <Vector>();

            foreach (var key in _provinces.Keys)
            {
                var provincePoints = _provinces[key];
                var newpoint       = new Vector(2);
                foreach (var point in provincePoints)
                {
                    newpoint.Add(point);
                }
                newpoint[0] /= provincePoints.Count;
                newpoint[1] /= provincePoints.Count;

                newpoint[0] = (newpoint[0] + key[0]) / 2;
                newpoint[1] = (newpoint[1] + key[1]) / 2;

                newPoints.Add(newpoint);
            }


            var height = Convert.ToInt32(txtHeight.Value);
            var width  = Convert.ToInt32(txtWidth.Value);
            var points = Convert.ToInt32(txtPoints.Value);

            OrderedPoints = newPoints
                            .Select(WrapVector)
                            .OrderBy(v => String.Format("{0:000000000}{1:000000000}", height - (int)v[1], (int)v[0]))
                            .ToList();

            for (var x = -1; x <= 1; x++)
            {
                for (var y = -1; y <= 1; y++)
                {
                    if (x == 0 && y == 0)
                    {
                        continue;
                    }
                    for (var i = 0; i < points; i++)
                    {
                        var point = newPoints[i];
                        newPoints.Add(new Vector(point[0] + (x * width), point[1] + (y * height)));
                    }
                }
            }

            _pointList = newPoints;
            //Text = _pointList.Count.ToString();
            _provinces       = null;
            picDiagram.Image = new Bitmap(width, height);
            Map.Neighbours   = new MultiValueDictionary <int, int>();
        }
Exemplo n.º 20
0
        public IVector Add(IVector vector)
        {
            var other = (CpuVector)vector;

            return(new CpuVector(_vector.Add(other._vector)));
        }
Exemplo n.º 21
0
            /// <summary>
            ///     Рассмотрим следующую задачу линейного программирования:
            ///     c^Tx -> max, Ax Le b, x Ge 0, b Ge 0.
            ///     Любая общая задача ЛП может быть приведена к канонической форме.
            ///     Приведение общей задачи ЛП к канонической форме достигается путем введения новых
            ///     (их называют дополнительными) переменных.
            ///     Двухфазный симплекс-метод
            ///     Причины использования
            ///     Если в условии задачи линейного программирования не все ограничения представлены неравенствами типа «≤», то далеко
            ///     не всегда нулевой вектор будет допустимым решением. Однако каждая итерация симплекс-метода является переходом от
            ///     одной вершины к другой, и если неизвестно ни одной вершины, алгоритм вообще не может быть начат.
            ///     Процесс нахождения исходной вершины не сильно отличается от однофазного симплекс-метода, однако может в итоге
            ///     оказаться сложнее, чем дальнейшая оптимизация.
            ///     Модификация ограничений
            ///     Все ограничения задачи модифицируются согласно следующим правилам:
            ///     ограничения типа «≤» переводятся на равенства созданием дополнительной переменной с коэффициентом «+1». Эта
            ///     модификация проводится и в однофазном симплекс-методе, дополнительные переменные в дальнейшем используются как
            ///     исходный базис.
            ///     ограничения типа «≥» дополняются одной переменной с коэффициентом «−1». Поскольку такая переменная из-за
            ///     отрицательного коэффициента не может быть использована в исходном базисе, необходимо создать ещё одну,
            ///     вспомогательную, переменную. Вспомогательные переменные всегда создаются с коэффициентом «+1».
            ///     ограничения типа «=» дополняются одной вспомогательной переменной.
            ///     Соответственно, будет создано некоторое количество дополнительных и вспомогательных переменных. В исходный базис
            ///     выбираются дополнительные переменные с коэффициентом «+1» и все вспомогательные. Осторожно: решение, которому
            ///     соответствует этот базис, не является допустимым.
            ///     После того, как было модифицировано условие, создаётся вспомогательная целевая функция
            ///     Если вспомогательные переменные были обозначены, как yi, i∈{1, .., k},
            ///     то вспомогательную функцию определим, как
            ///     z' = \sum_{i=1}^k y_i -> min
            ///     После этого проводится обыкновенный симплекс-метод относительно вспомогательной целевой функции.
            ///     Поскольку все вспомогательные переменные увеличивают значение z', в ходе алгоритма
            ///     они будут поочерёдно выводится из базиса, при этом после каждого перехода новое решение
            ///     будет всё ближе к множеству допустимых решений.
            ///     Когда будет найдено оптимальное значение вспомогательной целевой функции, могут возникнуть две ситуации:
            ///     оптимальное значение z' больше нуля. Это значит, что как минимум одна из вспомогательных переменных осталась в
            ///     базисе.
            ///     В таком случае можно сделать вывод, что допустимых решений данной задачи линейного программирования не существует.
            ///     оптимальное значение z' равно нулю. Это означает, что все вспомогательные переменные были выведены из базиса,
            ///     и текущее решение является допустимым.
            ///     Во втором случае мы имеем допустимый базис, или, иначе говоря, исходное допустимое решение. Можно проводить
            ///     дальнейшую оптимизацию с учётом исходной целевой функции, при этом уже не обращая внимания на вспомогательные
            ///     переменные. Это и является второй фазой решения.
            /// </summary>
            public bool DoubleSimplexMethod(ILinearMiniMax <T> minimax)
            {
                Debug.Assert(minimax.A.Rows == minimax.R.Count());
                Debug.Assert(minimax.A.Rows == minimax.B.Count());
                Debug.Assert(minimax.A.Columns == minimax.C.Count());

                AppendLineCallback appendLineCallback = AppendLineCallback;
                ProgressCallback   progressCallback   = ProgressCallback;
                CompliteCallback   compliteCallback   = CompliteCallback;

                // количество исходныx переменныx
                // количество неравенств==количество дополнительных переменных
                // количество вспомогательных переменных
                int n      = Math.Min(minimax.A.Columns, minimax.C.Count());
                int count  = Math.Min(minimax.A.Count(), minimax.B.Count());
                int count1 = minimax.R.Count(r => r == Comparer.Ge);

                var rowsIndex    = new StackListQueue <int>(Enumerable.Range(1 + n + count1, count + 1));
                var columnsIndex = new StackListQueue <int>(Enumerable.Range(1, n + count1));

                Debug.WriteLine("count = " + count);
                Debug.WriteLine((double)minimax.Target);

                //     Модификация ограничений
                //     Все ограничения задачи модифицируются согласно следующим правилам:
                //    ограничения типа «≤» переводятся на равенства созданием дополнительной переменной с коэффициентом «+1». Эта
                //     модификация проводится и в однофазном симплекс-методе, дополнительные переменные в дальнейшем используются как
                //     исходный базис.
                //     ограничения типа «≥» дополняются одной переменной с коэффициентом «−1». Поскольку такая переменная из-за
                //     отрицательного коэффициента не может быть использована в исходном базисе, необходимо создать ещё одну,
                //     вспомогательную, переменную. Вспомогательные переменные всегда создаются с коэффициентом «+1».
                //     ограничения типа «=» дополняются одной вспомогательной переменной.
                //     Соответственно, будет создано некоторое количество дополнительных и вспомогательных переменных. В исходный базис
                //     выбираются дополнительные переменные с коэффициентом «+1» и все вспомогательные. Осторожно: решение, которому
                //     соответствует этот базис, не является допустимым.
                //После того, как было модифицировано условие, создаётся вспомогательная целевая функция
                //Если вспомогательные переменные были обозначены, как yi, i∈{1, .., k},
                //то вспомогательную функцию определим, как
                //z' = \sum_{i=1}^k y_i -> min
                //После этого проводится обыкновенный симплекс-метод относительно вспомогательной целевой функции.
                //Поскольку все вспомогательные переменные увеличивают значение z', в ходе алгоритма
                //они будут поочерёдно выводится из базиса, при этом после каждого перехода новое решение
                //будет всё ближе к множеству допустимых решений.
                //Когда будет найдено оптимальное значение вспомогательной целевой функции, могут возникнуть две ситуации:
                //оптимальное значение z' больше нуля. Это значит, что как минимум одна из вспомогательных переменных осталась в базисе.
                //В таком случае можно сделать вывод, что допустимых решений данной задачи линейного программирования не существует.
                //оптимальное значение z' равно нулю. Это означает, что все вспомогательные переменные были выведены из базиса,
                //и текущее решение является допустимым.
                var random = new Random();
                var vector =
                    new Vector <double>(0)
                {
                    Enumerable.Repeat(0.0, n),
                    Enumerable.Range(0, count1)
                    .Select(x => 100000000000000.0 + 10000000000000.0 * random.NextDouble()),
                    Enumerable.Repeat(0.0, count),
                    0,
                };

                Add(vector);

                int i1 = 1 + n + count1;
                int i2 = 1 + n;

                for (int i = 0; i < count; i++)
                {
                    var value = new Vector <double>();
                    switch (minimax.R.ElementAt(i))
                    {
                    case Comparer.Le:
                        // ограничения типа «≤» переводятся на равенства созданием дополнительной переменной с коэффициентом «+1»
                        value.Add(Convert.ToDouble(minimax.B.ElementAt(i)));
                        value.Add(minimax.A.ElementAt(i).Select(x => Convert.ToDouble(x)));
                        value.Add(Enumerable.Repeat(0.0, count + count1 + 1));
                        value[i1++] = 1;
                        break;

                    case Comparer.Eq:
                        // ограничения типа «=» дополняются одной вспомогательной переменной
                        // Вспомогательные переменные всегда создаются с коэффициентом «+1»
                        value.Add(Convert.ToDouble(minimax.B.ElementAt(i)));
                        value.Add(minimax.A.ElementAt(i).Select(x => Convert.ToDouble(x)));
                        value.Add(Enumerable.Repeat(0.0, count + count1 + 1));
                        value[i1++] = 1;
                        break;

                    case Comparer.Ge:
                        // ограничения типа «≥» дополняются одной переменной с коэффициентом «−1»
                        // Поскольку такая переменная из-за отрицательного коэффициента не может быть использована
                        // в исходном базисе, необходимо создать ещё одну, вспомогательную, переменную
                        // Вспомогательные переменные всегда создаются с коэффициентом «+1»
                        value.Add(-Convert.ToDouble(minimax.B.ElementAt(i)));
                        value.Add(minimax.A.ElementAt(i).Select(x => - Convert.ToDouble(x)));
                        value.Add(Enumerable.Repeat(0.0, count + count1 + 1));
                        value[i1++] = 1;
                        value[i2++] = 1;
                        break;
                    }
                    Add(value);
                }

                Add(new Vector <double>(0)
                {
                    minimax.C.Select(x => - Convert.ToDouble(x)),
                    Enumerable.Repeat(0.0, count1),
                    Enumerable.Repeat(0.0, count),
                    1,
                });

                RowsIndex    = rowsIndex;
                ColumnsIndex = columnsIndex;

                if (appendLineCallback != null)
                {
                    appendLineCallback("Текущий опорный план:");
                }
                if (appendLineCallback != null)
                {
                    appendLineCallback(ToString());
                }
                Debug.WriteLine("Текущий опорный план:");
                Debug.WriteLine(ToString());

                //После этого проводится обыкновенный симплекс-метод относительно вспомогательной целевой функции.
                //Поскольку все вспомогательные переменные увеличивают значение z', в ходе алгоритма
                //они будут поочерёдно выводится из базиса, при этом после каждого перехода новое решение
                //будет всё ближе к множеству допустимых решений.
                //Когда будет найдено оптимальное значение вспомогательной целевой функции, могут возникнуть две ситуации:
                //оптимальное значение z' больше нуля. Это значит, что как минимум одна из вспомогательных переменных осталась в базисе.
                //В таком случае можно сделать вывод, что допустимых решений данной задачи линейного программирования не существует.
                //оптимальное значение z' равно нулю. Это означает, что все вспомогательные переменные были выведены из базиса,
                //и текущее решение является допустимым.

                //     Transform.ByColumns:
                //     все элементы индексной строки отрицательные или ноль - при минимизации

                // Ищем допустимое решение (все элементы индексной строки отрицательные или ноль)
                SimplexMethod(Transform.ByColumns, Target.Minimum);

                Debug.WriteLine("Текущий опорный план:");
                Debug.WriteLine(ToString());

                if (this[0][0] > 0)
                {
                    return(false);
                }

                this[0] = this[this.Count]; this.RemoveAt(this.Count - 1);

                rowsIndex = new StackListQueue <int>(RowsIndex);
                rowsIndex.Pop();
                RowsIndex = rowsIndex;

                columnsIndex = new StackListQueue <int>(ColumnsIndex);
                ColumnsIndex = new StackListQueue <int>(columnsIndex.Except(Enumerable.Range(1 + n + count, count1 + 1)));

                Debug.WriteLine("Текущий опорный план:");
                Debug.WriteLine(ToString());

                // Ищется допустимое и оптимальное решение
                // (все элементы индексной строки отрицательные или ноль - при минимизации
                // все элементы индексной строки положительные или ноль - при максимизации
                // все элементы индексного столбца положительные или ноль)

                //     Transform.ByColumns:
                //     все элементы индексной строки отрицательные или ноль - при минимизации
                //     все элементы индексной строки положительные или ноль - при максимизации
                //     Transform.ByRows:
                //     все элементы индексного столбца положительные или ноль

                // Ищем допустимое решение (все элементы индексной строки отрицательные или ноль)
                // Ищем допустимое и оптимальное решение
                SimplexMethod(Transform.ByColumns, minimax.Target);
                SimplexMethod(Transform.ByRows, minimax.Target);

                return(true);
            }
Exemplo n.º 22
0
            public static IEnumerable PartitionBy(IApply func, int maxParts, IEnumerable seq)
            {
                object previous = null;
                var all = new Vector();
                Vector v = null;
                foreach (var item in ToIter(seq))
                {
                    if (v == null)
                    {
                        v = new Vector();
                        v.Add(item);
                        previous = Funcall(func, item);
                    }
                    else {
                        var current = Funcall(func, item);
                        if (all.Count + 1 == maxParts || Equal(current, previous))
                        {
                            v.Add(item);
                        }
                        else {
                            all.Add(AsList(v));
                            v = new Vector();
                            previous = current;
                            v.Add(item);
                        }
                    }
                }

                if (v != null)
                {
                    all.Add(AsList(v));
                }
                return all;
            }
Exemplo n.º 23
0
 public Vector <T> Add <T>(Vector <T> left, Vector <T> right) where T : struct
 {
     return(Vector.Add <T>(left, right));
 }
Exemplo n.º 24
0
        /// <summary>
        /// Solves the matrix equation Ax = b, where A is the coefficient matrix, b is the
        /// solution vector and x is the unknown vector.
        /// </summary>
        /// <param name="matrix">The coefficient <see cref="Matrix"/>, <c>A</c>.</param>
        /// <param name="input">The solution <see cref="Vector"/>, <c>b</c>.</param>
        /// <param name="result">The result <see cref="Vector"/>, <c>x</c>.</param>
        /// <param name="iterator">The iterator to use to control when to stop iterating.</param>
        /// <param name="preconditioner">The preconditioner to use for approximations.</param>
        public void Solve(Matrix <float> matrix, Vector <float> input, Vector <float> result, Iterator <float> iterator, IPreconditioner <float> preconditioner)
        {
            if (matrix.RowCount != matrix.ColumnCount)
            {
                throw new ArgumentException(Resources.ArgumentMatrixSquare, "matrix");
            }

            if (result.Count != input.Count)
            {
                throw new ArgumentException(Resources.ArgumentVectorsSameLength);
            }

            if (input.Count != matrix.RowCount)
            {
                throw Matrix.DimensionsDontMatch <ArgumentException>(input, matrix);
            }

            if (iterator == null)
            {
                iterator = new Iterator <float>();
            }

            if (preconditioner == null)
            {
                preconditioner = new UnitPreconditioner <float>();
            }

            preconditioner.Initialize(matrix);

            // Compute r_0 = b - Ax_0 for some initial guess x_0
            // In this case we take x_0 = vector
            // This is basically a SAXPY so it could be made a lot faster
            var residuals = new DenseVector(matrix.RowCount);

            CalculateTrueResidual(matrix, residuals, result, input);

            // Choose r~ (for example, r~ = r_0)
            var tempResiduals = residuals.Clone();

            // create seven temporary vectors needed to hold temporary
            // coefficients. All vectors are mangled in each iteration.
            // These are defined here to prevent stressing the garbage collector
            var vecP     = new DenseVector(residuals.Count);
            var vecPdash = new DenseVector(residuals.Count);
            var nu       = new DenseVector(residuals.Count);
            var vecS     = new DenseVector(residuals.Count);
            var vecSdash = new DenseVector(residuals.Count);
            var temp     = new DenseVector(residuals.Count);
            var temp2    = new DenseVector(residuals.Count);

            // create some temporary float variables that are needed
            // to hold values in between iterations
            float currentRho = 0;
            float alpha      = 0;
            float omega      = 0;

            var iterationNumber = 0;

            while (iterator.DetermineStatus(iterationNumber, result, input, residuals) == IterationStatus.Continue)
            {
                // rho_(i-1) = r~^T r_(i-1) // dotproduct r~ and r_(i-1)
                var oldRho = currentRho;
                currentRho = tempResiduals.DotProduct(residuals);

                // if (rho_(i-1) == 0) // METHOD FAILS
                // If rho is only 1 ULP from zero then we fail.
                if (currentRho.AlmostEqualNumbersBetween(0, 1))
                {
                    // Rho-type breakdown
                    throw new Exception("Iterative solver experience a numerical break down");
                }

                if (iterationNumber != 0)
                {
                    // beta_(i-1) = (rho_(i-1)/rho_(i-2))(alpha_(i-1)/omega(i-1))
                    var beta = (currentRho / oldRho) * (alpha / omega);

                    // p_i = r_(i-1) + beta_(i-1)(p_(i-1) - omega_(i-1) * nu_(i-1))
                    nu.Multiply(-omega, temp);
                    vecP.Add(temp, temp2);
                    temp2.CopyTo(vecP);

                    vecP.Multiply(beta, vecP);
                    vecP.Add(residuals, temp2);
                    temp2.CopyTo(vecP);
                }
                else
                {
                    // p_i = r_(i-1)
                    residuals.CopyTo(vecP);
                }

                // SOLVE Mp~ = p_i // M = preconditioner
                preconditioner.Approximate(vecP, vecPdash);

                // nu_i = Ap~
                matrix.Multiply(vecPdash, nu);

                // alpha_i = rho_(i-1)/ (r~^T nu_i) = rho / dotproduct(r~ and nu_i)
                alpha = currentRho * 1 / tempResiduals.DotProduct(nu);

                // s = r_(i-1) - alpha_i nu_i
                nu.Multiply(-alpha, temp);
                residuals.Add(temp, vecS);

                // Check if we're converged. If so then stop. Otherwise continue;
                // Calculate the temporary result.
                // Be careful not to change any of the temp vectors, except for
                // temp. Others will be used in the calculation later on.
                // x_i = x_(i-1) + alpha_i * p^_i + s^_i
                vecPdash.Multiply(alpha, temp);
                temp.Add(vecSdash, temp2);
                temp2.CopyTo(temp);
                temp.Add(result, temp2);
                temp2.CopyTo(temp);

                // Check convergence and stop if we are converged.
                if (iterator.DetermineStatus(iterationNumber, temp, input, vecS) != IterationStatus.Continue)
                {
                    temp.CopyTo(result);

                    // Calculate the true residual
                    CalculateTrueResidual(matrix, residuals, result, input);

                    // Now recheck the convergence
                    if (iterator.DetermineStatus(iterationNumber, result, input, residuals) != IterationStatus.Continue)
                    {
                        // We're all good now.
                        return;
                    }

                    // Continue the calculation
                    iterationNumber++;
                    continue;
                }

                // SOLVE Ms~ = s
                preconditioner.Approximate(vecS, vecSdash);

                // temp = As~
                matrix.Multiply(vecSdash, temp);

                // omega_i = temp^T s / temp^T temp
                omega = temp.DotProduct(vecS) / temp.DotProduct(temp);

                // x_i = x_(i-1) + alpha_i p^ + omega_i s^
                temp.Multiply(-omega, residuals);
                residuals.Add(vecS, temp2);
                temp2.CopyTo(residuals);

                vecSdash.Multiply(omega, temp);
                result.Add(temp, temp2);
                temp2.CopyTo(result);

                vecPdash.Multiply(alpha, temp);
                result.Add(temp, temp2);
                temp2.CopyTo(result);

                // for continuation it is necessary that omega_i != 0.0
                // If omega is only 1 ULP from zero then we fail.
                if (omega.AlmostEqualNumbersBetween(0, 1))
                {
                    // Omega-type breakdown
                    throw new Exception("Iterative solver experience a numerical break down");
                }

                if (iterator.DetermineStatus(iterationNumber, result, input, residuals) != IterationStatus.Continue)
                {
                    // Recalculate the residuals and go round again. This is done to ensure that
                    // we have the proper residuals.
                    // The residual calculation based on omega_i * s can be off by a factor 10. So here
                    // we calculate the real residual (which can be expensive) but we only do it if we're
                    // sufficiently close to the finish.
                    CalculateTrueResidual(matrix, residuals, result, input);
                }

                iterationNumber++;
            }
        }
Exemplo n.º 25
0
        public double[] SolveEquationsSystem()
        {
            double[] solution = new double[_eqSystem.EquationFunctions.Count];

            //Выполняем нулевую итерацию на начальных значениях, пришедших из настроек.

            //Находим якобиан при начальных значениях.
            double epsJacobian = 0.00001;

            double[,] jacob = _eqSystem.GetJacobianMatrix(_settings.InitialValues, epsJacobian);
            double[] eqVals = _eqSystem.GetEquationsValues(_settings.InitialValues);

            Matrix <double> matrJacobian        = CreateMatrix.DenseOfArray(jacob);
            Vector <double> vectEquationsValues = CreateVector.DenseOfArray(eqVals);

            Matrix <double> matrInvJacobian = matrJacobian.Inverse();
            Vector <double> deltaX          = matrInvJacobian.Multiply(-1.0).Multiply(vectEquationsValues);

            Vector <double> vectPrevIterX = CreateVector.DenseOfArray(_settings.InitialValues);

            for (int i = 0; i < _settings.MaxIterations; i++)
            {
                Vector <double> vectCurrIterX = vectPrevIterX.Add(deltaX);
                solution = vectCurrIterX.ToArray();

                jacob  = _eqSystem.GetJacobianMatrix(vectCurrIterX.ToArray(), epsJacobian);
                eqVals = _eqSystem.GetEquationsValues(vectCurrIterX.ToArray());

                matrJacobian        = CreateMatrix.DenseOfArray(jacob);
                vectEquationsValues = CreateVector.DenseOfArray(eqVals);

                matrInvJacobian = matrJacobian.Inverse();
                deltaX          = matrInvJacobian.Multiply(-1.0).Multiply(vectEquationsValues);

                double[] currIterEpsX = new double[vectCurrIterX.Count];

                for (int j = 0; j < vectCurrIterX.Count; j++)
                {
                    currIterEpsX[j] = Math.Abs(vectCurrIterX[j] - vectPrevIterX[j]);
                }

                bool isPreciseSolution = true;

                for (int j = 0; j < currIterEpsX.Length; j++)
                {
                    if (currIterEpsX[j] > _settings.Precision)
                    {
                        isPreciseSolution = false;
                        break;
                    }
                }

                if (isPreciseSolution == true)
                {
                    break;
                }
                else
                {
                    vectPrevIterX = CreateVector.DenseOfArray(vectCurrIterX.ToArray());

                    bool isZeroEqVals = true;

                    for (int k = 0; k < eqVals.Length; k++)
                    {
                        if (Math.Abs(eqVals[k]) > _settings.Precision)
                        {
                            isZeroEqVals = false;
                            break;
                        }
                    }

                    if (isZeroEqVals == true)
                    {
                        break;
                    }
                }
            }

            return(solution);
        }
Exemplo n.º 26
0
        public double[] GetOtherRHSComponents(ISolverSubdomain subdomain, IVector <double> currentSolution)
        {
            //// u[id]: old solution
            //// v[id]: current solution
            //// vv: old acceleration
            //// v2: current acceleration
            //// v1: current velocity
            ////double vv = v2[id].Data[j];
            ////v2[id].Data[j] = a0 * (v[id].Data[j] - u[id].Data[j]) - a2 * v1[id].Data[j] - a3 * vv;
            ////v1[id].Data[j] += a6 * vv + a7 * v2[id].Data[j];

            //int id = subdomain.ID;
            //Vector<double> currentAcceleration = new Vector<double>(subdomain.Solution.Length);
            //Vector<double> currentVelocity = new Vector<double>(subdomain.Solution.Length);
            //Vector<double> uu = new Vector<double>(subdomain.Solution.Length);
            //Vector<double> uc = new Vector<double>(subdomain.Solution.Length);
            //for (int j = 0; j < subdomain.RHS.Length; j++)
            //{
            //    currentAcceleration.Data[j] = a0 * (currentSolution[j] - v[id].Data[j]) - a2 * v1[id].Data[j] - a3 * v2[id].Data[j];
            //    currentVelocity.Data[j] = v1[id].Data[j] + a6 * v2[id].Data[j] + a7 * currentAcceleration.Data[j];
            //    uu.Data[j] = a0 * currentSolution[j] + a2 * currentVelocity.Data[j] + a3 * currentAcceleration.Data[j];
            //    uc.Data[j] = a1 * currentSolution[j] + a4 * currentVelocity.Data[j] + a5 * currentAcceleration.Data[j];
            //}

            //Vector<double> tempResult = new Vector<double>(subdomain.Solution.Length);
            //Vector<double> result = new Vector<double>(subdomain.Solution.Length);
            //provider.MassMatrixVectorProduct(subdomain, uu, tempResult.Data);
            //result.Add(tempResult);

            //provider.DampingMatrixVectorProduct(subdomain, uc, tempResult.Data);
            //result.Add(tempResult);

            //return result.Data;

            Vector <double> result     = new Vector <double>(subdomain.Solution.Length);
            Vector <double> temp       = new Vector <double>(subdomain.Solution.Length);
            Vector <double> tempResult = new Vector <double>(subdomain.Solution.Length);

            //Vector<double> uu = new Vector<double>(subdomain.Solution.Length);
            //Vector<double> uc = new Vector<double>(subdomain.Solution.Length);
            //int id = subdomain.ID;
            //for (int j = 0; j < subdomain.RHS.Length; j++)
            //{
            //    uu.Data[j] = -a0 * (v[id].Data[j] - currentSolution[j]) - a2 * v1[id].Data[j] - a3 * v2[id].Data[j];
            //    uc.Data[j] = -a1 * (v[id].Data[j] - currentSolution[j]) - a4 * v1[id].Data[j] - a5 * v2[id].Data[j];
            //}
            //provider.MassMatrixVectorProduct(subdomain, uu, tempResult.Data);
            //result.Add(tempResult);
            //provider.DampingMatrixVectorProduct(subdomain, uc, tempResult.Data);
            //result.Add(tempResult);

            ////CalculateRHSImplicit(subdomain, result.Data, false);
            ////result.Scale(-1d);
            currentSolution.CopyTo(temp.Data, 0);
            temp.Scale(a0);
            provider.MassMatrixVectorProduct(subdomain, temp, tempResult.Data);
            result.Add(tempResult);

            currentSolution.CopyTo(temp.Data, 0);
            temp.Scale(a1);
            provider.DampingMatrixVectorProduct(subdomain, temp, tempResult.Data);
            result.Add(tempResult);

            return(result.Data);
        }
Exemplo n.º 27
0
        public static LinearRegressionResult LinearRegressionVector(this double[] X0, double[] Y0)
        {
            if (X0.Length != Y0.Length)
            {
                throw new ArgumentOutOfRangeException(nameof(X0), "X and Y must be the same length");
            }

            var simdLength = Vector <double> .Count;
            var overFlow   = X0.Length % simdLength;
            var X          = X0;
            var Y          = Y0;

            var vSumX = new Vector <double>(0);
            var vSumY = new Vector <double>(0);

            for (var i = 0; i < X.Length - simdLength + 1; i += simdLength)
            {
                var vaX = new Vector <double>(X, i);
                vSumX = Vector.Add(vaX, vSumX);
                var vaY = new Vector <double>(Y, i);
                vSumY = Vector.Add(vaY, vSumY);
            }
            var xAvg = 0.0;
            var yAvg = 0.0;

            for (var i = X.Length - overFlow; i < X.Length; i++)
            {
                xAvg += X[i];
                yAvg += Y[i];
            }

            for (var i = 0; i < simdLength; ++i)
            {
                xAvg += vSumX[i];
                yAvg += vSumY[i];
            }

            xAvg /= X0.Length;
            yAvg /= Y0.Length;

            var vMeanX = new Vector <double>(xAvg);
            var vMeanY = new Vector <double>(yAvg);

            vSumX = new Vector <double>(0);
            vSumY = new Vector <double>(0);
            var vSumC = new Vector <double>(0);

            for (var i = 0; i < X.Length - simdLength + 1; i += simdLength)
            {
                var vaX  = new Vector <double>(X, i);
                var vaMX = Vector.Subtract(vaX, vMeanX);
                var va2X = Vector.Multiply(vaMX, vaMX);
                vSumX = Vector.Add(va2X, vSumX);

                var vaY  = new Vector <double>(Y, i);
                var vaMY = Vector.Subtract(vaY, vMeanY);
                var va2Y = Vector.Multiply(vaMY, vaMY);
                vSumY = Vector.Add(va2Y, vSumY);

                var va2C = Vector.Multiply(vaMX, vaMY);
                vSumC = Vector.Add(va2C, vSumC);
            }

            double c = 0, vX = 0, vY = 0;

            for (var i = X.Length - overFlow; i < X.Length; i++)
            {
                var x1 = (X[i] - xAvg);
                var y1 = (Y[i] - yAvg);
                vX += x1 * x1;
                vY += y1 * y1;
                c  += x1 * y1;
            }

            for (var i = 0; i < simdLength; ++i)
            {
                c  += vSumC[i];
                vX += vSumX[i];
                vY += vSumY[i];
            }

            var beta  = c / vX;
            var alpha = yAvg - beta * xAvg;
            var R2    = beta * Sqrt(vX / vY);

            return(new LinearRegressionResult(alpha, beta, R2));
        }
Exemplo n.º 28
0
Arquivo: Add.cs Projeto: y8x/MathSharp
        public void Add_Theory(Vector256 <double> left, Vector256 <double> right, Vector4d expected)
        {
            Vector256 <double> result = Vector.Add(left, right);

            Assert.True(TestHelpers.AreEqual(expected, result), $"Expected {expected}, got {result}");
        }
Exemplo n.º 29
0
 public static Vector2 operator +(Vector2 left, Vector2 right)
 {
     return(Vector.Add(left, right));
 }
Exemplo n.º 30
0
            public static void SplitAt(int count, IEnumerable seq, out Cons left, out Cons right)
            {
                if (seq == null)
                {
                    left = null;
                    right = null;
                    return;
                }

                var vleft = new Vector();
                var iter = seq.GetEnumerator();

                if (count > 0)
                {
                    while (--count >= 0)
                    {
                        if (!iter.MoveNext())
                        {
                            break;
                        }

                        vleft.Add(iter.Current);
                    }
                }

                left = AsList(vleft);
                right = MakeCons(iter);
            }
Exemplo n.º 31
0
        /**
         * <summary>Main method for training the CBow version of Word2Vec algorithm.</summary>
         */
        private void TrainCbow()
        {
            var iteration       = new Iteration(_corpus, _parameter);
            var currentSentence = _corpus.GetSentence(iteration.GetSentenceIndex());
            var random          = new Random();
            var outputs         = new Vector(_parameter.GetLayerSize(), 0);
            var outputUpdate    = new Vector(_parameter.GetLayerSize(), 0);

            _corpus.ShuffleSentences(1);
            while (iteration.GetIterationCount() < _parameter.GetNumberOfIterations())
            {
                iteration.AlphaUpdate();
                var wordIndex   = _vocabulary.GetPosition(currentSentence.GetWord(iteration.GetSentencePosition()));
                var currentWord = _vocabulary.GetWord(wordIndex);
                outputs.Clear();
                outputUpdate.Clear();
                var b  = random.Next(_parameter.GetWindow());
                var cw = 0;
                int lastWordIndex;
                for (var a = b; a < _parameter.GetWindow() * 2 + 1 - b; a++)
                {
                    var c = iteration.GetSentencePosition() - _parameter.GetWindow() + a;
                    if (a != _parameter.GetWindow() && currentSentence.SafeIndex(c))
                    {
                        lastWordIndex = _vocabulary.GetPosition(currentSentence.GetWord(c));
                        outputs.Add(_wordVectors.GetRow(lastWordIndex));
                        cw++;
                    }
                }

                if (cw > 0)
                {
                    outputs.Divide(cw);
                    int    l2;
                    double f;
                    double g;
                    if (_parameter.IsHierarchicalSoftMax())
                    {
                        for (var d = 0; d < currentWord.GetCodeLength(); d++)
                        {
                            l2 = currentWord.GetPoint(d);
                            f  = outputs.DotProduct(_wordVectorUpdate.GetRow(l2));
                            if (f <= -MAX_EXP || f >= MAX_EXP)
                            {
                                continue;
                            }

                            f = _expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))];

                            g = (1 - currentWord.GetCode(d) - f) * iteration.GetAlpha();
                            outputUpdate.Add(_wordVectorUpdate.GetRow(l2).Product(g));
                            _wordVectorUpdate.Add(l2, outputs.Product(g));
                        }
                    }
                    else
                    {
                        for (var d = 0; d < _parameter.GetNegativeSamplingSize() + 1; d++)
                        {
                            int target;
                            int label;
                            if (d == 0)
                            {
                                target = wordIndex;
                                label  = 1;
                            }
                            else
                            {
                                target = _vocabulary.GetTableValue(random.Next(_vocabulary.GetTableSize()));
                                if (target == 0)
                                {
                                    target = random.Next(_vocabulary.Size() - 1) + 1;
                                }
                                if (target == wordIndex)
                                {
                                    continue;
                                }
                                label = 0;
                            }

                            l2 = target;
                            f  = outputs.DotProduct(_wordVectorUpdate.GetRow(l2));
                            g  = CalculateG(f, iteration.GetAlpha(), label);
                            outputUpdate.Add(_wordVectorUpdate.GetRow(l2).Product(g));
                            _wordVectorUpdate.Add(l2, outputs.Product(g));
                        }
                    }

                    for (var a = b; a < _parameter.GetWindow() * 2 + 1 - b; a++)
                    {
                        var c = iteration.GetSentencePosition() - _parameter.GetWindow() + a;
                        if (a != _parameter.GetWindow() && currentSentence.SafeIndex(c))
                        {
                            lastWordIndex = _vocabulary.GetPosition(currentSentence.GetWord(c));
                            _wordVectors.Add(lastWordIndex, outputUpdate);
                        }
                    }
                }

                currentSentence = iteration.SentenceUpdate(currentSentence);
            }
        }
Exemplo n.º 32
0
            public static IEnumerable Union(IEnumerable seq1, IEnumerable seq2, IApply test)
            {
                var z = new Vector();

                foreach (object item in ToIter(seq1))
                {
                    var mv = FindItem(z, item, test, null, null);

                    if (mv.Item2 == null)
                    {
                        z.Add(item);
                    }
                }

                foreach (object item in ToIter(seq2))
                {
                    var mv = FindItem(z, item, test, null, null);

                    if (mv.Item2 == null)
                    {
                        z.Add(item);
                    }
                }

                return z;
            }
        /// <summary>
        /// Aggregate the valuation profile onto a set of result curves to support result partitioning.
        /// </summary>
        protected override void ProcessResults(ValuationResults valResults, DealPartitionAssociations assoc, PriceFactorList factors, BaseTimeGrid baseTimes, ValuationOptions options, int partition)
        {
            var pvProfiles          = valResults.Results <PVProfiles>();
            var addOnProfiles       = valResults.Results <AddOnProfiles>();
            var positiveMtmProfiles = valResults.Results <PositiveMtmProfiles>();

            Debug.Assert(addOnProfiles != null, "No Add-On profiles. Cannot proceed with valuation.");
            Debug.Assert(positiveMtmProfiles != null, "No Positive mtM profiles. Cannot proceed with valuation.");

            fT = Deal.ValuationGrid(factors, baseTimes, Deal.EndDate());
            var tgi = new TimeGridIterator(fT);

            var nettedExposure     = new PVProfiles(factors.NumScenarios);
            var collateralExposure = new PVProfiles(factors.NumScenarios);

            var addOnsProfile  = new PVProfiles(factors.NumScenarios);
            var mtmTermProfile = new PVProfiles(factors.NumScenarios);

            DealBaselNettingCollateralSet nettingSetDeal = Deal as DealBaselNettingCollateralSet;

            bool collateralised = nettingSetDeal.Collateralised == YesNo.Yes;

            using (var cache = Vector.Cache(factors.NumScenarios))
            {
                Vector sumMtm         = cache.Get();
                Vector sumPositiveMtm = cache.Get();
                Vector addOns         = cache.Get();
                Vector netGrossRatio  = cache.Get();
                Vector value          = cache.Get();
                Vector term1          = cache.Get();
                Vector term2          = cache.Get();

                // Collateral related vectors.
                Vector mtmTermStart = cache.Get();
                Vector addOnHp      = cache.Get();

                // Loop to get the netting set exposure.
                while (tgi.Next())
                {
                    sumMtm.Clear();
                    sumPositiveMtm.Clear();
                    addOns.Clear();
                    value.Clear();

                    double date = tgi.Date;

                    // For MtM Plus Add-On deals PV profiles represents the sum of the MtM profile and Add-On profile.
                    // Subtract the Add-On profile to recover the MtM profile before flooring.
                    sumMtm.Assign(VectorMath.Max(pvProfiles[date] - addOnProfiles[date], 0.0));

                    addOns.Assign(addOnProfiles[date]);
                    sumPositiveMtm.Assign(positiveMtmProfiles[date]);

                    netGrossRatio.AssignConditional(sumPositiveMtm > 0, sumMtm / sumPositiveMtm, 0.0);

                    netGrossRatio.MultiplyBy(this.fNetGrossRatioCorrelation);
                    netGrossRatio.Add(1 - this.fNetGrossRatioCorrelation);

                    term2.AssignProduct(addOns, netGrossRatio);

                    term1.Assign(VectorMath.Max(sumMtm, 0.0));

                    value.AssignSum(term1, term2);

                    nettedExposure.AppendVector(date, value);

                    if (collateralised)
                    {
                        mtmTermProfile.AppendVector(date, term1);
                        addOnsProfile.AppendVector(date, term2);
                    }
                }

                nettedExposure.Complete(this.fT);

                var exposureResults = valResults.Results <Exposure>();
                if (exposureResults != null)
                {
                    exposureResults.Assign(nettedExposure);
                }

                // Collateral cases.
                if (collateralised)
                {
                    mtmTermProfile.Complete(this.fT);
                    addOnsProfile.Complete(this.fT);

                    double date = factors.BaseDate;

                    mtmTermProfile.GetValue(mtmTermStart, date);
                    addOnsProfile.GetValue(addOnHp, date + nettingSetDeal.Holding_Period);

                    // Assume we have post haircut collateral.
                    double collateral = nettingSetDeal.Balance;
                    double threshold  = nettingSetDeal.Threshold;

                    tgi.Reset();

                    // Loop to get the netting set exposure.
                    while (tgi.Next())
                    {
                        bool inHoldingPeriod = tgi.T < CalcUtils.DaysToYears(nettingSetDeal.Holding_Period);

                        CollateralBasel3(mtmTermStart, collateral, addOnHp, threshold, inHoldingPeriod, tgi.Date,
                                         nettedExposure,
                                         collateralExposure);
                    }

                    collateralExposure.Complete(this.fT);

                    if (exposureResults != null)
                    {
                        exposureResults.Assign(collateralExposure);
                    }
                }
            }

            if (options.PartitionCollateralMode != PartitionCollateralMode.Suppress_Collateral_And_Flooring || partition < options.NumTotalPartitions)
            {
                valResults.FloorResult(assoc.AggregationMode, options);
            }

            CollateralPlugIn.CollateralBalancesContainer coProfiles = valResults.Results <CollateralPlugIn.CollateralBalancesContainer>();

            // Store collateral information according to diagnostic collection rules.
            if (coProfiles != null)
            {
                coProfiles.StoreInformation(this);
            }
        }
        /// <summary>
        /// Adds a scalar to each element of the vector and stores the result in the result vector.
        /// </summary>
        /// <param name="scalar">The scalar to add.</param>
        /// <param name="result">The vector to store the result of the addition.</param>
        /// <exception cref="ArgumentNullException">If the result vector is <see langword="null" />.</exception>
        /// <exception cref="ArgumentException">If this vector and <paramref name="result"/> are not the same size.</exception>
        public override void Add(double scalar, Vector result)
        {
            if (result == null)
            {
                throw new ArgumentNullException("result");
            }

            if (this.Count != result.Count)
            {
                throw new ArgumentException(Resources.ArgumentVectorsSameLength, "result");
            }

            this.CopyTo(result);
            result.Add(scalar);
        }
Exemplo n.º 35
0
 public static HwVector operator +(HwVector left, HwVector right)
 {
     return(Vector.Add(left, right));
 }
Exemplo n.º 36
0
        private void SolveForYStar(Vector yStar, Vector[] coefficient, Vector[] coupon, Vector[] stdDev)
        {
            const int MaxIterations = 10;

            using (var cache = Vector.CacheLike(yStar))
            {
                Vector y           = cache.Get();
                Vector value       = cache.Get();
                Vector deriv       = cache.Get();
                Vector factor      = cache.Get();
                Vector dy          = cache.Get();
                Vector product     = cache.Get();
                Vector numerator   = cache.GetClear();
                Vector demoninator = cache.GetClear();

                int numberOfCoupons = coupon.Length;

                // Solve the equation to first order for the initial guess
                VectorEngine.For(0, numberOfCoupons, i =>
                {
                    product.Assign(coupon[i] * coefficient[i]);
                    numerator.Add(product);
                    demoninator.Add(product * stdDev[i]);
                    return(LoopAction.Continue);
                });

                y.Assign(numerator / demoninator);

                var dyAbs = cache.Get();

                // Newton-Raphson loop to find yStar
                VectorEngine.For(0, MaxIterations, iteration =>
                {
                    value.Clear();
                    deriv.Clear();

                    VectorEngine.For(0, numberOfCoupons, i =>
                    {
                        // Performs factor = c[i] * fCoefficient[i] * Exp(-stdDev[i] * y)
                        factor.Assign(CalcUtils.SafeExpMultiply(-stdDev[i] * y, coupon[i] * coefficient[i]));
                        value.Add(factor);
                        deriv.Subtract(stdDev[i] * factor);
                        return(LoopAction.Continue);
                    });

                    // Could get divide by zero
                    dy.Assign(value / deriv);

                    // Terminate if solution reached.
                    dyAbs.AssignAbs(dy);
                    if (dyAbs.MaxElement() == 0)
                    {
                        return(LoopAction.Break);
                    }

                    y.Subtract(dy);

                    return(LoopAction.Continue);
                });

                yStar.Assign(y);
            }
        }
Exemplo n.º 37
0
        public void Run(string[] args)
        {
            SetClass <SetClass <int> > ps = new SetClass <SetClass <int> >(new Vector <SetClass <int> >());

            ps.Data.Add(new SetClass <int>(new Vector <int>()));
            ps.Data[0].Data.Add(1);
            ps.Data[0].Data.Add(2);

            ps.Data.Add(new SetClass <int>(new Vector <int>()));
            ps.Data[1].Data.Add(3);
            ps.Data[1].Data.Add(4);

            ps.Data.Add(new SetClass <int>(new Vector <int>()));
            ps.Data[2].Data.Add(5);

            string s = ps.ToString();


            Vector <Tuple <int, int> > abc = new Vector <Tuple <int, int> >();

            abc.Add(new Tuple <int, int>(3, 4));

            if (args.Length < 2)
            {
                Console.WriteLine("Expected at least two params");
                return;
            }

            string        opName = args[0];
            OperationEnum op     = (OperationEnum)Enum.Parse(typeof(OperationEnum), opName);

            string         setAPath = "../../Data/Project01/" + args[1];
            SetClass <int> setB     = null;
            int            element  = 0;

            if (op == OperationEnum.MEMBERSHIP)
            {
                element = int.Parse(args[2]);
            }
            else if (args.Length == 3)
            {
                string       setBPath = "../../Data/Project01/" + args[2];
                Vector <int> setBData = null;
                DataSerializer <int> .LoadVectorFromTextFile(setBPath, ref setBData);

                if (setBData == null)
                {
                    Console.WriteLine("Failed to load data from input file");
                    return;
                }


                setB = new SetClass <int>(setBData);
            }


            Vector <int> setAData = null;

            DataSerializer <int> .LoadVectorFromTextFile(setAPath, ref setAData);

            if (setAData == null)
            {
                Console.WriteLine("Failed to load data from input file");
                return;
            }
            SetClass <int> setA = new SetClass <int>(setAData);



            switch (op)
            {
            case OperationEnum.CARTESIAN:
                Console.WriteLine(
                    string.Format("Cartesian of SetA- {0}, Set B- {1}, is = {2} ",
                                  setA.Data.ToString(),
                                  setB.Data.ToString(),
                                  setA.CartesianProduct <int>(setB).Data.ToString()
                                  )
                    ); break;

            case OperationEnum.MEMBERSHIP:
                Console.WriteLine(string.Format("Check membership of {0}, is {1}", element, setA.Membership(element))); break;

            case OperationEnum.SUBSET:
                Console.WriteLine(string.Format("Check subset of {0} in {1}, and result = {2}",
                                                setA.Data.ToString(),
                                                setB.Data.ToString(),
                                                setA.IsSubsetOf(setB)
                                                )
                                  ); break;

            case OperationEnum.INTERESECTION:
                var setC = setA.IntersectionWith(setB);
                Console.WriteLine(string.Format("Interesection of A- {0}, with B- {1} is {2}",
                                                setA.Data.ToString(),
                                                setB.Data.ToString(),
                                                setC.Data.ToString()

                                                ));

                DataSerializer <int> .SaveVectorToTextFile("f1.txt", setC.Data);   break;

            case OperationEnum.SUPERSET:
                Console.WriteLine(string.Format("Check power of {0}, result = {1}",
                                                setA.Data.ToString(),

                                                setA.Powerset()

                                                )); break;
            }
        }
Exemplo n.º 38
0
        public static Vector AsVector(IEnumerable seq)
        {
            if (seq == null)
            {
                return new Vector();
            }

            var v = seq as Vector;

            if (v != null)
            {
                return v;
            }

            v = new Vector();

            foreach (var item in seq)
            {
                v.Add(item);
            }

            return v;
        }
Exemplo n.º 39
0
 Vector nextCP()
 {
     return(Vector.Add(pos, cNext));
 }
Exemplo n.º 40
0
        /// <summary>
        /// Layout the nodes and endges
        /// </summary>
        /// <param name="nodes">list of nodes to process</param>
        /// <param name="edges">list of edges to process</param>
        public void Layout(IEnumerable nodes,
                            IEnumerable edges
                          )
        {
            Dictionary<object, NodeLayoutData> nodeLayoutDataByKey = new Dictionary<object, NodeLayoutData>();

            // build a dictionary of node layout data by node key
            foreach (object node in nodes)
            {
                object key = _getKeyFromNodeDelegate(node);
                nodeLayoutDataByKey.Add(key, new NodeLayoutData(node));
            }

            foreach (object edge in edges)
            {
                object sourceNodeKey = _getSourceNodeKeyFromEdgeDelegate(edge);
                object destinationNodeKey = _getDestinationNodeKeyFromEdgeDelegate(edge);

                if (sourceNodeKey != null && destinationNodeKey != null)
                {
                    NodeLayoutData sourceNodeLayoutData = null;
                    NodeLayoutData destinationNodeLayoutData = null;

                    nodeLayoutDataByKey.TryGetValue(sourceNodeKey, out sourceNodeLayoutData);
                    nodeLayoutDataByKey.TryGetValue(destinationNodeKey, out destinationNodeLayoutData);

                    if (sourceNodeLayoutData != null && destinationNodeLayoutData != null && sourceNodeLayoutData != destinationNodeLayoutData)
                    {
                        destinationNodeLayoutData.InputNodesLayoutData.Add(sourceNodeLayoutData);
                        sourceNodeLayoutData.NextNodesLayoutData.Add(destinationNodeLayoutData);
                    }
                }
            }

            PreSolve(nodeLayoutDataByKey);

            bool finished = false;

            double damping = _defaultDamping;
            double timestep = 0;
            double minKineticEnergy = _defaultStoppingKineticEnergyLevel;

            int maximumIterations = _defaultMaximumIterations;
            int maxElapsedSeconds = MaximumSeconds;

            DateTime startTime = DateTime.Now;
            DateTime lastRenderTime = DateTime.Now;

            while (!finished)
            {
                _lastEnergy = _energy;

                timestep++;
                double totalKineticEnergy = 0;

                foreach (NodeLayoutData nodeData in nodeLayoutDataByKey.Values)
                {
                    Vector netForceOnNode = new Vector(0, 0);

                    foreach (NodeLayoutData otherNodeData in nodeLayoutDataByKey.Values)
                    {
                        if (nodeData != otherNodeData)
                        {
                            Vector repulsiveForceBetweenNodes = CalculateRepulsiveForceBetweeNodes(nodeData, otherNodeData);
                            netForceOnNode.Add(repulsiveForceBetweenNodes);
                        }
                    }

                    foreach(NodeLayoutData inputNodeData in nodeData.InputNodesLayoutData)
                    {
                        Vector attractiveForceBetweenNodes = CalculateAttractiveForceBetweenNodes(nodeData, inputNodeData);
                        netForceOnNode.Add(attractiveForceBetweenNodes);
                    }

                    nodeData.Velocity.AddWithMultiplier(netForceOnNode, 1);
                    nodeData.Velocity.ApplyMultiplier(damping);

                    nodeData.Coordinates.X = nodeData.Coordinates.X + nodeData.Velocity.Dx;
                    nodeData.Coordinates.Y = nodeData.Coordinates.Y + nodeData.Velocity.Dy;

                    if ((Math.Abs(nodeData.Velocity.Dx) + Math.Abs(nodeData.Velocity.Dy)) > 0)
                    {
                        totalKineticEnergy = totalKineticEnergy + Math.Pow((Math.Abs(nodeData.Velocity.Dx) + Math.Abs(nodeData.Velocity.Dy)) / 2.0,2);
                    }
                }

                double elapsedSeconds = DateTime.Now.Subtract(startTime).TotalSeconds;

                double elapsedMilisecondsSinceLastRender = DateTime.Now.Subtract(lastRenderTime).TotalMilliseconds;

                if (elapsedMilisecondsSinceLastRender > _iterationDrawMiliseconds)
                {
                    if (totalKineticEnergy > 0)
                    {
                        SetNodeCoordinates(nodeLayoutDataByKey.Values);
                    }
                    lastRenderTime = DateTime.Now;
                }

                _energy = totalKineticEnergy;

                if (_energy < _lastEnergy)
                {
                    if (timestep >= maximumIterations || totalKineticEnergy < minKineticEnergy || elapsedSeconds > maxElapsedSeconds)
                    {
                        finished = true;
                        if (totalKineticEnergy > 0)
                        {
                            SetNodeCoordinates(nodeLayoutDataByKey.Values);
                        }
                    }
                }
            }
        }
Exemplo n.º 41
0
        public void Run(string[] args)
        {
            // manage the size of the problem here
            int problem_size = 10000;
            // create a vector class variable
            Vector <int> vector = new Vector <int>(problem_size);
            // this object measures time elapsed
            Stopwatch s = new Stopwatch();


            // generate a sequence of integers for the problem and store them in a separate array
            int[]  data = new int[problem_size];
            Random k    = new Random(100);

            for (int i = 0; i < problem_size; i++)
            {
                data[i] = k.Next(10000);
            }

            // print out array
            //Console.WriteLine("Initial data:");
            //Console.WriteLine(data);

            // ------------------ Default Sort ----------------------------------
            Console.WriteLine("\n::We are running Default Sort");
            Console.WriteLine("After sort in assending order:");
            vector.Clear();
            // this uploads integers to the vector every time before sorting
            for (int i = 0; i < problem_size; i++)
            {
                vector.Add(data[i]);
            }
            s.Restart();

            // !!!Sort the vector here in ascending order with Default Sort

            s.Stop();
            Console.WriteLine("Sorting Time: " + s.ElapsedMilliseconds);
            //Console.WriteLine(vector);

            Console.WriteLine("After sort in descending order:");
            vector.Clear();
            for (int i = 0; i < problem_size; i++)
            {
                vector.Add(data[i]);
            }
            s.Restart();

            // !!!Sort the vector here in descending order with Default Sort

            s.Stop();
            Console.WriteLine("Sorting Time: " + s.ElapsedMilliseconds);
            //Console.WriteLine(vector);


            // ------------------ BubbleSort ----------------------------------
            Console.WriteLine("\n::We are running BubbleSort");
            //vector.Sorter = new BubbleSort(); // uncomment, change to BubbleSort

            Console.WriteLine("After sort in assending order:");
            vector.Clear();
            for (int i = 0; i < problem_size; i++)
            {
                vector.Add(data[i]);
            }
            s.Restart();

            // Sort the vector here in ascending order with BubbleSort

            s.Stop();
            Console.WriteLine("Sorting Time: " + s.ElapsedMilliseconds);
            //Console.WriteLine(vector);

            Console.WriteLine("After sort in descending order:");
            vector.Clear();
            for (int i = 0; i < problem_size; i++)
            {
                vector.Add(data[i]);
            }
            s.Restart();

            // Sort the vector here in descending order with BubbleSort

            s.Stop();
            Console.WriteLine("Sorting Time: " + s.ElapsedMilliseconds);
            //Console.WriteLine(vector);


            // ------------------ SelectionSort ----------------------------------
            Console.WriteLine("\n::We are running SelectionSort");
            //vector.Sorter = new SelectionSort(); // uncomment, change to SelectionSort

            Console.WriteLine("After sort in assending order:");
            vector.Clear();
            for (int i = 0; i < problem_size; i++)
            {
                vector.Add(data[i]);
            }
            s.Restart();

            // Sort the vector here in ascending order with SelectionSort

            s.Stop();
            Console.WriteLine("Sorting Time: " + s.ElapsedMilliseconds);
            //Console.WriteLine(vector);

            Console.WriteLine("After sort in descending order:");
            vector.Clear();
            for (int i = 0; i < problem_size; i++)
            {
                vector.Add(data[i]);
            }
            s.Restart();

            // Sort the vector here in descending order with SelectionSort

            s.Stop();
            Console.WriteLine("Sorting Time: " + s.ElapsedMilliseconds);
            //Console.WriteLine(vector);


            // ------------------ InsertionSort ----------------------------------
            Console.WriteLine("\n::We are running InsertionSort");
            //vector.Sorter = new InsertionSort(); // uncomment, change to InsertionSort

            Console.WriteLine("After sort in assending order:");
            vector.Clear();
            for (int i = 0; i < problem_size; i++)
            {
                vector.Add(data[i]);
            }
            s.Restart();

            // Sort the vector here in ascending order with InsertionSort

            s.Stop();
            Console.WriteLine("Sorting Time: " + s.ElapsedMilliseconds);
            //Console.WriteLine(vector);

            Console.WriteLine("After sort in descending order:");
            vector.Clear();
            for (int i = 0; i < problem_size; i++)
            {
                vector.Add(data[i]);
            }
            s.Restart();

            // Sort the vector here in descending order with InsertionSort

            s.Stop();
            Console.WriteLine("Sorting Time: " + s.ElapsedMilliseconds);
            //Console.WriteLine(vector);


            // ------------------ RandomizedQuickSort ----------------------------------
            Console.WriteLine("\n::We are running RandomizedQuickSort");
            //vector.Sorter = new RandomizedQuickSort(); // uncomment, change to RandomizedQuickSort

            Console.WriteLine("After sort in assending order:");
            vector.Clear();
            for (int i = 0; i < problem_size; i++)
            {
                vector.Add(data[i]);
            }
            s.Restart();

            // Sort the vector here in ascending order with RandomizedQuickSort

            s.Stop();
            Console.WriteLine("Sorting Time: " + s.ElapsedMilliseconds);
            //Console.WriteLine(vector);

            Console.WriteLine("After sort in descending order:");
            vector.Clear();
            for (int i = 0; i < problem_size; i++)
            {
                vector.Add(data[i]);
            }
            s.Restart();

            // Sort the vector here in descending order with RandomizedQuickSort

            s.Stop();
            Console.WriteLine("Sorting Time: " + s.ElapsedMilliseconds);
            //Console.WriteLine(vector);

            Console.ReadLine();
        }
Exemplo n.º 42
0
        private void moveDrone(GameEvent gameEvent, General general, Drone drone)
        {
            Vector targetPosition = getCloudCenterPosition(gameEvent.model, general, drone);

            QuantumModel model             = gameEvent.model;
            double       cloudRadius       = model.cloudRadius;
            Vector       distanceToCenter  = Vector.Subtract(targetPosition, drone.Position);
            Vector       directionToCenter = distanceToCenter;


            double positionChange = model.dronSpeedConstant * gameEvent.deltaTime;

            if (directionToCenter.Length == 0)
            {
                drone.Position += new Vector(random.NextDouble(), random.NextDouble());
                return;
            }
            directionToCenter.Normalize();

            Vector droneMovement = Vector.Multiply(positionChange, directionToCenter);

            double precision   = 0.9;
            double randomValue = random.NextDouble() * precision * 2 + 1 - precision;

            double minDistanceForAction;

            if (drone.Order == DroneOrder.MoveToGeneral ||
                drone.Order == DroneOrder.MoveToOutpost)
            {
                minDistanceForAction = model.cloudRadius;
            }
            else if (drone.Order == DroneOrder.MoveToPosition)
            {
                minDistanceForAction = model.moveToPositionRadius;
            }
            else
            {
                minDistanceForAction = 1;
            }

            if (distanceToCenter.Length > minDistanceForAction + positionChange)
            {
                drone.Position = Vector.Add(drone.Position, Vector.Multiply(droneMovement, randomValue));
            }
            else if (drone.Order == DroneOrder.MoveToGeneral ||
                     drone.Order == DroneOrder.MoveToOutpost)
            {
                if (general.Team == Team.green)
                {
                    drone.Position = Vector.Add(drone.Position, new Vector(randomValue * droneMovement.Y, -randomValue * droneMovement.X));
                }
                else
                {
                    drone.Position = Vector.Add(drone.Position, new Vector(randomValue * -droneMovement.Y, randomValue * droneMovement.X));
                }
            }
            else if (drone.Order == DroneOrder.MoveToPosition)
            {
                drone.Order = DroneOrder.MoveToGeneral;
            }
        }
Exemplo n.º 43
0
            public static IEnumerable Partition(bool all, int size, int step, IEnumerable pad, IEnumerable seq)
            {
                if (size <= 0)
                {
                    throw new LispException("Invalid size: {0}", size);
                }

                if (step <= 0)
                {
                    throw new LispException("Invalid step: {0}", step);
                }

                // We never need more than size-1 pad elements
                var source = Runtime.Append(seq, Take(size - 1, pad));
                var v = new Vector();

                while (source != null)
                {
                    while (source != null && v.Count < size)
                    {
                        v.Add(Car(source));
                        source = Cdr(source);
                    }

                    if (all || v.Count == size)
                    {
                        yield return AsList(v);
                    }

                    if (source != null)
                    {
                        if (step < size)
                        {
                            v.RemoveRange(0, step);
                        }
                        else if (size < step)
                        {
                            source = Runtime.Drop(step - size, source);
                            v.Clear();
                        }
                        else {
                            v.Clear();
                        }
                    }
                }
            }
Exemplo n.º 44
0
        /// <summary>
        /// Initializes all constraint functions for value comparisons.
        /// </summary>
        private unsafe void SetConstraintFunctions()
        {
            switch (this.Region.ReadGroup.ElementDataType)
            {
            case DataType type when type == DataTypes.Byte:
                this.Changed                   = () => { return(Vector.Equals(this.CurrentValues, this.PreviousValues)); };
                this.Unchanged                 = () => { return(Vector.OnesComplement(Vector.Equals(this.CurrentValues, this.PreviousValues))); };
                this.Increased                 = () => { return(Vector.GreaterThan(this.CurrentValues, this.PreviousValues)); };
                this.Decreased                 = () => { return(Vector.LessThan(this.CurrentValues, this.PreviousValues)); };
                this.EqualToValue              = (value) => { return(Vector.Equals(this.CurrentValues, new Vector <Byte>(unchecked ((Byte)value)))); };
                this.NotEqualToValue           = (value) => { return(Vector.OnesComplement(Vector.Equals(this.CurrentValues, new Vector <Byte>(unchecked ((Byte)value))))); };
                this.GreaterThanValue          = (value) => { return(Vector.GreaterThan(this.CurrentValues, new Vector <Byte>(unchecked ((Byte)value)))); };
                this.GreaterThanOrEqualToValue = (value) => { return(Vector.GreaterThanOrEqual(this.CurrentValues, new Vector <Byte>(unchecked ((Byte)value)))); };
                this.LessThanValue             = (value) => { return(Vector.LessThan(this.CurrentValues, new Vector <Byte>(unchecked ((Byte)value)))); };
                this.LessThanOrEqualToValue    = (value) => { return(Vector.LessThanOrEqual(this.CurrentValues, new Vector <Byte>(unchecked ((Byte)value)))); };
                this.IncreasedByValue          = (value) => { return(Vector.Equals(this.CurrentValues, Vector.Add(this.PreviousValues, new Vector <Byte>(unchecked ((Byte)value))))); };
                this.DecreasedByValue          = (value) => { return(Vector.Equals(this.CurrentValues, Vector.Subtract(this.PreviousValues, new Vector <Byte>(unchecked ((Byte)value))))); };
                break;

            case DataType type when type == DataTypes.SByte:
                this.Changed                   = () => { return(Vector.AsVectorByte(Vector.Equals(Vector.AsVectorSByte(this.CurrentValues), Vector.AsVectorSByte(this.PreviousValues)))); };
                this.Unchanged                 = () => { return(Vector.OnesComplement(Vector.AsVectorByte(Vector.Equals(Vector.AsVectorSByte(this.CurrentValues), Vector.AsVectorSByte(this.PreviousValues))))); };
                this.Increased                 = () => { return(Vector.AsVectorByte(Vector.GreaterThan(Vector.AsVectorSByte(this.CurrentValues), Vector.AsVectorSByte(this.PreviousValues)))); };
                this.Decreased                 = () => { return(Vector.AsVectorByte(Vector.LessThan(Vector.AsVectorSByte(this.CurrentValues), Vector.AsVectorSByte(this.PreviousValues)))); };
                this.EqualToValue              = (value) => { return(Vector.AsVectorByte(Vector.Equals(Vector.AsVectorSByte(this.CurrentValues), new Vector <SByte>(unchecked ((SByte)value))))); };
                this.NotEqualToValue           = (value) => { return(Vector.OnesComplement(Vector.AsVectorByte(Vector.Equals(Vector.AsVectorSByte(this.CurrentValues), new Vector <SByte>(unchecked ((SByte)value)))))); };
                this.GreaterThanValue          = (value) => { return(Vector.AsVectorByte(Vector.GreaterThan(Vector.AsVectorSByte(this.CurrentValues), new Vector <SByte>(unchecked ((SByte)value))))); };
                this.GreaterThanOrEqualToValue = (value) => { return(Vector.AsVectorByte(Vector.GreaterThanOrEqual(Vector.AsVectorSByte(this.CurrentValues), new Vector <SByte>(unchecked ((SByte)value))))); };
                this.LessThanValue             = (value) => { return(Vector.AsVectorByte(Vector.LessThan(Vector.AsVectorSByte(this.CurrentValues), new Vector <SByte>(unchecked ((SByte)value))))); };
                this.LessThanOrEqualToValue    = (value) => { return(Vector.AsVectorByte(Vector.LessThanOrEqual(Vector.AsVectorSByte(this.CurrentValues), new Vector <SByte>(unchecked ((SByte)value))))); };
                this.IncreasedByValue          = (value) => { return(Vector.AsVectorByte(Vector.Equals(Vector.AsVectorSByte(this.CurrentValues), Vector.Add(Vector.AsVectorSByte(this.PreviousValues), new Vector <SByte>(unchecked ((SByte)value)))))); };
                this.DecreasedByValue          = (value) => { return(Vector.AsVectorByte(Vector.Equals(Vector.AsVectorSByte(this.CurrentValues), Vector.Subtract(Vector.AsVectorSByte(this.PreviousValues), new Vector <SByte>(unchecked ((SByte)value)))))); };
                break;

            case DataType type when type == DataTypes.Int16:
                this.Changed                   = () => { return(Vector.AsVectorByte(Vector.Equals(Vector.AsVectorInt16(this.CurrentValues), Vector.AsVectorInt16(this.PreviousValues)))); };
                this.Unchanged                 = () => { return(Vector.OnesComplement(Vector.AsVectorByte(Vector.Equals(Vector.AsVectorInt16(this.CurrentValues), Vector.AsVectorInt16(this.PreviousValues))))); };
                this.Increased                 = () => { return(Vector.AsVectorByte(Vector.GreaterThan(Vector.AsVectorInt16(this.CurrentValues), Vector.AsVectorInt16(this.PreviousValues)))); };
                this.Decreased                 = () => { return(Vector.AsVectorByte(Vector.LessThan(Vector.AsVectorInt16(this.CurrentValues), Vector.AsVectorInt16(this.PreviousValues)))); };
                this.EqualToValue              = (value) => { return(Vector.AsVectorByte(Vector.Equals(Vector.AsVectorInt16(this.CurrentValues), new Vector <Int16>(unchecked ((Int16)value))))); };
                this.NotEqualToValue           = (value) => { return(Vector.OnesComplement(Vector.AsVectorByte(Vector.Equals(Vector.AsVectorInt16(this.CurrentValues), new Vector <Int16>(unchecked ((Int16)value)))))); };
                this.GreaterThanValue          = (value) => { return(Vector.AsVectorByte(Vector.GreaterThan(Vector.AsVectorInt16(this.CurrentValues), new Vector <Int16>(unchecked ((Int16)value))))); };
                this.GreaterThanOrEqualToValue = (value) => { return(Vector.AsVectorByte(Vector.GreaterThanOrEqual(Vector.AsVectorInt16(this.CurrentValues), new Vector <Int16>(unchecked ((Int16)value))))); };
                this.LessThanValue             = (value) => { return(Vector.AsVectorByte(Vector.LessThan(Vector.AsVectorInt16(this.CurrentValues), new Vector <Int16>(unchecked ((Int16)value))))); };
                this.LessThanOrEqualToValue    = (value) => { return(Vector.AsVectorByte(Vector.LessThanOrEqual(Vector.AsVectorInt16(this.CurrentValues), new Vector <Int16>(unchecked ((Int16)value))))); };
                this.IncreasedByValue          = (value) => { return(Vector.AsVectorByte(Vector.Equals(Vector.AsVectorInt16(this.CurrentValues), Vector.Add(Vector.AsVectorInt16(this.PreviousValues), new Vector <Int16>(unchecked ((Int16)value)))))); };
                this.DecreasedByValue          = (value) => { return(Vector.AsVectorByte(Vector.Equals(Vector.AsVectorInt16(this.CurrentValues), Vector.Subtract(Vector.AsVectorInt16(this.PreviousValues), new Vector <Int16>(unchecked ((Int16)value)))))); };
                break;

            case DataType type when type == DataTypes.Int32:
                this.Changed                   = () => { return(Vector.AsVectorByte(Vector.Equals(Vector.AsVectorInt32(this.CurrentValues), Vector.AsVectorInt32(this.PreviousValues)))); };
                this.Unchanged                 = () => { return(Vector.OnesComplement(Vector.AsVectorByte(Vector.Equals(Vector.AsVectorInt32(this.CurrentValues), Vector.AsVectorInt32(this.PreviousValues))))); };
                this.Increased                 = () => { return(Vector.AsVectorByte(Vector.GreaterThan(Vector.AsVectorInt32(this.CurrentValues), Vector.AsVectorInt32(this.PreviousValues)))); };
                this.Decreased                 = () => { return(Vector.AsVectorByte(Vector.LessThan(Vector.AsVectorInt32(this.CurrentValues), Vector.AsVectorInt32(this.PreviousValues)))); };
                this.EqualToValue              = (value) => { return(Vector.AsVectorByte(Vector.Equals(Vector.AsVectorInt32(this.CurrentValues), new Vector <Int32>(unchecked ((Int32)value))))); };
                this.NotEqualToValue           = (value) => { return(Vector.OnesComplement(Vector.AsVectorByte(Vector.Equals(Vector.AsVectorInt32(this.CurrentValues), new Vector <Int32>(unchecked ((Int32)value)))))); };
                this.GreaterThanValue          = (value) => { return(Vector.AsVectorByte(Vector.GreaterThan(Vector.AsVectorInt32(this.CurrentValues), new Vector <Int32>(unchecked ((Int32)value))))); };
                this.GreaterThanOrEqualToValue = (value) => { return(Vector.AsVectorByte(Vector.GreaterThanOrEqual(Vector.AsVectorInt32(this.CurrentValues), new Vector <Int32>(unchecked ((Int32)value))))); };
                this.LessThanValue             = (value) => { return(Vector.AsVectorByte(Vector.LessThan(Vector.AsVectorInt32(this.CurrentValues), new Vector <Int32>(unchecked ((Int32)value))))); };
                this.LessThanOrEqualToValue    = (value) => { return(Vector.AsVectorByte(Vector.LessThanOrEqual(Vector.AsVectorInt32(this.CurrentValues), new Vector <Int32>(unchecked ((Int32)value))))); };
                this.IncreasedByValue          = (value) => { return(Vector.AsVectorByte(Vector.Equals(Vector.AsVectorInt32(this.CurrentValues), Vector.Add(Vector.AsVectorInt32(this.PreviousValues), new Vector <Int32>(unchecked ((Int32)value)))))); };
                this.DecreasedByValue          = (value) => { return(Vector.AsVectorByte(Vector.Equals(Vector.AsVectorInt32(this.CurrentValues), Vector.Subtract(Vector.AsVectorInt32(this.PreviousValues), new Vector <Int32>(unchecked ((Int32)value)))))); };
                break;

            case DataType type when type == DataTypes.Int64:
                this.Changed                   = () => { return(Vector.AsVectorByte(Vector.Equals(Vector.AsVectorInt64(this.CurrentValues), Vector.AsVectorInt64(this.PreviousValues)))); };
                this.Unchanged                 = () => { return(Vector.OnesComplement(Vector.AsVectorByte(Vector.Equals(Vector.AsVectorInt64(this.CurrentValues), Vector.AsVectorInt64(this.PreviousValues))))); };
                this.Increased                 = () => { return(Vector.AsVectorByte(Vector.GreaterThan(Vector.AsVectorInt64(this.CurrentValues), Vector.AsVectorInt64(this.PreviousValues)))); };
                this.Decreased                 = () => { return(Vector.AsVectorByte(Vector.LessThan(Vector.AsVectorInt64(this.CurrentValues), Vector.AsVectorInt64(this.PreviousValues)))); };
                this.EqualToValue              = (value) => { return(Vector.AsVectorByte(Vector.Equals(Vector.AsVectorInt64(this.CurrentValues), new Vector <Int64>(unchecked ((Int64)value))))); };
                this.NotEqualToValue           = (value) => { return(Vector.OnesComplement(Vector.AsVectorByte(Vector.Equals(Vector.AsVectorInt64(this.CurrentValues), new Vector <Int64>(unchecked ((Int64)value)))))); };
                this.GreaterThanValue          = (value) => { return(Vector.AsVectorByte(Vector.GreaterThan(Vector.AsVectorInt64(this.CurrentValues), new Vector <Int64>(unchecked ((Int64)value))))); };
                this.GreaterThanOrEqualToValue = (value) => { return(Vector.AsVectorByte(Vector.GreaterThanOrEqual(Vector.AsVectorInt64(this.CurrentValues), new Vector <Int64>(unchecked ((Int64)value))))); };
                this.LessThanValue             = (value) => { return(Vector.AsVectorByte(Vector.LessThan(Vector.AsVectorInt64(this.CurrentValues), new Vector <Int64>(unchecked ((Int64)value))))); };
                this.LessThanOrEqualToValue    = (value) => { return(Vector.AsVectorByte(Vector.LessThanOrEqual(Vector.AsVectorInt64(this.CurrentValues), new Vector <Int64>(unchecked ((Int64)value))))); };
                this.IncreasedByValue          = (value) => { return(Vector.AsVectorByte(Vector.Equals(Vector.AsVectorInt64(this.CurrentValues), Vector.Add(Vector.AsVectorInt64(this.PreviousValues), new Vector <Int64>(unchecked ((Int64)value)))))); };
                this.DecreasedByValue          = (value) => { return(Vector.AsVectorByte(Vector.Equals(Vector.AsVectorInt64(this.CurrentValues), Vector.Subtract(Vector.AsVectorInt64(this.PreviousValues), new Vector <Int64>(unchecked ((Int64)value)))))); };
                break;

            case DataType type when type == DataTypes.UInt16:
                this.Changed                   = () => { return(Vector.AsVectorByte(Vector.Equals(Vector.AsVectorUInt16(this.CurrentValues), Vector.AsVectorUInt16(this.PreviousValues)))); };
                this.Unchanged                 = () => { return(Vector.OnesComplement(Vector.AsVectorByte(Vector.Equals(Vector.AsVectorUInt16(this.CurrentValues), Vector.AsVectorUInt16(this.PreviousValues))))); };
                this.Increased                 = () => { return(Vector.AsVectorByte(Vector.GreaterThan(Vector.AsVectorUInt16(this.CurrentValues), Vector.AsVectorUInt16(this.PreviousValues)))); };
                this.Decreased                 = () => { return(Vector.AsVectorByte(Vector.LessThan(Vector.AsVectorUInt16(this.CurrentValues), Vector.AsVectorUInt16(this.PreviousValues)))); };
                this.EqualToValue              = (value) => { return(Vector.AsVectorByte(Vector.Equals(Vector.AsVectorUInt16(this.CurrentValues), new Vector <UInt16>(unchecked ((UInt16)value))))); };
                this.NotEqualToValue           = (value) => { return(Vector.OnesComplement(Vector.AsVectorByte(Vector.Equals(Vector.AsVectorUInt16(this.CurrentValues), new Vector <UInt16>(unchecked ((UInt16)value)))))); };
                this.GreaterThanValue          = (value) => { return(Vector.AsVectorByte(Vector.GreaterThan(Vector.AsVectorUInt16(this.CurrentValues), new Vector <UInt16>(unchecked ((UInt16)value))))); };
                this.GreaterThanOrEqualToValue = (value) => { return(Vector.AsVectorByte(Vector.GreaterThanOrEqual(Vector.AsVectorUInt16(this.CurrentValues), new Vector <UInt16>(unchecked ((UInt16)value))))); };
                this.LessThanValue             = (value) => { return(Vector.AsVectorByte(Vector.LessThan(Vector.AsVectorUInt16(this.CurrentValues), new Vector <UInt16>(unchecked ((UInt16)value))))); };
                this.LessThanOrEqualToValue    = (value) => { return(Vector.AsVectorByte(Vector.LessThanOrEqual(Vector.AsVectorUInt16(this.CurrentValues), new Vector <UInt16>(unchecked ((UInt16)value))))); };
                this.IncreasedByValue          = (value) => { return(Vector.AsVectorByte(Vector.Equals(Vector.AsVectorUInt16(this.CurrentValues), Vector.Add(Vector.AsVectorUInt16(this.PreviousValues), new Vector <UInt16>(unchecked ((UInt16)value)))))); };
                this.DecreasedByValue          = (value) => { return(Vector.AsVectorByte(Vector.Equals(Vector.AsVectorUInt16(this.CurrentValues), Vector.Subtract(Vector.AsVectorUInt16(this.PreviousValues), new Vector <UInt16>(unchecked ((UInt16)value)))))); };
                break;

            case DataType type when type == DataTypes.UInt32:
                this.Changed                   = () => { return(Vector.AsVectorByte(Vector.Equals(Vector.AsVectorUInt32(this.CurrentValues), Vector.AsVectorUInt32(this.PreviousValues)))); };
                this.Unchanged                 = () => { return(Vector.OnesComplement(Vector.AsVectorByte(Vector.Equals(Vector.AsVectorUInt32(this.CurrentValues), Vector.AsVectorUInt32(this.PreviousValues))))); };
                this.Increased                 = () => { return(Vector.AsVectorByte(Vector.GreaterThan(Vector.AsVectorUInt32(this.CurrentValues), Vector.AsVectorUInt32(this.PreviousValues)))); };
                this.Decreased                 = () => { return(Vector.AsVectorByte(Vector.LessThan(Vector.AsVectorUInt32(this.CurrentValues), Vector.AsVectorUInt32(this.PreviousValues)))); };
                this.EqualToValue              = (value) => { return(Vector.AsVectorByte(Vector.Equals(Vector.AsVectorUInt32(this.CurrentValues), new Vector <UInt32>(unchecked ((UInt32)value))))); };
                this.NotEqualToValue           = (value) => { return(Vector.OnesComplement(Vector.AsVectorByte(Vector.Equals(Vector.AsVectorUInt32(this.CurrentValues), new Vector <UInt32>(unchecked ((UInt32)value)))))); };
                this.GreaterThanValue          = (value) => { return(Vector.AsVectorByte(Vector.GreaterThan(Vector.AsVectorUInt32(this.CurrentValues), new Vector <UInt32>(unchecked ((UInt32)value))))); };
                this.GreaterThanOrEqualToValue = (value) => { return(Vector.AsVectorByte(Vector.GreaterThanOrEqual(Vector.AsVectorUInt32(this.CurrentValues), new Vector <UInt32>(unchecked ((UInt32)value))))); };
                this.LessThanValue             = (value) => { return(Vector.AsVectorByte(Vector.LessThan(Vector.AsVectorUInt32(this.CurrentValues), new Vector <UInt32>(unchecked ((UInt32)value))))); };
                this.LessThanOrEqualToValue    = (value) => { return(Vector.AsVectorByte(Vector.LessThanOrEqual(Vector.AsVectorUInt32(this.CurrentValues), new Vector <UInt32>(unchecked ((UInt32)value))))); };
                this.IncreasedByValue          = (value) => { return(Vector.AsVectorByte(Vector.Equals(Vector.AsVectorUInt32(this.CurrentValues), Vector.Add(Vector.AsVectorUInt32(this.PreviousValues), new Vector <UInt32>(unchecked ((UInt32)value)))))); };
                this.DecreasedByValue          = (value) => { return(Vector.AsVectorByte(Vector.Equals(Vector.AsVectorUInt32(this.CurrentValues), Vector.Subtract(Vector.AsVectorUInt32(this.PreviousValues), new Vector <UInt32>(unchecked ((UInt32)value)))))); };
                break;

            case DataType type when type == DataTypes.UInt64:
                this.Changed                   = () => { return(Vector.AsVectorByte(Vector.Equals(Vector.AsVectorUInt64(this.CurrentValues), Vector.AsVectorUInt64(this.PreviousValues)))); };
                this.Unchanged                 = () => { return(Vector.OnesComplement(Vector.AsVectorByte(Vector.Equals(Vector.AsVectorUInt64(this.CurrentValues), Vector.AsVectorUInt64(this.PreviousValues))))); };
                this.Increased                 = () => { return(Vector.AsVectorByte(Vector.GreaterThan(Vector.AsVectorUInt64(this.CurrentValues), Vector.AsVectorUInt64(this.PreviousValues)))); };
                this.Decreased                 = () => { return(Vector.AsVectorByte(Vector.LessThan(Vector.AsVectorUInt64(this.CurrentValues), Vector.AsVectorUInt64(this.PreviousValues)))); };
                this.EqualToValue              = (value) => { return(Vector.AsVectorByte(Vector.Equals(Vector.AsVectorUInt64(this.CurrentValues), new Vector <UInt64>(unchecked ((UInt64)value))))); };
                this.NotEqualToValue           = (value) => { return(Vector.OnesComplement(Vector.AsVectorByte(Vector.Equals(Vector.AsVectorUInt64(this.CurrentValues), new Vector <UInt64>(unchecked ((UInt64)value)))))); };
                this.GreaterThanValue          = (value) => { return(Vector.AsVectorByte(Vector.GreaterThan(Vector.AsVectorUInt64(this.CurrentValues), new Vector <UInt64>(unchecked ((UInt64)value))))); };
                this.GreaterThanOrEqualToValue = (value) => { return(Vector.AsVectorByte(Vector.GreaterThanOrEqual(Vector.AsVectorUInt64(this.CurrentValues), new Vector <UInt64>(unchecked ((UInt64)value))))); };
                this.LessThanValue             = (value) => { return(Vector.AsVectorByte(Vector.LessThan(Vector.AsVectorUInt64(this.CurrentValues), new Vector <UInt64>(unchecked ((UInt64)value))))); };
                this.LessThanOrEqualToValue    = (value) => { return(Vector.AsVectorByte(Vector.LessThanOrEqual(Vector.AsVectorUInt64(this.CurrentValues), new Vector <UInt64>(unchecked ((UInt64)value))))); };
                this.IncreasedByValue          = (value) => { return(Vector.AsVectorByte(Vector.Equals(Vector.AsVectorUInt64(this.CurrentValues), Vector.Add(Vector.AsVectorUInt64(this.PreviousValues), new Vector <UInt64>(unchecked ((UInt64)value)))))); };
                this.DecreasedByValue          = (value) => { return(Vector.AsVectorByte(Vector.Equals(Vector.AsVectorUInt64(this.CurrentValues), Vector.Subtract(Vector.AsVectorUInt64(this.PreviousValues), new Vector <UInt64>(unchecked ((UInt64)value)))))); };
                break;

            case DataType type when type == DataTypes.Single:
                this.Changed                   = () => { return(Vector.AsVectorByte(Vector.Equals(Vector.AsVectorSingle(this.CurrentValues), Vector.AsVectorSingle(this.PreviousValues)))); };
                this.Unchanged                 = () => { return(Vector.OnesComplement(Vector.AsVectorByte(Vector.Equals(Vector.AsVectorSingle(this.CurrentValues), Vector.AsVectorSingle(this.PreviousValues))))); };
                this.Increased                 = () => { return(Vector.AsVectorByte(Vector.GreaterThan(Vector.AsVectorSingle(this.CurrentValues), Vector.AsVectorSingle(this.PreviousValues)))); };
                this.Decreased                 = () => { return(Vector.AsVectorByte(Vector.LessThan(Vector.AsVectorSingle(this.CurrentValues), Vector.AsVectorSingle(this.PreviousValues)))); };
                this.EqualToValue              = (value) => { return(Vector.AsVectorByte(Vector.Equals(Vector.AsVectorSingle(this.CurrentValues), new Vector <Single>(unchecked ((Single)value))))); };
                this.NotEqualToValue           = (value) => { return(Vector.OnesComplement(Vector.AsVectorByte(Vector.Equals(Vector.AsVectorSingle(this.CurrentValues), new Vector <Single>(unchecked ((Single)value)))))); };
                this.GreaterThanValue          = (value) => { return(Vector.AsVectorByte(Vector.GreaterThan(Vector.AsVectorSingle(this.CurrentValues), new Vector <Single>(unchecked ((Single)value))))); };
                this.GreaterThanOrEqualToValue = (value) => { return(Vector.AsVectorByte(Vector.GreaterThanOrEqual(Vector.AsVectorSingle(this.CurrentValues), new Vector <Single>(unchecked ((Single)value))))); };
                this.LessThanValue             = (value) => { return(Vector.AsVectorByte(Vector.LessThan(Vector.AsVectorSingle(this.CurrentValues), new Vector <Single>(unchecked ((Single)value))))); };
                this.LessThanOrEqualToValue    = (value) => { return(Vector.AsVectorByte(Vector.LessThanOrEqual(Vector.AsVectorSingle(this.CurrentValues), new Vector <Single>(unchecked ((Single)value))))); };
                this.IncreasedByValue          = (value) => { return(Vector.AsVectorByte(Vector.Equals(Vector.AsVectorSingle(this.CurrentValues), Vector.Add(Vector.AsVectorSingle(this.PreviousValues), new Vector <Single>(unchecked ((Single)value)))))); };
                this.DecreasedByValue          = (value) => { return(Vector.AsVectorByte(Vector.Equals(Vector.AsVectorSingle(this.CurrentValues), Vector.Subtract(Vector.AsVectorSingle(this.PreviousValues), new Vector <Single>(unchecked ((Single)value)))))); };
                break;

            case DataType type when type == DataTypes.Double:
                this.Changed                   = () => { return(Vector.AsVectorByte(Vector.Equals(Vector.AsVectorDouble(this.CurrentValues), Vector.AsVectorDouble(this.PreviousValues)))); };
                this.Unchanged                 = () => { return(Vector.OnesComplement(Vector.AsVectorByte(Vector.Equals(Vector.AsVectorDouble(this.CurrentValues), Vector.AsVectorDouble(this.PreviousValues))))); };
                this.Increased                 = () => { return(Vector.AsVectorByte(Vector.GreaterThan(Vector.AsVectorDouble(this.CurrentValues), Vector.AsVectorDouble(this.PreviousValues)))); };
                this.Decreased                 = () => { return(Vector.AsVectorByte(Vector.LessThan(Vector.AsVectorDouble(this.CurrentValues), Vector.AsVectorDouble(this.PreviousValues)))); };
                this.EqualToValue              = (value) => { return(Vector.AsVectorByte(Vector.Equals(Vector.AsVectorDouble(this.CurrentValues), new Vector <Double>(unchecked ((Double)value))))); };
                this.NotEqualToValue           = (value) => { return(Vector.OnesComplement(Vector.AsVectorByte(Vector.Equals(Vector.AsVectorDouble(this.CurrentValues), new Vector <Double>(unchecked ((Double)value)))))); };
                this.GreaterThanValue          = (value) => { return(Vector.AsVectorByte(Vector.GreaterThan(Vector.AsVectorDouble(this.CurrentValues), new Vector <Double>(unchecked ((Double)value))))); };
                this.GreaterThanOrEqualToValue = (value) => { return(Vector.AsVectorByte(Vector.GreaterThanOrEqual(Vector.AsVectorDouble(this.CurrentValues), new Vector <Double>(unchecked ((Double)value))))); };
                this.LessThanValue             = (value) => { return(Vector.AsVectorByte(Vector.LessThan(Vector.AsVectorDouble(this.CurrentValues), new Vector <Double>(unchecked ((Double)value))))); };
                this.LessThanOrEqualToValue    = (value) => { return(Vector.AsVectorByte(Vector.LessThanOrEqual(Vector.AsVectorDouble(this.CurrentValues), new Vector <Double>(unchecked ((Double)value))))); };
                this.IncreasedByValue          = (value) => { return(Vector.AsVectorByte(Vector.Equals(Vector.AsVectorDouble(this.CurrentValues), Vector.Add(Vector.AsVectorDouble(this.PreviousValues), new Vector <Double>(unchecked ((Double)value)))))); };
                this.DecreasedByValue          = (value) => { return(Vector.AsVectorByte(Vector.Equals(Vector.AsVectorDouble(this.CurrentValues), Vector.Subtract(Vector.AsVectorDouble(this.PreviousValues), new Vector <Double>(unchecked ((Double)value)))))); };
                break;

            default:
                throw new ArgumentException();
            }
        }
Exemplo n.º 45
0
 public static IEnumerable Shuffle(IEnumerable seq)
 {
     var v = AsVector(seq);
     var v2 = new Vector();
     for (var i = v.Count; i > 0; --i)
     {
         var j = Random(i);
         v2.Add(v[j]);
         v.RemoveAt(j);
     }
     return AsList(v2);
 }
Exemplo n.º 46
0
        public void Test04()
        {
            IVector   iv = new Vector(1, 2, 3);
            Vector    vv = new Vector(1, 2, 3);
            RowVector rv = new RowVector(1, 2, 3);

            // IVector, Vector, RowVector 27パターン

            // IVector <-
            // iv = iv + iv;
            iv = Vector.Add(iv, iv);

            iv = vv + vv;
            iv = rv + rv;

            iv = vv + rv;
            iv = rv + vv;

            iv  = iv + vv;
            iv  = vv + iv;
            iv += vv;

            iv  = iv + rv;
            iv  = rv + iv;
            iv += rv;


            // Vector <-
            //vv = iv + iv;   // 不可(メソッドにしないとできない)
            vv = Vector.Add(iv, iv);

            vv  = vv + vv;
            vv += vv;

            vv = rv + rv;

            vv  = rv + vv;
            vv  = vv + rv;
            vv += rv;

            vv  = iv + vv;
            vv  = vv + iv;
            vv += iv;

            // RowVector <-
            //rv = iv + iv;   // 不可(メソッドにしないとできない)
            rv = RowVector.Add(iv, iv);

            //rv = vv + vv;   // 不可(メソッドにしないとできない)
            rv  = RowVector.Add(vv, vv);
            rv  = rv + rv;
            rv += rv;

            rv  = rv + vv;
            rv  = vv + rv;
            rv += vv;

            //rv = iv + vv;   // 不可(メソッドにしないとできない)
            //rv = vv + iv;   // 不可(メソッドにしないとできない)

            rv  = iv + rv;
            rv  = rv + iv;
            rv += iv;
        }
Exemplo n.º 47
0
            public static void SplitWith(IApply predicate, IEnumerable seq, out Cons left, out Cons right)
            {
                left = null;
                right = null;

                if (seq != null)
                {
                    var iter = seq.GetEnumerator();
                    var v = new Vector();

                    while (iter.MoveNext())
                    {
                        if (FuncallBool(predicate, iter.Current))
                        {
                            v.Add(iter.Current);
                        }
                        else {
                            left = AsList(v);
                            right = MakeCons(iter.Current, iter);
                            return;
                        }
                    }

                    left = AsList(v);
                }
            }
Exemplo n.º 48
0
        /// <summary>
        /// 固定宽巷模糊度(fix wide-lane ambiguity),以周为单位,波长是86cm
        /// 通过原始观测值构建宽巷观测值,取整固定
        /// </summary>
        /// <param name="rovReceiverInfo"></param>
        /// <param name="refReceiverInfo"></param>
        /// <param name="fixedIntWideLineAmbiCycles"></param>
        /// <returns></returns>
        private bool tryFixWideLaneAmbguity(EpochInformation rovReceiverInfo, EpochInformation refReceiverInfo, out Vector fixedIntWideLineAmbiCycles)
        {
            Vector Vector = new Vector();

            fixedIntWideLineAmbiCycles = new Vector();
            List <string> paraNames = new List <string>();

            foreach (var prn in rovReceiverInfo.EnabledPrns)
            {
                if (prn == CurrentBasePrn)
                {
                    continue;
                }
                string paramName = prn.ToString() + "-" + CurrentBasePrn + Gnsser.ParamNames.PhaseLengthSuffix;
                if (!DoubleDifferWideLaneAmbiCyclesDic.ContainsKey(paramName))
                {
                    DoubleDifferWideLaneAmbiCyclesDic.Add(paramName, new DDWideLineAmbiCycles());
                }

                EpochSatellite rovRoveSatInfo = rovReceiverInfo[prn];
                EpochSatellite rovBaseSatInfo = rovReceiverInfo[CurrentBasePrn];
                EpochSatellite refRoveSatInfo = refReceiverInfo[prn];
                EpochSatellite refBaseSatInfo = refReceiverInfo[CurrentBasePrn];

                //新弧段的判断,若有周跳、断裂等发生,重新计算新弧段MW平均值
                if (rovRoveSatInfo.IsUnstable == true || rovBaseSatInfo.IsUnstable == true ||
                    refRoveSatInfo.IsUnstable == true || refBaseSatInfo.IsUnstable == true ||
                    Math.Abs(DoubleDifferWideLaneAmbiCyclesDic[paramName].lastEpoch - rovRoveSatInfo.RecevingTime) > MinArcGap)
                {
                    DoubleDifferWideLaneAmbiCyclesDic[paramName] = new DDWideLineAmbiCycles();//是清零,而后再继续
                }

                if (rovRoveSatInfo.Polar.Elevation < 30 || rovBaseSatInfo.Polar.Elevation < 30 ||
                    refRoveSatInfo.Polar.Elevation < 30 || refBaseSatInfo.Polar.Elevation < 30
                    )         //|| Math.Abs(DoubleDifferWideLaneAmbiCyclesDic[paramName].lastEpoch - rovRoveSatInfo.RecevingTime) > MinArcGap
                {
                    continue; //是继续,而不是清零!
                }

                //double SatCurrentMwValue = SatCurrentInfo.Combinations.MwPhaseCombinationValue; //以周为单位,波长是86cm
                //var freqA = SatCurrentInfo.FrequenceA.Frequence;
                //var freqB = SatCurrentInfo.FrequenceB.Frequence;

                //double f1 = SatCurrentInfo.FrequenceA.Frequence.Value;
                //double f2 = SatCurrentInfo.FrequenceB.Frequence.Value;
                //double L1 = SatCurrentInfo.FrequenceA.PhaseRange.Value;
                //double L2 = SatCurrentInfo.FrequenceB.PhaseRange.Value;
                //double P1 = SatCurrentInfo.FrequenceA.PseudoRange.Value;
                //double P2 = SatCurrentInfo.FrequenceB.PseudoRange.Value;

                //double L11 = SatCurrentInfo.FrequenceA.PhaseRange.CorrectedValue + SatCurrentInfo.ApproxPhaseRangeA.Correction;
                //double L22 = SatCurrentInfo.FrequenceB.PhaseRange.CorrectedValue + SatCurrentInfo.ApproxPhaseRangeB.Correction;
                //double P11 = SatCurrentInfo.FrequenceA.PseudoRange.CorrectedValue + SatCurrentInfo.ApproxPseudoRangeA.Correction;
                //double P22 = SatCurrentInfo.FrequenceB.PseudoRange.CorrectedValue + SatCurrentInfo.ApproxPseudoRangeB.Correction;

                ////double L111=SatCurrentInfo.FrequenceA

                //double e = f1 / (f1 - f2);
                //double f = f2 / (f1 - f2);
                //double c = f1 / (f1 + f2);
                //double d = f2 / (f1 + f2);

                //double SatCurrentMwValue2 = SatCurrentInfo.Combinations.MwRangeCombination.Value / SatCurrentInfo.Combinations.MwRangeCombination.Frequence.WaveLength; //以周为单位,波长是86cm
                //double value = e * L1 - f * L2 - c * P1 - d * P2; //米为单位啊

                //double value1 = e * L11 - f * L22 - c * P11 - d * P22;//米为单位啊

                //double SatCurrentMwValue222 = value / SatCurrentInfo.Combinations.MwRangeCombination.Frequence.WaveLength;
                double SatCurrentMwValue = (rovRoveSatInfo.MwCycle - refRoveSatInfo.MwCycle) - (rovBaseSatInfo.MwCycle - refBaseSatInfo.MwCycle);
                DoubleDifferWideLaneAmbiCyclesDic[paramName].MwDic.Add(rovRoveSatInfo.ReceiverTime, SatCurrentMwValue);
                DoubleDifferWideLaneAmbiCyclesDic[paramName].lastEpoch = rovRoveSatInfo.ReceiverTime;
                //
                //根据Ge的论文,为避免估计偏差,AR不采纳观测时间小于20分钟的,同时中误差大于0.2周的也不用
                if (DoubleDifferWideLaneAmbiCyclesDic[paramName].MwDic.Count <= 40)
                {
                    continue;
                }
                //根据Ge的论文,为避免估计偏差,AR不采纳观测时间小于20分钟的,同时中误差大于0.2周的也不用
                if (DoubleDifferWideLaneAmbiCyclesDic[paramName].MwDic.Count > 260)
                {
                    //
                }

                #region 剔除大于3倍中误差的观测数据
                DataInfo DDMwAverage = cleanMwData(DoubleDifferWideLaneAmbiCyclesDic[paramName]);
                #endregion

                double floatWL, vW;
                //variance of wide-lane ambiguity
                vW = DDMwAverage.obsDataAverageVariance; // /(lam_WL * lam_WL));

                double dW = DDMwAverage.obsDataVariance; // /(lam_WL * lam_WL));


                // MW值是取观测值均值,其方差即是观测值均值的方差,不是观测值的方差,所以下面要还原为观测值的方差,剔除超出观测值三倍方差以为的数据
                if (Math.Sqrt(DDMwAverage.obsDataAverageVariance) > 0.4 || //|| Math.Sqrt(rovRoveMwAverage.obsDataVariance) > 0.1
                    DDMwAverage.obsDataCount < 40)//|| Math.Sqrt(vW) > 0.2|| Math.Sqrt(dW) > 0.2)//)
                {
                    continue;
                }

                //wide-lane ambiguity(以周为单位)
                floatWL = (DDMwAverage.obsDataAverage);// / lam_WL;// +wlbias[sat1.PRN - 1] - wlbias[sat2.PRN - 1];

                //就近取整,最接近BW的整数
                int intWL = (int)Math.Floor(floatWL + 0.5);

                double intWL0 = Math.Round(floatWL);
                if (intWL0 != intWL)
                {
                    throw new Exception("宽巷模糊度固定是取最接近实数的整数!此时没有取成功!");
                }

                //validation of integer wide-lane ambiguity
                // if (Math.Abs(NW - BW) <= thresar2 && conffunc(NW, BW, Math.Sqrt(vW)) >= thresar1)
                if (conffunc(intWL, floatWL, Math.Sqrt(vW)) > thresar1 && Math.Abs(intWL - floatWL) < 0.25)  //实数宽巷模糊度与其最近整数之差小于0.25周,剔除明显粗差影响
                {
                    Vector.Add(intWL, paramName);
                    paraNames.Add(paramName);
                }
            }

            fixedIntWideLineAmbiCycles            = Vector;
            fixedIntWideLineAmbiCycles.ParamNames = paraNames;
            if (fixedIntWideLineAmbiCycles.Count > 0)
            {
                return(true);
            }
            return(false);
        }
Exemplo n.º 49
0
 Cons ISyntax.GetSyntax(Symbol context)
 {
     var v = new Vector();
     foreach (var m in Members)
     {
         v.Add(Runtime.GetMethodSyntax(m, context));
     }
     return Runtime.AsList(Runtime.SeqBase.Distinct(v, Runtime.StructurallyEqualApply));
 }
Exemplo n.º 50
0
        private void SimulateRobotMovement()
        {
            var robotVelocity     = Robot.Settings.Velocity;
            var robotAcceleration = Robot.Settings.Acceleration;
            var trajectory        = Robot.Controller.Trajectory;

            var currentVector           = new Vector();
            var resultingVelocityVector = new Vector();
            var positionInCurrentVector = new Point(0, 0);

            bool positionIsInCurrentVector = false;

            double xDriveVelocity = 0;
            double yDriveVelocity = 0;

            double xDriveAcceleration = 0;
            double yDriveAcceleration = 0;

            for (LinkedListNode <Vector> node = trajectory.First; node != null;)
            {
                currentVector = node.Value;

                positionInCurrentVector   = new Point(0, 0);
                positionIsInCurrentVector = (currentVector.Length - ((Vector)positionInCurrentVector).Length) > 0;

                var arctangRadians = Math.Atan2(currentVector.Y, currentVector.X);

                var x = Math.Cos(arctangRadians);
                var y = Math.Sin(arctangRadians);

                xDriveVelocity = (robotVelocity * x) / RefreshFactor;
                yDriveVelocity = (robotVelocity * y) / RefreshFactor;

                xDriveAcceleration = (robotAcceleration * x) / RefreshFactor;
                yDriveAcceleration = (robotAcceleration * y) / RefreshFactor;

                // Stop each drive before changing vector
                DriveX.Velocity = 0;
                DriveY.Velocity = 0;

                while (positionIsInCurrentVector)
                {
                    engineTaskControllingEvent.WaitOne();
                    if (cancellationTokenSource.Token.IsCancellationRequested)
                    {
                        ResetRobotDrives();
                        return;
                    }

                    //Create separate thread for each drive + resources synchronization
                    resultingVelocityVector = UpdateRobotDrives(xDriveVelocity, yDriveVelocity, xDriveAcceleration, yDriveAcceleration);
                    positionInCurrentVector = Vector.Add(resultingVelocityVector, positionInCurrentVector);

                    positionIsInCurrentVector = (currentVector.Length - ((Vector)positionInCurrentVector).Length) > 0;
                    if (!positionIsInCurrentVector)
                    {
                        continue;
                    }

                    var newPosition = Vector.Add(resultingVelocityVector, Robot.CurrentPosition);
                    UpdateRobotCurrentPosition(newPosition);

                    Thread.Sleep(Tick);
                }

                node = node.Next;
            }

            Accelerating = false;
            while (resultingVelocityVector.Length != 0)
            {
                engineTaskControllingEvent.WaitOne();
                if (cancellationTokenSource.Token.IsCancellationRequested)
                {
                    ResetRobotDrives();
                    return;
                }

                resultingVelocityVector = UpdateRobotDrives(xDriveVelocity, yDriveVelocity, xDriveAcceleration, yDriveAcceleration);

                var newPosition = Vector.Add(resultingVelocityVector, Robot.CurrentPosition);
                UpdateRobotCurrentPosition(newPosition);

                Thread.Sleep(Tick);
            }
        }
        /// <summary>
        /// Adds another vector to this vector and stores the result into the result vector.
        /// </summary>
        /// <param name="other">The vector to add to this one.</param>
        /// <param name="result">The vector to store the result of the addition.</param>
        /// <exception cref="ArgumentNullException">If the other vector is <see langword="null" />.</exception> 
        /// <exception cref="ArgumentNullException">If the result vector is <see langword="null" />.</exception> 
        /// <exception cref="ArgumentException">If this vector and <paramref name="other"/> are not the same size.</exception>
        /// <exception cref="ArgumentException">If this vector and <paramref name="result"/> are not the same size.</exception>
        public override void Add(Vector other, Vector result)
        {
            if (result == null)
            {
                throw new ArgumentNullException("result");
            }

            if (this.Count != other.Count)
            {
                throw new ArgumentException(Resources.ArgumentVectorsSameLength, "other");
            }

            if (this.Count != result.Count)
            {
                throw new ArgumentException(Resources.ArgumentVectorsSameLength, "result");
            }

            if (ReferenceEquals(this, result) || ReferenceEquals(other, result))
            {
                var tmp = result.CreateVector(result.Count);
                Add(other, tmp);
                tmp.CopyTo(result);
            }
            else
            {
                this.CopyTo(result);
                result.Add(other);
            }
        }
            /*x(t + 1) = x(t) + rand([0,1]) * (x(BH) - x(t))
             * Siguiente posición = posición actual de la estrella + rand([0,1]) * (posición actual del agujero negro - posicion actual de la estrella)*/
            //Calcula la nueva posición de la estrella luego de haber sido atraida por el agujero negro.
            static Vector CalculateNewPosition(Vector star, Vector black_hole)
            {
                var newPosition = Vector.Add(star, Vector.Scale(Vector.Subtract(black_hole, star), (float)new Random().NextDouble()));

                return(newPosition);
            }
Exemplo n.º 53
0
        private void processData()
        {
            int channel = _currentChannelIndex;
            int startIndex = (_samplesProcessed == 0) ? _samplesProcessed : _lastRPeak;
            int step = 6000;    //efficiency is dependent?

            if (channel < NumberOfChannels)
            {
                if (startIndex + step >= _currentChannelLength)
                {
                    _currentVector = InputData.SignalsFiltered[_currentChannelIndex].Item2.SubVector(startIndex, _currentChannelLength - startIndex);
                    try {
                        switch (Params.Method)
                        {
                            case R_Peaks_Method.PANTOMPKINS:
                                _currentVector = PanTompkins(_currentVector, InputData_basic.Frequency);
                                break;
                            case R_Peaks_Method.HILBERT:
                                _currentVector = Hilbert(_currentVector, InputData_basic.Frequency);
                                break;
                            case R_Peaks_Method.EMD:
                                _currentVector = EMD(_currentVector, InputData_basic.Frequency);
                                break;
                        }
                        _currentVector.Add(startIndex, _currentVector);
                        _totalVector.SetSubVector(_numRPeaks, _currentVector.Count, _currentVector);
                        _numRPeaks = _numRPeaks + _currentVector.Count;
                    }
                    catch(Exception ex)
                    {
                        //no idea what logic put in this- no need any
                        //Console.WriteLine("No detected R peaks in final part of signal");
                    }
                    if (_numRPeaks != 0)
                    {
                        _currentVector = _totalVector.SubVector(0, _numRPeaks);
                        _currentVectorRRInterval = RRinMS(_currentVector, InputData_basic.Frequency);
                    }
                    else
                    {
                        _currentVector = _totalVector.SubVector(0, 1);
                        _currentVectorRRInterval = _totalVector.SubVector(0, 1);
                    }

                    OutputData.RPeaks.Add(new Tuple<string, Vector<double>>(InputData.SignalsFiltered[_currentChannelIndex].Item1, _currentVector));
                    OutputData.RRInterval.Add(new Tuple<string, Vector<double>>(InputData.SignalsFiltered[_currentChannelIndex].Item1, _currentVectorRRInterval));
                    _currentChannelIndex++;
                    if (_currentChannelIndex < NumberOfChannels)
                    {
                        _samplesProcessed = 0;
                        _lastRPeak = 0;
                        _numRPeaks = 0;
                        _currentChannelLength = InputData.SignalsFiltered[_currentChannelIndex].Item2.Count;
                        _currentVector = Vector<Double>.Build.Dense(_currentChannelLength);
                        _totalVector = Vector<Double>.Build.Dense(_currentChannelLength);
                    }

                }
                else
                {
                    _currentVector = InputData.SignalsFiltered[_currentChannelIndex].Item2.SubVector(startIndex, step);
                    try
                    {
                        switch (Params.Method)
                        {
                            case R_Peaks_Method.PANTOMPKINS:
                                _currentVector = PanTompkins(_currentVector, InputData_basic.Frequency);
                                break;
                            case R_Peaks_Method.HILBERT:
                                _currentVector = Hilbert(_currentVector, InputData_basic.Frequency);
                                break;
                            case R_Peaks_Method.EMD:
                                _currentVector = EMD(_currentVector, InputData_basic.Frequency);
                                break;
                        }
                        _currentVector.Add(startIndex, _currentVector);
                        _totalVector.SetSubVector(_numRPeaks, _currentVector.Count, _currentVector);
                        _numRPeaks = _currentVector.Count + _numRPeaks;
                        _lastRPeak = Convert.ToInt32(_currentVector[_currentVector.Count - 1]) + Convert.ToInt32(InputData_basic.Frequency * 0.1);
                    }
                    catch(Exception ex)
                    {
                        _lastRPeak = startIndex + step;
                        //Console.WriteLine("No detected R peaks in this part of signal");
                    }
                    //Vector<double> _currentVectorRRInterval = RRinMS(_currentVector, InputData_basic.Frequency);
                    _samplesProcessed = startIndex + step;

                }
            }
            else
            {
                OutputWorker.Save(OutputData);
                _ended = true;
            }
        }
Exemplo n.º 54
0
 public static HwVector4S operator ++(HwVector4S left) => Vector.Add(left, Vector.SingleConstants.One);
Exemplo n.º 55
0
        /// <summary>
        /// Calculates the <c>true</c> residual of the matrix equation Ax = b according to: residual = b - Ax
        /// </summary>
        /// <param name="matrix">Instance of the <see cref="Matrix"/> A.</param>
        /// <param name="residual">Residual values in <see cref="Vector"/>.</param>
        /// <param name="x">Instance of the <see cref="Vector"/> x.</param>
        /// <param name="b">Instance of the <see cref="Vector"/> b.</param>
        private static void CalculateTrueResidual(Matrix matrix, Vector residual, Vector x, Vector b)
        {
            // -Ax = residual
            matrix.Multiply(x, residual);
            residual.Multiply(-1, residual);

            // residual + b
            residual.Add(b, residual);
        }
Exemplo n.º 56
0
 public static HwVector4S operator +(HwVector4S left, HwVector4S right) => Vector.Add(left, right);
Exemplo n.º 57
0
 public static HwVector4S operator +(float left, HwVector4S right) => Vector.Add(Vector128.Create(left), right);
Exemplo n.º 58
0
 public static HwVector4S operator -(HwVector4S left, float right) => Vector.Add(left, Vector128.Create(right));
Exemplo n.º 59
0
        /// <summary>
        /// Calculates the <c>true</c> residual of the matrix equation Ax = b according to: residual = b - Ax
        /// </summary>
        /// <param name="matrix">Instance of the <see cref="Matrix"/> A.</param>
        /// <param name="residual">Residual values in <see cref="Vector"/>.</param>
        /// <param name="x">Instance of the <see cref="Vector"/> x.</param>
        /// <param name="b">Instance of the <see cref="Vector"/> b.</param>
        private static void CalculateTrueResidual(Matrix matrix, Vector residual, Vector x, Vector b)
        {
            // -Ax = residual
            matrix.Multiply(x, residual);
            
            // Do not use residual = residual.Negate() because it creates another object
            residual.Multiply(-1, residual);

            // residual + b
            residual.Add(b, residual);
        }
Exemplo n.º 60
0
 public Vector128 <float> MathSharp() => Vector.Add(_mathSharp1, _mathSharp2);