void WriteAlgorithmBenchmark(iTextSharp.text.Document doc, ISearchAlgorithm <string> algorithm, SearchReport <string> report) { iTextSharp.text.pdf.draw.LineSeparator line = new iTextSharp.text.pdf.draw.LineSeparator(1f, 100f, iTextSharp.text.BaseColor.BLACK, iTextSharp.text.Element.ALIGN_CENTER, -1); iTextSharp.text.Chunk linebreak = new iTextSharp.text.Chunk(line); Chunk c = new Chunk(algorithm.Name, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 24, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLUE)); c.SetGenericTag(algorithm.Name); doc.Add(new Paragraph(c)); // algorithm description Chunk desc = new Chunk(algorithm.Description, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12, iTextSharp.text.Font.ITALIC, iTextSharp.text.BaseColor.BLACK)); doc.Add(new Paragraph(desc)); // algorithm benchmark Chunk time = new Chunk("The algorithm took " + report.ElapsedTime + " to find the goal.", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12, iTextSharp.text.Font.BOLDITALIC, iTextSharp.text.BaseColor.BLACK)); doc.Add(new Paragraph(time)); // path time = new Chunk("The result path costs " + algorithm.CalculateCost(report.Result), new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12, iTextSharp.text.Font.BOLDITALIC, iTextSharp.text.BaseColor.BLACK)); doc.Add(new Paragraph(time)); // write steps foreach (var step in report.Steps) { WriteAlgorithmStep(doc, step.StepInformation, step.GraphCapture); } doc.NewPage(); }
public PdfReportCreator(Graph graph, ISearchAlgorithm searchAlgorithm, IGraphImageProvider graphImageProvider, IVertexColoringAlgorithm vertexColoringAlgorithm) { _graph = graph; _searchAlgorithm = searchAlgorithm; _graphImageProvider = graphImageProvider; _vertexColoringAlgorithm = vertexColoringAlgorithm; }
private void StartSearch_Click(object sender, RoutedEventArgs e) { ISearchAlgorithm sa = (ISearchAlgorithm)this.Algorithms.SelectedItem; _activeResults = sa.Search(_activeProblem); _activeResultsMethod = sa.ToString(); RefeshUIComponents(); }
private void LogSearch(State state, ISearchAlgorithm searcher, ISearchInfo info) { if (!EnableOutput) { return; } _output.WriteLine($"Search() on {state} with {searcher} yielded score={info.Score}, pv={string.Join(' ', info.Pv)}, nodesSearched={info.NodesSearched}"); }
// optimal cost of -1 represents no solution! private void TestSolver <TProblemState>(ISearchAlgorithm <TProblemState> solver, IProblem <TProblemState> problem, double optimalCost) where TProblemState : IProblemState <TProblemState> { output.WriteLine(solver.ToString()); var timer = new Stopwatch(); double lastTotalS = 0d; ulong lastEvals = 0UL; // https://docs.microsoft.com/en-us/dotnet/api/system.timers.timer?view=netframework-4.7.2 var reportingTimer = new Timer(10_000); Action reportingHeartbeat = () => { var currentTotalS = timer.Elapsed.TotalSeconds; var currentEvals = solver.StatesEvaluated; var statesPerSecond = (currentEvals - lastEvals) / (currentTotalS - lastTotalS); output.WriteLine($"evals: {solver.StatesEvaluated:#,0} ms: {timer.Elapsed.TotalMilliseconds} S/s: {statesPerSecond:#,#.###} cost: {solver.MaxCostEvaulated}"); lastTotalS = currentTotalS; lastEvals = currentEvals; }; reportingTimer.Elapsed += (Object source, ElapsedEventArgs e) => reportingHeartbeat(); reportingTimer.AutoReset = true; reportingTimer.Enabled = true; timer.Start(); var solution = solver.Solve(problem); timer.Stop(); reportingTimer.Enabled = false; reportingHeartbeat(); output.WriteLine("Time: {0}", timer.Elapsed); if (solution == null) { Assert.True(optimalCost == -1d, "Found no solution but one should exist."); } else { var state = problem.GetInitialState(); output.WriteLine("Initial State ----------------"); output.WriteLine(state.ToString()); int i = 0; double stepCost, totalCost = 0d; foreach (var move in solution) { i++; (state, stepCost) = problem.ApplyAction(state, move); totalCost += stepCost; //output.WriteLine(state.ToString()); } output.WriteLine("Final State ({0} moves, {1} cost) ----------------", i, totalCost); output.WriteLine(state.ToString()); Assert.True(problem.IsGoal(state), "Non-goal state claimed to be goal."); Assert.True(Math.Abs(optimalCost - totalCost) < 1e-8, "Found a non optimal cost: expected = " + optimalCost + "; actual = " + totalCost); } }
public static TimeSpan Measure(ISearchAlgorithm sortAlgorithm, IArrayGenerator arrayGenerator, int value) { var array = arrayGenerator.GetArray; Action act = () => sortAlgorithm.Contains(array, value); var stopwatch = new Stopwatch(); stopwatch.Start(); act.Invoke(); stopwatch.Stop(); return(stopwatch.Elapsed); }
public void PickMove_TerminalState_Fails(ISearchAlgorithm searcher) { // Checkmate var state = State.ParseFen("8/8/p7/8/P7/1Kbk4/1q6/8 w - - 4 59"); Assert.Throws <ArgumentException>(() => searcher.PickMove(state)); // Stalemate state = State.ParseFen("rn2k1nr/pp4pp/3p4/q1pP4/P1P2p1b/1b2pPRP/1P1NP1PQ/2B1KBNR w Kkq - 0 1"); Assert.Throws <ArgumentException>(() => searcher.PickMove(state)); }
public InOrderUnbalancedTreeIntersection(double splitAtRatio, ISearchAlgorithm<int> searchalg) { this.SplitAtRatio = splitAtRatio; if (this.SplitAtRatio > 0) { this.Randomized = false; } else { this.Randomized = true; this.rand = new Random (); } this.SearchAlgorithm = searchalg; }
private static void TestSearchFailure(ISearchAlgorithm<int[]> searcher, char[] s) { if (s.Length < 1) { throw new ArgumentException("s.Length < 1"); } int n = s.Length; // Build an impossible pattern by // modifying every character in s var pattern = s.Select(c => (char)(c + 1)).ToArray(); Assert.AreEqual(n, searcher.Search(s, pattern)); }
public Game() { StartNew(); search = new Search(); search.OnNewResult += Search_OnNewResult; worker = new BackgroundWorker(); worker.WorkerReportsProgress = true; worker.DoWork += Worker_DoWork; worker.RunWorkerCompleted += Worker_RunWorkerCompleted; worker.ProgressChanged += Worker_ProgressChanged; }
/// <summary> /// Outputs the results of a sample run /// </summary> public static void OutputResults(LinkedList<Node> solutionPath, ISearchAlgorithm searchAlgorithm, List<int> inputState) { var stackTrace = new StackTrace(); Console.WriteLine("Test name: {0}", stackTrace.GetFrame(1).GetMethod().Name); Console.Write("Input state: "); inputState.ForEach(e => Console.Write(e + " ")); Console.WriteLine(); Console.WriteLine("Number of nodes generated: {0}", searchAlgorithm.NumNodesGenerated); Console.WriteLine("Length of solution path: {0}", searchAlgorithm.LengthOfSolutionPath); Console.WriteLine("Execution time: {0:0} ms", searchAlgorithm.ExecutionTime.TotalMilliseconds); Console.WriteLine("Penetrance: {0:0.0000}", searchAlgorithm.Pentrance); PrintSolutionPath1(solutionPath); PrintSolutionPath2(solutionPath); }
private static SolverStats SolveAndRecordStats(ISearchAlgorithm <VacuumWorldState, VacuumWorldAction> solver) { var stats = new SolverStats(); var stopwatch = Stopwatch.StartNew(); solver.Solve(); stats.TimeToFinish = stopwatch.Elapsed; stats.NumberOfExploredStates = solver.NumberOfExploredStates; stats.FoundSolution = solver.IsSolved; stats.SolutionCost = solver.GetSolution().Count(); return(stats); }
public TestTower(BulletManager bulletManager, EnemyManager enemyManager, ParticleManager particleManager) : base(AssetManager.GetSprite("TowerBase2"), AssetManager.GetSprite("Tower1"), 26f, 250f) { BulletManager = bulletManager; EnemyManager = enemyManager; this.particleManager = particleManager; BaseLayerDepth = SortingOrder.GetLayerDepth(0, SortingLayer.TowerBase) + extraDepth; TopLayerDepth = SortingOrder.GetLayerDepth(0, SortingLayer.TowerTop) + extraDepth; barrelLength = 38f; ShootRate = 0.2f; shootBullet = BulletFactory.GetBullet("Bullet2"); SearchAlgorithm = new FirstEnemySearch(); }
public static void Log(ISearchAlgorithm sortAlgorithm, IArrayGenerator arrayGenerator, int value) { var elapsed = RuntimeTimer.Measure(sortAlgorithm, arrayGenerator, value); var arrayType = arrayGenerator.GetType().Name; var size = arrayGenerator.Length; var algorithmName = sortAlgorithm.GetType().Name; var benchmarkFileName = $"{algorithmName}_{arrayType}.csv"; var benchmarkDirectory = BenchmarksFolder + $"{algorithmName}/"; Directory.CreateDirectory(benchmarkDirectory); var message = $"Elapsed; {elapsed}; Array Size; {size}; Array Type; {arrayType}; {algorithmName};"; Console.WriteLine(message); using var sw = new StreamWriter(benchmarkDirectory + benchmarkFileName, true); sw.WriteLine(message); }
public void Search_TerminalState(ISearchAlgorithm searcher) { // Checkmate var state = State.ParseFen("8/8/p7/8/P7/1Kbk4/1q6/8 w - - 4 59"); var info = searcher.Search(state); LogSearch(state, searcher, info); Assert.Empty(info.Pv); Assert.InRange(info.Score, int.MinValue, -1); // getting mated should have a negative utility // Stalemate state = State.ParseFen("rn2k1nr/pp4pp/3p4/q1pP4/P1P2p1b/1b2pPRP/1P1NP1PQ/2B1KBNR w Kkq - 0 1"); info = searcher.Search(state); LogSearch(state, searcher, info); Assert.Empty(info.Pv); Assert.Equal(0, info.Score); }
public MachineGunPlaneTower(BulletManager bulletManager, EnemyManager enemyManager, ParticleManager particleManager) : base(AssetManager.GetSprite("TowerBase1"), AssetManager.GetSprite("Tower2"), 26f, 150f) { BulletManager = bulletManager; EnemyManager = enemyManager; this.particleManager = particleManager; BaseLayerDepth = SortingOrder.GetLayerDepth(0, SortingLayer.TowerBase) + extraDepth; TopLayerDepth = SortingOrder.GetLayerDepth(0, SortingLayer.Flying) + extraDepth; barrelLength = 10f; ShootRate = 0.1f; shootBullet = BulletFactory.GetBullet("Bullet1"); SearchAlgorithm = new FirstEnemySearch(); shadowSprite = AssetManager.GetSprite("PlaneShadow1"); rotationRadius = 150f; planeRotationSpeed = (float)Math.PI * 0.004f; }
public void Search_StressTest(ISearchAlgorithm searcher) { var rsg = GetRsg(); for (int i = 0; i < 100; i++) { var state = rsg.Next(); var info = searcher.Search(state); LogSearch(state, searcher, info); Assert.Equal(searcher.Depth, info.Depth); Assert.InRange(info.NodesSearched, 0, searcher.MaxNodes); Assert.InRange(info.Pv.Length, 0, searcher.Depth); // make sure all of the moves in the pv are valid var successor = state; foreach (var pvMove in info.Pv) { successor = successor.Apply(pvMove); } } }
/// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { // TODO: Add your initialization logic here for (int i = 0; i < g_mapDimension; i++) { for (int j = 0; j < g_mapDimension; j++) { if (g_map[j, i] == 1) { g_tiles[j, i] = new Tile(TileType.Impassable, i, j); } else { g_tiles[j, i] = new Tile(TileType.Passable, i, j); } } } g_currentSearchAlgorithm = new DepthFirstSearchAlgorithm(g_tiles, 1, 1, 7, 7); base.Initialize(); }
public Task <ResponseDTO> Handle(SearchRequestDTO request, CancellationToken cancellationToken) { ResponseDTO result = new ResponseDTO(); try { var dicAlgorithms = GetAlgorithmsDictionary(); ISearchAlgorithm algorithm = AlgorithmsCreator.GetAlgorithm(dicAlgorithms, request.AlgorithmKey, request.Matrix); var algorithmResult = algorithm.Find(request.WordStream); _unitOfWork.SearchesRepository.Add(new Searches() { UserName = request.UserName, AlgorithmKey = request.AlgorithmKey, Matrix = request.Matrix.Aggregate((x, y) => x + "," + y), WordStream = request.WordStream.Aggregate((x, y) => x + "," + y) }); _unitOfWork.SaveChanges(); result.Status = (int)eStatus.Success; result.Value = algorithmResult; } catch (WordFinderCustomException ex) { result.Status = (int)eStatus.Error; result.Message = ex.Message; } catch (Exception ex) { result.Status = (int)eStatus.Error; result.Message = "Unexpected error"; } return(Task.FromResult(result)); }
public HwangLinStaticPartition(ISearchAlgorithm<int> samplesearch, ISearchAlgorithm<int> blocksearch) { this.SampleSearch = samplesearch; this.BlockSearch = blocksearch; }
public BarbayRandomized(ISearchAlgorithm<int> searchalg) { this.SearchAlgorithm = searchalg; }
public BaezaYatesIntersection(ISearchAlgorithm<int> searchalg) { this.SearchAlgorithm = searchalg; }
public static IList <Audio> Search(this List <Audio> source, int referenceItemIndex, ISearchAlgorithm algorithm, object parameters = null) { return(source.Search(source[referenceItemIndex], algorithm, parameters)); }
public EstimationResult EstimateAlgorithm(ISearchAlgorithm algorithm, object parameters = null) { if (algorithm == null) { throw new ArgumentNullException("algorithm"); } Dictionary <SHA1Hash, Dictionary <SHA1Hash, int> > AutoScores = new Dictionary <SHA1Hash, Dictionary <SHA1Hash, int> >(); List <Audio> Audios = Core.GetAudios().ToList(); List <Audio> ReferenceList = Audios.ToList(); foreach (Audio ReferenceAudio in ReferenceList) { IList <Audio> Series = Audios.Search(ReferenceAudio, algorithm, parameters) .Where(audio => HashMap.Contains(audio.GetHash())) .ToList(); SHA1Hash ReferenceHash = ReferenceAudio.GetHash(); AutoScores.Add(ReferenceHash, new Dictionary <SHA1Hash, int>()); int Rank = 0; foreach (Audio TargetAudio in Series) { AutoScores[ReferenceHash].Add(TargetAudio.GetHash(), TransformRankToScore(Rank++, Series.Count)); } } List <double> Errors = new List <double>(); List <double> ManualScoresList = new List <double>(); List <double> ReducedAutoScoresList = new List <double>(); foreach (SHA1Hash Reference in ManualScores.Keys) { foreach (SHA1Hash Target in ManualScores[Reference].Keys) { if (AutoScores.ContainsKey(Reference) && AutoScores[Reference].ContainsKey(Target)) { int ReferenceScore = ManualScores[Reference][Target]; int AutoScore = AutoScores[Reference][Target]; int Error = ReferenceScore - AutoScore; Errors.Add(Error); ManualScoresList.Add(ReferenceScore); ReducedAutoScoresList.Add(AutoScore); } } } double Mean = Errors.Mean(); double StandardDeviation = Errors.StandardDeviation(); double Covariance = ManualScoresList.Covariance(ReducedAutoScoresList); double PearsonCoeff = Correlation.Pearson(ManualScoresList, ReducedAutoScoresList); EstimationResult Result = new EstimationResult() { AlgorithmName = algorithm.DisplayName, Parameters = Convert.ToString(parameters), Mean = Mean, StandardDeviation = StandardDeviation, Covariance = Covariance, PearsonCoeff = PearsonCoeff, Scores = AutoScores }; return(Result); }
public ComparisonBuilder(IEnumerable <IOperator> operators, ISearchAlgorithm searchAlgorithm) { _operators = operators; _searchAlgorithm = searchAlgorithm; _sitecoreService = (SitecoreService)ServiceLocator.ServiceProvider.GetService(typeof(ISitecoreService));; }
public GraphColoringAlgorithm(INodeAndArcRepository nodeAndArcRepository, ISearchAlgorithm searchAlgorithm) { _nodeAndArcRepository = nodeAndArcRepository; _searchAlgorithm = searchAlgorithm; }
private static void TestSearchMatches(ISearchAlgorithm<int[]> searcher, char[] s, char[] key, int expectedCount) { if (s.Length < 1) { throw new ArgumentException("s.Length < 1"); } if (key.Length < 1) { throw new ArgumentException("key.Length < 1"); } var keyLen = key.Length; var matchIndices = searcher.SearchAll(s, key); // Try to catch invalid indices early by // comparing result length with expected count Assert.AreEqual(expectedCount, matchIndices.Length); // For each match, compare every character to key foreach (var start in matchIndices) { var match = s.Skip(start).Take(keyLen).ToArray(); // Try to catch invalid match without evaluating chars // by comparing match length against search key length Assert.AreEqual(keyLen, match.Length); for (int ci = 0; ci < keyLen; ci++) { Assert.AreEqual(key[ci], match[ci]); } } }
public TextReportCreator(Graph graph, ISearchAlgorithm searchAlgorithm, IVertexColoringAlgorithm vertexColoringAlgorithm) { _graph = graph; _searchAlgorithm = searchAlgorithm; _vertexColoringAlgorithm = vertexColoringAlgorithm; }
private static void TestSearchSubstrLengths(ISearchAlgorithm<int[]> searcher, char[] s) { if (s.Length < 1) { throw new ArgumentException("s.Length < 1"); } int n = s.Length; for (int i = 1; i < n; i++) { TestSearchSubstr(searcher, s, i, n - i); } }
public BLsach(ISearchAlgorithm searchAlgorithm) { this._Search = searchAlgorithm; }
public LargeStepTThreshold(ISearchAlgorithm<int> searchalg) { this.SearchAlgorithm = searchalg; }
public BarbaySequential(ISearchAlgorithm<int> searchalg) { this.SearchAlgorithm = searchalg; }
public HwangLinMBlockWithCeiling(ISearchAlgorithm<int> samplesearch) : base(new BinarySearch<int>()) { this.SampleSearch = samplesearch; }
public SmallAdaptive(ISearchAlgorithm<int> SearchAlgorithm) { this.SearchAlgorithm = SearchAlgorithm; }
public HwangLinMBlock(ISearchAlgorithm<int> samplesearch, ISearchAlgorithm<int> blocksearch) { this.SampleSearch = samplesearch; this.BlockSearch = blocksearch; }
public AI(ISearchAlgorithm searcher) { _searcher = searcher; _history = new List <Move>(); _searchInfos = new List <ISearchInfo>(); }
public void RunSimulation() { try { this.Invoke(new Action(delegate { _gArea.ResetNodesColor(); tracetxt.Text = ""; })); selected_algorithm = (algorithms.SelectedItem as ComboBoxItem).Tag as ISearchAlgorithm <string>; Node <string> initial = (start_node.SelectedItem as ComboBoxItem).Tag as Node <string>; Node <string> final = (goal_node.SelectedItem as ComboBoxItem).Tag as Node <string>; this.Invoke(new Action(delegate { _gArea.ResetInitialGoal(); _gArea.SetInitialGoal(initial, final); selected_algorithm.Logged = checkBoxX1.Checked; })); selected_algorithm.OnResultFound += Selected_algorithm_OnResultFound; selected_algorithm.OnResetRequired += Selected_algorithm_OnResetRequired; // set event handlers simulation_thread = new Thread(new ThreadStart(delegate { sw.Start(); try { selected_algorithm.Initialize(); var sr = selected_algorithm.Search(initial, final.Key); this.Invoke(new Action(delegate { selected_algorithm.OnResultFound -= Selected_algorithm_OnResultFound; selected_algorithm.OnResetRequired -= Selected_algorithm_OnResetRequired; buttonX1.Text = "Run"; simulation_thread = null; if (sr.Found) { _gArea.ColorizePath(sr, Brushes.Red); TracePath(sr); } this.Invoke(new Action(delegate { tracetxt.AppendText("The path cost is " + selected_algorithm.CalculateCost(sr) + Environment.NewLine); })); MessageBoxEx.Show(this, "Simulation complete", "Simulation", MessageBoxButtons.OK, MessageBoxIcon.Information); })); } catch (Exception ex) { this.Invoke(new Action(delegate { MessageBoxEx.Show(this, ex.Message, "Simulation Process", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); })); } sw.Stop(); this.Invoke(new Action(delegate { tracetxt.AppendText("Elapsed time: " + sw.Elapsed); })); })); simulation_thread.Start(); }catch (Exception ex) { MessageBoxEx.Show(this, ex.Message, "Simulation Execution", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); } }
public SvS(ISearchAlgorithm<int> SearchAlgorithm) { this.SearchAlgorithm = SearchAlgorithm; }
public DirectionService(ISearchAlgorithm searchAlgorithm, InputOption inputOption) { _searchAlgorithm = searchAlgorithm; _inputOption = inputOption; }
public void SetUp() { _searchAlgorithm = new T(); }
public Searcher(ISearchAlgorithm searchAlgorithm) { this.searchAlgorithm = searchAlgorithm; }
public bool Search(Node start, Node target, ISearchAlgorithm algorithm, out List <Node> path) { return(algorithm.Search(start, target, out path)); }
public static IList <Audio> Search(this List <Audio> source, Audio referenceItem, ISearchAlgorithm algorithm, object parameters = null) { algorithm.Search(source, referenceItem, parameters); return(source); }
public InOrderTreeIntersection(ISearchAlgorithm<int> searchalg) { this.SearchAlgorithm = searchalg; }
private static void TestSearchSubstr(ISearchAlgorithm<int[]> searcher, char[] s, int start, int substrLen) { if (start < 0) { throw new ArgumentException("start < 0"); } if (substrLen < 1) { throw new ArgumentException("patternLen < 1"); } // Select substring as pattern from a random index var pattern = s.Skip(start).Take(substrLen).ToArray(); int result = searcher.Search(s, pattern); // Rather than comaring result with i, which would be a // bad test because i may not be the first occurence, // create match from result and compare with pattern. var match = s.Skip(result) .Take(pattern.Length) .ToArray(); start = 0; Assert.AreEqual(pattern.Length, match.Length); foreach (char c in pattern) { Assert.AreEqual(c, match[start++]); } }
public void SetSearchAlgorithm(ISearchAlgorithm searchAlgorithm) { this._Search = searchAlgorithm; }