Esempio n. 1
0
        public void SquareRandomMatrixLUDecomposition()
        {
            for (int d = 1; d <= 256; d += 11)
            {
                SquareMatrix M = CreateSquareRandomMatrix(d);

                // LU decompose the matrix
                //Stopwatch sw = Stopwatch.StartNew();
                LUDecomposition LU = M.LUDecomposition();
                //sw.Stop();
                //Console.WriteLine(sw.ElapsedMilliseconds);

                Assert.IsTrue(LU.Dimension == d);

                // test that the decomposition works
                SquareMatrix P = LU.PMatrix();
                SquareMatrix L = LU.LMatrix();
                SquareMatrix U = LU.UMatrix();
                Assert.IsTrue(TestUtilities.IsNearlyEqual(P * M, L * U));

                // check that the inverse works
                SquareMatrix MI = LU.Inverse();
                Assert.IsTrue(TestUtilities.IsNearlyEqual(M * MI, UnitMatrix.OfDimension(d)));

                // test that a solution works
                ColumnVector t = new ColumnVector(d);
                for (int i = 0; i < d; i++)
                {
                    t[i] = i;
                }
                ColumnVector s = LU.Solve(t);
                Assert.IsTrue(TestUtilities.IsNearlyEqual(M * s, t));
            }
        }
Esempio n. 2
0
        public void SquareRandomMatrixQRDecomposition()
        {
            for (int d = 1; d <= 100; d += 11)
            {
                Console.WriteLine("d={0}", d);

                SquareMatrix M = CreateSquareRandomMatrix(d);

                // QR decompose the matrix.
                SquareQRDecomposition QRD = M.QRDecomposition();

                // The dimension should be right.
                Assert.IsTrue(QRD.Dimension == M.Dimension);

                // Test that the decomposition works.
                SquareMatrix Q = QRD.QMatrix;
                SquareMatrix R = QRD.RMatrix;
                Assert.IsTrue(TestUtilities.IsNearlyEqual(Q * R, M));

                // Check that the inverse works.
                SquareMatrix MI = QRD.Inverse();
                Assert.IsTrue(TestUtilities.IsNearlyEqual(M * MI, UnitMatrix.OfDimension(d)));

                // Test that a solution works.
                ColumnVector t = new ColumnVector(d);
                for (int i = 0; i < d; i++)
                {
                    t[i] = i;
                }
                ColumnVector s = QRD.Solve(t);
                Assert.IsTrue(TestUtilities.IsNearlyEqual(M * s, t));
            }
        }
Esempio n. 3
0
        public void UnitMatrixArithmetic()
        {
            SquareMatrix A = new SquareMatrix(new double[, ] {
                { 1.0, -2.0 },
                { -3.0, 4.0 }
            });
            SquareMatrix AI = A * UnitMatrix.OfDimension(A.Dimension);

            Assert.IsTrue(A == AI);
            SquareMatrix IA = UnitMatrix.OfDimension(A.Dimension) * A;

            Assert.IsTrue(IA == A);

            ColumnVector c  = new ColumnVector(1.0, 2.0, 3.0);
            ColumnVector Ic = UnitMatrix.OfDimension(c.Dimension) * c;

            Assert.IsTrue(Ic == c);

            RowVector r  = new RowVector(0.0, 1.0);
            RowVector rI = r * UnitMatrix.OfDimension(r.Dimension);

            Assert.IsTrue(rI == r);

            Assert.IsTrue(UnitMatrix.OfDimension(A.Dimension) == UnitMatrix.OfDimension(A.Dimension));

            Assert.IsTrue(0.0 * UnitMatrix.OfDimension(3) == UnitMatrix.OfDimension(3) - UnitMatrix.OfDimension(3));

            Assert.IsTrue(1.0 * UnitMatrix.OfDimension(3) == UnitMatrix.OfDimension(3));

            Assert.IsTrue(2.0 * UnitMatrix.OfDimension(3) == UnitMatrix.OfDimension(3) + UnitMatrix.OfDimension(3));
        }
Esempio n. 4
0
        public void SquareUnitMatrixEigensystem()
        {
            int          d = 3;
            SquareMatrix I = UnitMatrix.OfDimension(d).ToSquareMatrix();
            ComplexEigendecomposition E = I.Eigendecomposition();

            Assert.IsTrue(E.Dimension == d);
            for (int i = 0; i < d; i++)
            {
                Complex val = E.Eigenpairs[i].Eigenvalue;
                Assert.IsTrue(val == 1.0);
                ComplexColumnVector vec = E.Eigenpairs[i].Eigenvector;
                for (int j = 0; j < d; j++)
                {
                    if (i == j)
                    {
                        Assert.IsTrue(vec[j] == 1.0);
                    }
                    else
                    {
                        Assert.IsTrue(vec[j] == 0.0);
                    }
                }
            }
        }
