Exemplo n.º 1
0
        public void Main()
        {
            // Create a matrix.
            var data = new double[12] {
                1, 5, 9,
                2, 6, 10,
                3, 7, 11,
                4, 8, 12
            };
            var matrix = DoubleMatrix.Dense(4, 3, data, StorageOrder.RowMajor);

            Console.WriteLine("Data matrix:");
            Console.WriteLine(matrix);
            Console.WriteLine();

            // Specify the rows to enumerate.
            var rowIndexes = IndexCollection.FromArray(new int[6] {
                0, 0, 1, 2, 3, 2
            });

            // Get the collection of the specified matrix rows.
            var rows = matrix.AsRowCollection(rowIndexes);

            // Enumerate the specified matrix rows.
            foreach (var row in rows)
            {
                Console.WriteLine("Row {0}: ", row.Index);
                Console.WriteLine(row);
            }
        }
Exemplo n.º 2
0
        public void Main()
        {
            // Create a matrix.
            var data = new Complex[8] {
                new Complex(1, -1), new Complex(5, -5),
                new Complex(2, -2), new Complex(6, -6),
                new Complex(3, -3), new Complex(7, -7),
                new Complex(4, -4), new Complex(8, -8)
            };
            var matrix = ComplexMatrix.Dense(4, 2, data, StorageOrder.RowMajor);

            Console.WriteLine("Data matrix:");
            Console.WriteLine(matrix);
            Console.WriteLine();

            // Specify the rows to enumerate.
            var rowIndexes = IndexCollection.FromArray(new int[6] {
                0, 0, 1, 2, 3, 2
            });

            // Get the collection of the specified matrix rows.
            var rows = matrix.AsRowCollection(rowIndexes);

            // Enumerate the specified matrix rows.
            foreach (var row in rows)
            {
                Console.WriteLine("Row {0}: ", row.Index);
                Console.WriteLine(row);
            }
        }
Exemplo n.º 3
0
        public void ToDoubleMatrixTest()
        {
            // This code example produces the following output:
            //
            //
            // Part identifier: 0
            //      indexes: 1
            //
            // Part identifier: 1
            //      indexes: 0, 5
            //
            // Part identifier: 2
            //      indexes: 2, 4
            //
            // Part identifier: 3
            //      indexes: 3
            //

            var target = new IndexPartition <double>
            {
                partIndetifiers = new List <double>(3)
                {
                    0.0,
                    1.0,
                    2.0,
                    3.0
                },

                parts = new Dictionary <double, IndexCollection>(3)
                {
                    { 0.0, IndexCollection.FromArray(new int[] { 1 }) },
                    { 1.0, IndexCollection.FromArray(new int[] { 0, 5 }) },
                    { 2.0, IndexCollection.FromArray(new int[] { 2, 4 }) },
                    { 3.0, IndexCollection.FromArray(new int[] { 3 }) }
                }
            };

            // Convert the partition to a matrix.
            var actual = (DoubleMatrix)target;

            // Conversion of a partition to a matrix:
            // 1
            // 0
            // 2
            // 3
            // 2
            // 1
            //
            var expected = DoubleMatrix.Dense(6, 1, new double[] {
                1,
                0,
                2,
                3,
                2,
                1
            });

            DoubleMatrixAssert.AreEqual(expected, actual, 1e-2);
        }
Exemplo n.º 4
0
 protected SortIndex00() :
     base(
         expected: new SortIndexResults() {
     SortedData    = DoubleMatrix.Dense(2, 2, new double[4] { 1, 2, 3, 4 }),
     SortedIndexes = IndexCollection.FromArray(new int[4] { 1, 3, 2, 0 })
 },
         data: TestableDoubleMatrix54.Get(),
         sortDirection: SortDirection.Ascending)
 {
 }
Exemplo n.º 5
0
 protected SortIndex02() :
     base(
         expected: new SortIndexResults()
 {
     SortedData    = DoubleMatrix.Dense(2, 3, new double[6] { -2, -1, 0, 0, 1, 2 }),
     SortedIndexes = IndexCollection.FromArray(new int[6] { 4, 5, 1, 3, 2, 0 })
 },
         data: TestableDoubleMatrix55.Get(),
         sortDirection: SortDirection.Ascending)
 {
 }
