Пример #1
0
        private void CreateAndSendPartialSolution(SolvePartialProblems message,
                        SolvePartialProblemsPartialProblem problem)
        {
            var taskSolver = CreateSolverOrSendError(message.ProblemType, message.CommonData);
            if (taskSolver == null) return;

            var resultData = taskSolver.Solve(problem.Data, new TimeSpan());

            var solution = new Solutions
            {
                Solutions1 = new[] {new SolutionsSolution
                {
                    TaskId = problem.TaskId,
                    TaskIdSpecified = true,
                    Type = SolutionsSolutionType.Partial,
                    TimeoutOccured = false,
                    ComputationsTime = 1,
                    Data = resultData
                }},
                Id = message.Id,
                ProblemType = "DVRP",
                CommonData = problem.Data
            };

            SendMessageNoResponse(solution);
        }
        public BarSettingItem(BarData bar, [JsonProperty("configuration.settingId")] string settingId) : base(bar)
        {
            this.Solutions = this.Bar.ServiceProvider.GetRequiredService <Solutions>();
            this.SettingId = settingId;

            this.ApplySetting();
        }
        ///--------------------------------------------------------------------------------
        /// <summary>This method loads a solution into the view model.</summary>
        ///
        /// <param name="solutionURL">The solution file path.</param>
        ///--------------------------------------------------------------------------------
        public SolutionViewModel LoadSolution(string solutionURL = null)
        {
            SolutionViewModel solutionView = null;

            try
            {
                // create a solution under solution
                if (solutionURL != null)
                {
                    if (File.Exists(solutionURL))
                    {
                        // load solution from xml
                        Solution solution = new Solution();
                        if (solutionURL != null)
                        {
                            solution.Load(solutionURL);
                        }
                        solution.ResetModified(false);
                        solutionView            = new SolutionViewModel(solution, solutionURL, true);
                        solutionView.Updated   += new EventHandler(Children_Updated);
                        solutionView.Loaded    += new EventHandler(solutionView_Loaded);
                        solutionView.IsSelected = true;

                        // compile and load into view
                        solutionView.BuildSolution(true);

                        // add to recent solutions
                        AddSolutionToRecentSolutions(solution, solutionURL);
                    }
                    else
                    {
                        // display bad path issue
                        ShowIssue(String.Format(DisplayValues.Issue_SolutionFileNotFound, solutionURL));
                    }
                }
                else
                {
                    // create new solution
                    Solution solution = new Solution();
                    solution.SolutionID     = Guid.NewGuid();
                    solution.Name           = Resources.DisplayValues.NodeName_SolutionDefault;
                    solutionView            = new SolutionViewModel(solution, solutionURL);
                    solutionView.Updated   += new EventHandler(Children_Updated);
                    solutionView.Loaded    += new EventHandler(solutionView_Loaded);
                    solutionView.IsSelected = true;
                    Solutions.Add(solutionView);
                    Items.Add(solutionView);
                    Refresh(false);
                }
            }
            catch (ApplicationException ex)
            {
                ShowException(ex);
            }
            catch (Exception ex)
            {
                ShowException(ex);
            }
            return(solutionView);
        }
 ///--------------------------------------------------------------------------------
 /// <summary>This method removes a solution from the view model.</summary>
 ///
 /// <param name="solution">The solution to close.</param>
 ///--------------------------------------------------------------------------------
 public void CloseSolution(SolutionViewModel solution)
 {
     Solutions.Remove(solution);
     Items.Remove(solution);
     solution.DisposeComplete();
     System.GC.Collect();
 }
Пример #5
0
        public void DownCountSolver_NoSolution()
        {
            DownCountGame game      = new DownCountGame(577, 9, 3, 4, 2, 1);
            Solutions     solutions = DownCountSolver.Solve(game);

            Assert.IsTrue(solutions.Count == 0);
        }
