示例#1
0
        public void Test_Merge()
        {
            IChanceAbstraction[] chanceAbstractions = new IChanceAbstraction[]
            {
                new LeducHeChanceAbstraction(LeducHeChanceAbstraction.FractionalResult),
                new LeducHeChanceAbstraction(LeducHeChanceAbstraction.FractionalResult)
            };

            CtMcGen.Tree tree1 = CtMcGen.Generate(_leducHeGd, chanceAbstractions, false, 10000, 333, null);
            CtMcGen.Tree tree2 = CtMcGen.Generate(_leducHeGd, chanceAbstractions, false, 10000, 333, null);

            UInt64 expSamplesCount = tree1.SamplesCount + tree2.SamplesCount;

            string fileName = Path.Combine(_outDir, "ctmcgen-tree2.dat");

            tree2.Write(fileName);
            tree1.Read(fileName);

            Assert.AreEqual(expSamplesCount, tree1.SamplesCount);

            ChanceTree ct1 = tree1.ConvertToChanceTree();
            ChanceTree ct2 = tree2.ConvertToChanceTree();

            // Compare two chance trees, they must be exactly the same.
            CompareChanceTrees cmp = new CompareChanceTrees();

            cmp.Compare(ct1, ct2);
            Assert.AreEqual(0, cmp.SumProbabDiff);
            for (int p = 0; p < chanceAbstractions.Length; ++p)
            {
                Assert.AreEqual(0, cmp.SumPotShareDiff[p]);
            }
        }
示例#2
0
        static int Main(string[] args)
        {
            if (!Parser.ParseArgumentsWithUsage(args, _cmdLine))
            {
                return(1);
            }
            if (_cmdLine.DebuggerLaunch)
            {
                Debugger.Launch();
            }

            foreach (string propsFile in _cmdLine.PropsFiles)
            {
                Console.WriteLine("Input file: {0}", propsFile);
                IChanceAbstraction ca = ChanceAbstractionHelper.CreateFromPropsFile(propsFile);
                if (_cmdLine.PreflopRanges)
                {
                    AnalyzeHeChanceAbstraction.PrintPreflopRanges(ca);
                }
                ShowHands(ca);
                Console.WriteLine();
            }

            return(0);
        }
示例#3
0
        public void Test_ReadWrite()
        {
            IChanceAbstraction[] chanceAbstractions = new IChanceAbstraction[]
            {
                new LeducHeChanceAbstraction(LeducHeChanceAbstraction.FractionalResult),
                new LeducHeChanceAbstraction(LeducHeChanceAbstraction.FractionalResult)
            };

            CtMcGen.Tree tree1 = CtMcGen.Generate(_leducHeGd, chanceAbstractions, false, 10000, (int)DateTime.Now.Ticks, null);
            ChanceTree   ct1   = tree1.ConvertToChanceTree();

            string fileName = Path.Combine(_outDir, "ctmcgen-tree.dat");

            tree1.Write(fileName);
            CtMcGen.Tree tree2 = new CtMcGen.Tree();
            tree2.Read(fileName);

            // Compare public data
            Assert.AreEqual(tree1.CalculateLeavesCount(), tree2.CalculateLeavesCount());
            Assert.AreEqual(tree1.SamplesCount, tree2.SamplesCount);
            Assert.AreEqual(tree1.Version, tree2.Version);

            ChanceTree ct2 = tree2.ConvertToChanceTree();

            // Compare two chance trees, they must be exactly the same.
            CompareChanceTrees cmp = new CompareChanceTrees();

            cmp.Compare(ct1, ct2);
            Assert.AreEqual(0, cmp.SumProbabDiff);
            for (int p = 0; p < chanceAbstractions.Length; ++p)
            {
                Assert.AreEqual(0, cmp.SumPotShareDiff[p]);
            }
        }
 public static IChanceAbstraction[] CreateFromPropsFiles(string[] fileNames)
 {
     IChanceAbstraction[] result = new IChanceAbstraction[fileNames.Length];
     for (int i = 0; i < result.Length; ++i)
     {
         result[i] = CreateFromPropsFile(fileNames[i]);
     }
     return(result);
 }
            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
 public void Test_Leduc__FullGame_FractionalResult()
 {
     IChanceAbstraction[] chanceAbstractions = new IChanceAbstraction[]
     {
         new LeducHeChanceAbstraction(LeducHeChanceAbstraction.FullGame),
         new LeducHeChanceAbstraction(LeducHeChanceAbstraction.FractionalResult)
     };
     // Typical situation - many runs
     GenerateAndVerifyCT("fgfr", _leducHeGd, chanceAbstractions, false, 100000, 10, 0.01, 0, 0.01, true);
     // Do one run only
     GenerateAndVerifyCT("fgfr", _leducHeGd, chanceAbstractions, false, 1000000, 1, 0.01, 0, 0.01, true);
     // Extreme case - very short runs (skip read/write).
     GenerateAndVerifyCT("fgfr", _leducHeGd, chanceAbstractions, false, 10, 10000, 0.05, 0, 0.05, true);
 }