Esempio n. 5
0
 public void SymmetricRandomMatrixInverse()
 {
     for (int d = 1; d <= 100; d = d + 11)
     {
         SymmetricMatrix M  = TestUtilities.CreateSymmetricRandomMatrix(d, 1);
         SymmetricMatrix MI = M.Inverse();
         Assert.IsTrue(TestUtilities.IsNearlyEqual(MI * M, UnitMatrix.OfDimension(d)));
     }
 }
Esempio n. 6
0
        public void UnitMatrixImmutable()
        {
            UnitMatrix I = UnitMatrix.OfDimension(2);

            try {
                I[0, 0] += 1.0;
                Assert.Fail();
            } catch (InvalidOperationException) { }
        }
Esempio n. 7
0
 public void SquareVandermondeMatrixInverse()
 {
     for (int d = 1; d < 8; d++)
     {
         SquareMatrix H  = CreateVandermondeMatrix(d);
         SquareMatrix HI = H.Inverse();
         Assert.IsTrue(TestUtilities.IsNearlyEqual(H * HI, UnitMatrix.OfDimension(d)));
     }
 }
Esempio n. 8
0
        public void UnitMatrixNorms()
        {
            UnitMatrix   I = UnitMatrix.OfDimension(4);
            SquareMatrix A = I.ToSquareMatrix();

            Assert.IsTrue(I.OneNorm() == A.OneNorm());
            Assert.IsTrue(I.InfinityNorm() == A.InfinityNorm());
            Assert.IsTrue(I.FrobeniusNorm() == A.FrobeniusNorm());
            Assert.IsTrue(I.MaxNorm() == A.MaxNorm());
        }
Esempio n. 9
0
 public void SymmetricHilbertMatrixInverse()
 {
     for (int d = 1; d < 4; d++)
     {
         SymmetricMatrix H  = TestUtilities.CreateSymmetricHilbertMatrix(d);
         SymmetricMatrix HI = H.Inverse();
         Assert.IsTrue(TestUtilities.IsNearlyEqual(HI * H, UnitMatrix.OfDimension(d)));
     }
     // fails for d >= 4; look into this
 }
Esempio n. 10
0
 public void SquareUnitMatrixLUDecomposition()
 {
     for (int d = 1; d <= 10; d++)
     {
         SquareMatrix I = UnitMatrix.OfDimension(d).ToSquareMatrix();
         Assert.IsTrue(I.Trace() == d);
         LUDecomposition LU = I.LUDecomposition();
         Assert.IsTrue(LU.Determinant() == 1.0);
         SquareMatrix II = LU.Inverse();
         Assert.IsTrue(TestUtilities.IsNearlyEqual(II, I));
     }
 }
Esempio n. 11
0
        public static void VectorsAndMatrices()
        {
            ColumnVector v = new ColumnVector(0.0, 1.0, 2.0);
            ColumnVector w = new ColumnVector(new double[] { 1.0, -0.5, 1.5 });

            SquareMatrix A = new SquareMatrix(new double[, ] {
                { 1, -2, 3 },
                { 2, -5, 12 },
                { 0, 2, -10 }
            });

            RowVector u = new RowVector(4);

            for (int i = 0; i < u.Dimension; i++)
            {
                u[i] = i;
            }

            Random            rng = new Random(1);
            RectangularMatrix B   = new RectangularMatrix(4, 3);

            for (int r = 0; r < B.RowCount; r++)
            {
                for (int c = 0; c < B.ColumnCount; c++)
                {
                    B[r, c] = rng.NextDouble();
                }
            }

            SquareMatrix AI = A.Inverse();

            PrintMatrix("A * AI", A * AI);

            PrintMatrix("v + 2.0 * w", v + 2.0 * w);
            PrintMatrix("Av", A * v);
            PrintMatrix("B A", B * A);

            PrintMatrix("v^T", v.Transpose);
            PrintMatrix("B^T", B.Transpose);

            Console.WriteLine($"|v| = {v.Norm()}");
            Console.WriteLine($"sqrt(v^T v) = {Math.Sqrt(v.Transpose * v)}");

            UnitMatrix I = UnitMatrix.OfDimension(3);

            PrintMatrix("IA", I * A);

            Console.WriteLine(v == w);
            Console.WriteLine(I * A == A);
        }