Пример #6
0
        private Solutions ChooseFinalSolution(Solutions solutions)
        {
            var taskSolver = CreateSolverOrSendError(solutions.ProblemType, solutions.CommonData);
            if (taskSolver == null) return null;

            var partialSolutions = solutions.Solutions1;

            var partialSolutionsData = new byte[partialSolutions.Length][];

            for (var i = 0; i < partialSolutions.Length; i++)
            {
                partialSolutionsData[i] = partialSolutions[i].Data;
            }

            var resultData = taskSolver.MergeSolution(partialSolutionsData);

            var solution = new Solutions
            {
                ProblemType = "DVRP",
                Id = solutions.Id,
                Solutions1 = new[]
                {
                    new SolutionsSolution
                    {
                        Type = SolutionsSolutionType.Final,
                        TimeoutOccured = false,
                        ComputationsTime = 0,
                        Data = resultData
                    }
                }
            };

            return solution;
        }
        /// <summary>
        /// handles solutions msg. according to specifiaction, Solutions message
        /// concerns only one problem
        /// </summary>
        /// <param name="solutions"></param>
        public Solutions HandleSolutions(Solutions solutions)
        {
            if (solutions.SolutionsList == null)
            {
                return(null);
            }
            log.DebugFormat("Adding partial solutions to TM's memory. ({0})", solutions.Id);
            foreach (var solution in solutions.SolutionsList)
            {
                if (!storage.ContainsIssue(solutions.Id) || !storage.ExistsTask(solutions.Id, solution.TaskId))
                {
                    throw new Exception("Invalid solutions message delivered to TM");
                }
                storage.AddSolutionToIssue(solutions.Id, solution.TaskId, solution);
            }
            //this is not possible:
            //if (currentProblems[solutions.Id].SolutionsCount > currentProblems[solutions.Id].ProblemsCount)

            //can be linked, because all of partial problems were solved & delivered
            if (storage.IssueCanBeLinked(solutions.Id))
            {
                log.DebugFormat("Linking solutions (id:{0})", solutions.Id);
                Solutions finalSolution = LinkSolutions(solutions.Id, solutions.ProblemType);
                storage.RemoveIssue(solutions.Id);
                return(finalSolution);
            }

            return(null);
        }
Пример #8
0
        /// <summary>
        /// Solve the given downcount game
        /// </summary>
        /// <param name="game"></param>
        /// <param name="allSolutions"></param>
        /// <returns></returns>
        public static Solutions Solve(DownCountGame game, bool allSolutions = true)
        {
            Solutions solutions = new Solutions();

            if (game.Numbers.Contains(game.TargetNumber))
            {
                solutions.Add(new Integer(game.TargetNumber));
            }

            if (!allSolutions && solutions.Count > 0)
            {
                return(solutions);
            }

            if (game.Numbers.Count == 1)
            {
                return(solutions);
            }

            for (int i = 0; i < game.Numbers.Count; ++i)
            {
                solutions.AddRange(SolveSubset(game, i, allSolutions));

                if (!allSolutions && solutions.Count > 0)
                {
                    return(solutions);
                }
            }

            return(solutions);
        }
Пример #9
0
        public void Calculate(double a, double b, double eps)
        {
            if (eps <= 0)
            {
                return;
            }

            if (a >= b)
            {
                return;
            }



            while (Math.Abs(b - a) >= eps)
            {
                double x = (a + b) / 2;
                if (pf.F(a) * pf.F(x) < 0)
                {
                    b = x;
                }
                else
                {
                    a = x;
                }
                Log.Add(x.ToString());
            }
            Log.Add(((a + b) / 2).ToString());
            Solutions.Add((a + b) / 2);
        }
Пример #10
0
        public void ForUpdate(Solutions input)
        {
            var email = _context.Email();

            input.ModifiedById = _contacts.ByEmail(email).Id;
            input.ModifiedOn   = DateTime.UtcNow;
        }
Пример #11
0
        /// <summary>
        /// aggregates the data from solving engines
        /// that were run in parallel partitions
        /// </summary>
        /// <param name="solvingEngine"></param>
        public void AggregateData(SolvingEngine solvingEngine)
        {
            if ((solvingEngine is null) || (solvingEngine.Solutions is null))
            {
                throw new ArgumentNullException(nameof(solvingEngine));
            }

            if (solvingEngine.Solutions.Count > 0)
            {
                lock (addLock)
                {
                    Solutions.AddRange(solvingEngine.Solutions);
                }
            }
            else if ((Solutions.Count == 0) && solvingEngine.HasClosestMatch) // no existing or new matches
            {
                // there is a race hazard reading Solutions.Count but the down side is trivial,
                // even the c# concurrent collections don't guarantee counts
                lock (updateLock)
                {
                    if (Math.Abs(solvingEngine.Difference) < Math.Abs(Difference)) // record the closest
                    {
                        Difference   = solvingEngine.Difference;
                        ClosestMatch = solvingEngine.ClosestMatch;
                    }
                }
            }
        }
