public void Test_LeducHe()
        {
            _gd = XmlSerializerExt.Deserialize <GameDefinition>(
                Props.Global.Expand("${bds.DataDir}ai.pkr.metastrategy/leduc-he.gamedef.xml"));
            ActionTree tree = CreateActionTreeByGameDef.Create(_gd);

            VerifyActionTree(tree, _expLeducHe);
        }
예제 #2
0
        public static StrategyTree CreateStrategyTree(GameDefinition gd, int pos)
        {
            ChanceTree   ct  = CreateChanceTreeByGameDef.Create(gd);
            ChanceTree   pct = ExtractPlayerChanceTree.ExtractS(ct, 0);
            ActionTree   at  = CreateActionTreeByGameDef.Create(gd);
            StrategyTree st  = CreateStrategyTreeByChanceAndActionTrees.CreateS(pct, at);

            return(st);
        }
예제 #3
0
            public GameDefParams(FictitiousPlay_Test test, string gameDefFile, double epsilon)
            {
                Epsilon = epsilon;

                GameDef = XmlSerializerExt.Deserialize <GameDefinition>(Props.Global.Expand("${bds.DataDir}ai.pkr.metastrategy/${0}", gameDefFile));

                Name = GameDef.Name;

                ChanceTree = CreateChanceTreeByGameDef.Create(GameDef);
                ActionTree = CreateActionTreeByGameDef.Create(GameDef);
            }
예제 #4
0
        /// <summary>
        /// This functions simulate a typical use case: create trees in many runs of MC sampling, write them, read again
        /// and merge into the master tree. The master tree is than verified.
        /// </summary>
        private void GenerateAndVerifyCT(string name, GameDefinition gd, IChanceAbstraction[] chanceAbstractions, bool areAbstractionsEqual, int samplesCount, int runsCount, double avRelProbabEps, double avPotShareEps, double eqValEps, bool visualize)
        {
            CtMcGen.Tree masterTree = new CtMcGen.Tree();

            int rngSeed = (int)DateTime.Now.Ticks;

            for (int run = 0; run < runsCount; ++run)
            {
                CtMcGen.Tree runTree  = CtMcGen.Generate(gd, chanceAbstractions, areAbstractionsEqual, samplesCount, rngSeed, null);
                string       fileName = Path.Combine(_outDir, String.Format("{0}-{1}-ct.dat", gd.Name, name));
                runTree.Write(fileName);
                masterTree.Read(fileName);

                // Do not use the timer anymore because the tests are too fast.
                rngSeed++;
            }

            ChanceTree actCt = masterTree.ConvertToChanceTree();

            VisChanceTree.Show(actCt, Path.Combine(_outDir, String.Format("{0}-{1}-ct.gv", gd.Name, name)));
            VerifyChanceTree.VerifyS(actCt);
            ChanceTree expCt = CreateChanceTreeByAbstraction.CreateS(gd, chanceAbstractions);

            Assert.AreEqual(expCt.PlayersCount, actCt.PlayersCount);
            CompareChanceTrees cmp = new CompareChanceTrees();

            cmp.IsVerbose = visualize;
            cmp.Output    = Console.Out;
            cmp.Compare(expCt, actCt);
            VisChanceTree.Show(expCt, Path.Combine(_outDir, String.Format("{0}-{1}-ct-exp.gv", gd.Name, name)));
            Assert.Less(cmp.AverageRelProbabDiff, avRelProbabEps);
            for (int p = 0; p < chanceAbstractions.Length; ++p)
            {
                Assert.Less(cmp.AveragePotShareDiff[p], avRelProbabEps);
            }

            ActionTree at = CreateActionTreeByGameDef.Create(gd);

            double [] actEqValues, expEqValues;
            EqLp.Solve(at, actCt, out actEqValues);
            EqLp.Solve(at, expCt, out expEqValues);
            for (int p = 0; p < chanceAbstractions.Length; ++p)
            {
                if (visualize)
                {
                    Console.WriteLine("Eq pos: {0} exp: {1} act: {2}", p, expEqValues[p], actEqValues[p]);
                }
                Assert.AreEqual(expEqValues[p], actEqValues[p], eqValEps);
            }
            if (visualize)
            {
                Console.WriteLine();
            }
        }
            public TestParams(FictitiousPlayMc_Test test, string gameDefFile,
                              IChanceAbstraction chanceAbstr, int [] cardCount, double epsilon)
            {
                Epsilon           = epsilon;
                GameDef           = XmlSerializerExt.Deserialize <GameDefinition>(Props.Global.Expand("${bds.DataDir}ai.pkr.metastrategy/${0}", gameDefFile));
                Name              = chanceAbstr.Name;
                ChanceAbstraction = chanceAbstr;

                ActionTree = CreateActionTreeByGameDef.Create(GameDef);
                Debug.Assert(GameDef.MinPlayers == 2);
                ChanceTree = CreateChanceTreeByAbstraction.CreateS(GameDef, new IChanceAbstraction[] { chanceAbstr, chanceAbstr });
                CardCount  = cardCount;
            }
