Example #1
0
        private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            // Get result and redraw the solution.
            result = e.Result as ProblemResult;
            Refresh();

            // Write statistics and results.
            foreach (var group in result.Groups.Keys)
            {
                file.Write(string.Format("{0}: ", group));

                foreach (var member in result.Groups[group])
                {
                    file.Write(string.Format("{0} ", member));
                }

                file.WriteLine();
            }
            file.WriteLine();
            file.WriteLine("Fitness: {0}, at progress 100%", result.Fitness);
            file.WriteLine("=====================================================================");
            file.WriteLine();

            file.Close();

            startToolStripButton.Enabled = true;
        }
Example #2
0
        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            ProblemResult    result = e.Argument as ProblemResult;

            solver.Start(worker, e);
        }
Example #3
0
        public bool IsBetter(ProblemResult results1, ProblemResult results2)
        {
            var metric1 = results1.CV.Count + results1.SubgraphEdges;
            var metric2 = results2.CV.Count + results2.SubgraphEdges;

            return(metric1 > metric2);
        }
Example #4
0
        public ProblemResult Solve()
        {
            var bestProblemResults = new ProblemResult
            {
                CV            = new List <int>(),
                CU            = new List <int>(),
                SubgraphEdges = 0
            };

            var greedySolver =
                new GreedyProblemSolver(_problemInput, _problemInput.V, _problemInput.U, bestProblemResults,
                                        _resultsComparator,
                                        _vertexComparerInG, _vertexComparerInH);

            return(bestProblemResults);
        }
Example #5
0
            public ProblemResult Solve()
            {
                SolveGreedy();

                if (IsCurrentMappingBetterThanCurrentlyBest())
                {
                    BestProblemResult = new ProblemResult
                    {
                        CV            = new List <int>(CV),
                        CU            = new List <int>(CU),
                        SubgraphEdges = _currentProblemResult.SubgraphEdges
                    }
                }
                ;

                return(BestProblemResult);
            }
Example #6
0
        public ProblemResult Solve()
        {
            var bestProblemResults = new ProblemResult
            {
                CV            = new List <int>(),
                CU            = new List <int>(),
                SubgraphEdges = 0
            };

            var recursiveSolver =
                new ExactProblemSolverRecursive(_problemInput, _problemInput.V, _problemInput.U, bestProblemResults,
                                                _resultsComparator);

            bestProblemResults = recursiveSolver.Solve();

            return(bestProblemResults);
        }
        public static CommandResult ShowToolWindow(Type type, string problem = null, int id = 0)
        {
            CommandResult commandResult = null;

            try
            {
                Instance.JoinableTaskFactory.RunAsync(async delegate
                {
                    try
                    {
                        using (var window = await Instance.ShowToolWindowAsync(type, id, create: true, Instance.DisposalToken))
                        {
                            if ((null == window) || (null == window.Frame))
                            {
                                throw new NotSupportedException("Cannot create tool window");
                            }

                            await Instance.JoinableTaskFactory.SwitchToMainThreadAsync();

                            var windowFrame = (IVsWindowFrame)window.Frame;
                            var result      = windowFrame.Show();

                            ErrorHandler.ThrowOnFailure(result);
                        }

                        commandResult = new SuccessResult();
                    }
                    catch (Exception ex)
                    {
                        commandResult = new ProblemResult(problem ?? ex.ExtendedMessage());
                    }
                });

                return(commandResult);
            }
            catch (Exception ex)
            {
                return(new ProblemResult(problem ?? ex.ExtendedMessage()));
            }
        }
Example #8
0
        private void Fix()
        {
            problem = new ProblemFinder(detecting_label, problem_label, progress);
            Pages.Invoke(new Action(() => Pages.TabIndex = 0));
            ProblemResult res = ProblemResult.OK;

            problem.Init();
            while (res != ProblemResult.NoMoreProblems)
            {
                res = problem.Solve();

                if (res == ProblemResult.Fail)
                {
                    Problem.Description = "A problem couldn't be fixed.";
                    Next();
                    return;
                }
                Thread.Sleep(100);
            }
            Problem.Title       = "All problems were fixed";
            Problem.Description = "All the problems that were detected are currently fixed.";
            Next();
        }