Пример #12
0
        /// <summary>
        /// Initialize/reset the integration method
        /// </summary>
        /// <param name="behaviors">Truncation behaviors</param>
        public virtual void Initialize(BehaviorList <BaseTransientBehavior> behaviors)
        {
            // Initialize variables
            Time       = 0.0;
            _savetime  = 0.0;
            Delta      = 0.0;
            Order      = 1;
            Prediction = null;
            DeltaOld.Clear(0.0);
            Solutions.Clear((Vector <double>)null);

            // Get parameters
            BaseParameters = Parameters.Get <IntegrationParameters>();

            // Register default truncation methods
            _transientBehaviors = behaviors;
            if (BaseParameters.TruncationMethod.HasFlag(IntegrationParameters.TruncationMethods.PerDevice))
            {
                Truncate += TruncateDevices;
            }
            if (BaseParameters.TruncationMethod.HasFlag(IntegrationParameters.TruncationMethods.PerNode))
            {
                Truncate += TruncateNodes;
            }

            // Last point was START so the current point is the point after a breakpoint (start)
            Break = true;
        }
Пример #13
0
        public AcErrorSolutionSelector(AcError acError)
        {
            InitializeComponent();
            DataContext = this;

            AcError = acError;
            Buttons = new[] { CancelButton };

            if (acError.BaseException != null)
            {
                ErrorMessage = string.Format(AppStrings.AcError_StackTrace, acError.BaseException);
            }
            else
            {
                Solutions = acError.GetSolutions().ToList();
                if (Solutions.Count == 0)
                {
                    ErrorMessage = AppStrings.AcError_SolutionsNotFound;
                }
                else
                {
                    SelectedSolution = Solutions.First();
                    SimilarErrors    = Solutions.OfType <IMultiSolution>().Any()
                            ? GetNearestErrors(acError).Where(x => x.Type == acError.Type).ApartFrom(acError).ToList() : new List <IAcError>();
                    MultiAppliable = SimilarErrors.Any();
                }
            }
        }
Пример #14
0
 public NumbersSolutionDto GetSolutionDto() => new NumbersSolutionDto
 {
     Target             = Target,
     Numbers            = Root.Numbers,
     DistanceFromTarget = DistanceFromTarget,
     Solutions          = Formatter.Format(Solutions.OrderBy(s => s.Depth))
 };
        private void Moore(Interval a, ref int k)
        {
            ++k;

            if (a.Width <= eps)
            {
                Solutions.Add(a);
                return;
            }

            if (dFdx(a).Contains(0.0))
            {
                Interval A1 = new Interval(a.Start, a.Middle - eps);
                Interval A2 = new Interval(a.Middle + eps, a.End);

                if (dFdx(A1).Contains(0.0))
                {
                    Moore(A1, ref k);
                }
                else
                {
                    var      c  = A1.Middle;
                    Interval U1 = A1.Middle - F(A1.Middle) / dFdx(A1);
                    Interval X1 = Interval.Intersection(U1, A1);
                    if (X1.Width > eps)
                    {
                        Moore(X1, ref k);
                    }
                }

                if (dFdx(A2).Contains(0.0))
                {
                    Moore(A2, ref k);
                }
                else
                {
                    var      c  = A1.Middle;
                    Interval U1 = A2.Middle - F(A2.Middle) / dFdx(A2);
                    Interval X1 = Interval.Intersection(U1, A2);
                    if (X1.Width > eps)
                    {
                        Moore(X1, ref k);
                    }
                }
            }
            else
            {
                double   c = a.Middle;
                Interval U = c - F(c) / dFdx(a);
                Interval X = Interval.Intersection(U, a);
                if (X.Width > eps)
                {
                    Moore(X, ref k);
                }
                else
                {
                    Solutions.Add(X);
                }
            }
        }
Пример #16
0
        private void ChooseAndSendFinalSolution(Solutions message)
        {
            var solution = ChooseFinalSolution(message);
            if (solution == null) return;

            SendMessageNoResponse(solution);
        }