Esempio n. 12
0
        public void SquareVandermondeMatrixLUDecomposition()
        {
            // fails now for d = 8 because determinant slightly off
            for (int d = 1; d < 8; d++)
            {
                // Analytic expression for determinant
                double[] x = new double[d];
                for (int i = 0; i < d; i++)
                {
                    x[i] = i;
                }
                double det = 1.0;
                for (int i = 0; i < d; i++)
                {
                    for (int j = 0; j < i; j++)
                    {
                        det = det * (x[i] - x[j]);
                    }
                }

                // LU decompose the matrix
                SquareMatrix    V  = CreateVandermondeMatrix(d);
                LUDecomposition LU = V.LUDecomposition();

                // Test that the decomposition works
                SquareMatrix P = LU.PMatrix();
                SquareMatrix L = LU.LMatrix();
                SquareMatrix U = LU.UMatrix();
                Assert.IsTrue(TestUtilities.IsNearlyEqual(P * V, L * U));

                // Check that the determinant agrees with the analytic expression
                Assert.IsTrue(TestUtilities.IsNearlyEqual(LU.Determinant(), det));

                // Check that the inverse works
                SquareMatrix VI = LU.Inverse();
                Assert.IsTrue(TestUtilities.IsNearlyEqual(V * VI, UnitMatrix.OfDimension(d)));

                // Test that a solution works
                ColumnVector t = new ColumnVector(d);
                for (int i = 0; i < d; i++)
                {
                    t[i] = 1.0;
                }
                ColumnVector s = LU.Solve(t);
                Assert.IsTrue(TestUtilities.IsNearlyEqual(V * s, t));
            }
        }
Esempio n. 13
0
        public void RandomRectangularSVD()
        {
            for (int c = 1; c < 64; c += 11)
            {
                Console.WriteLine(c);

                RectangularMatrix R = GenerateRandomMatrix(64, c);

                SingularValueDecomposition SVD = R.SingularValueDecomposition();

                Assert.IsTrue(SVD.RowCount == R.RowCount);
                Assert.IsTrue(SVD.ColumnCount == SVD.ColumnCount);
                Assert.IsTrue(SVD.Dimension == SVD.ColumnCount);

                // U has right dimensions and is orthogonal
                SquareMatrix U = SVD.LeftTransformMatrix;
                Assert.IsTrue(U.Dimension == R.RowCount);
                Assert.IsTrue(TestUtilities.IsNearlyEqual(U.Transpose * U, UnitMatrix.OfDimension(U.Dimension)));

                // V has right dimensions and is orthogonal
                SquareMatrix V = SVD.RightTransformMatrix;
                Assert.IsTrue(V.Dimension == R.ColumnCount);
                Assert.IsTrue(TestUtilities.IsNearlyEqual(V.Transpose * V, UnitMatrix.OfDimension(V.Dimension)));

                // The transforms decompose the matrix with the claimed singular values
                RectangularMatrix S = U.Transpose * R * V;
                for (int i = 0; i < SVD.Contributors.Count; i++)
                {
                    SingularValueContributor t = SVD.Contributors[i];
                    Assert.IsTrue(t.SingularValue >= 0.0);
                    Assert.IsTrue(TestUtilities.IsNearlyEqual(S[i, i], t.SingularValue));
                    Assert.IsTrue(TestUtilities.IsNearlyEqual(R * t.RightSingularVector, t.SingularValue * t.LeftSingularVector));
                }

                // We can reconstruct the original matrix from the claimed singular values
                RectangularMatrix R2 = new RectangularMatrix(SVD.RowCount, SVD.ColumnCount);
                foreach (SingularValueContributor t in SVD.Contributors)
                {
                    R2 += t.SingularValue * t.LeftSingularVector * t.RightSingularVector.Transpose;
                }
                Assert.IsTrue(TestUtilities.IsNearlyEqual(R, R2));
            }
        }
Esempio n. 14
0
        public void HilbertMatrixCholeskyDecomposition()
        {
            for (int d = 1; d <= 4; d++)
            {
                SymmetricMatrix H = TestUtilities.CreateSymmetricHilbertMatrix(d);

                // Decomposition succeeds
                CholeskyDecomposition CD = H.CholeskyDecomposition();
                Assert.IsTrue(CD != null);
                Assert.IsTrue(CD.Dimension == d);

                // Decomposition works
                SquareMatrix S = CD.SquareRootMatrix();
                Assert.IsTrue(TestUtilities.IsNearlyEqual(S * S.Transpose, H));

                // Inverse works
                SymmetricMatrix HI = CD.Inverse();
                Assert.IsTrue(TestUtilities.IsNearlyEqual(H * HI, UnitMatrix.OfDimension(d)));
            }
        }
Esempio n. 15
0
 private void ProcessUnitList( XmlNode n, UnitMatrix um )
 {
     string unitCode = "";
     decimal ep = 0.0M;
     foreach ( XmlNode unitNode in n.ChildNodes )
     {
         switch (unitNode.Name)
         {
             case "unitcode":
                 if ( unitCode.Length > 0 ) um.AddUnit( unitCode, ep );
                 unitCode = unitNode.InnerText;
                 break;
             case "ep":
                 ep = Decimal.Parse( unitNode.InnerText );
                 break;
             default:
                 break;
         }
     }
     um.AddUnit( unitCode, ep );
 }
Esempio n. 16
0
        public void UnitMatrixConversions()
        {
            UnitMatrix I = UnitMatrix.OfDimension(3);

            SquareMatrix A = I.ToSquareMatrix();

            Assert.IsTrue(I == A);
            A[0, 1] += 2.0;
            Assert.IsTrue(I != A);

            SymmetricMatrix B = I.ToSymmetricMatrix();

            Assert.IsTrue(I == B);
            B[0, 1] += 2.0;
            Assert.IsTrue(I != B);

            DiagonalMatrix C = I.ToDiagonalMatrix();

            Assert.IsTrue(I == C);
            C[2, 2] -= 1.0;
            Assert.IsTrue(I != C);
        }