Example #9
0
            public ExactProblemSolverRecursive(
                SubtaskInput problemInput,
                int initialV,
                int initialU,
                ProblemResult bestProblemResult,
                IProblemResultsComparator resultsComparator
                )
            {
                _problemInput      = problemInput;
                _resultsComparator = resultsComparator;
                BestProblemResult  = bestProblemResult;

                var n = _problemInput.G.VerticesCount;
                var m = _problemInput.H.VerticesCount;

                _currentProblemResult = new ProblemResult
                {
                    CV            = new List <int>(n),
                    CU            = new List <int>(m),
                    SubgraphEdges = 0
                };

                _neighborsV = new List <int>(n)
                {
                    initialV
                };
                _neighborsU = new List <int>(m)
                {
                    initialU
                };

                _closedV           = new bool[n];
                _closedV[initialV] = true;

                _closedU           = new bool[m];
                _closedU[initialU] = true;
            }
Example #10
0
        public async Task <IActionResult> Delete(int id)
        {
            Problem problem = await dbContext.Problems.Include(m => m.Tests).Include(m => m.Examples).FirstOrDefaultAsync(m => m.ProblemID == id);

            if (problem == null)
            {
                return(RedirectToAction(nameof(List)));
            }

            try
            {
                var users = userManager.Users
                            .Include(u => u.ProblemResults)
                            .ThenInclude(r => r.FirstResult)
                            .Include(u => u.ProblemResults)
                            .ThenInclude(r => r.BestResult)
                            .Where(u => u.ProblemResults.Exists(r => r.ProblemID == problem.ProblemID));

                // Remove problem results
                foreach (var user in users)
                {
                    ProblemResult problemResult = user.ProblemResults.Where(r => r.ProblemID == problem.ProblemID).First();
                    dbContext.Remove(problemResult.BestResult);
                    dbContext.Remove(problemResult.FirstResult);
                    dbContext.Remove(problemResult);
                }

                dbContext.Problems.Remove(problem);
                await dbContext.SaveChangesAsync();

                return(RedirectToAction(nameof(List)));
            }
            catch (DbUpdateException)
            {
                return(RedirectToAction(nameof(List)));
            }
        }
Example #11
0
            public GreedyProblemSolver(
                SubtaskInput problemInput,
                int initialV,
                int initialU,
                ProblemResult bestProblemResult,
                IProblemResultsComparator resultsComparator,
                IComparer <int> vertexComparerInG,
                IComparer <int> vertexComparerInH
                )
            {
                _problemInput      = problemInput;
                _resultsComparator = resultsComparator;
                BestProblemResult  = bestProblemResult;

                var n = _problemInput.G.VerticesCount;
                var m = _problemInput.H.VerticesCount;

                _currentProblemResult = new ProblemResult
                {
                    CV            = new List <int>(n),
                    CU            = new List <int>(m),
                    SubgraphEdges = 0
                };

                _neighborsV = new SortedSet <int>(vertexComparerInG);
                _neighborsU = new SortedSet <int>(vertexComparerInH);

                _neighborsV.Add(initialV);
                _neighborsU.Add(initialU);

                _closedV           = new bool[n];
                _closedV[initialV] = true;

                _closedU           = new bool[m];
                _closedU[initialU] = true;
            }