示例#7
0
        static int Main(string[] args)
        {
            if (!Parser.ParseArgumentsWithUsage(args, _cmdLine))
            {
                return(1);
            }
            if (_cmdLine.DebuggerLaunch)
            {
                Debugger.Launch();
            }
            Props caProps = XmlSerializerExt.Deserialize <Props>(_cmdLine.ChanceAbstractionFile);

            caProps.Set("IsCreatingClusterTree", "true");

            IChanceAbstraction ca = ChanceAbstractionHelper.CreateFromProps(caProps);

            Console.WriteLine("CA: {0}", ca.Name);

            List <int> samplesCount = new List <int>();

            foreach (string sc in  _cmdLine.SamplesCount.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
            {
                samplesCount.Add(int.Parse(sc));
            }

            int rngSeed = _cmdLine.RngSeed == 0 ? (int)DateTime.Now.Ticks : _cmdLine.RngSeed;

            Console.WriteLine("RNG seed: {0}", rngSeed);

            CaMcGen gen = new CaMcGen
            {
                Clusterizer = (IClusterizer)ca,
                IsVerbose   = true,
                // IsVerboseSamples = true,
                RngSeed      = rngSeed,
                SamplesCount = samplesCount.ToArray()
            };

            ClusterTree rt = new ClusterTree();

            rt.Root = gen.Generate();
            string dir      = Path.GetDirectoryName(_cmdLine.ChanceAbstractionFile);
            string file     = Path.GetFileNameWithoutExtension(_cmdLine.ChanceAbstractionFile) + ".dat";
            string fileName = Path.Combine(dir, file);

            Console.WriteLine("Writing range tree to {0}", fileName);
            rt.Write(fileName);

            return(0);
        }
示例#8
0
        public void Benchmark_Generate()
        {
            IChanceAbstraction[] chanceAbstractions = new IChanceAbstraction[]
            {
                new LeducHeChanceAbstraction(LeducHeChanceAbstraction.FullGame),
                new LeducHeChanceAbstraction(LeducHeChanceAbstraction.FullGame)
            };

            int      repCount  = 5000000;
            DateTime startTime = DateTime.Now;

            CtMcGen.Generate(_leducHeGd, chanceAbstractions, false, repCount, 1, null);
            double time = (DateTime.Now - startTime).TotalSeconds;

            Console.WriteLine("Repetitions: {0:0,0}, time: {1:0.0} s, {2:0,0} r/s", repCount, time, repCount / time);
        }
示例#9
0
        private static void ShowHands(IChanceAbstraction ca)
        {
            if (_cmdLine.Hands == null)
            {
                return;
            }

            foreach (string handS in _cmdLine.Hands)
            {
                handS.Trim();
                if (handS.Length % 2 != 0)
                {
                    Console.WriteLine("Wrong HE hand: {0}", handS);
                    continue;
                }
                string cards = "";
                for (int i = 0; i < handS.Length; i += 2)
                {
                    cards += handS.Substring(i, 2) + " ";
                }
                int[] hand = null;
                try
                {
                    hand = StdDeck.Descriptor.GetIndexes(cards);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Wrong HE hand: {0}, {1}", cards, e.ToString());
                    continue;
                }
                int round = HeHelper.HandSizeToRound[hand.Length];
                if (round == -1)
                {
                    Console.WriteLine("Wrong HE hand size: {0}", handS);
                    continue;
                }
                Console.Write("Abstract cards for hand {0}:", StdDeck.Descriptor.GetCardNames(hand));
                for (int r = 0; r <= round; ++r)
                {
                    int abstrCard = ca.GetAbstractCard(hand, HeHelper.RoundToHandSize[r]);
                    Console.Write(" {0}", abstrCard);
                }
                Console.WriteLine();
            }
        }
        public static IChanceAbstraction CreateFromProps(Props props)
        {
            ClassFactoryParams cfp = new ClassFactoryParams
            {
                TypeName     = props.Get("TypeName"),
                AssemblyFile = props.Get("AssemblyFileName"),
                Arguments    = new object[] { props }
            };

            if (string.IsNullOrEmpty(cfp.TypeName))
            {
                throw new ApplicationException("Missing required property 'TypeName'");
            }

            IChanceAbstraction ca = ClassFactory.CreateInstance <IChanceAbstraction>(cfp);

            return(ca);
        }
示例#11
0
        /// <summary>
        /// Creates files for each chance abstraction based on the template file.
        /// Tries to reuse the same chance abstration if buckets strings are the same
        /// to test Patience in this mode.
        /// </summary>
        /// <param name="runDir"></param>
        /// <param name="bucketizerStrings"></param>
        /// <returns></returns>
        private IChanceAbstraction[] PrepareConfigsAndChanceAbstractions(string runDir, string[] bucketizerStrings)
        {
            string botPropsFile = Path.Combine(runDir, "props.xml");
            Props  botProps     = XmlSerializerExt.Deserialize <Props>(botPropsFile);

            IChanceAbstraction[] chanceAbstractions = new IChanceAbstraction[bucketizerStrings.Length];

            string caPropsTemplateFile = Path.Combine(runDir, "chance-abstraction-props-template.xml");

            for (int p = 0; p < bucketizerStrings.Length; ++p)
            {
                for (int p1 = 0; p1 < p; ++p1)
                {
                    // Try to reuse the same chance abstraction.
                    if (bucketizerStrings[p1] == bucketizerStrings[p])
                    {
                        botProps.Set(string.Format("ChanceAbstraction-{0}", p),
                                     string.Format("chance-abstraction-props-{0}.xml", p1));
                        botProps.Set(string.Format("Strategy-{0}", p), string.Format("strategy-{0}.dat", p1));
                        chanceAbstractions[p] = chanceAbstractions[p1];
                        goto next;
                    }
                }

                Props caProps = XmlSerializerExt.Deserialize <Props>(caPropsTemplateFile);
                caProps.Set("BucketsString", bucketizerStrings[p]);
                botProps.Set(string.Format("ChanceAbstraction-{0}", p),
                             string.Format("chance-abstraction-props-{0}.xml", p));

                string caPropsFileRel = string.Format("chance-abstraction-props-{0}.xml", p);
                string caPropsFileAbs = Path.Combine(runDir, caPropsFileRel);
                XmlSerializerExt.Serialize(caProps, caPropsFileAbs);
                botProps.Set(string.Format("ChanceAbstraction-{0}", p), caPropsFileRel);
                botProps.Set(string.Format("Strategy-{0}", p), string.Format("strategy-{0}.dat", p));

                chanceAbstractions[p] = ChanceAbstractionHelper.CreateFromProps(caProps);

                next :;
            }
            XmlSerializerExt.Serialize(botProps, botPropsFile);
            File.Delete(caPropsTemplateFile);
            return(chanceAbstractions);
        }
示例#12
0
        public static void PrintPreflopRanges(IChanceAbstraction ca)
        {
            List <HePocketKind>[] abstrRanges = new List <HePocketKind> [0];
            int[] abstrRangesSizes            = new int[0];

            for (int p = 0; p < (int)HePocketKind.__Count; ++p)
            {
                HePocketKind kind      = (HePocketKind)p;
                CardSet      pocketCS  = HePocket.KindToCardSet(kind);
                int []       pocketArr = StdDeck.Descriptor.GetIndexesAscending(pocketCS).ToArray();
                int          abstrCard = ca.GetAbstractCard(pocketArr, pocketArr.Length);

                if (abstrCard >= abstrRanges.Length)
                {
                    Array.Resize(ref abstrRanges, abstrCard + 1);
                    Array.Resize(ref abstrRangesSizes, abstrCard + 1);
                }
                if (abstrRanges[abstrCard] == null)
                {
                    abstrRanges[abstrCard] = new List <HePocketKind>();
                }

                abstrRanges[abstrCard].Add(kind);
                abstrRangesSizes[abstrCard] += HePocket.KindToRange(kind).Length;
            }

            Console.WriteLine("Preflop ranges of CA: {0}", ca.Name);
            int total = 0;

            for (int i = abstrRanges.Length - 1; i >= 0; --i)
            {
                Console.Write("{0,2} ({1,4}):", i, abstrRangesSizes[i]);
                foreach (HePocketKind k in abstrRanges[i])
                {
                    Console.Write(" {0}", HePocket.KindToString(k));
                }
                Console.WriteLine();
                total += abstrRangesSizes[i];
            }
            Console.WriteLine("Total: {0}", total);
        }
示例#13
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 });
                }
            }
        public void Test_Kuhn()
        {
            GameDefinition gd = XmlSerializerExt.Deserialize <GameDefinition>(
                Props.Global.Expand("${bds.DataDir}ai.pkr.metastrategy/kuhn.gamedef.xml"));

            IChanceAbstraction[] abstractions = new IChanceAbstraction [] { new KuhnChanceAbstraction(), new KuhnChanceAbstraction() };

            ChanceTree ct  = CreateChanceTreeByGameDef.Create(gd);
            ChanceTree act = CreateChanceTreeByAbstraction.CreateS(gd, abstractions);

            VerifyChanceTree.VerifyS(act);

            VisChanceTree.Show(act, Path.Combine(_outDir, gd.Name + "-abct.gv"));

            UInt16[] activePlayersOne = ActivePlayers.Get(gd.MinPlayers, 1, 1);
            UInt16[] activePlayersAll = ActivePlayers.Get(gd.MinPlayers, 1, gd.MinPlayers);
            int      maxDepth         = gd.RoundsCount * gd.MinPlayers;

            Assert.AreEqual(act.PlayersCount, gd.MinPlayers);
            Assert.AreEqual(ct.NodesCount, act.NodesCount);
            double[] expPotShares = new double[gd.MinPlayers];
            double[] actPotShares = new double[gd.MinPlayers];
            for (int i = 0; i < ct.NodesCount; ++i)
            {
                Assert.AreEqual(ct.Nodes[i].Position, act.Nodes[i].Position);
                Assert.AreEqual(ct.Nodes[i].Card, act.Nodes[i].Card); // Kuhn abstraction has the same card
                Assert.AreEqual(ct.Nodes[i].Probab, act.Nodes[i].Probab);
                if (i == 0)
                {
                    continue;
                }
                UInt16[] activePlayers = ct.GetDepth(i) == maxDepth ? activePlayersAll : activePlayersOne;
                foreach (UInt16 ap in activePlayers)
                {
                    ct.Nodes[i].GetPotShare(ap, expPotShares);
                    act.Nodes[i].GetPotShare(ap, actPotShares);
                    Assert.AreEqual(expPotShares, actPotShares, String.Format("Node: {0}, ap: {1}", i, ap));
                }
            }
        }