Esempio n. 17
0
        public void SymmetricRandomMatrixEigenvectors()
        {
            for (int d = 1; d <= 100; d = d + 11)
            {
                SymmetricMatrix M = CreateSymmetricRandomMatrix(d, 1);

                RealEigendecomposition E = M.Eigendecomposition();

                Assert.IsTrue(E.Dimension == M.Dimension);

                double[] eigenvalues = new double[E.Dimension];
                for (int i = 0; i < E.Dimension; i++)
                {
                    double       e = E.Eigenpairs[i].Eigenvalue;
                    ColumnVector v = E.Eigenpairs[i].Eigenvector;
                    // The eigenvector works
                    Assert.IsTrue(TestUtilities.IsNearlyEigenpair(M, v, e));
                    // The eigenvalue is the corresponding diagonal value of D
                    Assert.IsTrue(E.DiagonalizedMatrix[i, i] == e);
                    // Remember eigenvalue to take sum in future
                    eigenvalues[i] = e;
                }

                // The eigenvectors sum to trace
                double tr = M.Trace();
                Assert.IsTrue(TestUtilities.IsSumNearlyEqual(eigenvalues, tr));

                // The decomposition works
                Assert.IsTrue(TestUtilities.IsNearlyEqual(
                                  E.DiagonalizedMatrix, E.TransformMatrix.Transpose * M * E.TransformMatrix
                                  ));

                // Transform matrix is orthogonal
                Assert.IsTrue(TestUtilities.IsNearlyEqual(
                                  E.TransformMatrix.Transpose * E.TransformMatrix, UnitMatrix.OfDimension(d)
                                  ));
            }
        }
Esempio n. 18
0
        public void RectangularQRDecomposition()
        {
            RectangularMatrix M = GenerateRandomMatrix(30, 10);

            QRDecomposition QRD = M.QRDecomposition();

            Assert.IsTrue(QRD.RowCount == M.RowCount);
            Assert.IsTrue(QRD.ColumnCount == M.ColumnCount);

            SquareMatrix Q = QRD.QMatrix;

            Assert.IsTrue(Q.Dimension == M.RowCount);
            Assert.IsTrue(TestUtilities.IsNearlyEqual(Q * Q.Transpose, UnitMatrix.OfDimension(Q.Dimension)));

            RectangularMatrix R = QRD.RMatrix;

            Assert.IsTrue(R.RowCount == M.RowCount);
            Assert.IsTrue(R.ColumnCount == M.ColumnCount);

            RectangularMatrix QR = Q * R;

            Assert.IsTrue(TestUtilities.IsNearlyEqual(QR, M));
        }
Esempio n. 19
0
 private void LoadState()
 {
     matrixHT = new Hashtable();
     UnitMatrix um = null;
     NflTeam team;
     RosterLib.Utility.Announce( "Loading saved Team EP" );
      bool exists = File.Exists("teamEP.xml");
      if (exists)
      {
     epDoc = new XmlDocument();
     epDoc.Load("teamEP.xml");
     XmlNode root = epDoc.ChildNodes[2];  // skip node 1 as it is a comment
     foreach (XmlNode playerNode in root.ChildNodes)
     {
        string teamCode = "";
        foreach (XmlNode n in playerNode.ChildNodes)
        {
           switch (n.Name)
           {
              case "teamcode":
                 teamCode = n.InnerText;
                 break;
              case "unit-list":
                 team = new NflTeam(teamCode);
                 um = new UnitMatrix(team);
                 ProcessUnitList(n, um);
                 break;
              default:
                 break;
           }
        }
        if (um != null)
           AddTeam(teamCode, um);
     }
     PrintIndexAndKeysAndValues(matrixHT);
      }
 }
Esempio n. 20
0
        public void UnitMatrixEntries()
        {
            int        n = 3;
            UnitMatrix I = UnitMatrix.OfDimension(n);

            Assert.IsTrue(I.Dimension == n);
            Assert.IsTrue(I.RowCount == n);
            Assert.IsTrue(I.ColumnCount == n);

            for (int r = 0; r < n; r++)
            {
                for (int c = 0; c < n; c++)
                {
                    if (r == c)
                    {
                        Assert.IsTrue(I[r, c] == 1.0);
                    }
                    else
                    {
                        Assert.IsTrue(I[r, c] == 0.0);
                    }
                }
            }
        }
Esempio n. 21
0
 private void AddTeam( string id, UnitMatrix um )
 {
     if ( id.Length > 0 )
         matrixHT.Add( id, um );
 }
