/// <summary> /// Solves the TSP. /// </summary> /// <param name="problem"></param> /// <returns></returns> protected override IRoute DoSolve(IProblem problem) { // initialize. List<int> solution = new List<int>(); for (int idx = 0; idx < problem.Size; idx++) { // add each customer again. solution.Add(idx); } // keep on looping until all the permutations // have been considered. PermutationEnumerable<int> enumerator = new PermutationEnumerable<int>( solution.ToArray()); int[] best = null; double bestWeight = double.MaxValue; foreach (int[] permutation in enumerator) { double weight = RouteExtensions.CalculateWeight(permutation, problem.First == problem.Last, problem); if (weight < bestWeight) { // the best weight has improved. bestWeight = weight; best = permutation; } } return new SimpleAsymmetricRoute(best.ToList<int>(), true); }
public ProblemItem(IProblem problem, Assembly assembly) { Problem = problem; _Assembly = assembly; var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies(); var loadedAssemblyNames = new List<string>(); foreach (var i in loadedAssemblies) { loadedAssemblyNames.Add(i.GetName().ToString()); } try { string url = @"http://chart.apis.google.com/chart?cht=tx&chf=bg,s,AAAAAA00&chs=" + 60 + "&chl=" + problem.Equation.Replace("+", "%2B"); BitmapImage bitmap = new BitmapImage(); bitmap.BeginInit(); bitmap.UriSource = new Uri(url, UriKind.RelativeOrAbsolute); bitmap.CacheOption = BitmapCacheOption.OnLoad; bitmap.EndInit(); EquationImage = bitmap; } catch { EquationImage = null; } }
private void SolveRecursive(IProblem problem, Board initial, Board board, IAssignmentCollection assignments) { var availableAssignments = problem.GetDomains(board).ToList(); // if there's no more assignments the game is done, save, then go back up the chain if (availableAssignments.Count == 0) { solutions.Add(new Solution(initial, assignments)); return; } foreach (var assignment in availableAssignments) { // keep a list of visited nodes. if we've seen this // before then skip it, no need to explore it again string hashCode = assignment.Board.ToString(false); if (visitedNodes.Contains(hashCode)) continue; else visitedNodes.Add(hashCode); // add assignment to previous lsit var newAssignments = assignments.Clone(); newAssignments.Add(assignment); // recurse down recursionLevel++; SolveRecursive(problem, initial, assignment.Board, newAssignments); recursionLevel--; } }
private static void WriteHeader(IProblem p) { Separator(); Debug.WriteLine(p.Name); Debug.WriteLine(p.Description); Separator(); }
/// <summary> /// Converts a problem. /// </summary> /// <param name="atsp"></param> /// <param name="name"></param> /// <param name="comment"></param> /// <returns></returns> public static TSPLIBProblem Convert(IProblem atsp, string name, string comment) { // convert the problem to a symetric one. IProblem symetric = atsp.ConvertToSymmetric(); return new TSPLIBProblem(name, comment, symetric.Size, symetric.WeightMatrix, TSPLIBProblemWeightTypeEnum.Explicit, TSPLIBProblemTypeEnum.TSP, 0, 0); }
private static void TimedExecute(IProblem problem) { var timer = Stopwatch.StartNew(); var result = problem.Execute(); timer.Stop(); Debug.WriteLine(string.Format("Executed in {0}ms", timer.ElapsedMilliseconds)); Debug.WriteLine(string.Format("Result: {0}", result)); }
private static void SolveProblem(IProblem problem) { Console.WriteLine("\n----------------------------"); string message = string.Format("Problem {0}: {1}", problem.Number.ToString().PadLeft(3, '0'), problem.Description); Console.WriteLine(message); var solution = problem.Solve(); Console.WriteLine("\nThe answer is: {0}", solution); Console.WriteLine("----------------------------"); }
/// <summary> /// Generates a random route. /// </summary> /// <param name="problem"></param> /// <returns></returns> public static IRoute DoSolveStatic(IProblem problem) { List<int> customers = new List<int>(); for (int customer = 0; customer < problem.Size; customer++) { customers.Add(customer); } customers.Shuffle<int>(); return DynamicAsymmetricRoute.CreateFrom(customers); }
static void ExecuteProblem(IProblem problem) { Stopwatch sw = new Stopwatch(); sw.Start(); Console.WriteLine("Execution of {0} started at {1}", problem.GetType().Name, DateTime.Now); Console.WriteLine("--------------------------"); Console.WriteLine(problem.Solve()); Console.WriteLine("--------------------------"); sw.Stop(); Console.WriteLine("Execution lasted {0}", sw.Elapsed); }
/// <summary> /// Creates new instance of TspLib95Item class /// </summary> /// <param name="problem">TSP problem to be encapsulated</param> /// <param name="optimalTour">Optimal tour of the problem</param> /// <param name="optimalTourDistance">Optimal tour distance</param> public TspLib95Item(IProblem problem, ITour optimalTour, double optimalTourDistance) { if (problem == null) { throw new ArgumentNullException("problem"); } Problem = problem; OptimalTour = optimalTour; _optimalTourDistance = optimalTourDistance; }
private static void writeInputData(StringBuilder text, IProblem problem) { text.AppendLine("\n" + @"\begin{large}Input data:\end{large}"); text.AppendLine("\n" + @"\begin{tabular}{l l l}" + "\nParameter & Data Type & Value" + @" \\ \hline"); foreach (var item in problem.InputData) { text.AppendLine(@"\texttt{" + item.Name + @"} & \texttt{" + item.Type + @"} & \texttt{" + item.Value + @"} \\"); } text.AppendLine(@"\hline"); text.AppendLine(@"\end{tabular}" + "\n"); }
private void SolveProblem(IProblem problem) { var stopwatch = new Stopwatch(); stopwatch.Start(); var result = problem.Solve(); stopwatch.Stop(); Console.WriteLine(result); Console.WriteLine("Program took {0}ms to solve", stopwatch.ElapsedMilliseconds); }
private void problemTabPage_DragDrop(object sender, DragEventArgs e) { if (e.Effect != DragDropEffects.None) { IProblem problem = e.Data.GetData("Value") as IProblem; if ((e.Effect & DragDropEffects.Copy) == DragDropEffects.Copy) { problem = (IProblem)problem.Clone(); } Content.Problem = problem; } }
public override void Eval(IEvolutionState state, int thread, GPData input, ADFStack stack, GPIndividual individual, IProblem problem) { var md = (MajorityData)input; md.Data0 = X0; md.Data1 = X1; }
/// <summary> /// Executes the solver. /// </summary> /// <param name="problem"></param> /// <returns></returns> public IRoute Solve(IProblem problem) { IProblem converted_problem = problem; bool first = problem.First.HasValue; bool last = problem.Last.HasValue; // convert the problem if needed. if (!first && !last) { // add a virtual customer with distance zero to all existing customers. double[][] new_weights = new double[problem.WeightMatrix.Length + 1][]; new_weights[0] = new double[problem.WeightMatrix.Length + 1]; for (int idx = 0; idx < problem.WeightMatrix.Length + 1; idx++) { new_weights[0][idx] = 0; } for(int idx = 0; idx < problem.WeightMatrix.Length; idx++) { new_weights[idx+1] = new double[problem.WeightMatrix.Length + 1]; new_weights[idx+1][0] = 0; problem.WeightMatrix[idx].CopyTo(new_weights[idx+1], 1); } converted_problem = MatrixProblem.CreateATSP(new_weights, 0); } else if (!last) { // set all weights to the first customer to zero. for (int idx = 0; idx < problem.WeightMatrix.Length; idx++) { problem.WeightMatrix[idx][problem.First.Value] = 0; } converted_problem = MatrixProblem.CreateATSP(problem.WeightMatrix, problem.First.Value); } // execute the solver on the converted problem. IRoute converted_route = this.DoSolve(converted_problem); // convert the route back. if (!first && !last) { // when a virtual customer was added the route needs converting. List<int> customers_list = converted_route.ToList<int>(); customers_list.RemoveAt(0); for (int idx = 0; idx < customers_list.Count; idx++) { customers_list[idx] = customers_list[idx] - 1; } converted_route = DynamicAsymmetricRoute.CreateFrom(customers_list, false); } else if (!last) { // the returned route will return to customer zero; convert the route. converted_route = DynamicAsymmetricRoute.CreateFrom(converted_route, false); } return converted_route; }
/// <summary> /// Creates SimulatedAnnealing algorithm instance /// </summary> /// <param name="graph">Graph on which algorithm will operate</param> /// <param name="problem">Problem for which algorithm will attempt to find solution</param> /// <param name="setup">Setup for algorithm's cooling process</param> //TODO: Introduce SavedState complex type public SimulatedAnnealing(Graph graph, IProblem problem, CoolingSetup setup, double? currentTemperature = null, Guid? id = null) : base(graph, problem, id) { if (setup == null) throw new ArgumentNullException(nameof(setup)); if (!setup.IsValid()) throw new ArgumentException("Setup is invalid", nameof(setup)); CoolingSetup = setup; if (currentTemperature.HasValue) CurrentTemperature = currentTemperature.Value; else CurrentTemperature = setup.InitialTemperature; }
public BidirectionalEightPuzzleProblem(EightPuzzleBoard initialState) : base(initialState, new EightPuzzleFunctions.ActionFunctionEB(), new EightPuzzleFunctions.ResultFunctionEB(), EightPuzzleFunctions.GOAL_STATE.Equals) { reverseProblem = new GeneralProblem <EightPuzzleBoard, IAction>( EightPuzzleFunctions.GOAL_STATE, new EightPuzzleFunctions.ActionFunctionEB(), new EightPuzzleFunctions.ResultFunctionEB(), initialState.Equals); }
protected Algorithm(Graph graph, IProblem problem, Guid? id) : base(id) { if (problem == null) throw new ArgumentNullException(nameof(problem)); if (graph == null) throw new ArgumentNullException(nameof(graph)); if (!graph.IsValid()) throw new ArgumentException("Graph is invalid", nameof(graph)); Graph = graph; Problem = problem; problem.Initialize(graph); }
public override void Eval(IEvolutionState state, int thread, GPData input, ADFStack stack, GPIndividual individual, IProblem problem) { var rd = ((TwoBoxData)(input)); var tb = ((TwoBox)problem); rd.x = tb.inputsh1[tb.currentIndex]; }
// Обновить описание для выбранной задачи private void UpdateProblemDescription() { int selectedProblemIndex = listBoxProblems.SelectedIndex; if (selectedProblemIndex < 0) { labelProblemDescription.Text = ""; return; } IProblem selectedProblem = problems[selectedProblemIndex]; labelProblemDescription.Text = selectedProblem.ProblemDescriptor.Description; }
public override ISolution Solve(IProblem problem) { var d = this.dt as Delta; var s = this.CurrentSolution as Solution; var p = problem as ControllerProblem; foreach (var c in p.CurrentQueue) { c.MainUpdate(d, s); } return(this.CurrentSolution); }
public override void Eval( IEvolutionState state, int thread, GPData input, ADFStack stack, GPIndividual individual, IProblem problem) { // Evaluate children. Easy as cake. Children[0].Eval(state, thread, input, stack, individual, problem); Children[1].Eval(state, thread, input, stack, individual, problem); Children[2].Eval(state, thread, input, stack, individual, problem); }
public void EvalPrint( IEvolutionState state, int thread, GPData input, ADFStack stack, GPIndividual individual, IProblem problem, int[][] map2) { // Evaluate both children. Easy as cake. ((IEvalPrint)Children[0]).EvalPrint(state, thread, input, stack, individual, problem, map2); ((IEvalPrint)Children[1]).EvalPrint(state, thread, input, stack, individual, problem, map2); }
public IEnumerable <Node> Expand(IProblem problem) { var listOfTuples = problem.GetSuccessor(this.State); var nodesOut = new List <Node>(); foreach (var t in listOfTuples) { var nNode = new Node(t.Item2, this, t.Item1, problem.GetPathCost(this.PathCost, this.State, t.Item1, t.Item2)); nodesOut.Add(nNode); } return(nodesOut); }
public List <List <ResultModel> > RunWithMultipleExtraTabu(int iterations, IProblem problem, ISolver solver, int searchIteration, int minTabu, List <int> extraTabu, int timeLimitInSeconds) { var output = new List <List <ResultModel> >(); foreach (var i in extraTabu) { var results = Run(iterations, new LADS(problem), solver, searchIteration, minTabu, i, timeLimitInSeconds); output.Add(results); } return(output); }
/// <summary> /// Calculate by using TspLib95 functions /// </summary> /// <param name="tspLibProblem"></param> public void CalculateDistance(IProblem tspLibProblem) { problem = tspLibProblem; var nodes = problem.NodeProvider.GetNodes(); for (int i = 1; i <= Size; i++) { for (int j = 1; j <= Size; j++) { Matrix[i, j] = problem.EdgeWeightsProvider.GetWeight(nodes[i - 1], nodes[j - 1]); } } }
public SearchAgent(IProblem <S, A> p, ISearchForActions <S, A> search) { ICollection <A> actions = search.findActions(p); actionList = CollectionFactory.CreateQueue <A>(); if (null != actions) { actionList.AddAll(actions); } // actionIterator = actionList.iterator(); searchMetrics = search.getMetrics(); }
public GenerationalGeneticAlgorithm( IProblem <T> problem, int populationSize, ISelectionOperator <T> selectionOperator, ICrossoverOperator <T> crossoverOperator, IMutationOperator <T> mutationOperator, ITerminationCondition terminationCondition, double elitismRate) : base(problem, populationSize, selectionOperator, crossoverOperator, mutationOperator, terminationCondition) { _elitismRate = elitismRate; }
public NeuralNetwork Train(IProblem problem) { var description = problem.Get(); var neuralNetwork = _networkLayers.Create(description.InputNeurons.Count(), description.HiddenLayers.Select(x => x.NeuronsCount).ToList(), description.OutputNeurons.Count(), description.AutoAdjuctHiddenLayer); OnNetworkReconfigured?.Invoke(this, new NetworkReconfiguredEventArgs(neuralNetwork.HiddenLayers.Aggregate(new List <int>(), (list, layer) => { list.Add(layer.Count()); return(list); }))); neuralNetwork.MathFunctions = description.MathFunctions; neuralNetwork.Name = description.NeuronNetworkName; neuralNetwork.Divisor = description.Divisor; var iteration = 0; while (++iteration < int.MaxValue) { //train _trainSet.Train(neuralNetwork, description); //can NN train any more? if (_validationSet.StopIterations(neuralNetwork, description)) { OnLearningCycleComplete?.Invoke(this, new LearningCycleCompleteEventArgs(iteration, neuralNetwork.NeuralNetworkError)); break; } OnLearningCycleComplete?.Invoke(this, new LearningCycleCompleteEventArgs(iteration, neuralNetwork.NeuralNetworkError)); //neuralNetwork.LearningRate = neuralNetwork.LearningRate * 1d / (iteration + 1); } //store NN _neuralNetworkSetup.Add(neuralNetwork); _neuralNetworkSetup = _neuralNetworkSetup.OrderBy(x => x.NeuralNetworkError).Take(5).ToList(); //check if we have to reconfigure or retrain NN if (!_validationSet.StopTraining(neuralNetwork, description)) { neuralNetwork = Train(problem); } //choose best NN Setup neuralNetwork = _neuralNetworkSetup.OrderBy(x => x.NeuralNetworkError).First(); //test, find real life error _testSet.Test(neuralNetwork, description); return(neuralNetwork); }
private int?SelectX( IProblem problem, FixedSymmetricRoute route, EdgeSet X, EdgeSet Y, EdgeList x, int customer, HashSet <int> exceptions) { // select the only two edges that have the given customer in the given route. int[] neigbours = route.GetNeigbours(customer); int previous = neigbours[0]; int next = neigbours[1]; int? best_neighour = null; double best_weight = double.MinValue; if (previous > 0 && (exceptions == null || !exceptions.Contains(previous)) && !x.Contains(customer, previous)) //&& !X.Contains(customer, previous)) //&& !Y.Contains(customer, previous)) { //if (x.Count > 2) //{ double weight = problem.Weight(customer, previous); if (weight > best_weight) { best_neighour = previous; best_weight = weight; } //} //else //{ return(previous); //} } if (next > 0 && (exceptions == null || !exceptions.Contains(next)) && !x.Contains(customer, next)) //&& !X.Contains(customer, previous)) //&& !Y.Contains(customer, previous)) { //if (x.Count > 2) //{ double weight = problem.Weight(customer, next); if (weight > best_weight) { best_neighour = next; best_weight = weight; } //} //else //{ return(next); //} } return(best_neighour); }
public override List <IAction> Search(IProblem problem) { var node = new Node(null, 0, 0, problem.InitialState(), null); var children = new List <Node>(); var frontier = new List <Node>(); var explored = new List <IState>(); Node tmp; // On ajoute la racine frontier.Add(node); do { // Si la frontiere est vide, on arr�te if (frontier.Count == 0) { return(null); } // Si on trouve la solution, on la retourne if (problem.GoalTest(node.State)) { return(Solution(node)); } // On prend le noeud avec le cout le plus petit node = frontier[0]; frontier.RemoveAt(0); // On l'ajoute � la lsite des noeuds explor�s si besoin if (!explored.Contains(node.State)) { explored.Add(node.State); } // On g�n�re les enfants children = Expand(node, problem); // On ajoute l'enfant au bon endroit for (var i = 0; i < children.Count; i++) { if (!explored.Contains(children[i].State)) { frontier.Add(children[i]); for (var j = frontier.Count - 1; j > 0; j--) { if (frontier[j].Cost < frontier[j - 1].Cost) { tmp = frontier[j]; frontier[j] = frontier[j - 1]; frontier[j - 1] = tmp; } } } } } while (true); }
static void Main(string[] args) { var parser = new ArgParser(); var parameters = parser.GetParameters(_args); var factory = new WorkerFactory(); IProblem worker = (IProblem)factory.GetWorker(parameters.Problem); worker.Solve(parameters.Input); Console.WriteLine("Press any key to quit"); Console.ReadKey(); }
public static void RunProblem(IProblem problem) { Console.WriteLine(problem.GetProblemDescription()); Console.WriteLine(); var stopwatch = new Stopwatch(); stopwatch.Start(); var result = problem.Solve(); stopwatch.Stop(); Console.WriteLine("Solution to problem {0}: {1}", problem.GetProblemNumber(), result); Console.WriteLine("Problem solved in {0}", stopwatch.Elapsed); }
private static void writePlot(IProblem problem, StringBuilder text, bool showLegend) { if (text == null) { text = new StringBuilder(); } text.AppendLine("\n" + @"\begin{large}Problem plot:\end{large}" + "\n"); text.AppendLine(@"\begin{tikzpicture}"); text.Append(@"\begin{axis}[axis x line=bottom, axis y line=left,"); if (!string.IsNullOrEmpty(problem.Result.VisualTitleKey) && !string.IsNullOrEmpty(problem.Result.VisualTitleValue)) { text.Append("xlabel=$" + problem.Result.VisualTitleKey + "$, ylabel=$" + problem.Result.VisualResult + "$,"); } text.Append(" legend pos= north east]\n"); int titlesCount = 0; //foreach (var plot in problem.Result.VisualResult) //{ // text.AppendLine(@"\addplot[mark=none,black,thick] coordinates {"); // for (int i = 0; i < plot.Keys.Length; ++i) // { // text.Append("(" + plot.Keys[i].ToString().Replace(",", ".") + ", " + plot.Values[i].ToString().Replace(",", ".") + ")"); // } // text.Append("};\n"); // if (!string.IsNullOrEmpty(plot.Title)) // { // ++titlesCount; // } //} //if (titlesCount == problem.Result.VisualResult.Count && showLegend) //{ // text.Append(@"\legend{"); // for (int i = 0; i < problem.Result.VisualResult.Count; ++i) // { // text.Append("$" + problem.Result.VisualResult[i].Title.Replace(" ", "") + "$"); // if (i < problem.Result.VisualResult.Count - 1) // { // text.Append(","); // } // } // text.Append("};\n"); //} text.AppendLine(@"\end{axis}"); text.AppendLine(@"\end{tikzpicture}"); }
/// <summary> /// @param Problem /// @return /// </summary> public override List <IAction> Search(IProblem problem) { var depthLimit = 999;//max depth to avoid infinite loop for (var depth = 0; depth < depthLimit; depth++) { var result = DepthLimitedSearchF(problem, depth); if (result != null) { return(result); } } return(null); }
private void OnSolve(object sender, System.EventArgs e) { _answer.Text = string.Empty; _elapsed.Text = string.Empty; IProblem problem = Problem; if (problem == null) { MessageBox.Show(this, "The selected problem is not an IProblem", "Euler", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } Enabled = false; _worker.RunWorkerAsync(problem); }
protected internal void CalculateShortestPath(IProblem <T> problem, IPath <T> startPath, IList <int> leftToVisit) { if (leftToVisit.Count == 1) { IPath <T> path = startPath.To(leftToVisit[0]); SetBestPath(path); } else { List <IPath <T> > nextPaths = new List <IPath <T> >(); IPath <T> globalBestPath = problem.GetBestPath(); foreach (int?nextLocation in leftToVisit) { IPath <T> nextPath = startPath.To(nextLocation.Value); //if (globalBestPath == null || nextPath.getLength() < globalBestPath.getLength()) { if (nextPath.IsBetter(globalBestPath)) { nextPaths.Add(nextPath); } } problem.CalculateLengths(nextPaths); nextPaths.Sort(); if (problem.GetLocationsCount() - startPath.GetLocationsCount() > 8 && Volatile.Read(ref taskCount) <= threadCount) { foreach (IPath <T> nextPath in nextPaths) { IList <int> newLeftToVisit = new List <int>(leftToVisit); int nextLocation = nextPath.GetLast(); newLeftToVisit.Remove(nextLocation); Interlocked.Increment(ref taskCount); ThreadPool.QueueUserWorkItem(state => { CalculateShortestPath(problem, nextPath, newLeftToVisit); Interlocked.Decrement(ref taskCount); }); } } else { foreach (IPath <T> nextPath in nextPaths) { IList <int> newLeftToVisit = new List <int>(leftToVisit); int nextLocation = nextPath.GetLast(); newLeftToVisit.Remove(nextLocation); CalculateShortestPath(problem, nextPath, newLeftToVisit); } } } }
public Traversal( IProblem <TState, TCost> problem, IScenario <TState, TCost> scenario, TState initstate ) { Problem = problem; Scenario = scenario; var initstateestimateddistance = scenario.GetDistance(initstate); OpenNodes = new NodeRepository <TState, TCost>( new Node.Primitive <TState, TCost>(null, initstate, Problem.InitCost, initstateestimateddistance, Problem.Accumulate(Problem.InitCost, initstateestimateddistance)), Problem.Comparer); }
public BidirectionalMapProblem(Map map, string initialState, string goalState, GoalTest <string> goalTest) : base(initialState, MapFunctions.createActionsFunction(map), MapFunctions.createResultFunction(), goalTest, MapFunctions.createDistanceStepCostFunction(map)) { reverseProblem = new GeneralProblem <string, MoveToAction>( goalState, MapFunctions.createReverseActionsFunction(map), MapFunctions.createResultFunction(), initialState.Equals, MapFunctions.createDistanceStepCostFunction(map)); }
public override IHandleResult Handle(IProblem problem) { if (problem is TypeTwoProblem) { return(new Result() { Description = $"TypeTwoHandler managed {problem.GetDescription()}" }); } else { return(base.Handle(problem)); } }
public List <IParticle> Initialize(IProblem problem, int number) { List <IParticle> particles = new List <IParticle>(number); for (int i = 0; i < number; i++) { StandardParticle particle = new StandardParticle(); particle.Parameters = Parameters; particle.Initialize(problem); particles.Add(particle); } return(particles); }
public override void Eval(IEvolutionState state, int thread, GPData input, ADFStack stack, GPIndividual individual, IProblem problem) { Children[0].Eval(state, thread, input, stack, individual, problem); var md = (MajorityData)input; md.Data0 = ~(md.Data0); md.Data1 = ~(md.Data1); }
private const int _problemNumber = 4; // Set the value according to the problem number from https://projecteuler.net/archives static void Main(string[] args) { IProblem problem = ProblemFactory.Create(_problemNumber); if (problem != null) { var result = problem.GetResult(); Console.WriteLine(result); } else { Console.WriteLine("Sorry, it looks like Ark Fen did not yet have time to solve this problem yet ))"); } }
public virtual IHandleResult Handle(IProblem problem) { if (this._nextHandler != null) { return(this._nextHandler.Handle(problem)); } else { return(new Result() { Description = $"Unfortunately, none of handlers managed {problem.GetDescription()}" }); } }
/// <summary> /// Solves the problem. /// </summary> /// <returns></returns> protected override IRoute DoSolve(IProblem problem) { // generate some random route first. //IRoute route = OsmSharp.Math.TravellingSalesman.Random.RandomSolver.DoSolve( // problem); IRoute route = solver.Solve(problem); // improve the existing solution. double difference; this.Improve(problem, route, out difference); return(route); }
private static void GetSolution(int numProblem) { IProblem prob = null; string padNum = numProblem.ToString().PadLeft(3, '0'); Type type = Type.GetType("ProjectEuler.Problems.Problem" + padNum); prob = (IProblem)Activator.CreateInstance(type); Stopwatch stopWatch = Stopwatch.StartNew(); prob.Solution(); stopWatch.Stop(); Console.WriteLine("Elapsed Time: " + stopWatch.Elapsed + " / " + stopWatch.ElapsedTicks + " ticks"); }
private static bool TryGetProblem(int number, out IProblem problem) { var type = typeof(Program).Assembly .DefinedTypes .FirstOrDefault(t => t.GetCustomAttribute <ProblemAttribute>()?.Number == number); if (type != null) { problem = (IProblem)Activator.CreateInstance(type.AsType()); return(true); } problem = null; return(false); }
public Position InitializeFar(IProblem pb) { // Try to find a new position that is "far" from all the memorised ones //Note: memPos is a global variable double[] coord = new double[Constants.MMax]; double[] interv = new double[2]; var xFar = new Position(Constants.DMax) { size = pb.SwarmSize.D }; for (int d = 0; d < pb.SwarmSize.D; d++) // For each dimension { for (int n = 0; n < this.Size; n++) coord[n] = this.M[n].x[d]; // All the coordinates on // this dimension Array.Sort(coord); // Sort them // by increasing order // Find the biggest intervall interv[0] = coord[0]; interv[1] = coord[1]; double delta = interv[1] - interv[0]; for (int n = 1; n < this.Size - 1; n++) { if (coord[n + 1] - coord[n] < delta) continue; interv[0] = coord[n]; interv[1] = coord[n + 1]; delta = interv[1] - interv[0]; } // Particular case, xMax if (pb.SwarmSize.max[d] - coord[this.Size - 1] > delta) { xFar.x[d] = pb.SwarmSize.max[d]; delta = pb.SwarmSize.max[d] - coord[this.Size - 1]; } // Particular case, xMin if (coord[0] - pb.SwarmSize.min[d] > delta) xFar.x[d] = pb.SwarmSize.min[d]; else xFar.x[d] = 0.5 * (interv[1] + interv[0]);// Take the middle } xFar = Position.Discrete(xFar, pb); xFar.f = pb.Evaluate(xFar); return xFar; }
public IEnumerable<Solution> Solve(IProblem problem) { recursionLevel = 0; visitedNodes.Clear(); solutions.Clear(); Board initialState = problem.GetInitialState(); var watch = Stopwatch.StartNew(); SolveRecursive(problem, initialState, initialState, new AssignmentCollection()); watch.Stop(); EllapsedTimeInSeconds = watch.Elapsed.TotalSeconds; return solutions; }
//maybe this could change into some kind of reflection program that could pick up the latest program static void RunProblem(IProblem prob) { Stopwatch sp = new Stopwatch(); sp.Start(); prob.Run(); sp.Stop(); if (sp.ElapsedMilliseconds > 1000) { Console.WriteLine("Time Elapsed in Seconds: " + sp.Elapsed.TotalSeconds.ToString()); } else { Console.WriteLine("Time Elapsed in Milliseconds: " + sp.ElapsedMilliseconds.ToString()); } Console.ReadKey(); }
private Node RecursiveDls(Node node, IProblem problem, int limit) { if (problem.IsGoalTest(node.State)) return node; if(node.Depth == limit) return new DepthLimitReached(node.State); foreach (var successor in node.Expand(problem)) { var result = RecursiveDls(successor, problem, limit); if(result != null) return result; } return new DepthLimitReached(node.State); }
public static string getTexMarkupForProblem(IProblem problem, bool showLegend) { StringBuilder fileContent = new StringBuilder(); writeTexHeader(fileContent, showLegend); fileContent.AppendLine(@"\definecolor{light-gray}{gray}{0.5}\pagenumbering{gobble}"); fileContent.AppendLine(@"\begin{document}"); fileContent.AppendLine(@"\begin{center}"); writeHeader(fileContent, problem); writeInputData(fileContent, problem); writeEmptyEquation(fileContent); writePlot(problem, fileContent, showLegend); writeEmptyEquation(fileContent); writeWatermark(fileContent); fileContent.AppendLine(@"\end{center}"); fileContent.AppendLine(@"\end{document}"); return fileContent.ToString(); }
/// <summary> /// Creates instance of genetic algorithm /// </summary> /// <param name="graph">Graph on which algorithm will operate</param> /// <param name="problem">Problem for which algorithm will attempt to find solution</param> /// <param name="geneticOperators">Genetic operators used for breeding new generations</param> /// <param name="settings">General settings for solution finding process</param> /// <param name="startingPopulation">Starting population for algorithm</param> //TODO: Introduce SavedState complex type public GeneticAlgorithm(Graph graph, IProblem problem, GeneticOperators geneticOperators, GeneticAlgorithmSettings settings, ICollection<Individual> startingPopulation = null, uint currentGeneration = 0, Guid? id = null) : base(graph, problem, id) { if (geneticOperators == null) throw new ArgumentNullException(nameof(geneticOperators)); if (!geneticOperators.IsValid()) throw new ArgumentException("Genetic operators are not valid", nameof(geneticOperators)); if (settings == null) throw new ArgumentNullException(nameof(settings)); GeneticOperators = geneticOperators; Settings = settings; if (startingPopulation == null || startingPopulation.Count == 0 || !startingPopulation.All(IsIndividualValid)) GenerateInitialPopulation(); else { CurrentPopulation = new SortedSet<Individual>(); foreach (var element in startingPopulation) CurrentPopulation.Add(element); } CurrentGeneration = currentGeneration; }
private RouteFound AfterSelectt2(IProblem problem, RouteFound route, EdgeSet X, EdgeSet Y, EdgeList x) { int t_2 = x[0].To; // try and find a better route with t_1. RouteFound new_route = new RouteFound() { RouteWeight = float.MaxValue, Route = null }; // step 4 and step 10. HashSet<int> t_3_exceptions = new HashSet<int>(); EdgeList y = new EdgeList(); int? result = this.SelectY(problem, route.Route, X, Y, x, y, t_3_exceptions); while (result != null) { // select t_3. int t_3 = result.Value; t_3_exceptions.Add(t_3); // add y_1 to the edge list. Edge y_edge = new Edge() { From = t_2, To = t_3, Weight = problem.Weight(t_2, t_3) }; y.Add(y_edge); Y.Add(y_edge); // search route with t_3. new_route = this.AfterSelectt3(problem, route, X, Y, x, y); if (new_route.Route != null && new_route.RouteWeight < route.RouteWeight) { // trackback to t_1 if a better route is found. break; } // remove y_1 again and backtrack. y.RemoveLast(); result = this.SelectY(problem, route.Route, X, Y, x, y, t_3_exceptions); } return new_route; }
/// <summary> /// Does the actual solving. /// </summary> /// <param name="problem"></param> /// <returns></returns> protected override IRoute DoSolve(IProblem problem) { // convert to a symetric problem if needed. IProblem _problem = problem; if (!_problem.Symmetric) { _problem = Convertor.ConvertToSymmetric(_problem); _was_asym = true; } // create the list of customers. _customers = new List<int>(); for (int customer = 0; customer < _problem.Size; customer++) { _customers.Add(customer); } _sparse_set = SparseSetHelper.CreateNearestNeighourSet(_problem, _customers, _customers.Count / 10); //_sparse_set = SparseSetHelper.CreateNonSparseSet(_problem, _customers); // construct a route from the customers. //FixedSymmetricRoute init_route = new FixedSymmetricRoute(_customers); // construct a random route using best-placement. ArbitraryInsertionSolver bp_solver = new ArbitraryInsertionSolver(); IRoute bp_route = bp_solver.Solve(_problem); FixedSymmetricRoute init_route = new FixedSymmetricRoute(bp_route); double init_route_weight = LinKernighanSolver.Weight(_problem, init_route); RouteFound route = new RouteFound() { Route = init_route, RouteWeight = init_route_weight }; OsmSharp.Logging.Log.TraceEvent("LinKernighanSolver", Logging.TraceEventType.Information, "Route {0}:{1}", route.Route.ToString(), route.RouteWeight); // step 2. EdgeSet X = new EdgeSet(); EdgeSet Y = new EdgeSet(); IList<int> untried_t_1 = new List<int>(route.Route); while (untried_t_1.Count > 0) { // select t1. int t_1 = untried_t_1[0]; untried_t_1.RemoveAt(0); // search route with t_1. RouteFound t_1_route = this.AfterSelectt1(_problem, route, X, Y, t_1); // select the better route. if (t_1_route.RouteWeight < route.RouteWeight) { untried_t_1 = new List<int>(route.Route); route = RouteFound.SelectBest(route, t_1_route); X = new EdgeSet(); Y = new EdgeSet(); } } // step 2 and step 12. // convert back to asym solution if needed. //result.RemoveAt(result.Count - 1); if (_was_asym) { return this.ConvertToASymRoute(new List<int>(route.Route)); } return route.Route; }
///// <summary> ///// A naive selection method. ///// </summary> ///// <param name="problem"></param> ///// <param name="route"></param> ///// <param name="X"></param> ///// <param name="Y"></param> ///// <param name="x"></param> ///// <param name="y"></param> ///// <param name="exceptions"></param> ///// <returns></returns> //private int? SelectY( // IProblem problem, FixedSymmetricRoute route, EdgeSet X, EdgeSet Y, EdgeList x, EdgeList y, HashSet<int> exceptions) //{ // int from = x.Last.To; // // search an edge with weight smaller than g. // // VERY NAIVE METHOD! // List<int> test_list = new List<int>(); // float best_extra = float.MaxValue; // int? best_customer = null; // for (int other_customer = 0; other_customer < problem.Size; other_customer++) // { // if (other_customer != from && exceptions != null && !exceptions.Contains(other_customer)) // { // if (!x.Contains(from, other_customer) // && !route.Contains(from, other_customer)) // //&& !Y.Contains(from, other_customer)) // //&& !X.Contains(from, other_customer)) // { // float extra = problem.Weight(from, other_customer); // if (y.Weight + extra < x.Weight) // { // if (x.Count < 3) // { // best_customer = other_customer; // best_extra = extra; // break; // } // test_list.Add(other_customer); // if (extra < best_extra) // { // best_customer = other_customer; // best_extra = extra; // if (x.Count < 3) // { // break; // } // } // } // } // } // } // return best_customer; //} /// <summary> /// Selects with special priority. /// </summary> /// <param name="problem"></param> /// <param name="route"></param> /// <param name="X"></param> /// <param name="Y"></param> /// <param name="x"></param> /// <param name="y"></param> /// <param name="exceptions"></param> /// <returns></returns> private int? SelectY( IProblem problem, FixedSymmetricRoute route, EdgeSet X, EdgeSet Y, EdgeList x, EdgeList y, HashSet<int> exceptions) { int from = x.Last.To; // search an edge with weight smaller than g. //float best_priority = float.MinValue; int? best_customer = null; foreach (Edge edge in _sparse_set.GetFor(from)) { if (exceptions == null || !exceptions.Contains(edge.To)) { if (edge.From != edge.To && !x.Contains(edge) && !y.Contains(edge) && !route.Contains(edge.From, edge.To) //&& !Y.Contains(from, other_customer)) && !X.Contains(from, edge.To)) { double extra = edge.Weight; if (y.Weight + extra < x.Weight) { //if (x.Count < 2) //{ best_customer = edge.To; break; //} //// calculate priority. //int? x_other = this.SelectX(problem, route, X, Y, x, edge.To, null); //float priority = float.MinValue; //if (x_other != null) //{ // float x_other_weight = problem.Weight(edge.To, x_other.Value); // priority = x_other_weight - extra; //} //if (priority > best_priority) //{ // best_customer = edge.To; // best_priority = priority; //} } } } } return best_customer; }
private int? SelectX( IProblem problem, FixedSymmetricRoute route, EdgeSet X, EdgeSet Y, EdgeList x, int customer, HashSet<int> exceptions) { // select the only two edges that have the given customer in the given route. int[] neigbours = route.GetNeigbours(customer); int previous = neigbours[0]; int next = neigbours[1]; int? best_neighour = null; double best_weight = double.MinValue; if (previous > 0 && (exceptions == null || !exceptions.Contains(previous)) && !x.Contains(customer, previous)) //&& !X.Contains(customer, previous)) //&& !Y.Contains(customer, previous)) { //if (x.Count > 2) //{ double weight = problem.Weight(customer, previous); if (weight > best_weight) { best_neighour = previous; best_weight = weight; } //} //else //{ return previous; //} } if (next > 0 && (exceptions == null || !exceptions.Contains(next)) && !x.Contains(customer, next)) //&& !X.Contains(customer, previous)) //&& !Y.Contains(customer, previous)) { //if (x.Count > 2) //{ double weight = problem.Weight(customer, next); if (weight > best_weight) { best_neighour = next; best_weight = weight; } //} //else //{ return next; //} } return best_neighour; }
private RouteFound AfterSelectt5(IProblem problem, RouteFound route, EdgeSet X, EdgeSet Y, EdgeList x, EdgeList y) { int t_1 = x[0].From; int t_2i_min_1 = y[y.Count - 1].To; // try and find a better route with t_1. RouteFound new_route = new RouteFound() { RouteWeight = float.MaxValue, Route = null }; HashSet<int> exceptions = new HashSet<int>(); int? result = this.SelectX(problem, route.Route, X, Y, x, t_2i_min_1, exceptions); while (result != null) // do backtacking over x: TODO: improve this and immidiately find the correct tour. { int t_2i = result.Value; exceptions.Add(t_2i); // step 6. t_2i = result.Value; Edge x_edge = new Edge() { From = t_2i_min_1, To = t_2i, Weight = problem.Weight(t_2i_min_1, t_2i) }; x.Add(x_edge); X.Add(x_edge); // Test the route T' for feasability and weight. y.Add(new Edge() { From = t_2i, To = t_1, Weight = problem.Weight(t_2i, t_2i) }); new_route.Route = this.Replace(route.Route, x, y); y.RemoveLast(); // remove the perliminary y. if (new_route.Route.IsValid()) { // stop the search for now if the route is already better. new_route.RouteWeight = LinKernighanSolver.Weight(problem, new_route.Route); if (new_route.RouteWeight < route.RouteWeight) { // break. OsmSharp.Logging.Log.TraceEvent("LinKernighanSolver", Logging.TraceEventType.Information, "Route {0}:{1}", new_route.Route.ToString(), new_route.RouteWeight); return new_route; } // choose next y. result = this.SelectY(problem, route.Route, X, Y, x, y, null); if (result != null) { int t_2_plus_1 = result.Value; Edge y_edge = new Edge() { From = t_2i, To = t_2_plus_1, Weight = problem.Weight(t_2i, t_2_plus_1) }; y.Add(y_edge); Y.Add(y_edge); // choose next. new_route = this.AfterSelectt5(problem, route, X, Y, x, y); if (new_route.RouteWeight < route.RouteWeight) { // break. OsmSharp.Logging.Log.TraceEvent("LinKernighanSolver", Logging.TraceEventType.Information, "Route {0}:{1}", new_route.Route.ToString(), new_route.RouteWeight); return new_route; } // remove y again. y.RemoveLast(); } x.RemoveLast(); break; // the other x cannot be valid! } // backtrack over x. x.RemoveLast(); result = this.SelectX(problem, route.Route, X, Y, x, t_2i_min_1, exceptions); } return new_route; }
private RouteFound AfterSelectt4(IProblem problem, RouteFound route, EdgeSet X, EdgeSet Y, EdgeList x, EdgeList y) { int t_1 = x[0].From; int t_3 = y[0].To; int t_4 = x[1].To; // try and find a better route with t_1. RouteFound new_route = new RouteFound() { RouteWeight = float.MaxValue, Route = null }; // choose t_5 for backtracking later. HashSet<int> t_5_exceptions = new HashSet<int>(); int? result = this.SelectY(problem, route.Route, X, Y, x, y, t_5_exceptions); while (result != null) { // choose t_5. int t_5 = result.Value; t_5_exceptions.Add(t_5); Edge y_2 = new Edge() { From = t_4, To = t_5, Weight = problem.Weight(t_4, t_5) }; y.Add(y_2); Y.Add(y_2); // try and find a better route by selecting more customer. new_route = this.AfterSelectt5(problem, route, X, Y, x, y); if (new_route.Route != null && new_route.RouteWeight < route.RouteWeight) { // trackback to t_1 if a better route is found. break; } // remove and backtrack y_2. y.RemoveLast(); result = this.SelectY(problem, route.Route, X, Y, x, y, t_5_exceptions); } // choose t_5 return new_route; }
private RouteFound AfterSelectt3(IProblem problem, RouteFound route, EdgeSet X, EdgeSet Y, EdgeList x, EdgeList y) { int t_1 = x[0].From; int t_3 = y[0].To; // try and find a better route with t_1. RouteFound new_route = new RouteFound() { RouteWeight = float.MaxValue, Route = null }; // choose t_4 for backtracking later. HashSet<int> t_4_exceptions = new HashSet<int>(); int? result = this.SelectX(problem, route.Route, X, Y, x, t_3, t_4_exceptions); while (result != null) { // select t_4. int t_4 = result.Value; t_4_exceptions.Add(t_4); // add to x and test with perliminary y. Edge x_edge = new Edge() { From = t_3, To = t_4, Weight = problem.Weight(t_3, t_4) }; x.Add(x_edge); X.Add(x_edge); // Test the route T' for feasability and weight. y.Add(new Edge() { From = t_4, To = t_1, Weight = problem.Weight(t_4, t_1) }); new_route.Route = this.Replace(route.Route, x, y); y.RemoveLast(); // remove the perliminary y. if (new_route.Route.IsValid()) { // stop the search for now if the route is already better. new_route.RouteWeight = LinKernighanSolver.Weight(problem, new_route.Route); if (new_route.RouteWeight < route.RouteWeight) { // break. OsmSharp.Logging.Log.TraceEvent("LinKernighanSolver", Logging.TraceEventType.Information, "Route {0}:{1}", new_route.Route.ToString(), new_route.RouteWeight); x.RemoveLast(); // remove the latest x here! break; } } // choose t_5 here. new_route = this.AfterSelectt4(problem, route, X, Y, x, y); if (new_route.Route != null && new_route.RouteWeight < route.RouteWeight) { // trackback to t_1 if a better route is found. break; } // reset the new route. new_route.Route = null; new_route.RouteWeight = float.MaxValue; // remove and backtrack x_2. x.RemoveLast(); result = this.SelectX(problem, route.Route, X, Y, x, t_3, t_4_exceptions); } // choose t_4 return new_route; }