示例#15
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));

            if (gd.MinPlayers != _cmdLine.ChanceAbstractionFiles.Length)
            {
                Console.WriteLine("Number of chance abstractions ({0}) does not match to the minimal number of players in game definition ({1})",
                                  _cmdLine.ChanceAbstractionFiles.Length, gd.MinPlayers);
                return(1);
            }

            IChanceAbstraction[] chanceAbstractions = new IChanceAbstraction[_cmdLine.ChanceAbstractionFiles.Length];
            bool   areAbstractionsEqual             = true;
            string fileName0 = _cmdLine.ChanceAbstractionFiles[0].Get().ToUpperInvariant();

            for (int p = 0; p < chanceAbstractions.Length; ++p)
            {
                string fileName = _cmdLine.ChanceAbstractionFiles[p];
                if (fileName.ToUpperInvariant() != fileName0)
                {
                    areAbstractionsEqual = false;
                }
                chanceAbstractions[p] = ChanceAbstractionHelper.CreateFromPropsFile(fileName);
                Console.WriteLine("CA pos {0}: {1}", p, chanceAbstractions[p].Name);
            }

            Console.WriteLine("Abstractions are {0}.", areAbstractionsEqual ? "equal" : "unequal");
            Console.Write("Samples: {0:#,#}. ", _cmdLine.SamplesCount);

            if (_cmdLine.RunsCount > 0)
            {
                Console.Write("Runs: {0:#,#}", _cmdLine.RunsCount);
            }
            else
            {
                Console.WriteLine("Runs: unlimited");
                Console.Write("Press 'q' to quit asap, 'f' to finish run.");
            }
            Console.WriteLine();

            for (int run = 0; ;)
            {
                int rngSeed = (int)DateTime.Now.Ticks;

                Console.Write("Run:{0}, seed:{1}. ", run, rngSeed);

                DateTime startTime = DateTime.Now;

                CtMcGen.Tree tree = CtMcGen.Generate(gd, chanceAbstractions, areAbstractionsEqual, _cmdLine.SamplesCount, rngSeed, Feedback);

                double genTime = (DateTime.Now - startTime).TotalSeconds;

                string fileName = SaveFile(tree, gd, chanceAbstractions);

                Int64 samplesDone = (Int64)tree.SamplesCount;

                Console.WriteLine("Samples: {0:#,#}, time: {1:0.0} s, {2:#,#} sm/s, file: {3}",
                                  samplesDone,
                                  genTime,
                                  samplesDone / genTime,
                                  fileName);

                ++run;
                if (_cmdLine.RunsCount > 0)
                {
                    if (run >= _cmdLine.RunsCount)
                    {
                        break;
                    }
                }
                else
                {
                    ProcessKeys();
                    if (_quitAsap || _finishRun)
                    {
                        Console.WriteLine("Exiting on user request");
                        break;
                    }
                }
            }
            return(0);
        }