Esempio n. 22
0
        public NflTeam(string codeIn, string seasonIn)
        {
            PlayersLost = "";
             PlayersGot = "";
             //RosterLib.Utility.Announce(string.Format("  2. Constructing team {0} for {1}", codeIn, seasonIn));

             PlayerList = new ArrayList();
             Season = seasonIn;
             TeamCode = codeIn;
             var dr = Utility.TflWs.TeamDataFor(codeIn, seasonIn);
             GetTeamValuesFromData(dr);
             _spotList = new ArrayList();

             if (Config.DoProjections() || Config.DoMatchups())
             {
            //  Load Schedule
            LoadSchedule();
            ProjectionList = new ArrayList();
             }

             if (Config.ReportType == "New")
             {
            //  New stuff
            SetRecord(seasonIn, skipPostseason: false);

            //  Team record

            LoadGames(codeIn, seasonIn);
            if (Config.DoExperience())
            {
               if (Utility.Wz == null) Utility.Wz = new WizSeason(Utility.LastSeason(), "01", "17");
               Matrix = Utility.Wz.GetMatrix(TeamCode);
            }
             }

             InitialiseRatings();
        }
Esempio n. 23
0
 private static decimal TallyExperience(UnitMatrix m )
 {
     var tot = 0.0M;
     if (Utility.UnitList == null) Utility.LoadUnits();
     foreach (TeamUnit u in Utility.UnitList)
     {
         var exp = m.GetUnit(u.UnitCode);
         tot += exp[RosterLib.Constants.K_WEEKS_IN_A_SEASON, 0];
     }
     return tot;
 }
Esempio n. 24
0
        /// <summary>
        ///   Crunches a game then increments the exp PTS for
        ///   the 6 units on each team.
        /// </summary>
        /// <param name="homeMatrix">The home Matrix.</param>
        /// <param name="awayMatrix">The away Matrix.</param>
        /// <param name="game">The game.</param>
        private void IncrementExpPts( UnitMatrix homeMatrix, UnitMatrix awayMatrix, GameStats game )
        {
            //RosterLib.Utility.Announce( string.Format( "Evaluating game {0} {1}@{2}",
            //                                    game.Code, game.AwayTeam, game.HomeTeam ) );

            #if DEBUG
            homeMatrix.DumpToLog();
            awayMatrix.DumpToLog();
            #endif
            EvaluatePo( game, homeMatrix, awayMatrix, true );
            EvaluatePo( game, awayMatrix, homeMatrix, false );
            EvaluateRo( game, homeMatrix, awayMatrix, true );
            EvaluateRo( game, awayMatrix, homeMatrix, false );
            EvaluatePp( game, homeMatrix, awayMatrix, true );
            EvaluatePp( game, awayMatrix, homeMatrix, false );
        }
Esempio n. 25
0
 /// <summary>
 ///   Each Team is the season gets a set of stats.
 /// </summary>
 private void InitialiseMatrix()
 {
     Utility.Announce( "Initializing Matrix " );
     var ds = Utility.TflWs.GetTeams( _season, "" );
     _teams = ds.Tables[ "teams" ];
     foreach ( DataRow dr in _teams.Rows )
     {
         var teamCode = dr[ "TEAMID" ].ToString();
         var team = Masters.Tm.GetTeam( _season, teamCode );
         var unit = new UnitMatrix( team );
         _matrixList.Add( unit );
     }
 }
Esempio n. 26
0
        private static void GetEp( string unitCode, decimal[,] exp, NFLGame g, UnitMatrix u, int weekOffset,
											decimal metric )
        {
            var ep = g.ExperiencePoints( unitCode, u.Team.TeamCode );
            IncrementMatrix( ep, weekOffset, exp, metric );
            return;
        }
Esempio n. 27
0
        public UnitMatrix GetMatrix()
        {
            // generate it if it is not there, but first see if you have it in xml
             //RosterLib.Utility.Announce( "NFLTeam.GetMatrix" );
             if (Matrix == null)
             {
            Matrix = LoadMatrixFromXml();

            if (Matrix == null)
            {
               if (Utility.Wz == null)
                  Utility.ExperiencePoints(Utility.CurrentWeek() == "00"
                                              ? Utility.LastSeason()
                                              : Utility.CurrentSeason());
               if (Utility.Wz != null)
                  Matrix = Utility.Wz.GetMatrix(TeamCode);
            }
             }
             return Matrix;
        }