예제 #6
0
        static int Main(string[] args)
        {
            if (!Parser.ParseArgumentsWithUsage(args, _cmdLine))
            {
                return(1);
            }

            if (_cmdLine.DebuggerLaunch)
            {
                Debugger.Launch();
            }

            GameDefinition gd = XmlSerializerExt.Deserialize <GameDefinition>(_cmdLine.GameDef.Get(Props.Global));

            string     chanceTreeFile = _cmdLine.ChanceTree.Get(Props.Global);
            ChanceTree ct;

            if (string.IsNullOrEmpty(chanceTreeFile))
            {
                ct = CreateChanceTreeByGameDef.Create(gd);
            }
            else
            {
                ct = ChanceTree.Read <ChanceTree>(chanceTreeFile);
            }

            ActionTree at = CreateActionTreeByGameDef.Create(gd);

            double []       values;
            StrategyTree [] st = EqLp.Solve(at, ct, out values);
            if (st == null)
            {
                Console.WriteLine("Cannot find solution");
                return(1);
            }
            string output   = _cmdLine.Output.Get(Props.Global);
            string basePath = string.IsNullOrEmpty(output) ? gd.Name : output;
            string baseDir  = Path.GetDirectoryName(basePath);
            string baseName = Path.GetFileNameWithoutExtension(basePath);

            for (int p = 0; p < st.Length; ++p)
            {
                string fileName = Path.Combine(baseDir, string.Format("{0}-{1}.dat", baseName, p));
                Console.WriteLine("Eq value pos {0}: {1}, file: {2}", p, values[p], fileName);
                st[p].Write(fileName);
            }



            return(0);
        }
예제 #7
0
        public void Test_LeducHe()
        {
            GameDefinition gd = XmlSerializerExt.Deserialize <GameDefinition>(
                Props.Global.Expand("${bds.DataDir}ai.pkr.metastrategy/leduc-he.gamedef.xml"));

            ActionTree ct = CreateActionTreeByGameDef.Create(gd);

            using (TextWriter w = new StreamWriter(File.Open(Path.Combine(_outDir, "leduc-at.gv"), FileMode.Create)))
            {
                VisActionTree vis = new VisActionTree {
                    Output = w
                };
                vis.Show(ct);
            }
        }