Exemplo n.º 6
0
 protected SortIndex03() :
     base(
         expected: new SortIndexResults()
 {
     SortedData    = DoubleMatrix.Dense(2, 3, new double[6] { 2, 1, 0, 0, -1, -2 }),
     SortedIndexes = IndexCollection.FromArray(new int[6] { 0, 2, 1, 3, 5, 4 })
 },
         data: TestableDoubleMatrix56.Get(),
         sortDirection: SortDirection.Descending)
 {
 }
Exemplo n.º 7
0
        public void TryGetPartTest()
        {
            // Part identifier: "false"
            //      indexes: 0, 10
            //
            // Part identifier: "true"
            //      indexes: 5, 15
            //
            var falsePart = IndexCollection.FromArray(new int[2] {
                0, 10
            });
            var truePart = IndexCollection.FromArray(new int[2] {
                5, 15
            });

            var target = new IndexPartition <string>
            {
                partIndetifiers = new List <string>(2)
                {
                    "false",
                    "true"
                },

                parts = new Dictionary <string, IndexCollection>(2)
                {
                    { "false", falsePart },
                    { "true", truePart }
                }
            };

            bool partFound;

            partFound = target.TryGetPart("unknown", out IndexCollection part);
            Assert.AreEqual(expected: false, actual: partFound);
            Assert.IsNull(part);

            partFound = target.TryGetPart("false", out part);
            Assert.AreEqual(expected: true, actual: partFound);
            IndexCollectionAssert.AreEqual(expected: falsePart, actual: part);

            partFound = target.TryGetPart("true", out part);
            Assert.AreEqual(expected: true, actual: partFound);
            IndexCollectionAssert.AreEqual(expected: truePart, actual: part);
        }
        public void NextTest()
        {
            // In what follows we are sampling
            // permutations of 5 indexes.
            // Their number is 5! = 120.
            // The quantile of order .9 for
            // the Chi Squared distribution having 120-1
            // degrees of freedom is 139.1495
            // (as from R function qchisq(.9,119))

            int[] indexesArray = new int[] { 2, 4, 10, 8, 3 };
            var   indexes      = IndexCollection.FromArray(indexesArray);

            int numberOfRandomPermutations = 12000;

            double criticalValue = 139.1495;

            Next.Succeed(
                indexes: indexes,
                numberOfRandomPermutations: numberOfRandomPermutations,
                criticalValue: criticalValue);
        }
Exemplo n.º 9
0
        public void IndexerGetTest()
        {
            // Create an array of strings.
            var elements = new string[6] {
                "one",
                "two",
                "one",
                "one",
                "three",
                "three"
            };

            // Partition the array positions by their contents.
            var target = IndexPartition.Create(elements);

            // The partition contains three parts, identified, respectively,
            // by the strings "one", "two", and "three".

            // Expected:
            //
            // Part identifier: one
            //      indexes: 0, 2, 3
            //
            // Part identifier: three
            //      indexes: 4, 5
            //
            // Part identifier: two
            //      indexes: 1

            // partIdentifier is null
            {
                ArgumentExceptionAssert.Throw(
                    () =>
                {
                    var part = target[(string)null];
                },
                    expectedType: typeof(ArgumentNullException),
                    expectedPartialMessage: ArgumentExceptionAssert.NullPartialMessage,
                    expectedParameterName: "partIdentifier");
            }

            // partIdentifier is not a key
            {
                ArgumentExceptionAssert.Throw(
                    () =>
                {
                    var part = target["four"];
                },
                    expectedType: typeof(ArgumentException),
                    expectedPartialMessage: ImplementationServices.GetResourceString(
                        "STR_EXCEPT_PAR_IS_NOT_A_PART_IDENTIFIER"),
                    expectedParameterName: "partIdentifier");
            }

            // Valid partIdentifier
            {
                var actual = target["one"];

                var expected = IndexCollection.FromArray(new int[3] {
                    0, 2, 3
                });

                IndexCollectionAssert.AreEqual(expected, actual);
            }
        }