Пример #17
0
        /// <summary>
        /// checks computations - sends solutionRequest msg
        /// </summary>
        /// <param name="request"></param>
        /// <returns>complete solution if cluster finished task</returns>
        public virtual Solutions CheckComputations(SolutionRequest request)
        {
            Message[] requests        = creator.Create(request);
            Message[] responses       = this.SendMessages(clusterClient, requests);
            Solutions solutionReponse = null;

            foreach (var response in responses)
            {
                switch (response.MessageType)
                {
                case MessageType.NoOperationMessage:
                    log.Debug("NoOperation acquired: updating backups");
                    this.UpdateBackups(response.Cast <NoOperation>());
                    break;

                case MessageType.SolutionsMessage:
                    log.Debug("Solutions acquired: checking...");
                    if (solutionReponse != null)
                    {
                        throw new Exception("Multiple solutions msg from CS to CC");
                    }
                    solutionReponse = response.Cast <Solutions>();
                    break;

                default:
                    throw new Exception("Wrong msg type delivered to CC: " + response.ToString());
                }
            }
            if (solutionReponse == null)
            {
                throw new Exception("No Solutions message from server delivered (it always should do that)");
            }
            //could (or couldn't?) be null:
            return(solutionReponse);
        }
        void taskSolver_SolutionsMergingFinished(EventArgs eventArgs, TaskSolver sender)
        {
            var _bestSolution = new Solutions()
            {
                Id          = allSolutions.Id,
                CommonData  = allSolutions.CommonData,
                ProblemType = allSolutions.ProblemType,
                Solutions1  = new SolutionsSolution[1] {
                    new SolutionsSolution()
                    {
                        Data             = taskSolver.Solution,
                        TaskIdSpecified  = false,
                        TimeoutOccured   = allSolutions.Solutions1.Any(sol => sol.TimeoutOccured),
                        ComputationsTime = allTime,
                        Type             = SolutionsSolutionType.Final
                    }
                }
            };
            bool result = Send(SerializeMessage <Solutions>(_bestSolution));

            Console.WriteLine("Sending final solution to server.");
            Console.WriteLine("Work done");
            m_lockStatus.WaitOne();
            m_lastChangeTime    = DateTime.Now;
            m_status.Threads[0] = new StatusThread()
            {
                State   = StatusThreadState.Idle,
                HowLong = 0,
                ProblemInstanceIdSpecified = false,
                ProblemType     = "",
                TaskIdSpecified = false
            };
            m_lockStatus.Release();
        }
Пример #19
0
        public ISolution1D CreateExactTimeDependentSolution(IGrid1D grid, object physicalData, double dt)
        {
            var solution = new DbGroup1D((DbGrid1D)grid, physicalData, dt);

            Solutions.Add(solution);
            return(solution);
        }
        protected override void HandleCore(ClientMessage <SolutionRequest> message)
        {
            var problem = manager.GetProblemForSending(message.Message.Id);

            if (problem == null)
            {
                message.Respond(sender, new Solutions());
            }
            else
            {
                var response = new Solutions
                {
                    Id            = message.Message.Id,
                    ProblemType   = problem.Type,
                    SolutionsList = problem.SubProblems.Select(s => new Solution
                    {
                        TaskId = s.Id,
                        Type   = problem.State == ProblemState.Completed ? SolutionType.Final : s.IsFinished ? SolutionType.Partial : SolutionType.Ongoing,
                        Data   = s.Result
                    }).ToArray()
                };
                message.Respond(sender, response);
                manager.MarkAsSent(problem.Id);
            }
        }
Пример #21
0
        public ISolution1D CreateExactSolution(IGrid1D grid, object physicalData)
        {
            var solution = new DbGroup1D((DbGrid1D)grid, physicalData);

            Solutions.Add(solution);
            return(solution);
        }
Пример #22
0
        public ISolution1D CreateNumericTimeDependentSolution(IGrid1D grid, object physicalData, double dt, Type solverType)
        {
            var solution = new DbGroup1D((DbGrid1D)grid, physicalData, dt, solverType);

            Solutions.Add(solution);
            return(solution);
        }
Пример #23
0
        /// <summary>
        /// Calculate the solution to the game
        /// </summary>
        private static Solutions CalculateSolution(DownCountGame game)
        {
            Solutions solutions = DownCountSolver.Solve(game, false);

            if (solutions.Count == 0)
            {
                //Look for a 'close' soltion
                DownCountGame closeGame = new DownCountGame(game.TargetNumber, game.Numbers.ToArray());;
                for (int i = 1; i <= 10; ++i)
                {
                    closeGame.TargetNumber = game.TargetNumber - i;
                    solutions = DownCountSolver.Solve(closeGame, false);
                    if (solutions.Count > 0)
                    {
                        return(solutions);
                    }

                    closeGame.TargetNumber = game.TargetNumber + i;
                    solutions = DownCountSolver.Solve(closeGame, false);
                    if (solutions.Count > 0)
                    {
                        return(solutions);
                    }
                }
            }

            return(solutions);
        }
