void AiMove(Board board) { IMoveStrategy minimax = new AlphaBeta(4); Move bestMove = minimax.execute(board); Action aFunction = () => { Debug.Log(minimax.getMessage()); //BoardManager.Instance.moveMadeUpdate(PlayerType.COMPUTER); var sourceCoordinate = GetXAndY(bestMove.getCurrentCoordinate()); var destinationCoordinate = GetXAndY(bestMove.getDestinationCoordinate()); selectedChessPiece = chessPieces[sourceCoordinate.Key, sourceCoordinate.Value]; sourceTile = board.getTile(bestMove.getCurrentCoordinate()); movedPiece = sourceTile.getPiece(); if (movedPiece == null) { sourceTile = null; } int tileCoordinate = bestMove.getDestinationCoordinate(); selectionX = destinationCoordinate.Key; selectionY = destinationCoordinate.Value; moveChessPiece(tileCoordinate, selectionX, selectionY); }; QueueMainThreadFunction(aFunction); }
string GenDetABLabelStr(AlphaBeta AB) { if (AB.α == null || AB.β == null) { return("AB nil"); } int αidx = 0; for (αidx = AB.α.Length - 1; αidx > 0; αidx--) { if (AB.α[αidx] != 0) { break; } } int βidx = 0; for (βidx = AB.β.Length - 1; βidx > 0; βidx--) { if (AB.β[βidx] != 0) { break; } } int mx = Math.Max(αidx, βidx); int minl = Math.Min(αidx, βidx); double[] potential = new double[4]; potential[0] = αidx; potential[1] = AB.α[αidx]; potential[2] = βidx; potential[3] = AB.β[βidx]; return(string.Format("AB {0,4}:{1,8}{2,4}:{3,8}", potential[0], potential[1], potential[2], potential[3])); }
public void MakeMoveTest() { Board board = new Board(); bool? win; AlphaBeta alphaBeta = new AlphaBeta(); int result = 0; //_______ //X_X_X_X //board.PutToken(0); //board.PutToken(2); //board.PutToken(4); //board.PutToken(6); //alphaBeta.MakeMove(false, board); //O_____ //O_____ //O___XX board = new Board(); board.PutToken(1); board.PutToken(1); board.PutToken(1); board.PutToken(6); board.PutToken(5); alphaBeta.MakeMove(true, true, board); }
public void CheckThirdSituationDiagonallyTest() { Board board = new Board(); bool? win; AlphaBeta alphaBeta = new AlphaBeta(); int result = 0; //XX_____ //XX_____ board.PutToken(0); board.PutToken(0); board.PutToken(1); board.PutToken(1); alphaBeta.CheckThirdSituationDiagonally(true, board, ref result); Assert.AreEqual(result, 30000); //XX___XX //XX___XX board.PutToken(6); board.PutToken(6); board.PutToken(5); board.PutToken(5); result = 0; alphaBeta.CheckThirdSituationDiagonally(true, board, ref result); Assert.AreEqual(result, 60000); }
//lancia un torneo su population; alla fine di tutto, ordina i pesi in population in base al migliore risultato del torneo public SortedList <WeightScore, int> LaunchTournament(SortedList <WeightScore, int> population, List <WeightsForBoardEval> testPopulation) { SortedList <WeightScore, int> newPopulation = new SortedList <WeightScore, int>(); Dictionary <WeightScore, int> scores = new Dictionary <WeightScore, int>(); for (int i = 0; i < population.Count; i++) { WeightScore ws1 = population.Keys[i]; for (int j = 0; j < testPopulation.Count; j++) { WeightsForBoardEval testPlayer = testPopulation[j]; AlphaBeta ws1AsGoose = new AlphaBeta(PawnType.Goose, 3, ws1.weights, false); AlphaBeta ws1AsFox = new AlphaBeta(PawnType.Fox, 3, ws1.weights, false); AlphaBeta ws2AsGoose = new AlphaBeta(PawnType.Goose, 3, testPlayer, false); AlphaBeta ws2AsFox = new AlphaBeta(PawnType.Fox, 3, testPlayer, false); PairOfScores pairOfScoresGoose = MatchTwoAi(ws1AsGoose, ws2AsFox, 1, i, j); PairOfScores pairOfScoresFox = MatchTwoAi(ws1AsFox, ws2AsGoose, 1, i, j); if (!scores.ContainsKey(ws1)) { scores[ws1] = 0; } scores[ws1] += pairOfScoresGoose.first; scores[ws1] += pairOfScoresFox.first; } WeightScore ws = new WeightScore(ws1.weights, scores[ws1]); newPopulation.Add(ws, scores[ws1]); } return(newPopulation); }
static void Main(string[] args) { var game = new Piskvorky3D(); var alphabeta = new AlphaBeta <Position, ulong>(game); var moves = new List <ulong>(); while (true) { var eval = alphabeta.Alphabeta_recursive(ref moves, 8, game.InitialState, double.MinValue, double.MaxValue); Console.WriteLine("Eval: " + eval); moves.Reverse(); var state = game.InitialState; //todo clone game.Apply(ref state, moves.First()); Console.WriteLine(BitBoard.DebugPrintUlong(state.White) + "\n"); Console.WriteLine(BitBoard.DebugPrintUlong(state.Black) + "\n"); int opponentMove = int.Parse(Console.ReadLine()); // todo zkontrolovat 1-16 var possibleMoves = game.Generator.GetActions(state); ulong ONE = (ulong)1; ulong column = (ONE) + (ONE << 16) + (ONE << 32) + (ONE << 48); column = (column << (opponentMove - 1)); foreach (var move in possibleMoves) { if ((column & move) != 0) { game.Apply(ref state, move); break; } } Console.WriteLine(BitBoard.DebugPrintUlong(state.White) + "\n"); Console.WriteLine(BitBoard.DebugPrintUlong(state.Black) + "\n"); } //var generator = new StonePlacementGenerator(); // //var pos = new Position(0, 0, 1); //pos.White |= ((ulong)1 << 5); //pos.White |= ((ulong)1 << 8); //pos.White |= ((ulong)1 << 0); //pos.White |= ((ulong)1 << 16); // //var a = generator.GetActions(pos); // //Console.WriteLine(BitBoard.DebugPrintUlong(pos.White) + "\n"); //Console.WriteLine(BitBoard.DebugPrintUlong(pos.Black) + "\n"); // //foreach (var item in a) //{ // Console.WriteLine(BitBoard.DebugPrintUlong(item) + "\n"); //} }
List <string> GenDetABStr(AlphaBeta AB) { List <string> ls = new List <string>(); if (AB.α == null || AB.β == null) { ls.Add(" A B"); } int αidx = 0; for (αidx = AB.α.Length - 1; αidx > 0; αidx--) { if (AB.α[αidx] != 0) { break; } } int βidx = 0; for (βidx = AB.β.Length - 1; βidx > 0; βidx--) { if (AB.β[βidx] != 0) { break; } } int mx = Math.Max(αidx, βidx); int minl = Math.Min(αidx, βidx); double[] potential = new double[4]; potential[0] = αidx; potential[1] = AB.α[αidx]; potential[2] = βidx; potential[3] = AB.β[βidx]; ls.Add(string.Format(" {0,8} {1,8}", "A", "B")); for (int i = 0; i < minl; i++) { ls.Add(string.Format("{0,4}:{1,8} {2,8}", i, AB.α[i], AB.β[i])); } for (int i = minl; i < mx; i++) // check for uneven column { if (i <= αidx && i <= βidx) { ls.Add(string.Format("{0,4}:{1,8} {2,8}", i, AB.α[i], AB.β[i])); } else if (i <= αidx && i > βidx) { ls.Add(string.Format("{0,4}:{1,8} {2,8}", i, AB.α[i], string.Empty)); } else if (i > αidx && i <= βidx) { ls.Add(string.Format("{0,4}:{1,8} {2,8}", i, string.Empty, AB.β[i])); } } return(ls); }
static void TimeAB() { var uct = new AlphaBeta(true, 5); var board = new Board(); while (board.Result == Result.None) { TimeOneMove(uct, board); } }
void FillAlgorithmComboBoxes() { IAlgorithm minMax = new MinMax(); IAlgorithm alphaBeta = new AlphaBeta(); player1AlgorithmChoice.Items.Add(minMax); player1AlgorithmChoice.Items.Add(alphaBeta); player2AlgorithmChoice.Items.Add(minMax); player2AlgorithmChoice.Items.Add(alphaBeta); }
/* Invoked when the user has chosen which player he wants to play as */ private void OnPlayerChosen(object sender, object args) { humanPlayer = (PawnType)args; cpuPlayer = humanPlayer == PawnType.Fox ? PawnType.Goose : PawnType.Fox; ClearBoard(); mainCamera.GetComponent <MoveCamera>().PositionCamera(humanPlayer); game = new Game(15, false); //weights must be in absolute value alphaBeta = new AlphaBeta(cpuPlayer, 5, new WeightsForBoardEval(4, 3, 0, -1, 0, 0, 0), false); CheckState(); if (game.turn == cpuPlayer) { AiMoves(); } }
public override int getAlphaBetaValue(GameState state) { if (getPlayerToMove(state).ToUpper().Equals("W")) { AlphaBeta initial = new AlphaBeta(int.MinValue, int.MaxValue); int max = maxValue(state, initial); return(max); } else { //invert? AlphaBeta initial = new AlphaBeta(int.MinValue, int.MaxValue); return(minValue(state, initial)); } }
public override int GetAlphaBetaValue(GameState state) { if (String.Compare(this.GetPlayerToMove(state), "X", true) == 0) { var initial = new AlphaBeta(Int32.MinValue, Int32.MaxValue); var max = MaxValue(state, initial); return(max); } else { // invert? var initial = new AlphaBeta(Int32.MinValue, Int32.MaxValue); return(MinValue(state, initial)); } }
public void CalculateCurrentBoardTest() { Board board = new Board(); bool? win; AlphaBeta alphaBeta = new AlphaBeta(); int result = 0; //_______ //X_X_X_X board.PutToken(0); board.PutToken(2); board.PutToken(4); board.PutToken(6); alphaBeta.CalculateCurrentBoard(true, board); }
public void CheckFourthSituationTest() { Board board = new Board(); bool? win; AlphaBeta alphaBeta = new AlphaBeta(); int result = 0; //_______ //X_X_X_X board.PutToken(0); board.PutToken(2); board.PutToken(4); board.PutToken(6); alphaBeta.CheckFourthSituation(true, board, ref result); Assert.AreEqual(result, 320); }
public void CheckThirdSituationTest() { Board board = new Board(); bool? win; AlphaBeta alphaBeta = new AlphaBeta(); int result = 0; //XX_____ //XX_____ board.PutToken(0); board.PutToken(0); board.PutToken(1); board.PutToken(1); alphaBeta.CheckThirdSituation(true, board, ref result); Assert.AreEqual(result, 170000); }
public override int getAlphaBetaValue(GameState state) { if (getPlayerToMove(state).equalsIgnoreCase("X")) { AlphaBeta initial = new AlphaBeta(int.MIN_VALUE, int.MAX_VALUE); int max = maxValue(state, initial); return(max); } else { // invert? AlphaBeta initial = new AlphaBeta(int.MIN_VALUE, int.MAX_VALUE); return(minValue(state, initial)); } }
private static AuxContainer PrepareContainer(OmegaModel model, decimal recieverDepth) { var alphaBeta = AlphaBeta.CreateFrom(model.Section1D); var c = AuxContainer.CreateContainer(model, 0, recieverDepth); const double lambda = 0; c.Eta = PlanCalculator.CalculateEta(model, lambda); c.Exp = PlanCalculator.CalculateExp(model, c.Eta); c.Q = PlanCalculator.CalculateQ1(alphaBeta, c.Eta, c.Exp); c.P = PlanCalculator.CalculateP1(alphaBeta, c.Eta, c.Exp); c.A = PlanCalculator.CalculateA1(model, c); return(c); }
static void MainWithOptions(Options options) { Stopwatch stopwatch = null; BoardState board = Risk.RandomizedBoardPlacement(0); var pool = new ControlledThreadPool(options.Cores - 1); if (options.Time) { stopwatch = new Stopwatch(); stopwatch.Start(); } Move move = (options.AlphaBeta, options.Parallel, options.YoungBrothersWait) switch { (true, false, true) => AlphaBeta.ParallelYbw <BoardState, Move>(board, options.MaxDepth, pool), (true, true, false) => AlphaBeta.Parallel <BoardState, Move>(board, options.MaxDepth), (true, false, false) => AlphaBeta.Serial <BoardState, Move>(board, options.MaxDepth), (false, false, true) => Minimax.ParallelYbw <BoardState, Move>(board, options.MaxDepth, pool), (false, true, false) => Minimax.Parallel <BoardState, Move>(board, options.MaxDepth), (false, false, false) => Minimax.Serial <BoardState, Move>(board, options.MaxDepth), _ => throw new ArgumentException() }; stopwatch?.Stop(); if (move.IsAttack) { Console.WriteLine($"Attack dotfrom {(Risk.Id)move.FromId} to {(Risk.Id)move.ToId}"); } else if (move.FortifyCount > 0) { Console.WriteLine($"Pass turn and fortify {move.FortifyCount} troops from {(Risk.Id)move.FromId} to {(Risk.Id)move.ToId}"); } else { Console.WriteLine("Pass turn and don't fortify."); } if (options.Time) { Console.WriteLine($"Runtime (s): {stopwatch.Elapsed.TotalSeconds}"); } }
private void StartButton_Click(object sender, EventArgs e) { ab = new AlphaBeta(); uct = new UCT(Math.Sqrt(2), 123, 100000); puct = new PUCT(Math.Sqrt(2), 123, 100000); ucb1tuned = new UCB1TUNED(1, 123, 100000); if (playerRB.Checked) { vs = VS.Player; } else if (abRB.Checked) { vs = VS.AlphaBeta; } else { vs = VS.MCTS; } if (puctRB.Checked) { algorithm = puct; } if (uctRB.Checked) { algorithm = uct; } if (tunedRB.Checked) { algorithm = ucb1tuned; } yourTurn = youStartBox.Checked; board = new Board(); firstPlayer = play = start = true; MainPanel.Invalidate(); if (!yourTurn) { PlayMove(); CheckResult(); firstPlayer = !firstPlayer; MainPanel.Invalidate(); } }
public void CheckSecondSituationVerticallyTest() { Board board = new Board(); bool? win; AlphaBeta alphaBeta = new AlphaBeta(); int result = 0; board.PutToken(1); board.PutToken(1); board.PutToken(1); alphaBeta.CheckSecondSituationVertically(true, board, ref result); Assert.AreEqual(900000, result); board.PutToken(3); board.PutToken(3); board.PutToken(3); alphaBeta.CheckSecondSituationVertically(true, board, ref result); Assert.AreEqual(int.MaxValue, result); }
public void StartTest() { MatchAlgo matchAlgo = new MatchAlgo(); GeneticAlgo geneticAlgo = new GeneticAlgo(); System.Random rand = new System.Random(); List <WeightsForBoardEval> weights = new List <WeightsForBoardEval>(); for (int i = 0; i < 50; i++) { WeightsForBoardEval w = new WeightsForBoardEval(rand); weights.Add(w); Console.WriteLine("pesInizRand = " + w); } SortedList <WeightScore, int> scoreMap = new SortedList <WeightScore, int>(); //per ogni peso = giocatore, fa giocare 3 match come oca e 3 match come volpe al giocatore contro un giocatore casuale for (int i = 0; i < weights.Count; i++) { int score = 0; WeightsForBoardEval weight = weights[i]; AlphaBeta playerAsFox = new AlphaBeta(PawnType.Fox, 3, weight, false); AlphaBeta playerAsGoose = new AlphaBeta(PawnType.Goose, 3, weight, false); score = matchAlgo.MatchTwoAi(playerAsFox, null, 3, -1, -1).first; score += matchAlgo.MatchTwoAi(playerAsGoose, null, 3, -1, -1).first; WeightScore ws = new WeightScore(weight, score); scoreMap.Add(ws, score); } Console.WriteLine("aiTester prima di evoluzione"); // evolve 50 volte la popolazione for (int i = 0; i < 50; i++) { Console.WriteLine("\n \n \n \n inizio evoluzione generazione " + i); scoreMap = geneticAlgo.Evolve(scoreMap, 0.3, 0.1, 0.01); } Console.WriteLine("best weights " + scoreMap.Keys[0]); Console.WriteLine("finito completamente aiTester ore: " + DateTime.Now.ToString("h:mm:ss tt")); Console.ReadKey(); }
Vector3 PlayerMove() { Vector3 action_ = Vector3.zero; if (select_algorithm == 1) { Minimax action = new Minimax(this, depth); action_ = action.GetAction(); } else if (select_algorithm == 2) { AlphaBeta action = new AlphaBeta(this, depth); action_ = action.GetAction(); } else if (select_algorithm == 3) { Expectimax action = new Expectimax(this, depth); action_ = action.GetAction(); } return(action_); }
private GreenScalarCalculator( ILogger logger, OmegaModel model, FieldToField ftof, IntegrationType integrationType) { if (logger == null) { throw new ArgumentNullException(nameof(logger)); } if (model == null) { throw new ArgumentNullException(nameof(model)); } _logger = logger; _model = model; _ftof = ftof; _integrationType = integrationType; _alphaBeta = AlphaBeta.CreateFrom(model.Section1D); }
IEnumerator StartGame(GameController gc) { yield return(1); TileState ts = null; //ts = RandomMove(tileStates); AlphaBeta ab = new AlphaBeta(this.MyTurnID); ab.budget = TimeBudget; ab.depthBudget = DepthBudget; ab.randomMoveInLevels = randomMoveInLevels; isMoveComputed = false; ts = null; AlphaBeta.TotalNodesEvaluated = 0; AlphaBeta.MaxTreeSize = 0; AlphaBeta.TreeSize = 0; Thread thread = new Thread(() => ab.NextMove(gc.grid.grid, gc.player_tiles[gc.currentTurn], gc.player_tiles[1 - gc.currentTurn], gc.availableTiles, callback)); thread.Start(); //this.OnPlayFinished(ts); }
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e) { List <string> ls = null; if (e.Node.Parent == null) { if (e.Node.Tag == null) { return; } else { Type t = (Type)e.Node.Tag; if (t == typeof(TestParameters)) { TestParameters d = N.App.DB.TestParameters.Get(); ls = d.ToDBElementList(generate: true).AlignedNameValueList; } } } else { object o = e.Node.Parent.Tag; if (o == null) { return; } else // display content in the right-hand pane { Type t = e.Node.Tag.GetType(); if (t == typeof(ItemId)) { ls = ((ParameterBase)e.Node.Tag).ToDBElementList(generate: true).AlignedNameValueList; } else if (t == typeof(Detector)) { ls = GenDetIdStr(((Detector)e.Node.Tag).Id); } else if (t == typeof(Isotopics)) { ls = ((ParameterBase)e.Node.Tag).ToDBElementList(generate: true).AlignedNameValueList; } else if (t == typeof(CompositeIsotopics)) { ls = ((ParameterBase)e.Node.Tag).ToDBElementList(generate: true).AlignedNameValueList; } else if (t == typeof(CollarItemId)) { ls = ((ParameterBase)e.Node.Tag).ToDBElementList(generate: true).AlignedNameValueList; } else if (t == typeof(Stratum)) { ls = ((ParameterBase)e.Node.Tag).ToDBElementList(generate: true).AlignedNameValueList; } else if (t == typeof(INCCDB.Descriptor)) { INCCDB.Descriptor d = (INCCDB.Descriptor)e.Node.Tag; ls = new List <string>(); ls.Add(d.Item1 + ": " + d.Item2); } else if (t == typeof(AnalysisMethods)) { AnalysisMethods d = (AnalysisMethods)e.Node.Tag; ls = d.ToDBElementList(generate: true).AlignedNameValueList; } else if (t == typeof(AcquireParameters)) { AcquireParameters d = (AcquireParameters)e.Node.Tag; ls = d.ToDBElementList(generate: true).AlignedNameValueList; } else if (t == typeof(AlphaBeta)) { AlphaBeta AB = (AlphaBeta)e.Node.Tag; ls = GenDetABStr(AB); } else if (t == typeof(Multiplicity)) { Multiplicity m = (Multiplicity)e.Node.Tag; ls = GenDetMultStr((Detector)o, m); } else if (t == typeof(DataSourceIdentifier)) { DataSourceIdentifier d = (DataSourceIdentifier)e.Node.Tag; ls = GenDetIdStr(d); } else if (t == typeof(INCCDB.IndexedResults)) { ls = GenMeasStr((INCCDB.IndexedResults)e.Node.Tag);; } } } StringBuilder sb = new StringBuilder(100); if (ls != null) { foreach (string s in ls) { sb.Append(s); sb.Append('\r'); } richTextBox1.Text = sb.ToString(); } }
void Awake(){ makingListEntities (); playersTurn = true; ai = new AlphaBeta(diffLevel); }
public void CheckSecondSituationDiagonallyLeftTopTest() { Board board = new Board(); bool? win; AlphaBeta alphaBeta = new AlphaBeta(); int result = 0; //O //OX______ //OXX_____ //OXXX____ board.PutToken(0); board.PutToken(0); board.PutToken(0); board.PutToken(0); board.PutToken(1); board.PutToken(1); board.PutToken(1); board.PutToken(2); board.PutToken(2); board.PutToken(3); alphaBeta.CheckSecondSituationDiagonallyLeftTop(true, board, ref result); Assert.AreEqual(50000, result); //OX //OXX //OXXX result = 0; board.RemoveToken(0); alphaBeta.CheckSecondSituationDiagonallyLeftTop(true, board, ref result); Assert.AreEqual(900000, result); //_ //_X //_XX //_XXX result = 0; board.RemoveToken(0); board.RemoveToken(0); board.RemoveToken(0); board.RemoveToken(0); alphaBeta.CheckSecondSituationDiagonallyLeftTop(true, board, ref result); Assert.AreEqual(900000, result); //_______ //__XX___ //__OOX__ //OXOXOX_ //OXOXOX_ board = new Board(); result = 0; board.PutToken(0); board.PutToken(0); board.PutToken(1); board.PutToken(1); board.PutToken(2); board.PutToken(2); board.PutToken(2); board.PutToken(2); board.PutToken(3); board.PutToken(3); board.PutToken(3); board.PutToken(3); board.PutToken(4); board.PutToken(4); board.PutToken(4); board.PutToken(5); board.PutToken(5); alphaBeta.CheckSecondSituationDiagonallyLeftTop(true, board, ref result); Assert.AreEqual(int.MaxValue, result); }
public void CheckSecondSituation() { Board board = new Board(); bool? win; AlphaBeta alphaBeta = new AlphaBeta(); int result = 0; //LEFT TOP //_______ //__XX___ //__OOX__ //OXOXOX_ //OXOXOX_ board.PutToken(0); board.PutToken(0); board.PutToken(1); board.PutToken(1); board.PutToken(2); board.PutToken(2); board.PutToken(2); board.PutToken(2); board.PutToken(3); board.PutToken(3); board.PutToken(3); board.PutToken(3); board.PutToken(4); board.PutToken(4); board.PutToken(4); board.PutToken(5); board.PutToken(5); alphaBeta.CheckSecondSituation(true, board, ref result); Assert.AreEqual(int.MaxValue, result); //RIGHT TOP //_______ //___XX__ //__XOX__ //_XOOX__ //_OXOO__ result = 0; board = new Board(); board.PutToken(1); board.PutToken(1); board.PutToken(2); board.PutToken(2); board.PutToken(2); board.PutToken(3); board.PutToken(3); board.PutToken(3); board.PutToken(3); board.PutToken(4); board.PutToken(4); board.PutToken(4); board.PutToken(4); alphaBeta.CheckSecondSituation(true, board, ref result); Assert.AreEqual(int.MaxValue, result); //VERTICALLY //_______ //____X__ //__XOXX_ //_XOOXX_ //_OXOOX_ board.RemoveToken(3); result = 0; board.PutToken(5); board.PutToken(5); board.PutToken(5); alphaBeta.CheckSecondSituation(true, board, ref result); Assert.AreEqual(int.MaxValue, result); //HORIZONTALLY //_XXX_ //OOXOX //OOOXO board = new Board(); result = 0; board.PutToken(0); board.PutToken(0); board.PutToken(1); board.PutToken(1); board.PutToken(1); board.PutToken(2); board.PutToken(2); board.PutToken(2); board.PutToken(3); board.PutToken(3); board.PutToken(3); board.PutToken(4); board.PutToken(4); alphaBeta.CheckSecondSituation(true, board, ref result); Assert.AreEqual(int.MaxValue, result); }
/// <summary> /// Calc alpha beta, save result in cache /// NEXT: extend with Numerics.BigInteger replacing BigFloat, as per above (for when phi is non-zero) /// </summary> /// <param name="key">three values needed for alpha beta (max bin count, gatewidth, phi aka multiplicity T) </param> /// <param name="AB">The alpha beta array as used on detectors and multiplicity counting results</param> public static void SetAlphaBeta(ABKey key, AlphaBeta AB) { AlphaBeta _AB = AlphaBetaCache.GetAlphaBeta(key); if (_AB != null) { AB.α = _AB.α; AB.β = _AB.β; return; } if (key.bins != AB.α.Length) { AB.Resize((int)key.bins + 1); } AB.α[0] = 0.0; AB.β[0] = 0.0; if (key.deadTimeCoefficientTinNanoSecs == 0.0) { double n = 0; for (uint i = 1; i < key.bins; i++) { n = i; AB.α[i] = n; AB.β[i] = (n * (n - 1.0)) / 2.0; } } else if (key.gateWidthTics != 0.0) { uint biggestKey = key.bins - 1; AB.Init((int)key.bins); if (biggestKey <= 1) { goto cache; } double gateInSeconds = key.gateWidthTics * 1e-7; double phi = (key.deadTimeCoefficientTinNanoSecs / 1E9) / gateInSeconds; AB.α[0] = 0.0; AB.α[1] = 1.0; AB.β[0] = 0.0; AB.β[1] = 0.0; if (biggestKey > 1) { for (int n = 2; n <= biggestKey; n++) { if (phi > 1e-20) { AB.α[n] = 1.0; double alphaCoeff = 0; for (int k = 0; k <= (n - 2); k++) { alphaCoeff = binomialCoefficient(n - 1, k + 1) * Math.Pow((k + 1) * phi, k) / Math.Pow(1.0 - ((k + 1) * phi), k + 2); AB.α[n] += alphaCoeff; } } else { AB.α[n] = 1.0; } } AB.β[0] = 0.0; AB.β[1] = 0.0; AB.β[2] = AB.α[2] - 1.0; for (int n = 3; n <= biggestKey; n++) { if (phi > 1e-20) { AB.β[n] = AB.α[n] - 1.0; for (int k = 0; k <= (n - 3); k++) { double betaCoeff; betaCoeff = binomialCoefficient(n - 1, k + 2) * (k + 1) * Math.Pow((k + 2) * phi, k) / Math.Pow(1.0 - ((k + 2) * phi), k + 3); AB.β[n] += betaCoeff; } } else { AB.β[n] = 0.0; } } } } cache : AlphaBetaCache.AddAlphaBeta(key, AB); }
string GenDetABLabelStr(AlphaBeta AB) { if (AB.α == null || AB.β == null) return "AB nil"; int αidx = 0; for (αidx = AB.α.Length - 1; αidx > 0; αidx--) { if (AB.α[αidx] != 0) break; } int βidx = 0; for (βidx = AB.β.Length - 1; βidx > 0; βidx--) { if (AB.β[βidx] != 0) break; } int mx = Math.Max(αidx, βidx); int minl = Math.Min(αidx, βidx); double[] potential = new double[4]; potential[0] = αidx; potential[1] = AB.α[αidx]; potential[2] = βidx; potential[3] = AB.β[βidx]; return string.Format("AB {0,4}:{1,8}{2,4}:{3,8}", potential[0], potential[1], potential[2], potential[3]); }
List<string> GenDetABStr(AlphaBeta AB) { List<string> ls = new List<string>(); if (AB.α == null || AB.β == null) ls.Add(" A B"); int αidx = 0; for (αidx = AB.α.Length - 1; αidx > 0; αidx--) { if (AB.α[αidx] != 0) break; } int βidx = 0; for (βidx = AB.β.Length - 1; βidx > 0; βidx--) { if (AB.β[βidx] != 0) break; } int mx = Math.Max(αidx, βidx); int minl = Math.Min(αidx, βidx); double[] potential = new double[4]; potential[0] = αidx; potential[1] = AB.α[αidx]; potential[2] = βidx; potential[3] = AB.β[βidx]; ls.Add(string.Format(" {0,8} {1,8}", "A", "B")); for (int i = 0; i < minl; i++) { ls.Add(string.Format("{0,4}:{1,8} {2,8}", i, AB.α[i], AB.β[i])); } for (int i = minl; i < mx; i++) // check for uneven column { if (i <= αidx && i <= βidx) ls.Add(string.Format("{0,4}:{1,8} {2,8}", i, AB.α[i], AB.β[i])); else if (i <= αidx && i > βidx) ls.Add(string.Format("{0,4}:{1,8} {2,8}", i, AB.α[i], string.Empty)); else if (i > αidx && i <= βidx) ls.Add(string.Format("{0,4}:{1,8} {2,8}", i, string.Empty, AB.β[i])); } return ls; }
public JoueurIA(string Order, char id, System.ConsoleColor color) : base(id, color) { Nom = "Mr Robot"; AlphaBeta Alphabeta = new AlphaBeta(); }
void Awake() { makingListEntities(); playersTurn = true; ai = new AlphaBeta(diffLevel); }
/// <summary> /// Calc alpha beta, save result in cache /// NEXT: extend with Numerics.BigInteger replacing BigFloat, as per above (for when phi is non-zero) /// </summary> /// <param name="key">three values needed for alpha beta (max bin count, gatewidth, phi aka multiplicity T) </param> /// <param name="AB">The alpha beta array as used on detectors and multiplicity counting results</param> public static void SetAlphaBeta(ABKey key, AlphaBeta AB) { AlphaBeta _AB = AlphaBetaCache.GetAlphaBeta(key); if (_AB != null) { AB.α = _AB.α; AB.β = _AB.β; return; } if (key.bins != AB.α.Length) AB.Resize((int)key.bins + 1); AB.α[0] = 0.0; AB.β[0] = 0.0; if (key.deadTimeCoefficientTinNanoSecs == 0.0) { double n = 0; for (uint i = 1; i < key.bins; i++) { n = i; AB.α[i] = n; AB.β[i] = (n * (n - 1.0)) / 2.0; } } else if (key.gateWidthTics != 0.0) { uint biggestKey = key.bins - 1; AB.Init((int)key.bins); if (biggestKey <= 1) goto cache; double gateInSeconds = key.gateWidthTics * 1e-7; double phi = (key.deadTimeCoefficientTinNanoSecs / 1E9) / gateInSeconds; AB.α[0] = 0.0; AB.α[1] = 1.0; AB.β[0] = 0.0; AB.β[1] = 0.0; if (biggestKey > 1) { for (int n = 2; n <= biggestKey; n++) { if (phi > 1e-20) { AB.α[n] = 1.0; double alphaCoeff = 0; for (int k = 0; k <= (n - 2); k++) { alphaCoeff = binomialCoefficient(n - 1, k + 1) * Math.Pow((k + 1) * phi, k) / Math.Pow(1.0 - ((k + 1) * phi), k + 2); AB.α[n] += alphaCoeff; } } else { AB.α[n] = 1.0; } } AB.β[0] = 0.0; AB.β[1] = 0.0; AB.β[2] = AB.α[2] - 1.0; for (int n = 3; n <= biggestKey; n++) { if (phi > 1e-20) { AB.β[n] = AB.α[n] - 1.0; for (int k = 0; k <= (n - 3); k++) { double betaCoeff; betaCoeff = binomialCoefficient(n - 1, k + 2) * (k + 1) * Math.Pow((k + 2) * phi, k) / Math.Pow(1.0 - ((k + 2) * phi), k + 3); AB.β[n] += betaCoeff; } } else { AB.β[n] = 0.0; } } } } cache: AlphaBetaCache.AddAlphaBeta(key, AB); }