Exemplo n.º 10
0
        public void CreateFromIndexCollectionTest()
        {
            // elements is null
            {
                bool partitioner(int linearIndex)
                {
                    return(linearIndex < 3);
                }

                ArgumentExceptionAssert.Throw(
                    () =>
                {
                    var partition = IndexPartition.Create(
                        (IndexCollection)null,
                        partitioner);
                },
                    expectedType: typeof(ArgumentNullException),
                    expectedPartialMessage: ArgumentExceptionAssert.NullPartialMessage,
                    expectedParameterName: "elements");
            }

            // partitioner is null
            {
                Func <int, bool> partitioner = null;

                ArgumentExceptionAssert.Throw(
                    () =>
                {
                    var partition = IndexPartition.Create(
                        IndexCollection.Default(3),
                        partitioner);
                },
                    expectedType: typeof(ArgumentNullException),
                    expectedPartialMessage: ArgumentExceptionAssert.NullPartialMessage,
                    expectedParameterName: "partitioner");
            }

            // Valid parameters
            {
                // Create a matrix.
                var data = new double[16] {
                    -3, 3, 3, -1,
                    0, 2, -2, 2,
                    2, 1, -4, -5,
                    -8, 2, 7, -1
                };
                var matrix = DoubleMatrix.Dense(4, 4, data, StorageOrder.RowMajor);

                // Create the collection of linear indexes corresponding
                // to entries on the matrix main diagonal.
                var elements =
                    IndexCollection.Sequence(0, 1 + matrix.NumberOfRows, matrix.Count);

                // Create a partitioner which returns true if
                // the absolute value in a entry having the specified linear
                // index is less than 3, otherwise false.
                bool partitioner(int linearIndex)
                {
                    return(Math.Abs(matrix[linearIndex]) < 3.0);
                }

                // Partition the diagonal linear indexes through the
                // specified partitioner.
                var actual = IndexPartition.Create(elements, partitioner);

                // Two parts are created, one for diagonal
                // entries less than 3 in absolute value, the other for
                // entries not satisfying that condition.

                // Expected:
                //
                // Part identifier: False
                //      indexes: 0, 10
                //
                // Part identifier: True
                //      indexes: 5, 15
                //
                var expected = new IndexPartition <bool>
                {
                    partIndetifiers = new List <bool>(2)
                    {
                        false,
                        true
                    },

                    parts = new Dictionary <bool, IndexCollection>(2)
                    {
                        { false, IndexCollection.FromArray(new int[2] {
                                0, 10
                            }) },
                        { true, IndexCollection.FromArray(new int[2] {
                                5, 15
                            }) }
                    }
                };

                IndexPartitionAssert.AreEqual(expected, actual);
            }
        }
Exemplo n.º 11
0
        public void CreateFromEnumerableTest()
        {
            // elements is null
            {
                ArgumentExceptionAssert.Throw(
                    () =>
                {
                    var partition = IndexPartition.Create((string[])null);
                },
                    expectedType: typeof(ArgumentNullException),
                    expectedPartialMessage: ArgumentExceptionAssert.NullPartialMessage,
                    expectedParameterName: "elements");
            }

            // elements is not null
            {
                // Create an array of strings.
                var elements = new string[6] {
                    "one",
                    "two",
                    "one",
                    "one",
                    "three",
                    "three"
                };

                // Partition the array positions by their contents.
                var actual = IndexPartition.Create(elements);

                // The partition contains three parts, identified, respectively,
                // by the strings "one", "two", and "three".

                // Expected:
                //
                // Part identifier: one
                //      indexes: 0, 2, 3
                //
                // Part identifier: three
                //      indexes: 4, 5
                //
                // Part identifier: two
                //      indexes: 1

                var expected = new IndexPartition <string>
                {
                    partIndetifiers = new List <string>(3)
                    {
                        "one",
                        "three",
                        "two"
                    },

                    parts = new Dictionary <string, IndexCollection>(3)
                    {
                        { "one", IndexCollection.FromArray(new int[] { 0, 2, 3 }) },
                        { "three", IndexCollection.Range(4, 5) },
                        { "two", IndexCollection.FromArray(new int[] { 1 }) }
                    }
                };

                IndexPartitionAssert.AreEqual(expected, actual);
            }
        }