예제 #8
0
        public void Test_Leduc()
        {
            GameDefinition gd = XmlSerializerExt.Deserialize <GameDefinition>(
                Props.Global.Expand("${bds.DataDir}ai.pkr.metastrategy/leduc-he.gamedef.xml"));

            string[] strategyFilesRel = new string[] { "eq-LeducHe-0-s.xml", "eq-LeducHe-1-s.xml" };
            string[] StrategyFilesAbs = new string[gd.MinPlayers].Fill(i => Path.Combine(_testResDir, strategyFilesRel[i]));

            StrategyTree[] strategiesOrig = new StrategyTree[gd.MinPlayers].Fill(i =>
                                                                                 XmlToStrategyTree.Convert(StrategyFilesAbs[i], gd.DeckDescr));

            ChanceTree ct = CreateChanceTreeByGameDef.Create(gd);
            ActionTree at = CreateActionTreeByGameDef.Create(gd);

            GameValue gv1 = new GameValue {
                ActionTree = at, ChanceTree = ct, Strategies = strategiesOrig
            };

            gv1.Solve();

            for (int p = 0; p < gd.MinPlayers; ++p)
            {
                StrategyTree[] strategiesMerged = new StrategyTree[gd.MinPlayers].Fill(i =>
                                                                                       XmlToStrategyTree.Convert(StrategyFilesAbs[i], gd.DeckDescr));

                // Merge strategy to the stategy at postion p.
                for (int pSrc = 0; pSrc < gd.MinPlayers; ++pSrc)
                {
                    if (p == pSrc)
                    {
                        continue;
                    }
                    MergeStrategies.Merge(strategiesMerged[p], strategiesMerged[pSrc], pSrc);
                }
                // Copy strategy at position p to the other positions
                for (int pCopy = 0; pCopy < gd.MinPlayers; ++pCopy)
                {
                    strategiesMerged[pCopy] = strategiesMerged[p];
                }

                GameValue gv2 = new GameValue {
                    ActionTree = at, ChanceTree = ct, Strategies = strategiesMerged
                };
                gv2.Solve();
                Assert.AreEqual(gv1.Values, gv2.Values);
            }
        }
예제 #9
0
            public OcfrParams(GameValue_Test test, string name, string gameDefFile, IChanceAbstraction[] abstractions, string[] ocfrFiles, double[] expectedResult, double epsilon)
            {
                Epsilon        = epsilon;
                ExpectedResult = expectedResult;

                GameDef = XmlSerializerExt.Deserialize <GameDefinition>(
                    Props.Global.Expand("${bds.DataDir}ai.pkr.metastrategy/${0}",
                                        gameDefFile));

                Name = name;

                OcfrFiles = new string[GameDef.MinPlayers].Fill(i => Path.Combine(test._testResDir, ocfrFiles[i]));
                if (abstractions == null)
                {
                    ChanceTree = CreateChanceTreeByGameDef.Create(GameDef);
                }
                else
                {
                    ChanceTree = CreateChanceTreeByAbstraction.CreateS(GameDef, abstractions);
                }

                //VisChanceTree.Show(ChanceTree, Path.Combine(test._outDir, String.Format("{0}-c.gv", GameDef.Name)));

                ActionTree = CreateActionTreeByGameDef.Create(GameDef);

                StrategyTrees = new StrategyTree[GameDef.MinPlayers];

                for (int p = 0; p < GameDef.MinPlayers; ++p)
                {
                    ChanceTree pct = ExtractPlayerChanceTree.ExtractS(ChanceTree, p);
                    StrategyTrees[p] = CreateStrategyTreeByChanceAndActionTrees.CreateS(pct, ActionTree);


                    OpenCfrStrategyConverter conv = new OpenCfrStrategyConverter
                    {
                        GameDef           = GameDef,
                        HeroPosition      = p,
                        SourceFile        = OcfrFiles[p],
                        Strategy          = StrategyTrees[p],
                        ChanceAbstraction = abstractions == null ? null : abstractions[p]
                    };
                    conv.Convert();

                    //VisStrategyTree.Show(StrategyTrees[p], Path.Combine(test._outDir, String.Format("{0}-str-{1}.gv", GameDef.Name, p)));
                }
            }