Example #12
0
        private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            // Get result and redraw the solution.
            result = e.UserState as ProblemResult;
            Refresh();

            // Write progress statistics.

            /*foreach (var group in result.Groups.Keys)
             * {
             *  file.Write(string.Format("{0}: ", group));
             *
             *  foreach (var member in result.Groups[group])
             *  {
             *      file.Write(string.Format("{0} ", member));
             *  }
             *
             *  file.WriteLine();
             * }
             * file.WriteLine();*/
            file.WriteLine("Fitness: {0}, at progress {1}%", result.Fitness, e.ProgressPercentage);
            //file.WriteLine("=====================================================================");
            //file.WriteLine();
        }
		private static async Task ExecuteProblemResultAsync(HttpContext context, Problem problem)
		{
			var result = new ProblemResult(problem);
			var actionContext = new ActionContext(context, null, null);
			await result.ExecuteResultAsync(actionContext);
		}
Example #14
0
 public bool IsBetter(ProblemResult results1, ProblemResult results2)
 {
     return(results1.CV.Count > results2.CV.Count);
 }
Example #15
0
        private Task GetTask(Problem problem)
        {
            switch (problem.TypeId)
            {
            case 1:
                return(new Task(() =>
                {
                    try
                    {
                        var antennasRadiationPatternProblemResult =
                            AntennasRadiationPatternProblemAlgorithmType1.Calculate(problem);
                        var resultXml = SerializationService.ToXmlString(antennasRadiationPatternProblemResult);
                        var result = new ProblemResult {
                            Result = resultXml
                        };
                        lock (_lockRero)
                        {
                            var insertedResult = _repository.Insert(result);
                            problem.ResultId = insertedResult.Id;
                            problem.StateId = 3;
                            _repository.Update(problem);
                        }
                    }
                    catch (Exception)
                    {
                        lock (_lockRero)
                        {
                            problem.StateId = 5;
                            _repository.Update(problem);
                        }
                    }
                }));

            case 2:
                return(new Task(() =>
                {
                    try
                    {
                        var antennasRadiationPatternProblemResult = AntennasRadiationPatternProblemAlgorithmType2.Calculate(problem);
                        var resultXml = SerializationService.ToXmlString(antennasRadiationPatternProblemResult);
                        var result = new ProblemResult {
                            Result = resultXml
                        };
                        lock (_lockRero)
                        {
                            var insertedResult = _repository.Insert(result);
                            problem.ResultId = insertedResult.Id;
                            problem.StateId = 3;
                            _repository.Update(problem);
                        }
                    }
                    catch (Exception)
                    {
                        lock (_lockRero)
                        {
                            problem.StateId = 5;
                            _repository.Update(problem);
                        }
                    }
                }));

            case 3:
                return(new Task(() =>
                {
                    try
                    {
                        var branchingPointsProblem = BranchingPointsProblem1.Calculate(problem);
                        var resultXml = SerializationService.ToXmlString(branchingPointsProblem);
                        var result = new ProblemResult {
                            Result = resultXml
                        };
                        lock (_lockRero)
                        {
                            var insertedResult = _repository.Insert(result);
                            problem.ResultId = insertedResult.Id;
                            problem.StateId = 3;
                            _repository.Update(problem);
                        }
                    }
                    catch (Exception)
                    {
                        lock (_lockRero)
                        {
                            problem.StateId = 5;
                            _repository.Update(problem);
                        }
                    }
                }));

            default:
                return(new Task(() =>
                {
                    try
                    {
                        var branchingPointsProblem = BranchingPointsProblem1.Calculate(problem);
                        var resultXml = SerializationService.ToXmlString(branchingPointsProblem);
                        var result = new ProblemResult {
                            Result = resultXml
                        };
                        lock (_lockRero)
                        {
                            var insertedResult = _repository.Insert(result);
                            problem.ResultId = insertedResult.Id;
                            problem.StateId = 3;
                            _repository.Update(problem);
                        }
                    }
                    catch (Exception)
                    {
                        lock (_lockRero)
                        {
                            problem.StateId = 5;
                            _repository.Update(problem);
                        }
                    }
                }));
            }
        }