Exemplo n.º 12
0
        public void CreateFromDoubleMatrixTest()
        {
            // elements is null
            {
                ArgumentExceptionAssert.Throw(
                    () =>
                {
                    var partition = IndexPartition.Create((DoubleMatrix)null);
                },
                    expectedType: typeof(ArgumentNullException),
                    expectedPartialMessage: ArgumentExceptionAssert.NullPartialMessage,
                    expectedParameterName: "elements");
            }

            // elements is a vector
            {
                // Create a matrix
                var data = new double[18] {
                    0, 0, 1,
                    0, 0, 1,
                    0, 1, 0,
                    0, 1, 0,
                    1, 0, 0,
                    1, 0, 0
                };
                var matrix = DoubleMatrix.Dense(6, 3, data, StorageOrder.RowMajor);

                // Partition the matrix row indexes by the contents of column 0:
                // a part is created for each distinct value in column 0
                var elements = matrix[":", 0];
                var actual   = IndexPartition.Create(elements);

                // Each part is identified by its corresponding value and contains
                // the indexes of the rows in which the identifier
                // is positioned in column 0

                // Expected:
                //
                // Part identifier: 0
                //      indexes: 0, 1, 2, 3
                //
                // Part identifier: 1
                //      indexes: 4, 5

                IndexPartition <double> expected = new()
                {
                    partIndetifiers = new List <double>(2)
                    {
                        0.0,
                        1.0
                    },

                    parts = new Dictionary <double, IndexCollection>(2)
                    {
                        { 0.0, IndexCollection.Default(3) },
                        { 1.0, IndexCollection.Range(4, 5) }
                    }
                };

                IndexPartitionAssert.AreEqual(expected, actual);
            }

            // elements is a matrix of signs
            {
                // Create a matrix.
                var data = new double[8] {
                    0, 1, -2, -3,
                    0, -1, 2, 3
                };
                var matrix = DoubleMatrix.Dense(2, 4, data, StorageOrder.RowMajor);

                // Check the sign of its entries
                var signs = DoubleMatrix.Dense(matrix.NumberOfRows, matrix.NumberOfColumns);
                for (int i = 0; i < matrix.Count; i++)
                {
                    signs[i] = Math.Sign(matrix[i]);
                }

                // Partition the matrix linear indexes by the sign of each entry
                var actual = IndexPartition.Create(signs);

                // The partition contains three parts, the zero part, identified by 0,
                // the negative part (identified by -1), and the positive one
                // (identified by 1).

                // Expected:
                //
                // Part identifier: -1
                //      indexes: 3, 4, 6
                //
                // Part identifier: 0
                //      indexes: 0, 1
                //
                // Part identifier: 1
                //      indexes: 2, 5, 7
                //

                IndexPartition <double> expected = new()
                {
                    partIndetifiers = new List <double>(3)
                    {
                        -1.0,
                        0.0,
                        1.0
                    },

                    parts = new Dictionary <double, IndexCollection>(3)
                    {
                        { -1.0, IndexCollection.FromArray(new int[] { 3, 4, 6 }) },
                        { 0.0, IndexCollection.Default(1) },
                        { 1.0, IndexCollection.FromArray(new int[] { 2, 5, 7 }) }
                    }
                };

                IndexPartitionAssert.AreEqual(expected, actual);
            }

            // elements is a matrix of data
            {
                // Create a matrix
                var data = new double[6] {
                    1, 3,
                    0, 2,
                    2, 1
                };
                var elements = DoubleMatrix.Dense(3, 2, data, StorageOrder.RowMajor);

                // Partition the matrix linear indexes by the content of
                // matrix entries: a part is created for each distinct matrix value
                var actual = IndexPartition.Create(elements);

                // Each part is identified by its corresponding value and contains
                // the linear indexes of the entries in which the identifier
                // is positioned.

                // This code example produces the following output:
                //
                //
                // Part identifier: 0
                //      indexes: 1
                //
                // Part identifier: 1
                //      indexes: 0, 5
                //
                // Part identifier: 2
                //      indexes: 2, 4
                //
                // Part identifier: 3
                //      indexes: 3
                //

                var expected = new IndexPartition <double>
                {
                    partIndetifiers = new List <double>(3)
                    {
                        0.0,
                        1.0,
                        2.0,
                        3.0
                    },

                    parts = new Dictionary <double, IndexCollection>(3)
                    {
                        { 0.0, IndexCollection.FromArray(new int[] { 1 }) },
                        { 1.0, IndexCollection.FromArray(new int[] { 0, 5 }) },
                        { 2.0, IndexCollection.FromArray(new int[] { 2, 4 }) },
                        { 3.0, IndexCollection.FromArray(new int[] { 3 }) }
                    }
                };

                IndexPartitionAssert.AreEqual(expected, actual);
            }
        }