예제 #10
0
        public void Test_Kuhn()
        {
            GameDefinition gd = XmlSerializerExt.Deserialize <GameDefinition>(
                Props.Global.Expand("${bds.DataDir}ai.pkr.metastrategy/kuhn.gamedef.xml"));

            ChanceTree ct = CreateChanceTreeByGameDef.Create(gd);
            ActionTree at = CreateActionTreeByGameDef.Create(gd);

            StrategyTree [] playerTrees = new StrategyTree[2];
            for (int p = 0; p < 2; ++p)
            {
                ChanceTree   pct = ExtractPlayerChanceTree.ExtractS(ct, p);
                StrategyTree st  = CreateStrategyTreeByChanceAndActionTrees.CreateS(pct, at);
                playerTrees[p] = st;

                VisStrategyTree.Show(st, Path.Combine(_outDir, string.Format("pt-{0}.gv", p)));
            }
        }
        public void Test_Leduc()
        {
            GameDefinition gd = XmlSerializerExt.Deserialize <GameDefinition>(
                Props.Global.Expand("${bds.DataDir}ai.pkr.metastrategy/leduc-he.gamedef.xml"));
            ActionTree at  = CreateActionTreeByGameDef.Create(gd);
            ChanceTree ct  = CreateChanceTreeByGameDef.Create(gd);
            ChanceTree pct = ExtractPlayerChanceTree.ExtractS(ct, 0);

            TestWalker tw = new TestWalker {
                ActionTree = at, PlayerChanceTree = pct
            };

            tw.Walk();
            Console.WriteLine("Begin: a:{0} c:{1} total:{2}", tw.BeginCount[0], tw.BeginCount[1], tw.BeginCount[0] + tw.BeginCount[1]);
            Assert.AreEqual(674, tw.BeginCount[0]);
            Assert.AreEqual(48, tw.BeginCount[1]);
            Assert.AreEqual(_leduc, tw.Text);
        }
예제 #12
0
        public void Test_Eq()
        {
            GameDefinition gd = XmlSerializerExt.Deserialize <GameDefinition>("kuhn8.gamedef.xml");
            ChanceTree     ct = CreateChanceTreeByGameDef.Create(gd);

            VisChanceTree.Show(ct, "kuhn8-ct.gv");
            ActionTree at = CreateActionTreeByGameDef.Create(gd);

            VisActionTree.Show(at, "kuhn8-at.gv");



            double[]        values;
            StrategyTree [] strategies = EqLp.Solve(at, ct, out values);
            Console.WriteLine("Kuhn8 eq values: {0}, {1}", values[0], values[1]);
            VisStrategyTree.Show(strategies[0], "kuhn8-eq-0.gv");
            VisStrategyTree.Show(strategies[1], "kuhn8-eq-1.gv");

            // Make strategy for T same as for Q
            //strategies[0].Nodes[strategies[0].FindNode("0d0 0p0", null)].Probab = 0.5;
            //strategies[0].Nodes[strategies[0].FindNode("0d0 0p0 1p1 0p1", null)].Probab = 0.5;
            //strategies[0].Nodes[strategies[0].FindNode("0d0 0p1", null)].Probab = 0.5;


            // Make strategy for Q same as for T
            strategies[0].Nodes[strategies[0].FindNode("0d2 0p0", null)].Probab         = 0;
            strategies[0].Nodes[strategies[0].FindNode("0d2 0p0 1p1 0p1", null)].Probab = 0;
            strategies[0].Nodes[strategies[0].FindNode("0d2 0p1", null)].Probab         = 1;

            VisStrategyTree.Show(strategies[0], "kuhn8-eq-0-adj.gv");


            Br br = new Br {
                ActionTree = at, ChanceTree = ct, HeroPosition = 1
            };

            br.Strategies = new StrategyTree[] { strategies[0], null };
            br.Solve();
            StrategyTree br0 = br.Strategies[1];

            Console.WriteLine("Br against pos 0: {0}", br.Value);
            VisStrategyTree.Show(strategies[1], "kuhn8-eq-br-0.gv");
        }
예제 #13
0
            public GameDefParams(GameValue_Test test, string gameDefFile, string[] strategyFiles, double[] expectedResult, double epsilon)
            {
                Epsilon        = epsilon;
                ExpectedResult = expectedResult;

                GameDef = XmlSerializerExt.Deserialize <GameDefinition>(
                    Props.Global.Expand("${bds.DataDir}ai.pkr.metastrategy/${0}",
                                        gameDefFile));

                Name = GameDef.Name;

                StrategyFiles = new string[GameDef.MinPlayers].Fill(i => Path.Combine(test._testResDir, strategyFiles[i]));

                StrategyTrees = new StrategyTree[GameDef.MinPlayers].Fill(i =>
                                                                          XmlToStrategyTree.Convert(StrategyFiles[i], GameDef.DeckDescr));

                ChanceTree = CreateChanceTreeByGameDef.Create(GameDef);
                ActionTree = CreateActionTreeByGameDef.Create(GameDef);
            }