Пример #24
0
        private static HashSet <string> pruneTreeSearch = new HashSet <string>(); // To prune branches of tree search

        /// <summary>Creator of search process</summary>
        /// <param name="initialBase">Initial base of numbers<</param>
        /// <param name="target">Number to find</param>

        public Search(ulong[] initialBase, ulong target)
        {
            BaseNbrs = new Base(initialBase); // Setup initial base of numbers
            BestSol  = new Solutions(target); // Setup target
            BestSol.CheckCandidate(BaseNbrs); // initialBase could already contains solutions
            Loop(BaseNbrs);                   // Start recursive search
        }
Пример #25
0
        public void Solutions_DivideOperator_Test()
        {
            //Try to represent the equation ((5+1) x 3) - 4
            IEquation node1     = new AddOperation(new Integer(5), new Integer(1));
            IEquation node2     = new MultiplyOperation(node1, new Integer(3));
            IEquation equation1 = new MinusOperation(node2, new Integer(4));

            //Try to represent the equation 1 + 2  +3
            IEquation node3     = new AddOperation(new Integer(1), new Integer(2));
            IEquation equation2 = new AddOperation(node3, new Integer(3));

            Solutions solutions = new Solutions();

            solutions.Add(equation1);
            solutions.Add(equation2);

            IEquation equation3 = new Integer(14);

            Solutions new_solutions = solutions / equation3;

            Assert.AreEqual(2, new_solutions.Count);
            Assert.AreEqual(1, new_solutions[0].Value);
            Assert.AreEqual((decimal)6 / (decimal)14, new_solutions[1].Value);

            new_solutions = solutions / new Integer(3);
            Assert.AreEqual(2, new_solutions.Count);
            Assert.AreEqual((decimal)14 / (decimal)3, new_solutions[0].Value);
            Assert.AreEqual(2, new_solutions[1].Value);
        }
Пример #26
0
 public void CreateNew()
 {
     Solutions.Clear();
     Title    = string.Format(R.solutionCollection, ++counter);
     Filename = null;
     Modified = false;
 }
Пример #27
0
        public bool Load(string filepath)
        {
            string AppDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? ".";

            solutions = Solutions.FromFile(provider, Path.GetFullPath(filepath, AppDir));
            return(solutions.All.Count != 0);
        }
Пример #28
0
        public void Solutions_MinusOperator_Test()
        {
            //Try to represent the equation ((5+1) x 3) - 4
            IEquation node1 = new AddOperation(new Integer(5), new Integer(1));
            IEquation node2 = new MultiplyOperation(node1, new Integer(3));
            IEquation equation1 = new MinusOperation(node2, new Integer(4));

            //Try to represent the equation 1 + 2  +3
            IEquation node3 = new AddOperation(new Integer(1), new Integer(2));
            IEquation equation2 = new AddOperation(node3, new Integer(3));

            Solutions solutions = new Solutions();
            solutions.Add(equation1);
            solutions.Add(equation2);

            IEquation equation3 = new Integer(4);

            Solutions new_solutions = solutions - equation3;
            Assert.AreEqual(2, new_solutions.Count);
            Assert.AreEqual(10, new_solutions[0].Value);
            Assert.AreEqual(2, new_solutions[1].Value);

            new_solutions = equation3 - solutions;
            Assert.AreEqual(2, new_solutions.Count);
            Assert.AreEqual(-10, new_solutions[0].Value);
            Assert.AreEqual(-2, new_solutions[1].Value);
        }
Пример #29
0
        private void UpdateSolutions(sbyte[] solution)
        {
            // For SolutionMode.Single:
            if (SolutionMode == SolutionMode.Single)
            {
                Solutions.Add(solution);
                return;
            }

            var symmetricalSolutions = Utility.GetSymmetricalSolutions(solution);

            // For SolutionMode.All, add this solution and all its symmetrical counterparts to Solutions.
            if (SolutionMode == SolutionMode.All)
            {
                Solutions.Add(solution);
                symmetricalSolutions.ForEach(s => Solutions.Add(s));
                return;
            }

            // For SolutionMode.Unique: Add this solution to Solutions only if no overlaps between Solutions and symmetricalSolutions are found.
            if (!Solutions.Overlaps(symmetricalSolutions))
            {
                Solutions.Add(solution);
            }
        }
Пример #30
0
        public void SerializeSolutions()
        {
            Solutions d   = new Solutions();
            string    xml = d.SerializeToXML();

            Assert.IsNotNull(xml);
        }
 /// <summary>
 /// Получено решение для миграции
 /// </summary>
 /// <param name="message"></param>
 private void OnMigrateSolutions(MigrateSolutionsMessage message)
 {
     foreach (var solution in message.Solutions)
     {
         Solutions.Add(solution);
     }
 }