Esempio n. 28
0
        private void EvaluateRo( GameStats game, UnitMatrix offMatrix, UnitMatrix defMatrix, bool bHome )
        {
            decimal avgMetric = AverageMetric( ( Total.AwayTDruns + Total.HomeTDruns )/2 );
            //			RosterLib.Utility.Announce( string.Format( "League Average Tdr is {0:###.#} (tot={1:###.#})",
            //				avgMetric, Total.AwayTDruns + Total.HomeTDruns ) );

            decimal gp = offMatrix.GamesPlayed;
            decimal tdr = offMatrix.RoMetrics;
            decimal offMult = Multiplier( tdr/gp, avgMetric );
            decimal defMult = Multiplier( avgMetric, defMatrix.RdMetrics/defMatrix.GamesPlayed );

            //			RosterLib.Utility.Announce( string.Format( "Offense {1} averages {0:###.#} Tdr/game",
            //				offMatrix.ROMetrics / offMatrix.GamesPlayed, offMatrix.TeamCode ) );
            //			RosterLib.Utility.Announce( string.Format( "Defence {1} averages {0:###.#} Tdr allowed/game",
            //				defMatrix.RDMetrics / defMatrix.GamesPlayed, defMatrix.TeamCode ) );

            decimal metric = ( bHome ) ? game.HomeTDruns : game.AwayTDruns;
            //string result = ResultOf( metric, 100.0M, 125.0M );
            string result = ResultOf( metric, 0.0M, 1.0M );
            //			RosterLib.Utility.Announce( "Result=" + result );

            decimal offPoints;
            decimal defPoints;

            switch ( result )
            {
                case "L":
                    offPoints = KPointsLoss;
                    defPoints = KPointsWin;
                    break;
                case "D":
                    offPoints = KPointsDraw;
                    defPoints = KPointsDraw;
                    break;
                default:
                    offPoints = KPointsWin;
                    defPoints = KPointsLoss;
                    break;
            }

            offMatrix.AddRoPoints( offPoints, defMult, game );
            defMatrix.AddRdPoints( defPoints, offMult, game );
            DistributeEp( "RO", offPoints, defMult, game, bHome );
            DistributeEp( "RD", defPoints, offMult, game, bHome );
            Explain( offMatrix, defMatrix, "Rush Offence", offPoints,
                        defPoints, "RO", "RD", offMult, defMult, result,
                        ( offMatrix.RoPoints - offPoints ), ( defMatrix.RdPoints - defPoints ), metric, bHome );
        }
Esempio n. 29
0
 private static void UnitList( UnitMatrix m, XmlWriter writer )
 {
     writer.WriteStartElement( "unit-list" );
     foreach ( TeamUnit u in Utility.UnitList )
     {
         WriteElement( writer, "unitcode", u.UnitCode );
         var exp = m.GetUnit( u.UnitCode );
         WriteElement( writer, "ep", string.Format( "{0:#0.0}", exp[ Constants.K_WEEKS_IN_A_SEASON, 0 ] ) );
     }
     writer.WriteEndElement();
 }
Esempio n. 30
0
        private void EvaluatePp( GameStats game, UnitMatrix offMatrix, UnitMatrix defMatrix, bool bHome )
        {
            decimal avgMetric = AverageMetric( ( Total.AwaySacksAllowed + Total.HomeSacksAllowed )/2 );
            #if DEBUG
            Utility.Announce( string.Format( "League Average Sacks Allowed is {0:###.#} (tot={1:###.#})",
                                                            avgMetric, Total.AwaySacksAllowed + Total.HomeSacksAllowed ) );
            #endif
            //  Multipliers
            var sakAllowed = offMatrix.PpMetrics;
            var saks = defMatrix.PrMetrics;

            var offMult = Multiplier( avgMetric, DivByZeroCheck( sakAllowed, offMatrix.GamesPlayed ) );
            #if DEBUG
            Utility.Announce( string.Format( "Defence {1} averages {0:###.#} Sacks/game",
                                                            DivByZeroCheck( defMatrix.PrMetrics, defMatrix.GamesPlayed ),
                                                            defMatrix.TeamCode ) );
            Utility.Announce( string.Format( "Offense {1} averages {0:###.#} Sacks allowed/game",
                                                            DivByZeroCheck( sakAllowed, offMatrix.GamesPlayed ), offMatrix.TeamCode ) );
            #endif
            var defMult = Multiplier( DivByZeroCheck( saks, defMatrix.GamesPlayed ), avgMetric );

            if ( offMult == 0.0M ) offMult = 1.0M;
            if ( defMult == 0.0M ) defMult = 1.0M;
            #if DEBUG
            Utility.Announce( string.Format( "Offensive multiplier is {0:##.##}", offMult ) );
            Utility.Announce( string.Format( "Defensive multiplier is {0:##.##}", defMult ) );
            #endif
            var metric = ( bHome ) ? game.HomeSacksAllowed : game.AwaySacksAllowed;
            decimal offPoints;
            decimal defPoints;
            var result = ResultOf( metric, 2.0M, 4.0M );
            //RosterLib.Utility.Announce( "Result=" + result );
            switch ( result )
            {
                case "W":
                    offPoints = KPointsLoss;
                    defPoints = KPointsWin;
                    break;
                case "D":
                    offPoints = KPointsDraw;
                    defPoints = KPointsDraw;
                    break;
                default:
                    offPoints = KPointsWin;
                    defPoints = KPointsLoss;
                    break;
            }

            offMatrix.AddPpPoints( offPoints, defMult, game );
            defMatrix.AddPrPoints( defPoints, offMult, game );
            DistributeEp( "PP", offPoints, defMult, game, bHome );
            DistributeEp( "PR", defPoints, offMult, game, bHome );
            #if DEBUG
            Explain( offMatrix, defMatrix, "Pass Protection", offPoints,
                        defPoints, "PP", "PR", offMult, defMult, result,
                        ( offMatrix.PpPoints - offPoints ), ( defMatrix.PrPoints - defPoints ), metric, bHome );
            #endif
        }