예제 #14
0
        private static bool ProcessActionTree()
        {
            ActionTree tree;

            if (_cmdLine.Input != "")
            {
                tree = UFTree.Read <ActionTree>(_cmdLine.Input);
            }
            else
            {
                tree = CreateActionTreeByGameDef.Create(_gd);
            }

            if (_outputFormat == ".gv")
            {
                using (TextWriter w = new StreamWriter(File.Open(_cmdLine.Output, FileMode.Create)))
                {
                    VisActionTree vis = new VisActionTree {
                        Output = w
                    };
                    if (_cmdLine.ClearExpr)
                    {
                        vis.ShowExpr.Clear();
                    }
                    vis.ShowExprFromString(_cmdLine.ShowExpr);
                    vis.PruneIfExt = (t, n, s, d) => s[d].Round > _cmdLine.MaxRound;
                    vis.MatchPath  = _cmdLine.MatchPath;
                    vis.Show(tree);
                }
            }
            else if (_outputFormat == ".dat")
            {
                tree.Write(_cmdLine.Output);
            }
            else
            {
                Console.Error.WriteLine("Unsupported output format '{0}' for tree kind '{1}'", _outputFormat, _cmdLine.TreeKind);
                return(false);
            }
            return(true);
        }
예제 #15
0
            public TestParams(Breb_Test test, string gameDefFile,
                              IChanceAbstraction chanceAbstr, double epsilon)
            {
                Epsilon           = epsilon;
                GameDef           = XmlSerializerExt.Deserialize <GameDefinition>(Props.Global.Expand("${bds.DataDir}ai.pkr.metastrategy/${0}", gameDefFile));
                Name              = chanceAbstr == null ? GameDef.Name : chanceAbstr.Name;
                ChanceAbstraction = chanceAbstr;

                ActionTree = CreateActionTreeByGameDef.Create(GameDef);
                Debug.Assert(GameDef.MinPlayers == 2);
                if (chanceAbstr == null)
                {
                    ChanceTree = CreateChanceTreeByGameDef.Create(GameDef);
                }
                else
                {
                    ChanceTree = CreateChanceTreeByAbstraction.CreateS(GameDef,
                                                                       new IChanceAbstraction[]
                                                                       { chanceAbstr, chanceAbstr });
                }
            }
예제 #16
0
        public void Test_Verify()
        {
            string [] strFiles = new string[] { "eq-KunhPoker-0-s.xml", "eq-KunhPoker-1-s.xml" };

            GameDefinition gd = XmlSerializerExt.Deserialize <GameDefinition>(
                Props.Global.Expand("${bds.DataDir}ai.pkr.metastrategy/kuhn.gamedef.xml"));

            StrategyTree[] st = new StrategyTree[gd.MinPlayers];
            for (int i = 0; i < gd.MinPlayers; ++i)
            {
                string strPath = Path.Combine(_testResDir, strFiles[i]);
                st[i] = XmlToStrategyTree.Convert(strPath, gd.DeckDescr);
            }
            ActionTree at = CreateActionTreeByGameDef.Create(gd);
            ChanceTree ct = CreateChanceTreeByGameDef.Create(gd);
            string     error;

            Assert.IsTrue(VerifyEq.Verify(at, ct, st, 0.0000001, out error), error);
            // Now modify the strategy (with a J: not always fold to a r)
            st[1].Nodes[10].Probab = 0.5;
            st[1].Nodes[11].Probab = 0.5;
            Assert.IsFalse(VerifyEq.Verify(at, ct, st, 0.0000001, out error));
        }