Пример #32
0
        protected override void HandleCore(DivideProblem message)
        {
            logger.Info($"Received order to divide problems for task {message.Id}.");
            Task.Factory.StartNew(() =>
            {
                var taskSolver = taskSolverFactory.GetTaskSolver(Constants.ProblemName, message.Data);

                var data = taskSolver.DivideProblem(5);
                List <Solution> solutions = new List <Solution>();
                for (int i = 0; i < data.GetLength(0); i++)
                {
                    solutions.Add(new Solution()
                    {
                        TaskId = (ulong)i,
                        NodeID = message.NodeID,
                        Type   = SolutionType.Ongoing,
                        Data   = data[i]
                    });
                }

                var problems = new Solutions
                {
                    Id            = message.Id,
                    ProblemType   = message.ProblemType,
                    CommonData    = message.Data,
                    SolutionsList = solutions.ToArray()
                };
                var client = serverClientFactory();
                client.Send(problems);
            });
        }
Пример #33
0
        public SimplexAnswer(SimplexTable finalTable, AnswerStatus status = AnswerStatus.NoSolutions)
        {
            Status = status;
            Solution solution = new Solution();

            solution.BasisIndexes = (int[])finalTable.BasisVariablesIndexes.Clone();
            solution.OptimalValue = finalTable.GoalFunctionValue;
            double[]   optimalCoefficients = new double[finalTable.CountOfVariables];
            List <int> freeIndexes         = new List <int>();

            // все небазисные (свободные) переменные равны 0
            for (int i = 0; i < finalTable.CountOfVariables; i++)
            {
                if (finalTable.BasisVariablesIndexes.Contains(i))
                {
                    optimalCoefficients[i] = finalTable.FreeMemebers[i];
                }
                else
                {
                    freeIndexes.Add(i);
                    optimalCoefficients[i] = 0;
                }
            }
            solution.FreeIndexes         = freeIndexes.ToArray();
            solution.OptimalCoefficients = optimalCoefficients;
            solution.StartIndexes        = finalTable.StartVariablesIndexes;
            Solutions.Add(solution);
        }
