public override bool Execute() { string aim = "Hello friends"; int dim = aim.Length; Func <string, double> fn1 = (s => s.Select((b, i) => ((int)b - aim[i]) * 2 * ((int)b - aim[i])).Sum()); Func <string, double> fn = (s => fn1(s)); SimulatedAnnealing <string> sa = new SimulatedAnnealing <string>() { NeighborhoodProvider = Neighbors, EnergyProvider = fn, CurrentElement = "^ùsprôqù;rqô;ùvere!wlpc\"!".Substring(0, dim) }; for (int i = 0; i < 100; ++i) { sa.Run(100); sa.CurrentElement = sa.BestFound; } if (IsVerbose) { Console.WriteLine(" ::!:: " + sa.BestFound); } if (sa.BestFound != aim) { return(false); } return(true); }
private static ISolver SimulatedAnnealingGenerator() { GreedyFastHeuristic randomSolver = new GreedyFastHeuristic() { MaxOverfillUnits = 0, DiagnosticMessages = true, }; CompoundSolver compundSolver = new CompoundSolver() { MaxLoops = 7, DiagnosticMessages = true, }; SimulatedAnnealing simulatedAnnealing = new SimulatedAnnealing() { DiagnosticMessages = true, ScoringFunction = new Scorer(), StepsAnalyzedWithoutImprovementToStop = 200, NumberOfLoopsWithoutActionsToStop = 1, PropagateRandomSeed = true, Seed = 100, Description = "SimulatedAnnealing", IntegrityLossMultiplier = 1000.0, }; simulatedAnnealing.InitialSolvers.Add(randomSolver); simulatedAnnealing.InitialSolvers.Add(compundSolver); return(simulatedAnnealing); }
public ActionResult StartSimulatedAnnealing(SimulatedAnnealingRequestViewModel algorithmRequest) { if (!ModelState.IsValid) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } var graph = new Graph(); graph.FillGraphRandomly(algorithmRequest.NumberOfNodesToGenerate, algorithmRequest.MaxNeighboursForNode); var hubContext = GlobalHost.ConnectionManager.GetHubContext <SimulatedAnnealingHub>(); var algorithm = new SimulatedAnnealing(graph, new MinimumVertexCover(), new CoolingSetup(4000, 0.03, new AllRandomCooling())); algorithm.LaunchAlgorithm(); algorithm.ProgressReportChanged.Subscribe(report => { Observable.Timer(TimeSpan.FromMilliseconds(500)).Subscribe(_ => { hubContext.Clients.Group(algorithm.Id.ToString()).send(report.AsReportViewModel()); }); }); return(new JsonResult { Data = new { graph = graph.AsD3ViewModel(), hubId = algorithm.Id }, ContentType = "application/x-javascript", JsonRequestBehavior = JsonRequestBehavior.AllowGet }); }
static void Main(string[] args) { IntelligentRandom intelligentRandom = new IntelligentRandom(); BasicFitnessCalculator basicCalculator = new BasicFitnessCalculator(); var simulatedAnnealing = new SimulatedAnnealing(); simulatedAnnealing.Simulate( startTemperature: 10000, boardSize: 10, generator: intelligentRandom, calculator: basicCalculator ); Console.WriteLine(simulatedAnnealing.Result); var tabuSearch = new TabuSearch(); tabuSearch.Simulate( maxTabuListCount: 1500, boardSize: 10, generator: intelligentRandom, calculator: basicCalculator ); Console.WriteLine(tabuSearch.Result); }
static void Main(string[] args) { string[] lines = File.ReadAllLines("C:\\Users\\igork\\source\\repos\\TLD\\TLD\\tests.txt"); string[] _density = lines[1].Split(","); List <int> _den = new List <int>(); foreach (string d in _density) { _den.Add(int.Parse(d)); } Junction jn = new Junction(int.Parse(lines[0]), _den.ToArray()); Constraints cons = new Constraints(int.Parse(lines[0])); string[] temp = lines[2].Split("|"); foreach (string s in temp) { string[] p = s.Split(","); cons.Add_cons(int.Parse(p[0]), int.Parse(p[1])); } jn = SimulatedAnnealing.Compute(jn, 20f, 0.000001f, 50); // Console.WriteLine(tools.DeepToString(_den.ToArray())); Console.WriteLine(jn); //for(int i = 0; i < jn.getOrder().Length; i++) { // Console.Write(" " + jn.getOrder()[i]); //} }
static List <Simulation> RunSimulatedAnnealing(Simulation s, int duration) { SimulatedAnnealing SA = HeuristicFactory.CreateSA(s, duration, SimulatedAnnealingBase.DebugLevel.All); SA.Run(); return(SA.BestSolutions); }
private void CalculateDistancesAndCreateAreas() { if (NrOfSalesmans <= 1) { foreach (SilverlightEdge edge in _slEdges) { foreach (SilverlightEdge edge1 in _slEdges) { edge.PolarCords.Center(new Point(300, 400)); } } annealingForOne = new SimulatedAnnealing(); List <int> order = annealingForOne.CalculateInit(_slEdges, distances, Alpha, Temp, Epsilon); DrawLines(order); } else { Clusters = CreateAreas(NrOfSalesmans); foreach (Cluster clust in Clusters) { foreach (SilverlightEdge edge in clust.Edges) { foreach (SilverlightEdge edge1 in clust.Edges) { edge.PolarCords.Center(clust.ClusterCenter); } } clust.Color = Common.ColorPallete.GetColor(); List <int> order = clust.Annealing.CalculateInit(clust.Edges, distances, Alpha, Temp, Epsilon); DrawLines(order); } } }
private static void Main(string[] args) { var voc = Vocabulary.GetVocabularyFromFile(@"Vocabulary.json"); var grammar = new Grammar(voc); ProgramParams programParams; using (var file = File.OpenText(@"ProgramParameters.json")) { var serializer = new JsonSerializer(); programParams = (ProgramParams)serializer.Deserialize(file, typeof(ProgramParams)); } if (programParams.DataWithMovement) { CreateMovementGrammar(grammar); } else { CreateSimpleGrammar(grammar); } grammar.GenerateDerivedRulesFromSchema(); var p = new Parser(grammar); var data = p.GenerateSentences(programParams.NumberOfDataSentences); using (var sw = File.AppendText("SessionReport.txt")) { sw.WriteLine("-------------------"); sw.WriteLine("Session {0} ", DateTime.Now.ToString("MM/dd/yyyy h:mm tt")); sw.WriteLine("sentences: {0}, runs: {1}, movement: {2}", programParams.NumberOfDataSentences, programParams.NumberOfRuns, programParams.DataWithMovement); } var stopWatch = StartWatch(); var learner = new Learner(voc, grammar.NonTerminalsTypeDictionary, grammar.POSTypes, data, grammar); learner.originalGrammar.GenerateDerivedRulesFromSchema(); var targetGrammarEnergy = learner.Energy(learner.originalGrammar); learner.originalGrammar.GenerateInitialRulesFromDerivedRules(); var s = string.Format("Target Hypothesis:\r\n{0} with energy: {1}\r\n", learner.originalGrammar, targetGrammarEnergy); Console.WriteLine(s); using (var sw = File.AppendText("SessionReport.txt")) { sw.WriteLine(s); } for (var i = 0; i < programParams.NumberOfRuns; i++) { var sa = new SimulatedAnnealing(learner); sa.Run(); } StopWatch(stopWatch); }
public void Test_That_Simulated_Annealing_On_Sphere_Works() { SimulatedAnnealing <double[]> garden = new SimulatedAnnealing <double[]>(); Sphere sphere = new Sphere(); garden.create(sphere.getConfiguration()); garden.fullIteration(); }
public SimulatedAnnealingTests() { Algorithm = new SimulatedAnnealing( _graphFactory.ProvideValid(), _problemProvider.ProvideSubstitute(), _coolingSetupFactory.ProvideValid()); }
public void Test_That_Knapsack_Simulated_Annealing_Works() { this.Load(Constants.SAMPLE_MKNAPCB4_DATASET); Console.WriteLine($"Goal:\t{this.goal}"); SimulatedAnnealing <List <int> > sa = new SimulatedAnnealing <List <int> >(); sa.create(this.getConfiguration()); List <int> finalSolution = sa.fullIteration(); }
private void btnSimAne_Click(object sender, EventArgs e) { label5.Text = "Processando, aguarde..."; label5.Refresh(); CarregaValores(); SimulatedAnnealing s = new SimulatedAnnealing(); s.Process(); ImprimeResultado(s.MelhorResultado); //this }
private SimulatedAnnealing CreateSimulatedAnnealingRastriginSample() { SimulatedAnnealing sa = new SimulatedAnnealing(); #region Problem Configuration var problem = new SingleObjectiveTestFunctionProblem(); problem.BestKnownQuality.Value = 0.0; problem.BestKnownSolutionParameter.Value = new RealVector(new double[] { 0, 0 }); problem.Bounds = new DoubleMatrix(new double[, ] { { -5.12, 5.12 } }); problem.EvaluatorParameter.Value = new RastriginEvaluator(); problem.Maximization.Value = false; problem.ProblemSize.Value = 2; problem.SolutionCreatorParameter.Value = new UniformRandomRealVectorCreator(); #endregion #region Algorithm Configuration sa.Name = "Simulated Annealing - Rastrigin"; sa.Description = "A simulated annealing algorithm that solves the 2-dimensional Rastrigin test function"; sa.Problem = problem; var annealingOperator = sa.AnnealingOperatorParameter.ValidValues .OfType <ExponentialDiscreteDoubleValueModifier>() .Single(); annealingOperator.StartIndexParameter.Value = new IntValue(0); sa.AnnealingOperator = annealingOperator; sa.EndTemperature.Value = 1E-6; sa.InnerIterations.Value = 50; sa.MaximumIterations.Value = 100; var moveEvaluator = sa.MoveEvaluatorParameter.ValidValues .OfType <RastriginAdditiveMoveEvaluator>() .Single(); moveEvaluator.A.Value = 10; sa.MoveEvaluator = moveEvaluator; var moveGenerator = sa.MoveGeneratorParameter.ValidValues .OfType <StochasticNormalMultiMoveGenerator>() .Single(); moveGenerator.SigmaParameter.Value = new DoubleValue(1); sa.MoveGenerator = moveGenerator; sa.MoveMaker = sa.MoveMakerParameter.ValidValues .OfType <AdditiveMoveMaker>() .Single(); sa.Seed.Value = 0; sa.SetSeedRandomly.Value = true; sa.StartTemperature.Value = 1; #endregion sa.Engine = new ParallelEngine.ParallelEngine(); return(sa); }
private ISolver SimulatedAnnealingMaker() { SimulatedAnnealing solver = new SimulatedAnnealing() { ScoringFunction = new Scorer(), DiagnosticMessages = true, PropagateRandomSeed = true, TimeLimit = new TimeSpan(0, 3, 0), StepsAnalyzedWithoutImprovementToStop = 300, Description = "simulated_annealing_test", }; return(solver); }
static void Main(string[] args) { var inf = int.MaxValue; var arr = new int[, ] { { inf, 21, 53, 11, 72, 13, 54, 25, 66, 57 }, { 21, inf, 32, 28, 97, 16, 95, 54, 73, 23 }, { 53, 32, inf, 86, 65, 24, 83, 12, 31, 40 }, { 11, 28, 86, inf, 31, 42, 13, 24, 45, 16 }, { 72, 97, 65, 31, inf, 78, 57, 76, 45, 65 }, { 13, 16, 24, 42, 78, inf, 4, 95, 15, 35 }, { 54, 95, 83, 13, 57, 4, inf, 11, 72, 83 }, { 25, 54, 12, 24, 76, 95, 11, inf, 44, 44 }, { 66, 73, 31, 45, 45, 15, 72, 44, inf, 59 }, { 57, 23, 40, 16, 65, 35, 83, 44, 95, inf } }; var graph = new Graph(arr); Console.WriteLine($"{"algorithm name",40} {"iterations",15} {"result",10} {"time (ms)",15}"); ReturnData bruteForceSearch = BruteForceSearch.Search(graph); Console.WriteLine($"{bruteForceSearch.AlgorithmName,40} {bruteForceSearch.Iterations,15} " + $"{bruteForceSearch.Result,10} {bruteForceSearch.TimeInMs,15}"); ReturnData greedyAlgorithm = GreedyAlgorithm.Search(graph); Console.WriteLine($"{greedyAlgorithm.AlgorithmName,40} {greedyAlgorithm.Iterations,15} " + $"{greedyAlgorithm.Result,10} {greedyAlgorithm.TimeInMs,15}"); ReturnData branchAndBoundAlgorithm = BranchAndBoundAlgorithm.Search(graph); Console.WriteLine($"{branchAndBoundAlgorithm.AlgorithmName,40} {branchAndBoundAlgorithm.Iterations,15} " + $"{branchAndBoundAlgorithm.Result,10} {branchAndBoundAlgorithm.TimeInMs,15}"); ReturnData localSearch2Algorithm = LocalSearch2.Search(graph); Console.WriteLine($"{localSearch2Algorithm.AlgorithmName,40} {localSearch2Algorithm.Iterations,15} " + $"{localSearch2Algorithm.Result,10} {localSearch2Algorithm.TimeInMs,15}"); ReturnData simulatedAnnealingAlgorithm_lin = SimulatedAnnealing.Search(graph, SimulatedAnnealing.GetNewTemperature_Linear); Console.WriteLine($"{simulatedAnnealingAlgorithm_lin.AlgorithmName + "(lin)",40} {simulatedAnnealingAlgorithm_lin.Iterations,15} " + $"{simulatedAnnealingAlgorithm_lin.Result,10} {simulatedAnnealingAlgorithm_lin.TimeInMs,15}"); ReturnData simulatedAnnealingAlgorithm_pow = SimulatedAnnealing.Search(graph, SimulatedAnnealing.GetNewTemperature_Power); Console.WriteLine($"{simulatedAnnealingAlgorithm_pow.AlgorithmName + "(pow)",40} {simulatedAnnealingAlgorithm_pow.Iterations,15} " + $"{simulatedAnnealingAlgorithm_pow.Result,10} {simulatedAnnealingAlgorithm_pow.TimeInMs,15}"); }
private void CalculateDistancesAndCreateAreasThread() { if (_nrOfSalesman <= 1) { annealingForOne = new SimulatedAnnealing(); List <int> order = annealingForOne.CalculateInit(_slEdges, distances, _alpha, _temp, _epsilon); } else { foreach (Cluster clust in Clusters) { List <int> order = clust.Annealing.CalculateInit(clust.Edges, distances, _alpha, _temp, _epsilon); } } }
private ISolver SimulatedAnnealingMakerParametrized(double alpha, double beta, string name) { SimulatedAnnealing solver = new SimulatedAnnealing() { ScoringFunction = new Scorer(), DiagnosticMessages = true, PropagateRandomSeed = true, TimeLimit = new TimeSpan(0, 3, 0), TemperatureMultiplier = alpha, TemperatureAddition = beta, StepsAnalyzedWithoutImprovementToStop = 300, Description = name, }; return(solver); }
private ISolver SimulatedAnnealingBest() { SimulatedAnnealing solver = new SimulatedAnnealing() { ScoringFunction = new Scorer(), DiagnosticMessages = true, PropagateRandomSeed = true, TimeLimit = new TimeSpan(1, 30, 0), TemperatureMultiplier = 0.999973432905173, TemperatureAddition = 3.51023731470062E-06, StepsAnalyzedWithoutImprovementToStop = 600, Description = "annealing_best", }; return(solver); }
/// <summary> /// Compute traffic lights cycle's order, MUST HAVE CONSTRAINTS IN PLACE! /// sends to the result adapter the results /// </summary> /// <param name="_nor"> Number of elements (roads or traffic lights) </param> /// <param name="_density"> Density of each element as list : (road number 1, density(0)),.... </param> /// <returns> Open order for elements based on constraints. each row represent cycles segment, /// each column represents number of element to open. </returns> public void AlgoRun(int _nor, List <int> _density) { cycleTime = numOfRoads * timeForCycle; Constraints _cons = new Constraints(_nor); foreach (string s in constraintList) { string[] temp = s.Split(','); _cons.Add_cons(int.Parse(temp[0]), int.Parse(temp[1])); } Junction _jn = new Junction(_nor, _density.ToArray()); Junction _result = SimulatedAnnealing.Compute(_jn, 20, 0.00001f, 3500); Debug.Log(_result); resultAdapter.GetComponent <resultAdapter>().schedule(_result, cycleTime); }
public static SimulatedAnnealingEntity AsEntityModel(this SimulatedAnnealing model, GraphEntity graph = null) { var usedGraph = graph ?? model.Graph.AsEntityModel(); var problem = model.Problem.AsEntityModelResolved(graph); return(new SimulatedAnnealingEntity { Id = model.Id, Graph = graph, CoolingRate = model.CoolingSetup.CoolingRate, CoolingStrategy = CoolingFactory.ProvideMappingType(model.CoolingSetup.CoolingStrategy), CurrentTemperature = model.CurrentTemperature, InitialTemperature = model.CoolingSetup.InitialTemperature, Problem = problem, TotalProcessorTimeCost = model.TotalProcessorTimeCost }); }
public void AnnealingTest1() { file = root + "\\bays29.xml"; XDocument tspFile = XDocument.Load(file); AdjacencyMatrix testMatrix = new AdjacencyMatrix(tspFile); SimulatedAnnealing test = new SimulatedAnnealing(testMatrix); test.SetTemperature(10, (float)0.997, 1, 5000); for (int i = 0; i < 1000; i++) { float result = test.Calculate(); if (result > 3500) // best result world known is 2020 { Assert.Fail(); } } }
public static void KnapsackTest() { Console.WriteLine("============"); Console.WriteLine("SA Knapsack problem example"); Console.WriteLine("Knapsack instances are generated according to this paper:"); Console.WriteLine("http://www.dcs.gla.ac.uk/~pat/cpM/jchoco/knapsack/papers/hardInstances.pdf"); Console.WriteLine("============"); var logger = new Logger <SimulatedAnnealing <KnapsackSolution> >(new LoggerFactory()); var cooler = new QuadraticCooler(0.998, 800); var mover = new KnapsackMover(); var instances = new KnapsackInstancesFactory(50, 5000, 1) .GenDistribution(DistributionVariant.Strong, 3) .GenDistribution(DistributionVariant.Uncorrelated, 3) .Collect(); var stop = new NotGettingBetter <KnapsackSolution>(cooler, OptimizationType.Maximization, 500000, 300000); Console.WriteLine("COMMON ELEMENTS"); Console.WriteLine($" Stop criteria: {stop}"); Console.WriteLine($" Cooler: {cooler}"); Console.WriteLine("INSTANCES"); for (int i = 0; i < instances.Count; i++) { var instance = instances[i]; Console.WriteLine($"Instance name: {instance.Name}"); var sa = new SimulatedAnnealing <KnapsackSolution>(cooler, mover, stop, logger); var obj = new KnapsackObj(instance); var constraint = new KnapsackConstraint(instance); var objAggr = new WeightedObjectiveAggregator <KnapsackSolution>(new[] { obj }, new double[] { 1 }); var constraintAggr = new WeightedConstraintAggregator <KnapsackSolution>(new[] { constraint }, new double[] { 1 }); var criterion = new Criterion <KnapsackSolution>(OptimizationType.Maximization, objAggr, constraintAggr); var solution = new KnapsackSolution(instance); var bestSol = sa.Solve(solution, criterion); Console.WriteLine(instance); Console.WriteLine(bestSol); Console.WriteLine("----"); } }
public static void Main(string[] args) { Utils.Parse.CSV <Category>(FILE_CATEGORY); Utils.Parse.CSV <Location>(FILE_LOCATION); Distances.Parse(FILE_DISTANCES); GRASP GRASP = new GRASP(Location.Instance("Plaza del Adelantado")); SimulatedAnnealing SA = new SimulatedAnnealing(50, .05, Location.Instance("Plaza del Adelantado")); TabuSearch TS = new TabuSearch(7, Location.Instance("Plaza del Adelantado")); VariableNeighborhoodSearch VNS = new VariableNeighborhoodSearch(5, Location.Instance("Plaza del Adelantado")); Console.WriteLine("GRASP:"); Run(GRASP, 20); Console.WriteLine("\nSA:"); //Run(SA, 20); Console.WriteLine("\nTS:"); Run(TS, 20); //Console.WriteLine("\nVNS:"); //Run(VNS, 20); }
/// <summary> /// Tests a simulated annealing. /// </summary> /// <typeparam name="TGene"></typeparam> /// <param name="testNumber">The number of the test.</param> /// <param name="testDescription">The description of the test.</param> /// <param name="simulatedAnnealing">The simulated annealing to test.</param> /// <param name="objectiveFunction">The objective funtion to test.</param> /// /// <param name="maxIterationCount">The maximum number of iterations (the computational budget).</param> /// <param name="acceptableEnergy">The acceptable energy.</param> /// /// <param name="initialTemperature">The initial temperature.</param> /// <param name="finalTemperature">The final temperature.</param> /// <apra private static void Test <T>(int testNumber, string testDescription, SimulatedAnnealing <T> simulatedAnnealing, ObjectiveFunction <T> objectiveFunction, int maxIterationCount, double acceptableEnergy, double initialTemperature, double finalTemperature) { // Print the number of the test and its description. Console.WriteLine("Test " + testNumber + " : " + testDescription); // Run the simulated annealing. DateTime startTime = DateTime.Now; int usedIterationCount; double achievedEnergy; T[] solution = simulatedAnnealing.Run(objectiveFunction, maxIterationCount, out usedIterationCount, acceptableEnergy, out achievedEnergy, initialTemperature, finalTemperature ); DateTime endTime = DateTime.Now; // Build the solution string. StringBuilder solutionSB = new StringBuilder(); solutionSB.Append("["); foreach (T component in solution) { solutionSB.Append(component + ", "); } if (solution.Length != 0) { solutionSB.Remove(solutionSB.Length - 2, 2); } solutionSB.Append("]"); // Print the results. Console.WriteLine("Test " + testNumber + " : Duration: " + (endTime - startTime)); Console.WriteLine("Test " + testNumber + " : Number of iterations taken : " + usedIterationCount); Console.WriteLine("Test " + testNumber + " : Best solution : " + solutionSB.ToString()); Console.WriteLine("Test " + testNumber + " : Best solution's evaluation : " + achievedEnergy); }
void Start() { World initialWorld = new World(); for (int i = 0; i < locationCount; i++) { float angle = Random.Range(0, 2 * Mathf.PI); float r = Random.Range(minWorldRadius, maxWorldRadius); initialWorld.Locations.Add(new Vector3(r * Mathf.Sin(angle), r * Mathf.Cos(angle), r * Mathf.Cos(angle))); } VertexProvider vProvider = new VertexProvider(targetObj.GetComponent <MeshFilter>().mesh, targetObj.transform); initialWorld.Locations = vProvider.GetVertexSamples(1000); sa = new SimulatedAnnealing(initialTemp, coolingRate, initialWorld); sa.Findsolution(); // Prepare camera for render Camera.main.clearFlags = CameraClearFlags.SolidColor; Camera.main.backgroundColor = Color.white; StartCoroutine(DontClearCamera()); }
private static void Main(string[] args) { // Load file with instances if (args.Length != 1) { Console.WriteLine("Wrong number of arguments! Second argument has to be file with instances!"); return; } var files = Directory.GetFiles(args[0], "*.txt"); var instances = new List <Formula>(); foreach (var file in files) { var formula = Reader.LoadInstance(file); if (!formula.CheckInstance()) { Console.WriteLine("Formula wrongly loaded! (count of variables of clauses not match)"); continue; } instances.Add(formula); } // INIT TEMP for (var i = 100; i <= 2500; i += 600) { long time = 0; foreach (var formula in instances) { var sw = new Stopwatch(); sw.Start(); var sa = new SimulatedAnnealing(i, 10, 0.95, 400); sa.Solve(formula); sw.Stop(); time += sw.ElapsedMilliseconds; } Console.WriteLine("INIT TEMP: " + i); Console.WriteLine("TIME: " + Math.Round((double)time / instances.Count, 4)); } Console.WriteLine(); // INSIDE CYCLE for (var i = 100; i <= 500; i += 100) { long time = 0; foreach (var formula in instances) { var sw = new Stopwatch(); sw.Start(); var sa = new SimulatedAnnealing(500, 10, 0.95, i); sa.Solve(formula); sw.Stop(); time += sw.ElapsedMilliseconds; } Console.WriteLine("CYCLE: " + i); Console.WriteLine("TIME: " + Math.Round((double)time / instances.Count, 4)); } Console.WriteLine(); // COEFF. COOLING for (var i = 0.55; i < 1; i += 0.1) { long time = 0; foreach (var formula in instances) { var sw = new Stopwatch(); sw.Start(); var sa = new SimulatedAnnealing(500, 10, i, 400); sa.Solve(formula); sw.Stop(); time += sw.ElapsedMilliseconds; } Console.WriteLine("CC: " + i); Console.WriteLine("TIME: " + Math.Round((double)time / instances.Count, 4)); } /* * var inst = instances[0]; * // solve formula with brute-force * //var bruteResult = BruteForce.Solve(inst); * * //Console.WriteLine(bruteResult); * * // solve formula with simulated annealing * var sw = new Stopwatch(); * sw.Start(); * var saSolver = new SimulatedAnnealing(); * var saResult = saSolver.Solve(inst); * sw.Stop(); * * Console.WriteLine(saResult); * Console.WriteLine(sw.ElapsedMilliseconds); */ }
public async Task <IActionResult> Index(ICollection <IFormFile> files, UserInput u) { /* Uploader File */ user_input = u; var uploads = Path.Combine(_environment.WebRootPath, "uploads"); foreach (var file in files) { if (file.Length > 0) { uploads = Path.Combine(uploads, file.FileName); using (var fileStream = new FileStream(uploads, FileMode.Create)) { await file.CopyToAsync(fileStream); } } } var openFile = new FileStream(uploads, FileMode.Open, FileAccess.Read); using (var readStream = new StreamReader(openFile)) { int conflict = 0; string line; Boolean isRuangan = false; Boolean isKelas = false; string temp = ""; char b; RuanganManagement listOfRuangan = new RuanganManagement(); KelasManagement listOfKelas = new KelasManagement(); /* ADT RUANGAN */ string nama = ""; // Contoh: "7602" int jam_buka = 0; // Contoh: 7 (buka mulai jam 7) int jam_tutup = 0; // Contoh: 14 (tutup jam 14) List <int> hari_buka = new List <int>(); /* ADT KELAS */ // Domain value yang dimiliki 'Kelas' string ruangan = ""; List <string> domainRuangan = new List <string>(); List <int> domainMulai = new List <int>(); // Contoh: [7, 8, 9] (Kelas hanya bisa mulai jam 7, 8, atau 9) List <int> domainHari = new List <int>(); // Contoh: [1, 3, 5] (Kelas hanya bisa dilakukan hari Senin, Rabu, atau Jumat) int durasi = 0; // Contoh: 4 (4 jam) while ((line = readStream.ReadLine()) != null) { if (line.Equals("")) { // Do nothing } else if (line.Equals("Ruangan")) { isRuangan = true; isKelas = false; } else if (line.Equals("Jadwal")) { isRuangan = false; isKelas = true; } /* Membaca data ruangan */ else if (isRuangan) { var sr = new StringReader(line); int point = 0; temp = ""; hari_buka = new List <int>(); domainMulai = new List <int>(); for (int k = 0; k < line.Length; k++) { b = (char)sr.Read(); if (b == ';') { if (point == 0) { nama = temp; } else if (point == 1) { jam_buka = timeToInt(temp); } else if (point == 2) { jam_tutup = timeToInt(temp); } point++; temp = ""; } else { if (b != ',') { temp += b; } } } var parse = new StringReader(temp); for (int j = 0; j < temp.Length; j++) { char val = (char)parse.Read(); hari_buka.Add(Int32.Parse(val.ToString())); } listOfRuangan.addRuangan(new Ruangan(nama, jam_buka, jam_tutup, hari_buka)); } /* Menambah info kelas */ else if (isKelas) { var sr = new StringReader(line); int point = 0; temp = ""; hari_buka = new List <int>(); domainRuangan = new List <string>(); for (int k = 0; k < line.Length; k++) { b = (char)sr.Read(); if ((point == 1) && (b != ';')) { if (b == ',') { domainRuangan.Add(temp); temp = ""; } else { temp += b; } } else if (b == ';') { if (point == 0) { nama = temp; } else if (point == 1) { domainRuangan.Add(temp); } else if (point == 2) { jam_buka = timeToInt(temp); } else if (point == 3) { jam_tutup = timeToInt(temp); } else if (point == 4) { durasi = Int32.Parse(temp); } point++; temp = ""; } else { if (b != ',') { temp += b; } } } var parse = new StringReader(temp); for (int j = 0; j < temp.Length; j++) { char val = (char)parse.Read(); hari_buka.Add(Int32.Parse(val.ToString())); } Kelas c = new Kelas(nama, domainRuangan, jam_buka, jam_tutup, durasi, hari_buka, listOfRuangan); listOfKelas.addKelas(c); } } KelasManagement ans = new KelasManagement(); if (user_input.choice == 0) { HillClimbing hc = new HillClimbing(listOfKelas, listOfRuangan); ans = hc.getSol(); ViewData["Choice"] = "Hill Climbing"; } else if (user_input.choice == 1) { SimulatedAnnealing sa = new SimulatedAnnealing(listOfKelas, listOfRuangan); sa.execute(1000, 0.9f); ans = sa.getSol(); ViewData["Choice"] = "Simulated Annealing"; } else if (user_input.choice == 2) { Population p = new Population(); p.generatePopulation(200, listOfKelas); GeneticAlgorithm ga = new GeneticAlgorithm(p); for (int ax = 0; ax < 100000; ax++) { if (ga.getSolution().getConflict() == 0) { break; } else { ga.crossover(); ga.mutation(); } } ans = ga.getSolution(); ViewData["Choice"] = "Genetic Algorithm"; } ViewData["tes"] = ans.getConflict(); int i = 0; // Inisialisasi for (int j = 7; j < 18; j++) { for (int k = 1; k < 6; k++) { ViewData["marker" + j.ToString() + k.ToString()] = 5; ViewData["nama" + j.ToString() + k.ToString()] = ""; ViewData["ruangan" + j.ToString() + k.ToString()] = ""; } } // Pengisian kelas di tabel foreach (Kelas k in ans.getArrayKelas()) { ViewData["nama" + i.ToString()] = k.getNama(); ViewData["ruangan" + i.ToString()] = k.getNamaRuangan(); ViewData["durasi" + i.ToString()] = k.getDurasi(); ViewData["hari" + i.ToString()] = k.getHari(); ViewData["jam" + i.ToString()] = k.getMulai(); for (int z = k.getMulai(); z < (k.getMulai() + k.getDurasi()); z++) { if (ViewData["ruangan" + z.ToString() + k.getHari().ToString()].Equals("")) { ViewData["kelas" + z.ToString() + k.getHari().ToString()] = i.ToString(); ViewData["marker" + z.ToString() + k.getHari().ToString()] = 0; ViewData["nama" + z.ToString() + k.getHari().ToString()] = k.getNama(); ViewData["ruangan" + z.ToString() + k.getHari().ToString()] = k.getNamaRuangan(); //Kurangi waktu available dan tambahkan waktu terpakai; listOfRuangan.getRuangan(k.getNamaRuangan()).decrement_waktu_available(); } else if (cekRuanganSama(k.getNamaRuangan(), ViewData["ruangan" + z.ToString() + k.getHari().ToString()].ToString())) { conflict++; ViewData["kelas" + z.ToString() + k.getHari().ToString()] = i.ToString(); ViewData["marker" + z.ToString() + k.getHari().ToString()] = 1; ViewData["nama" + z.ToString() + k.getHari().ToString()] += " " + k.getNama(); ViewData["ruangan" + z.ToString() + k.getHari().ToString()] += " " + k.getNamaRuangan(); } else { ViewData["kelas" + z.ToString() + k.getHari().ToString()] += " " + i.ToString(); ViewData["marker" + z.ToString() + k.getHari().ToString()] = 2; ViewData["nama" + z.ToString() + k.getHari().ToString()] += " " + k.getNama(); ViewData["ruangan" + z.ToString() + k.getHari().ToString()] += " " + k.getNamaRuangan(); /* Kurangi waktu available dan tambahkan waktu terpakai*/ listOfRuangan.getRuangan(k.getNamaRuangan()).decrement_waktu_available(); } } i++; } ViewData["tes"] = conflict; ViewData["Length"] = i; /* Memasukkan data keefektifan untuk ditampilkan di web */ int nRuangan = 0; foreach (Ruangan ruang_ruang in listOfRuangan.getAllRuangan()) { ViewData["namaruangan" + nRuangan.ToString()] = ruang_ruang.getName(); ViewData["efektifitas" + nRuangan.ToString()] = ruang_ruang.getEfektifitasRuangan(); nRuangan++; } ViewData["banyakruangan"] = nRuangan; } ViewData["color0"] = "green"; ViewData["color1"] = "yellow"; ViewData["color2"] = "brown"; ViewData["color3"] = "blue"; ViewData["color4"] = "black"; ViewData["color5"] = "aqua"; ViewData["color6"] = "purple"; ViewData["color7"] = "wood"; ViewData["color8"] = "pink"; ViewData["color9"] = "orange"; ViewData["Start"] = 1; return(View()); }
public ActionResult Result(TSPViewModel model) { var algorithmType = (TSPAlgorithm)Enum.Parse( typeof(TSPAlgorithm), model.SelectedPosition); var crossoverType = (CrossoverType)Enum.Parse( typeof(CrossoverType), model.SelectedCrossoverPosition); var selectionType = (SelectionType)Enum.Parse( typeof(SelectionType), model.SelectedSelectionPosition); IAlgorithm algorithm = null; List <City> cities; if (!string.IsNullOrEmpty(model.Cities)) { cities = new List <City>(); foreach (var line in model.Cities.Split('\n')) { var words = line.Split(';'); var city = new City() { Name = words[0], X = double.Parse(words[1]), Y = double.Parse(words[2]) }; cities.Add(city); } } else if (model.RandomData) { cities = TSPCreatorHelper.GenerateCity(30); } else { cities = DemoTSPData.Get(); } if (algorithmType == TSPAlgorithm.GeneticAlgorithm) { algorithm = new GeneticAlgorithm( model.MutatorValue, model.GenerationCount, model.PopulationSize, crossoverType, selectionType, cities); } else if (algorithmType == TSPAlgorithm.SimulatedAnnealing) { algorithm = new SimulatedAnnealing( model.Temperature, model.CoolingRate, model.Number, cities); } else { throw new Exception(); } algorithm.Execute(); var result = new TSPResultViewModel() { Result = algorithm.GetResult(), Cities = TourManager.Cities }; return(View(result)); }
public async Task CalculateSA() { ClearTextBox(); cts[3].Cancel(); cts[3] = new CancellationTokenSource(); progressSA.Visibility = Visibility.Visible; double temperature; if (!Double.TryParse(textB_temperature.Text, out temperature)) { textB_temperature.Background = Brushes.Coral; errorTB.Push(textB_temperature); return; } double absTemperature; if (!Double.TryParse(textB_absoluteTemperature.Text, out absTemperature)) { textB_absoluteTemperature.Background = Brushes.Coral; errorTB.Push(textB_absoluteTemperature); return; } double coolingRate; if (!Double.TryParse(textB_coolingRate.Text, out coolingRate)) { textB_coolingRate.Background = Brushes.Coral; errorTB.Push(textB_coolingRate); return; } SimulatedAnnealing algorithm = null; Stopwatch time = null; int[] solve = null; Task thisTask = (Task.Run(() => { algorithm = new SimulatedAnnealing(temperature, absTemperature, coolingRate); time = new Stopwatch(); time.Start(); solve = algorithm.Solution(cities); time.Stop(); })); tasks.Enqueue(thisTask); await Task.Run(() => { while (true) { if (cts[3].Token.IsCancellationRequested || thisTask.IsCompleted) { break; } } }); if (solve != null) { DrawLines(solve, graphs[3]); timeSA.Content = time.ElapsedMilliseconds.ToString(); lengthSA.Content = algorithm.TotalDistance.ToString("F2"); } progressSA.Visibility = Visibility.Hidden; }
private static void Main() { Parameters.Verbosity = VerbosityLevels.Normal; // this next line is to set the Debug statements from OOOT to the Console. Trace.Listeners.Add(new TextWriterTraceListener(Console.Out)); /* In this example, we first present how the details of an optimzation * problem can be saved to an XML-file so that it can be read in * and solved as opposed to defining all the details in an imperative * (code line by code line) way. In the first function, the xml file * name "test1.xml" is created. */ makeAndSaveProblemDefinition(); /* now we create a series of different optimization methods and test * them on the problem. The problem is now opened from the file and * the details are stored in an object of class "Problem Definition".*/ var stream = new FileStream(filename, FileMode.Open); double[] xStar; ProblemDefinition probTest1 = ProblemDefinition.OpenprobFromXml(stream); abstractOptMethod opty; /******************Exhaustive Search ***********************/ //SearchIO.output("******************Exhaustive Search ***********************"); //Console.ReadKey(); //opty = new ExhaustiveSearch(probTest1.SpaceDescriptor, optimize.minimize); //opty.Add(probTest1); ///* No convergence criteria is needed as the process concludes when all // * states have been visited but for this problem that is 4 trillion states.*/ //opty.ConvergenceMethods.Clear(); ///* if you DID KNOW the best, you can include a criteria like...*/ //opty.ConvergenceMethods.Add(new ToKnownBestXConvergence(new[] { 3.0, 3.0 }, 0.0000001)); //var timer = Stopwatch.StartNew(); //var fStar = opty.Run(out xStar); ///* you probably will never see this process complete. Even with the added // * convergence criteria (which is not factored into the estimated time of // * completion), you are probably looking at 1 to 2 years. */ //printResults(opty, xStar, fStar, timer); /***********Gradient Based Optimization with Steepest Descent****************/ //SearchIO.output("***********Gradient Based Optimization with Steepest Descent****************"); //Console.ReadKey(); //opty = new GradientBasedOptimization(); //opty.Add(probTest1); //abstractSearchDirection searchDirMethod = new SteepestDescent(); //opty.Add(searchDirMethod); ////abstractLineSearch lineSearchMethod = new ArithmeticMean(0.0001, 1, 100); ////abstractLineSearch lineSearchMethod = new DSCPowell(0.0001, 1, 100); //abstractLineSearch lineSearchMethod = new GoldenSection(0.0001, 1); //opty.Add(lineSearchMethod); //opty.Add(new squaredExteriorPenalty(opty, 10)); ///* since this is not a population-based optimization method, we need to remove the MaxSpan criteria. */ //opty.ConvergenceMethods.RemoveAll(a => a is MaxSpanInPopulationConvergence); //timer = Stopwatch.StartNew(); //fStar = opty.Run(out xStar); //printResults(opty, xStar, fStar, timer); ///***********Gradient Based Optimization with Fletcher-Reeves****************/ //SearchIO.output("***********Gradient Based Optimization with Fletcher-Reeves****************"); //Console.ReadKey(); ///* we don't need to reset (invoke the constructor) for GradientBasedOptimization since we are only // * change the seaach direction method. */ //searchDirMethod = new FletcherReevesDirection(); ///* you could also try the remaining 3 search direction methods. */ ////searchDirMethod = new CyclicCoordinates(); ////searchDirMethod = new BFGSDirection(); ////searchDirMethod = new PowellMethod(0.001, 6); //opty.Add(searchDirMethod); //timer = Stopwatch.StartNew(); //opty.ResetFunctionEvaluationDatabase(); //fStar = opty.Run(out xStar); //printResults(opty, xStar, fStar, timer); ///******************Generalized Reduced Gradient***********************/ //SearchIO.output("******************Generalized Reduced Gradient***********************"); //Console.ReadKey(); //opty = new GeneralizedReducedGradientActiveSet(); //opty.Add(probTest1); //opty.Add(new squaredExteriorPenalty(opty, 10)); //opty.ConvergenceMethods.RemoveAll(a => a is MaxSpanInPopulationConvergence); //timer = Stopwatch.StartNew(); //fStar = opty.Run(out xStar); //printResults(opty, xStar, fStar, timer); /* GRG is the ONLY one here that handles constraints explicity. It find the * optimal very quickly and accurately. However, many of the other show a * better value of f*, this is because they are using an imperfect penalty * function (new squaredExteriorPenalty(opty, 10)). While it seems that GRG * includes it as well, it is only used in the the line search method. */ /******************Random Hill Climbing ***********************/ probTest1.SpaceDescriptor = new DesignSpaceDescription(new[] { new VariableDescriptor(-5000, 5000, 0.1), new VariableDescriptor(-5000, 5000, 0.1) }); SearchIO.output("******************Random Hill Climbing ***********************"); Console.ReadKey(); opty = new HillClimbing(); opty.Add(probTest1); opty.Add(new squaredExteriorPenalty(opty, 8)); opty.Add(new RandomNeighborGenerator(probTest1.SpaceDescriptor)); opty.Add(new KeepSingleBest(optimize.minimize)); opty.ConvergenceMethods.RemoveAll(a => a is MaxSpanInPopulationConvergence); /* the deltaX convergence needs to be removed as well, since RHC will end many iterations * at the same point it started. */ opty.ConvergenceMethods.RemoveAll(a => a is DeltaXConvergence); var timer = Stopwatch.StartNew(); var fStar = opty.Run(out xStar); printResults(opty, xStar, fStar, timer); /******************Exhaustive Hill Climbing ***********************/ SearchIO.output("******************Exhaustive Hill Climbing ***********************"); Console.ReadKey(); /* Everything else about the Random Hill Climbing stays the same. */ opty.Add(new ExhaustiveNeighborGenerator(probTest1.SpaceDescriptor)); timer = Stopwatch.StartNew(); fStar = opty.Run(out xStar); printResults(opty, xStar, fStar, timer); /******************Simulated Annealing***********************/ SearchIO.output("******************Simulated Annealing***********************"); Console.ReadKey(); opty = new SimulatedAnnealing(optimize.minimize); opty.Add(probTest1); opty.Add(new squaredExteriorPenalty(opty, 10)); opty.Add(new RandomNeighborGenerator(probTest1.SpaceDescriptor, 100)); opty.Add(new SACoolingSangiovanniVincentelli(100)); opty.ConvergenceMethods.RemoveAll(a => a is MaxSpanInPopulationConvergence); /* the deltaX convergence needs to be removed as well, since RHC will end many iterations * at the same point it started. */ opty.ConvergenceMethods.RemoveAll(a => a is DeltaXConvergence); timer = Stopwatch.StartNew(); fStar = opty.Run(out xStar); printResults(opty, xStar, fStar, timer); }
public void NelderOtherHeuristics() { int thinningPeriod = 4; int treeCount = 75; #if DEBUG treeCount = 25; #endif PlotsWithHeight nelder = PublicApi.GetNelder(); OrganonConfiguration configuration = OrganonTest.CreateOrganonConfiguration(new OrganonVariantNwo()); configuration.Treatments.Harvests.Add(new ThinByIndividualTreeSelection(thinningPeriod)); OrganonStand stand = nelder.ToOrganonStand(configuration, 20, 130.0F, treeCount); stand.PlantingDensityInTreesPerHectare = TestConstant.NelderReplantingDensityInTreesPerHectare; Objective landExpectationValue = new Objective() { IsLandExpectationValue = true, PlanningPeriods = 9 }; Objective volume = new Objective() { PlanningPeriods = landExpectationValue.PlanningPeriods }; HeuristicParameters defaultParameters = new HeuristicParameters() { UseScaledVolume = false }; GeneticParameters geneticParameters = new GeneticParameters(treeCount) { PopulationSize = 7, MaximumGenerations = 5, UseScaledVolume = defaultParameters.UseScaledVolume }; GeneticAlgorithm genetic = new GeneticAlgorithm(stand, configuration, landExpectationValue, geneticParameters); TimeSpan geneticRuntime = genetic.Run(); GreatDeluge deluge = new GreatDeluge(stand, configuration, volume, defaultParameters) { RainRate = 5, LowerWaterAfter = 9, StopAfter = 10 }; deluge.RandomizeTreeSelection(TestConstant.Default.SelectionPercentage); TimeSpan delugeRuntime = deluge.Run(); RecordTravel recordTravel = new RecordTravel(stand, configuration, landExpectationValue, defaultParameters) { StopAfter = 10 }; recordTravel.RandomizeTreeSelection(TestConstant.Default.SelectionPercentage); TimeSpan recordRuntime = recordTravel.Run(); SimulatedAnnealing annealer = new SimulatedAnnealing(stand, configuration, volume, defaultParameters) { Iterations = 100 }; annealer.RandomizeTreeSelection(TestConstant.Default.SelectionPercentage); TimeSpan annealerRuntime = annealer.Run(); TabuParameters tabuParameters = new TabuParameters() { UseScaledVolume = defaultParameters.UseScaledVolume }; TabuSearch tabu = new TabuSearch(stand, configuration, landExpectationValue, tabuParameters) { Iterations = 7, //Jump = 2, MaximumTenure = 5 }; tabu.RandomizeTreeSelection(TestConstant.Default.SelectionPercentage); TimeSpan tabuRuntime = tabu.Run(); ThresholdAccepting thresholdAcceptor = new ThresholdAccepting(stand, configuration, volume, defaultParameters); thresholdAcceptor.IterationsPerThreshold.Clear(); thresholdAcceptor.Thresholds.Clear(); thresholdAcceptor.IterationsPerThreshold.Add(10); thresholdAcceptor.Thresholds.Add(1.0F); thresholdAcceptor.RandomizeTreeSelection(TestConstant.Default.SelectionPercentage); TimeSpan acceptorRuntime = thresholdAcceptor.Run(); RandomGuessing random = new RandomGuessing(stand, configuration, volume, defaultParameters) { Iterations = 4 }; TimeSpan randomRuntime = random.Run(); configuration.Treatments.Harvests.Clear(); configuration.Treatments.Harvests.Add(new ThinByPrescription(thinningPeriod)); PrescriptionParameters prescriptionParameters = new PrescriptionParameters() { Maximum = 60.0F, Minimum = 50.0F, Step = 10.0F, UseScaledVolume = defaultParameters.UseScaledVolume }; PrescriptionEnumeration enumerator = new PrescriptionEnumeration(stand, configuration, landExpectationValue, prescriptionParameters); TimeSpan enumerationRuntime = enumerator.Run(); // heuristics assigned to volume optimization this.Verify(deluge); this.Verify(annealer); this.Verify(thresholdAcceptor); this.Verify(random); // heuristics assigned to net present value optimization this.Verify(genetic); this.Verify(enumerator); this.Verify(recordTravel); this.Verify(tabu); HeuristicSolutionDistribution distribution = new HeuristicSolutionDistribution(1, thinningPeriod, treeCount); distribution.AddRun(annealer, annealerRuntime, defaultParameters); distribution.AddRun(deluge, delugeRuntime, defaultParameters); distribution.AddRun(thresholdAcceptor, acceptorRuntime, defaultParameters); distribution.AddRun(genetic, geneticRuntime, defaultParameters); distribution.AddRun(enumerator, enumerationRuntime, defaultParameters); distribution.AddRun(recordTravel, recordRuntime, defaultParameters); distribution.AddRun(tabu, tabuRuntime, defaultParameters); distribution.AddRun(random, randomRuntime, defaultParameters); distribution.OnRunsComplete(); }