Exemplo n.º 13
0
        /// <inheritdoc/>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="performances"/> is <b>null</b>.<br/>
        /// -or-<br/>
        /// <paramref name="sample"/> is <b>null</b>.
        /// </exception>
        protected internal override sealed double UpdateLevel(
            DoubleMatrix performances,
            DoubleMatrix sample,
            EliteSampleDefinition eliteSampleDefinition,
            double rarity,
            out DoubleMatrix eliteSample)
        {
            if (performances is null)
            {
                throw new ArgumentNullException(nameof(performances));
            }

            if (sample is null)
            {
                throw new ArgumentNullException(nameof(sample));
            }

            var performanceArray = performances.GetStorage();

            SortHelper.Sort(
                performanceArray,
                SortDirection.Ascending,
                out int[] indexTable);

            if (this.TraceExecution)
            {
                Trace.WriteLine(
                    "Sample points ordered by performance:");
                var sampleInfo = DoubleMatrix.Dense(
                    numberOfRows: sample.NumberOfRows,
                    numberOfColumns: this.StateDimension + 1);
                sampleInfo.SetColumnName(0, "Performance");
                for (int j = 1; j < sampleInfo.NumberOfColumns; j++)
                {
                    sampleInfo.SetColumnName(j, "S" + j);
                }
                sampleInfo[":", 0] = performances;
                sampleInfo[":", IndexCollection.Range(1, this.StateDimension)]
                    = sample[
                          IndexCollection.FromArray(indexTable, false), ":"];
                Trace.WriteLine(sampleInfo);
            }

            int eliteFirstIndex = 0;
            int eliteLastIndex  = 0;
            int sampleSize      = sample.NumberOfRows;

            double level = Double.NaN;

            double thresholdLevel = this.ThresholdLevel;

            // Compute the relevant sample percentile (the level)
            // and achieved performance
            switch (eliteSampleDefinition)
            {
            case EliteSampleDefinition.HigherThanLevel:
                eliteFirstIndex = Convert.ToInt32(
                    Math.Ceiling(sampleSize * (1 - rarity)));
                eliteLastIndex = sampleSize - 1;

                level = performanceArray[eliteFirstIndex];
                if (level > thresholdLevel)
                {
                    level = thresholdLevel;
                }
                break;

            case EliteSampleDefinition.LowerThanLevel:
                eliteFirstIndex = 0;
                eliteLastIndex  = Convert.ToInt32(
                    Math.Ceiling(sampleSize * rarity));

                level = performanceArray[eliteLastIndex];
                if (level < thresholdLevel)
                {
                    level = thresholdLevel;
                }
                break;
            }

            // Update the reference parameter
            var eliteSamplePositions =
                IndexCollection.Range(eliteFirstIndex, eliteLastIndex);

            if (this.TraceExecution)
            {
                Trace.WriteLine(
                    string.Format(
                        CultureInfo.InvariantCulture,
                        "Elite positions: {0} - {1}.",
                        eliteFirstIndex,
                        eliteLastIndex));
            }

            var sortedIndexes =
                IndexCollection.FromArray(indexTable, false);

            eliteSample = sample[sortedIndexes[eliteSamplePositions], ":"];

            return(level);
        }