Пример #34
0
        /// <summary>
        /// Method to select parents from the population based on the Parent Selection Method setting.
        /// </summary>
        /// <returns></returns>
        public List <Chromosome> SelectParents()
        {
            //apply a Fisher-Yates shuffle
            Solutions.ShuffleFast(RandomProvider.GetThreadRandom());

            switch (ParentSelectionMethod)
            {
            case ParentSelectionMethod.FitnessProportionateSelection:
            {
                return(GetFpsSelection());
            }

            case ParentSelectionMethod.StochasticUniversalSampling:
            {
                return(GetSusSelection());
            }

            case ParentSelectionMethod.TournamentSelection:
            {
                return(GetTournamentSelection());
            }

            default:
            {
                return(GetFpsSelection());
            }
            }
        }
        /// <summary>
        /// Response for clients solution request
        /// </summary>
        /// <param name="networkAdapter"></param>
        /// <param name="message"></param>
        /// <param name="messageType"></param>
        /// <param name="timeout"></param>        
        public void HandleMessage(ServerNetworkAdapter networkAdapter, string message, MessageType messageType, TimeSpan timeout)
        {
            SolutionRequest request = MessageSerialization.Deserialize<SolutionRequest>(message);

            if (request == null)
                return;

            DvrpProblem.WaitEvent.WaitOne();

            if (!DvrpProblem.Problems.ContainsKey(request.Id))
            {
                DvrpProblem.WaitEvent.Set();
                return;
            }
            if (DvrpProblem.ProblemSolutions.ContainsKey(request.Id))
            {
                Solutions solution = DvrpProblem.ProblemSolutions[request.Id];

                DvrpProblem.ProblemsID.Remove(request.Id);
                DvrpProblem.Problems.Remove(request.Id);
                DvrpProblem.ProblemSolutions.Remove(request.Id);

                networkAdapter.Send(solution);
                DvrpProblem.WaitEvent.Set();
                return;
            }

            SolveRequest problem = DvrpProblem.Problems[request.Id];
            Solutions response = new Solutions();
            response.Id = request.Id;
            response.ProblemType = problem.ProblemType;
            response.CommonData = problem.Data;
            List<SolutionsSolution> solutionList = new List<SolutionsSolution>();

            if (DvrpProblem.PartialSolutions.ContainsKey(request.Id))
                solutionList.AddRange(DvrpProblem.PartialSolutions[request.Id]);

            if (DvrpProblem.PartialProblems.ContainsKey(request.Id))
                foreach (var element in DvrpProblem.PartialProblems[request.Id])
                    if (element.Value > 0)
                    {
                        SolutionsSolution sol = new SolutionsSolution();
                        sol.TaskId = element.Key.TaskId;
                        sol.Data = element.Key.Data;
                        sol.Type = SolutionsSolutionType.Ongoing;
                        solutionList.Add(sol);
                    }

            if (solutionList.Count > 0)
                response.Solutions1 = solutionList.ToArray();
            else
                response.Solutions1 = new SolutionsSolution[] { new SolutionsSolution { Data = new byte[1] } };

            networkAdapter.Send(response);
            DvrpProblem.WaitEvent.Set();
        }
        public void RegisterFinalSolution()
        {
            DvrpProblem.ProblemSolutions.Clear();
            Solutions request = new Solutions()
            {
                Id = 1,
                CommonData = new byte[1],
                Solutions1 = new SolutionsSolution[] {new SolutionsSolution() {Type = SolutionsSolutionType.Final,Data = new byte[1]},},
                ProblemType = "dvrp",
            };
            SolutionsStrategy solutionsStrategy = new SolutionsStrategy();
            string msg = MessageSerialization.Serialize(request);

            solutionsStrategy.HandleMessage(networkAdapterMock.Object, msg, MessageType.RegisterMessage, new TimeSpan(0, 1, 0));

            Assert.AreEqual(DvrpProblem.ProblemSolutions.Count, 1);
        }
        public void ResponseIfProblemIsSolved()
        {
            DvrpProblem.Problems.Clear();
            DvrpProblem.ProblemSolutions.Clear();
            SolveRequest solveRequest = new SolveRequest() {Data = new byte[1]};
            DvrpProblem.Problems.Add(1, solveRequest);
            Solutions solution = new Solutions()
            {
                CommonData = new byte[1],
                Solutions1 = new SolutionsSolution[] {new SolutionsSolution() {Data = new byte[1]}}
            };
            SolutionRequest request = new SolutionRequest() {Id = 1};
            DvrpProblem.ProblemSolutions.Add(request.Id, solution);
            string msg = MessageSerialization.Serialize(request);
            SolutionRequestStrategy solutionRequestStrategy = new SolutionRequestStrategy();

            solutionRequestStrategy.HandleMessage(networkAdapterMock.Object, msg, MessageType.SolutionRequestMessage, new TimeSpan(0,1,0));

            networkAdapterMock.Verify(p => p.Send(It.IsAny<Solutions>()), Times.Once);
            //Assert.AreEqual(DvrpProblem.ProblemSolutions.Count, 0);
        }
Пример #38
0
        /// <summary>
        /// Solve the game by solving the subset that considedrs the ith element in isolation
        /// </summary>
        /// <param name="game"></param>
        /// <param name="i"></param>
        /// <returns></returns>
        private static Solutions SolveSubset(DownCountGame game, int i, bool allSolutions = true)
        {
            Solutions solutions = new Solutions();
            int currentNumber = game.Numbers[i];
            IntegerSet subset = game.Numbers.SubsetNotIncluding(i);
            DownCountGame gameAdd = new DownCountGame();
            gameAdd.TargetNumber = game.TargetNumber - currentNumber;
            gameAdd.Numbers = subset;
            solutions.AddRange(Solve(gameAdd, allSolutions) + new Integer(currentNumber));
            if (!allSolutions && solutions.Count > 0)
                return solutions;

            DownCountGame gameMinus = new DownCountGame();
            gameMinus.TargetNumber = game.TargetNumber + currentNumber;
            gameMinus.Numbers = subset;
            solutions.AddRange(Solve(gameMinus, allSolutions) - new Integer(currentNumber));
            if (!allSolutions && solutions.Count > 0)
                return solutions;

            DownCountGame gameMultiply = null;
            if (game.TargetNumber % currentNumber == 0)
            {
                gameMultiply = new DownCountGame();
                gameMultiply.TargetNumber = game.TargetNumber / currentNumber;
                gameMultiply.Numbers = subset;
                solutions.AddRange(Solve(gameMultiply, allSolutions) * new Integer(currentNumber));
                if (!allSolutions && solutions.Count > 0)
                    return solutions;
            }

            DownCountGame gameDivide = new DownCountGame();
            gameDivide.TargetNumber = game.TargetNumber * currentNumber;
            gameDivide.Numbers = subset;
            solutions.AddRange(Solve(gameDivide, allSolutions) / new Integer(currentNumber));
            if (!allSolutions && solutions.Count > 0)
                return solutions;

            return solutions;
        }