示例#16
0
        void Initialize()
        {
            _playerInfoProps = new Props();
            string strDir = _creationParams.Get("StrategyDir");

            _playerInfoProps.Set("StrategyDir", strDir);
            string propsFile = Path.Combine(strDir, "props.xml");
            Props  props     = XmlSerializerExt.Deserialize <Props>(propsFile);

            int rngSeed = int.Parse(_creationParams.GetDefault("RngSeed", "0"));

            if (rngSeed == 0)
            {
                rngSeed = (int)DateTime.Now.Ticks;
            }

            _checkBlinds = bool.Parse(_creationParams.GetDefault("CheckBlinds", "true"));

            string amountCompareMethodText = _creationParams.GetDefault("AmountSearchMethod", "Equal");

            if (amountCompareMethodText == "Equal")
            {
                _amountSearchMethod = AmountSearchMethod.Equal;
            }
            else if (amountCompareMethodText == "Closest")
            {
                _amountSearchMethod = AmountSearchMethod.Closest;
            }
            else
            {
                throw new ApplicationException(string.Format("Unknown amount compare method {0}", amountCompareMethodText));
            }

            _relProbabIgnoreLevel = double.Parse(_creationParams.GetDefault("RelProbabIgnoreLevel", "0.0"), CultureInfo.InvariantCulture);
            _playerInfoProps.Set("RelProbabIgnoreLevel", _relProbabIgnoreLevel.ToString());

            // Use MersenneTwister because it is under our control on all platforms and
            // is probably better than System.Random.
            Random underlyingRng = new MersenneTwister(rngSeed);

            _moveSelector = new DiscreteProbabilityRng(underlyingRng);
            _playerInfoProps.Set("RngSeed", rngSeed.ToString());

            _deckDescr = XmlSerializerExt.Deserialize <DeckDescriptor>(props.Get("DeckDescriptor"));

            _chanceAbsrtractions = new IChanceAbstraction[0];

            // Create chance abstractions
            for (int pos = 0; ; pos++)
            {
                string caPropName  = String.Format("ChanceAbstraction-{0}", pos);
                string relFileName = props.Get(caPropName);
                if (string.IsNullOrEmpty(relFileName))
                {
                    break;
                }
                Array.Resize(ref _chanceAbsrtractions, _chanceAbsrtractions.Length + 1);

                string absFileName = Path.Combine(strDir, relFileName);
                _chanceAbsrtractions[pos] = ChanceAbstractionHelper.CreateFromPropsFile(absFileName);
                _playerInfoProps.Set(caPropName + ".Name", _chanceAbsrtractions[pos].Name);
            }

            Dictionary <string, int> fileToPos = new Dictionary <string, int>();

            _strategies = new StrategyTree[0];
            _strIndexes = new UFTreeChildrenIndex[0];

            // Load strategies, reuse if file is the same
            for (int pos = 0; ; pos++)
            {
                string strPropName = String.Format("Strategy-{0}", pos);
                string relFileName = props.Get(strPropName);
                if (string.IsNullOrEmpty(relFileName))
                {
                    break;
                }
                Array.Resize(ref _strategies, _strategies.Length + 1);
                Array.Resize(ref _strIndexes, _strIndexes.Length + 1);

                string absFileName = Path.Combine(strDir, relFileName);
                int    existingPos;
                if (fileToPos.TryGetValue(absFileName, out existingPos))
                {
                    _strategies[pos] = _strategies[existingPos];
                    _strIndexes[pos] = _strIndexes[existingPos];
                }
                else
                {
                    fileToPos.Add(absFileName, pos);
                    _strategies[pos] = StrategyTree.ReadFDA <StrategyTree>(absFileName);
                    _strIndexes[pos] = new UFTreeChildrenIndex(_strategies[pos], Path.Combine(strDir, "strategy-idx.dat"), false);
                }
                _playerInfoProps.Set(strPropName + ".Version", _strategies[pos].Version.ToString());
            }

            // Read blinds
            for (int strPos = 0; strPos < _strategies.Length; ++strPos)
            {
                StringBuilder sb = new StringBuilder();
                for (int playerPos = 0; playerPos < _strategies.Length; ++playerPos)
                {
                    StrategyTreeNode stNode = new StrategyTreeNode();
                    _strategies[strPos].GetNode(playerPos + 1, &stNode);
                    sb.AppendFormat("{0:0.000000 }", stNode.Amount);
                }
                _playerInfoProps.Set("Blinds." + strPos.ToString(), sb.ToString());
            }
        }