Example #16
0
 public ProblemResult Solve()
 {
     if (IsInputDataSet)
     {
         Result = Execute(null);
         return Result;
     }
     else
     {
         throw new ArgumentException("Input data not set.");
     }
 }
Example #17
0
 public ProblemResult Solve(DoWorkEventArgs args)
 {
     if (IsInputDataSet)
     {
         Result = Execute(args);
         return Result;
     }
     else
     {
         throw new ArgumentException("Input data not set.");
     }
 }
Example #18
0
            private void SolveRecursively()
            {
                if (IsCurrentMappingBetterThanCurrentlyBest())
                {
                    BestProblemResult = new ProblemResult
                    {
                        CV            = new List <int>(CV),
                        CU            = new List <int>(CU),
                        SubgraphEdges = _currentProblemResult.SubgraphEdges
                    }
                }
                ;

                // Use for because the collection is modified during enumeration
                // which results in an exception when using foreach
                for (var i = 0; i < _neighborsV.Count; i++)
                {
                    var v = _neighborsV[i];

                    for (var j = 0; j < _neighborsU.Count; j++)
                    {
                        var u = _neighborsU[j];

                        var(maintainsIsomorphism, edgesAddedAfterExpansion) = CanExpandAndMaintainIsomorphism(v, u);
                        if (!maintainsIsomorphism)
                        {
                            continue;
                        }

                        // Expand cV and cU by v and u
                        _neighborsV.Remove(v);
                        _neighborsU.Remove(u);

                        CV.Add(v);
                        CU.Add(u);

                        var newNeighborsInG = G.GetNeighbors(v)
                                              .Where(x => !_closedV[x])
                                              .ToList();
                        var newNeighborsInH = H.GetNeighbors(u)
                                              .Where(x => !_closedU[x])
                                              .ToList();

                        foreach (var x in newNeighborsInG)
                        {
                            _closedV[x] = true;
                            _neighborsV.Add(x);
                        }

                        foreach (var x in newNeighborsInH)
                        {
                            _closedU[x] = true;
                            _neighborsU.Add(x);
                        }

                        _currentProblemResult.SubgraphEdges += edgesAddedAfterExpansion;

                        // Solve recursively
                        SolveRecursively();

                        // Revert expansion
                        _neighborsV.Add(v);
                        _neighborsU.Add(u);

                        CV.RemoveAt(CV.Count - 1);
                        CU.RemoveAt(CU.Count - 1);

                        foreach (var x in newNeighborsInG)
                        {
                            _closedV[x] = false;
                            _neighborsV.Remove(x);
                        }

                        foreach (var x in newNeighborsInH)
                        {
                            _closedU[x] = false;
                            _neighborsU.Remove(x);
                        }

                        _currentProblemResult.SubgraphEdges -= edgesAddedAfterExpansion;
                    }
                }
            }