Пример #39
0
        /// <summary>
        /// Sends partial solutions to task (if any is available)
        /// </summary>
        public static void Work(ulong taskId, ServerNetworkAdapter networkAdapter)
        {
            if (DvrpProblem.ProblemsDividing[taskId].Count > 0 || DvrpProblem.SolutionsMerging[taskId].Count > 0)
                return;

            ulong problemId = 0;

            var problems = new List<ulong>(DvrpProblem.ProblemsID);

            foreach (var list in DvrpProblem.ProblemsDividing.Values)
                foreach (var el in list)
                    problems.Remove(el);

            foreach (var list in DvrpProblem.SolutionsMerging.Values)
                foreach (var el in list)
                    problems.Remove(el);

            foreach (var id in problems)
                if (!DvrpProblem.PartialProblems.ContainsKey(id) && DvrpProblem.PartialSolutions.ContainsKey(id) && !DvrpProblem.ProblemSolutions.ContainsKey(id))
                {
                    problemId = id;
                    break;
                }

            if (problemId == 0)
                return;

            var partialSolutions = DvrpProblem.PartialSolutions[problemId];
            SolveRequest problem = DvrpProblem.Problems[problemId];
            Solutions response = new Solutions();
            response.Id = problemId;
            response.ProblemType = problem.ProblemType;
            response.CommonData = problem.Data;
            response.Solutions1 = partialSolutions.ToArray();

            if (networkAdapter.Send(response))
                DvrpProblem.SolutionsMerging[taskId].Add(problemId);
        }
Пример #40
0
        /// <summary>
        /// Solve the given downcount game
        /// </summary>
        /// <param name="game"></param>
        /// <param name="allSolutions"></param>
        /// <returns></returns>
        public static Solutions Solve(DownCountGame game, bool allSolutions = true)
        {
            Solutions solutions = new Solutions();

            if (game.Numbers.Contains(game.TargetNumber))
                solutions.Add(new Integer(game.TargetNumber));

            if (!allSolutions && solutions.Count > 0)
                return solutions;

            if (game.Numbers.Count == 1)
                return solutions;

            for (int i = 0; i < game.Numbers.Count; ++i)
            {
                solutions.AddRange(SolveSubset(game, i, allSolutions));

                if (!allSolutions && solutions.Count > 0)
                    return solutions;
            }

            return solutions;
        }
Пример #41
0
 public static void AddBackup(List<MerginSolutionBackup> list, int compID, Solutions sol)
 {            
     var element = new MerginSolutionBackup() { ComponentID = compID, Solution = sol };
     list.Add(element);
 }
Пример #42
0
 private void ReceiveSolutions(Solutions solutions)
 {
     this.solution = solutions;
 }
        private void Solution()
        {
            try
            {
                List<SolutionsSolution> s = new List<SolutionsSolution>();
                foreach(var e in solutions)
                {
                    s.Add(new SolutionsSolution
                    {
                        Type = SolutionsSolutionType.Partial,
                        Data = e.Value,
                        TaskId = e.Key,
                        TaskIdSpecified = true,
                        ComputationsTime = computationsTime,
                        TimeoutOccured = timeOccured
                    });
                }

                var solution = new Solutions
                {
                    ProblemType = problem.ProblemType,
                    Id = problem.Id,
                    Solutions1 = s.ToArray(),
                    CommonData = problem.CommonData,
                };

                networkAdapter.Send(solution, true);
            }
            catch (Exception)
            {
                Console.WriteLine("Cannot send partial solution to server");
            }
        }
Пример #44
0
        private void SendFinalSolution(ulong id)
        {
            try
            {
                List<byte[]> solutions = new List<byte[]>();
                foreach (var partialSolution in solution.Solutions1)
                {
                    solutions.Add(partialSolution.Data);
                }
                taskSolver.MergeSolution(solutions.ToArray());

                var solutionToSend = new Solutions
                {
                    ProblemType = "DVRP",
                    Id = 1,
                    Solutions1 = new[] { new SolutionsSolution { Type = SolutionsSolutionType.Final, TaskId = (ulong) id, Data = taskSolver.Solution} }
                };
                networkAdapter.Send(solutionToSend, true);
            }
            catch (Exception)
            {
                Console.WriteLine("Cannot send final solution to server");
            }
        }