Esempio n. 31
0
        private static void SpitTeam( UnitMatrix m, XmlTextWriter writer )
        {
            m.Team.ExperiencePoints = TallyExperience(m);
            writer.WriteStartElement( "team" );

            WriteElement( writer, "teamcode", m.Team.TeamCode );
            WriteElement( writer, "name", m.Team.NameOut() );
            WriteElement( writer, "ep", m.Team.ExperiencePoints.ToString() );

            UnitList( m, writer );

            writer.WriteEndElement();
        }
Esempio n. 32
0
        /// <summary>
        /// Evaluates the Passing Offense and Defence, based on passing yards.
        /// </summary>
        /// <param name="game">The game.</param>
        /// <param name="offMatrix">The off Matrix.</param>
        /// <param name="defMatrix">The def Matrix.</param>
        /// <param name="bHome">if set to <c>true</c> [b home].</param>
        private void EvaluatePo( GameStats game, UnitMatrix offMatrix, UnitMatrix defMatrix, bool bHome )
        {
            //  What is the league average for Tdp
            var avgMetric = AverageMetric( ( Total.AwayTDpasses + Total.HomeTDpasses )/2 );

            //  How does the offence compare against the League
            var offMult = Multiplier( offMatrix.PoMetrics/offMatrix.GamesPlayed, avgMetric );
            #if DEBUG
            Utility.Announce( string.Format( "League Average Tdp is {0:###.#} (tot={1:###.#})",
                                                            avgMetric, Total.AwayTDpasses + Total.HomeTDpasses ) );
            Utility.Announce( string.Format( "Defence {1} gives up an average of {0:###.#} Tdp/game",
                                                            defMatrix.PpMetrics/defMatrix.GamesPlayed, defMatrix.TeamCode ) );
            Utility.Announce( string.Format( "Offense {1} averages {0:###.#} Tdp/game",
                                                            offMatrix.PoMetrics/offMatrix.GamesPlayed, offMatrix.TeamCode ) );
            #endif
            var defMult = Multiplier( avgMetric, defMatrix.PdMetrics/defMatrix.GamesPlayed ); //  Avg Def = 1.0

            var metric = ( bHome ) ? game.HomeTDpasses : game.AwayTDpasses;

            decimal offPoints;
            decimal defPoints;
            var result = ResultOf( metric, 0.0M, 1.0M );

            //Utility.Announce( string.Format( "  WizSeason.EvaluatePO Result for {1} = {0}", result, offMatrix.Team.Name ) );

            #region  tally

            switch ( result )
            {
                case "L":
                    offPoints = KPointsLoss;
                    defPoints = KPointsWin;
                    break;
                case "D":
                    offPoints = KPointsDraw;
                    defPoints = KPointsDraw;
                    break;
                default:
                    offPoints = KPointsWin;
                    defPoints = KPointsLoss;
                    break;
            }

            offMatrix.AddPoPoints( offPoints, defMult, game );
            defMatrix.AddPdPoints( defPoints, offMult, game );
            //  Give each member of the passing unit the experience too
            DistributeEp( "PO", offPoints, defMult, game, bHome );
            DistributeEp( "PD", defPoints, offMult, game, bHome );

            #endregion

            Explain( offMatrix, defMatrix, "Pass Offence", offPoints,
                        defPoints, "PO", "PD", offMult, defMult, result,
                        ( offMatrix.PoPoints - ( offPoints*defMult ) ), ( defMatrix.PdPoints - ( defPoints*offMult ) ),
                        metric, bHome );
        }
Esempio n. 33
0
        private static void ProcessGame(UnitMatrix u, NFLGame g)
        {
            var weekOffset = Int32.Parse(g.Week) - 1;
            Utility.Announce(string.Format("Game {0}", g.GameCodeOut()));
            if ((weekOffset < 0) || (weekOffset > 20))
                Utility.Announce(string.Format("Game {0} has week {1}", g.GameCodeOut(), g.Week));
            else
            {
                if (!g.MetricsCalculated) g.TallyMetrics(String.Empty);

                decimal metric = (g.IsHome(u.Team.TeamCode) ? g.HomeTDp : g.AwayTDp);
                GetEp("PO", u.PoExp, g, u, weekOffset, metric);

                metric = (g.IsHome(u.Team.TeamCode) ? g.HomeTDr : g.AwayTDr);
                GetEp("RO", u.RoExp, g, u, weekOffset, metric);

                metric = (g.IsHome(u.Team.TeamCode) ? g.HomeSaKa : g.AwaySaKa);
                GetEp("PP", u.PpExp, g, u, weekOffset, metric);

                metric = (g.IsHome(u.Team.TeamCode) ? g.AwaySaKa : g.HomeSaKa);
                GetEp("PR", u.PrExp, g, u, weekOffset, metric);

                metric = (g.IsHome(u.Team.TeamCode) ? g.AwayTDr : g.HomeTDr);
                GetEp("RD", u.RdExp, g, u, weekOffset, metric);

                metric = (g.IsHome(u.Team.TeamCode) ? g.AwaySaKa : g.HomeSaKa);
                GetEp("PD", u.PdExp, g, u, weekOffset, metric);
            }
        }