Example #19
0
        public async Task <IActionResult> Result(int id, string filePath)
        {
            Problem problem = await dbContext.Problems.Include(m => m.Tests).FirstOrDefaultAsync(p => p.ProblemID == id);

            if (problem == null)
            {
                return(RedirectToAction(nameof(List)));
            }

            if (!System.IO.File.Exists(filePath))
            {
                return(RedirectToAction(nameof(Solve), new { id }));
            }

            string parentFolderPath = Directory.GetParent(filePath).FullName;

            ResultViewModel viewModel = new ResultViewModel()
            {
                ProblemID           = problem.ProblemID,
                Name                = problem.Name,
                ShowFailedTestCases = problem.ShowFailedTestCases
            };
            UserProgram userProgram = new UserProgram();

            var result = userProgram.SetSource(filePath);

            viewModel.CompilationResult = result;

            if (result.Status == UserProgram.Result.StatusType.Failed)
            {
                Directory.Delete(parentFolderPath, true);

                return(View(viewModel));
            }

            result = userProgram.Compile();
            viewModel.CompilationResult = result;

            if (result.Status == UserProgram.Result.StatusType.Failed)
            {
                Directory.Delete(parentFolderPath, true);

                viewModel.CompilationResult = result;
                return(View(viewModel));
            }

            int passed = 0;

            foreach (Test t in problem.Tests)
            {
                result = userProgram.Execute(t.GivenInput);
                ResultViewModel.TestResult testResult = new ResultViewModel.TestResult()
                {
                    Test = t, ExecutionResult = result
                };

                if (result.Status == UserProgram.Result.StatusType.Successful)
                {
                    // Format expected output lines
                    string[] expectedOutputLines = t.ExpectedOutput.Split('\n');
                    for (int i = 0; i < expectedOutputLines.Length; i++)
                    {
                        expectedOutputLines[i] = expectedOutputLines[i].Trim('\u202c').Trim();
                    }

                    result = userProgram.EvaluateAndGetResultIfFailed(expectedOutputLines);

                    if (result.Status == UserProgram.Result.StatusType.Successful)
                    {
                        passed++;
                    }

                    testResult.EvaluationResult = result;
                    viewModel.TestResults.Add(testResult);
                }
                else
                {
                    viewModel.TestResults.Add(testResult);
                }
            }

            viewModel.PassedTests = passed;

            try
            {
                Directory.Delete(parentFolderPath, true);
            }
            catch (UnauthorizedAccessException) // Sometimes the process isn't killed fast enough
            {
                Thread.Sleep(100);
                Directory.Delete(parentFolderPath, true);
            }

            ApplicationUser partialUser = await userManager.GetUserAsync(User);

            ApplicationUser currentUser = await userManager.Users
                                          .Include(u => u.ProblemResults)
                                          .ThenInclude(r => r.FirstResult)
                                          .Include(u => u.ProblemResults)
                                          .ThenInclude(r => r.BestResult)
                                          .FirstOrDefaultAsync(u => u == partialUser);

            if (currentUser != null)
            {
                bool hasProblem           = currentUser.ProblemResults.Exists(r => r.ProblemID == problem.ProblemID);
                bool gotPerfectPercentage = false;
                if (hasProblem)
                {
                    ProblemResult problemResult  = currentUser.ProblemResults.Where(r => r.ProblemID == problem.ProblemID).First();
                    int           bestPercentage = problemResult.BestResult.PercentageResult;
                    gotPerfectPercentage = bestPercentage < 100;
                }

                bool isAdmin = await userManager.IsInRoleAsync(currentUser, "Admin");

                // A unique user solved the problem and is not an Admin
                if (passed == problem.Tests.Count && (!hasProblem || (hasProblem && gotPerfectPercentage)) && !isAdmin)
                {
                    problem.TimesSolved++;

                    if (await TryUpdateModelAsync(problem))
                    {
                        try
                        {
                            await dbContext.SaveChangesAsync();
                        }
                        catch (DbUpdateException)
                        {
                            return(View(viewModel));
                        }
                    }
                }

                ProgramResult programResult = viewModel.GetProgramResult();
                if (currentUser.ProblemResults.Exists(r => r.ProblemID == problem.ProblemID))
                {
                    // Tried to solve the problem again
                    ProblemResult problemResult = currentUser.ProblemResults.First(r => r.ProblemID == problem.ProblemID);
                    if (programResult.PercentageResult > problemResult.BestResult.PercentageResult)
                    {
                        if (problemResult.BestResult != problemResult.FirstResult)
                        {
                            dbContext.Remove(problemResult.BestResult);
                        }
                        problemResult.BestResult = programResult;
                    }
                }
                else
                {
                    // Solved this problem for the first time
                    ProblemResult problemResult = new ProblemResult()
                    {
                        ProblemID   = problem.ProblemID,
                        FirstResult = programResult,
                        BestResult  = programResult
                    };
                    currentUser.ProblemResults.Add(problemResult);
                }

                await userManager.UpdateAsync(currentUser);
            }

            return(View(viewModel));
        }