예제 #17
0
        void SolveGame(string runDir, GameDefinition gd, IChanceAbstraction [] chanceAbstractions, double [] brValues)
        {
            ChanceTree ct = CreateChanceTreeByAbstraction.CreateS(gd, chanceAbstractions);
            ActionTree at = CreateActionTreeByGameDef.Create(gd);

            double[]       eqValues;
            StrategyTree[] eqStrategies = EqLp.Solve(at, ct, out eqValues);

            string error;

            for (int p = 0; p < gd.MinPlayers; ++p)
            {
                Assert.IsTrue(VerifyAbsStrategy.Verify(eqStrategies[p], p, 1e-7, out error), error);
            }
            // Verify eq
            Assert.IsTrue(VerifyEq.Verify(at, ct, eqStrategies, 1e-7, out error), error);

            StrategyTree[] brStrategies = new StrategyTree[gd.MinPlayers];

            // Find BR for each position
            for (int heroPos = 0; heroPos < gd.MinPlayers; ++heroPos)
            {
                Br br = new Br
                {
                    HeroPosition = heroPos,
                    ActionTree   = at,
                    ChanceTree   = ct,
                    Strategies   = (StrategyTree[])eqStrategies.Clone()
                };
                br.Solve();
                brStrategies[heroPos] = br.Strategies[heroPos];
                brValues[heroPos]     = br.Value;
            }

            MergeAndSaveStrategies(runDir, "", eqStrategies, chanceAbstractions);
            MergeAndSaveStrategies(runDir, "-br", brStrategies, chanceAbstractions);
        }
예제 #18
0
        private static bool ProcessStrategyTree()
        {
            StrategyTree tree;

            if (_cmdLine.Input != "")
            {
                if (_inputFormat == ".dat")
                {
                    tree = UFTree.Read <StrategyTree>(_cmdLine.Input);
                }
                else if (_inputFormat == ".txt")
                {
                    tree = DumpStrategyTree.FromTxt(_cmdLine.Input);
                }
                else
                {
                    Console.Error.WriteLine("Unsupported input format '{0}' for tree kind '{1}'", _inputFormat, _cmdLine.TreeKind);
                    return(false);
                }
            }
            else
            {
                ActionTree at  = CreateActionTreeByGameDef.Create(_gd);
                ChanceTree ct  = CreateChanceTreeByGameDef.Create(_gd);
                ChanceTree pct = ExtractPlayerChanceTree.ExtractS(ct, _cmdLine.Position);
                tree = CreateStrategyTreeByChanceAndActionTrees.CreateS(pct, at);
            }

            if (_outputFormat == ".gv")
            {
                using (TextWriter w = new StreamWriter(File.Open(_cmdLine.Output, FileMode.Create)))
                {
                    VisStrategyTree vis = new VisStrategyTree {
                        Output = w
                    };
                    if (_gd != null)
                    {
                        vis.CardNames = _gd.DeckDescr.CardNames;
                    }
                    if (_cmdLine.ClearExpr)
                    {
                        vis.ShowExpr.Clear();
                    }
                    vis.ShowExprFromString(_cmdLine.ShowExpr);
                    vis.PruneIfExt = (t, n, s, d) => s[d].Round > _cmdLine.MaxRound;
                    vis.MatchPath  = _cmdLine.MatchPath;
                    vis.Show(tree, _cmdLine.Root);
                }
            }
            else if (_outputFormat == ".xml")
            {
                using (TextWriter w = new StreamWriter(File.Open(_cmdLine.Output, FileMode.Create)))
                {
                    XmlWriterSettings settings = new XmlWriterSettings();
                    settings.Encoding = Encoding.ASCII;
                    settings.Indent   = true;
                    using (XmlWriter xmlWriter = XmlWriter.Create(w, settings))
                    {
                        StrategyTreeToXml xmlizer = new StrategyTreeToXml {
                            Output = xmlWriter
                        };
                        if (_cmdLine.ClearExpr)
                        {
                            xmlizer.ShowExpr.Clear();
                        }
                        xmlizer.ShowExprFromString(_cmdLine.ShowExpr);
                        xmlizer.Convert(tree);
                    }
                }
            }
            else if (_outputFormat == ".dat")
            {
                tree.Write(_cmdLine.Output);
            }
            else if (_outputFormat == ".txt")
            {
                DumpStrategyTree.ToTxt(tree, _cmdLine.Output);
            }
            else
            {
                Console.Error.WriteLine("Unsupported ouput format '{0}' for tree kind '{1}'", _outputFormat, _cmdLine.TreeKind);
                return(false);
            }
            return(true);
        }