Esempio n. 34
0
        public void SquareMatrixSVD()
        {
            for (int d = 4; d < 64; d += 7)
            {
                SquareMatrix A = CreateSquareRandomMatrix(d, d);

                SingularValueDecomposition SVD = A.SingularValueDecomposition();

                Assert.IsTrue(SVD.Dimension == A.Dimension);

                // U has right dimensions and is orthogonal
                SquareMatrix U = SVD.LeftTransformMatrix;
                Assert.IsTrue(U.Dimension == A.Dimension);
                Assert.IsTrue(TestUtilities.IsNearlyEqual(U.MultiplyTransposeBySelf(), UnitMatrix.OfDimension(U.Dimension)));

                // V has right dimensions and is orthogonal
                SquareMatrix V = SVD.RightTransformMatrix;
                Assert.IsTrue(V.Dimension == A.Dimension);
                Assert.IsTrue(TestUtilities.IsNearlyEqual(V.MultiplyTransposeBySelf(), UnitMatrix.OfDimension(V.Dimension)));
                Assert.IsTrue(SVD.Dimension == A.Dimension);

                // The transforms decompose the matrix with the claimed singular values
                SquareMatrix S = U.Transpose * A * V;
                for (int i = 0; i < SVD.Contributors.Count; i++)
                {
                    SingularValueContributor t = SVD.Contributors[i];
                    Assert.IsTrue(t.SingularValue >= 0.0);
                    Assert.IsTrue(TestUtilities.IsNearlyEqual(S[i, i], t.SingularValue));
                }

                // We can solve a rhs using the SVD
                ColumnVector x = new ColumnVector(d);
                for (int i = 0; i < d; i++)
                {
                    x[i] = i;
                }
                ColumnVector b = A * x;
                ColumnVector y = SVD.Solve(b);
                Assert.IsTrue(TestUtilities.IsNearlyEqual(x, y));
            }
        }
Esempio n. 35
0
        public static void Explain( UnitMatrix offMatrix, UnitMatrix defMatrix,
											 string area, decimal offEp, decimal defEp, string offUnit, string defUnit,
											 decimal offMult, decimal defMult, string result, decimal offPtsBefore,
											 decimal defPtsBefore,
											 decimal metric, bool bHome )
        {
            if ( bExplain )
            {
                RosterLib.Utility.Announce( string.Format( "Considering {0} {1} team", area, bHome ? "Home" : "Away" ) );
                RosterLib.Utility.Announce( MultiplierLine( "Off team " + offMatrix.TeamCode, offUnit, metric,
                                                                 offMult ) );
                RosterLib.Utility.Announce( MultiplierLine( "Def team " + defMatrix.TeamCode, defUnit, metric,
                                                                 defMult ) );
                RosterLib.Utility.Announce( PointsLine( offMatrix.TeamCode, offUnit, offPtsBefore, offEp ) );
                RosterLib.Utility.Announce( PointsLine( defMatrix.TeamCode, defUnit, defPtsBefore, defEp ) );
            }
        }
Esempio n. 36
0
        public NflTeam(string nameIn, string divIn, string codeIn, string shortNameIn,
                     string seasonIn)
        {
            PlayersLost = "";
             PlayersGot = "";
             //
             //  constructor for new roster 5 paras
             //
             //RosterLib.Utility.Announce("  5. Constructing New Roster Team " + codeIn);
             PlayerList = new ArrayList();

             Season = seasonIn;
             Name = nameIn;
             NickName = shortNameIn;
             Div = divIn;
             TeamCode = codeIn;

             if (nameIn == "") Name = Utility.TflWs.TeamFor(codeIn, seasonIn);

             _spotList = new ArrayList();

             if (Config.DoProjections() && (Season != ""))
            InitialiseProjections();

             //  New stuff
             SetRecord(seasonIn, skipPostseason: false);

             //  Team record
             GameList = new ArrayList();
             LoadGames(codeIn, seasonIn);

             if (Config.DoExperience() || Config.DoMatchups())
             {
            if (Utility.Wz == null)
               Utility.Wz = new WizSeason(Utility.LastSeason(), "01", "17");
            Matrix = Utility.Wz.GetMatrix(TeamCode);
             }

             LoadDivisionalOpponents();

             SetDefence();

             LoadTeamCard();
        }