-
Notifications
You must be signed in to change notification settings - Fork 222
Adds Simulated Annealing diagram #82
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,82 +1,119 @@ | ||
| $(document).ready(function(){ | ||
| $.ajax({ | ||
| url : "simulatedAnnealing.js", | ||
| dataType: "text", | ||
| success : function (data) { | ||
| $("#simulatedAnnealingCode").html(data); | ||
| } | ||
| }); | ||
|
|
||
| var annealingCanvas; | ||
| var text,line,background; | ||
| var w,h; | ||
| var two; | ||
| var sa; | ||
|
|
||
| var x = 0; // Current Index | ||
| var f; // The objective function | ||
|
|
||
| var DELAY = 1 * 60; | ||
| var POINTS = 30; // Number of points of the objective function | ||
| var INITIAL_TEMP = 50; | ||
| var K = 1; // Boltzmann constant | ||
|
|
||
| function init(){ | ||
| annealingCanvas = document.getElementById("annealingCanvas"); | ||
| annealingCanvas.addEventListener("click", handleClick, false); | ||
| w = annealingCanvas.offsetWidth; | ||
| h = 300; | ||
| two = new Two({ width: w, height: h }).appendTo(annealingCanvas); | ||
| sa = new SimulatedAnnealing(x,K,INITIAL_TEMP); | ||
| text = two.makeText("Temperature: "+INITIAL_TEMP,w/2 ,10,'normal'); | ||
| line = two.makeLine(x,0,x,h); | ||
| line.stroke = 'orangered'; | ||
| line.linewidth = 5; | ||
| setupScene(); | ||
| } | ||
|
|
||
| init(); | ||
|
|
||
| two.bind('update', function(frameCount){ | ||
| if(frameCount % DELAY == 0){ | ||
| x = sa.anneal(f); | ||
| // Translate the point according to the new chosen point | ||
| line.translation.set(x*w/POINTS,h/2); | ||
| y = Math.round(f[x]*100)/100; | ||
| text.value = "Temperature: "+sa.T + " ("+x+" , "+y+")"; | ||
| } | ||
| }).play(); | ||
|
|
||
| function handleClick(){ | ||
| // When ever the canvas is clicked | ||
| // recalculate and redraw the background | ||
| // and reinitialize the sa object | ||
| setupScene(); | ||
| x = 0; | ||
| sa = new SimulatedAnnealing(x,K,INITIAL_TEMP); | ||
| } | ||
|
|
||
| function setupScene(){ | ||
| // If background already exists, | ||
| // then clear it | ||
| if(background != null) | ||
| two.remove(background); | ||
| f = new Array(POINTS); | ||
| background = new Array(POINTS-1); | ||
| f[0] = 0; | ||
| for(var i = 1; i < f.length; i++){ | ||
| // f[i] ranges between 0 and 3*h/4 | ||
| f[i] = Math.random() * 3*h/4; | ||
| sx = (i-1) * w/POINTS; | ||
| sy = h - f[i-1]; | ||
| fx = i * w/POINTS; | ||
| fy = h - f[i]; | ||
| // Draw lines connecting all f[i] | ||
| background[i-1] = two.makeLine(sx,sy,fx,fy); | ||
| background[i-1].linewidth = 2; | ||
| background[i-1].stroke = '#090A3B'; | ||
| } | ||
| two.update(); | ||
| } | ||
| $(document).ready(function() { | ||
|
|
||
| //Wrapper class for the diagram | ||
| class SimulatedAnnealingDiagram extends HillWorld { | ||
| constructor(selector, h, w, sliderSelector) { | ||
| super(selector, h, w); | ||
| this.sliderElement = $(sliderSelector); | ||
| } | ||
|
|
||
| init(delay, k) { | ||
| this.delay = delay; | ||
| this.initial = this.hillClimber.getCurrentState(); | ||
| this.simulatedAnnealing = new SimulatedAnnealing(this.hill, this.initial, k); | ||
| this.colorScale = d3.scaleLinear().domain([0, 50]).range([70, 30]).clamp(true); | ||
| this.showAllStates(); | ||
| this.bindListeners(); | ||
| this.paintGlobalMaxima(); | ||
| this.showTemperature(100); | ||
| this.sliderElement.val(100); | ||
| this.startAnnealing(); | ||
| } | ||
|
|
||
| showAllStates() { | ||
| this.hillDiagram.svgRects.transition() | ||
| .duration(200) | ||
| .style('opacity', 1); | ||
| } | ||
|
|
||
| paintGlobalMaxima() { | ||
| this.hillDiagram.svgRects.classed('hill-maxima', (d) => d.maxima); | ||
| } | ||
|
|
||
| teleportRobot(currentState) { | ||
| let robotLocation = currentState; | ||
| let robotStateValue = this.hill.getStates()[currentState]; | ||
| this.hillClimberDiagram.robot | ||
| .attr('x', this.hillClimberDiagram.xScale(robotLocation) - this.hillClimberDiagram.xOffset) | ||
| .attr('y', this.h - this.hillClimberDiagram.yScale(robotStateValue) - this.hillClimberDiagram.yOffset); | ||
| } | ||
|
|
||
| updateAnnealRegion(currentState) { | ||
| this.hillDiagram.svgRects.classed('hill-anneal-current-state', d => d.state == currentState); | ||
| } | ||
|
|
||
| showTemperature(t) { | ||
| this.svgTemp = this.hillDiagram.svg.append('text') | ||
| .attr('x', this.w - 180) | ||
| .attr('y', this.h - 470) | ||
| //Displaying temperature with 2 digit precision | ||
| .text(`Temperature : ${Math.round(t*100)/100}`); | ||
| } | ||
|
|
||
| updateTemperature(t) { | ||
| this.svgTemp.text(`Temperature : ${Math.round(t*100)/100}`); | ||
| } | ||
|
|
||
| nextMove(temp) { | ||
| let nextNode = this.simulatedAnnealing.anneal(temp); | ||
| if (nextNode.temp <= 0) { | ||
| this.updateTemperature(0); | ||
| return false; | ||
| } else { | ||
| let nextState = nextNode.state; | ||
| this.hillClimber.changeState(nextState); | ||
| this.teleportRobot(nextState); | ||
| this.updateAnnealRegion(nextState); | ||
| return true; | ||
| } | ||
| } | ||
|
|
||
| startAnnealing() { | ||
| //Stop annealing if already running. | ||
| this.stopAnnealing(); | ||
| this.annealIntervalFunction = setInterval(() => { | ||
| if (!this.nextMove(this.sliderElement.val())) { | ||
| this.stopAnnealing(); | ||
| } | ||
| }, this.delay); | ||
| } | ||
|
|
||
| stopAnnealing() { | ||
| clearInterval(this.annealIntervalFunction, this.delay); | ||
| } | ||
|
|
||
| destroy() { | ||
| this.stopAnnealing(); | ||
| } | ||
|
|
||
| bindListeners() { | ||
| this.sliderElement.mouseup(() => { | ||
| if (this.sliderElement.val() > 0) { | ||
| this.startAnnealing(); | ||
| } | ||
| }); | ||
| this.sliderElement.mousemove(() => { | ||
| this.updateTemperature(this.sliderElement.val()) | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| var simulatedAnnealingDiagram; | ||
|
|
||
| function init() { | ||
| simulatedAnnealingDiagram = new SimulatedAnnealingDiagram('#annealingCanvas', 500, 1000, '#tempSelector'); | ||
|
|
||
| let delay = 20; | ||
|
|
||
| let k = 0.3; | ||
| simulatedAnnealingDiagram.init(delay, k); | ||
| }; | ||
|
|
||
| function restart() { | ||
| simulatedAnnealingDiagram.destroy(); | ||
| init(); | ||
| } | ||
|
|
||
| init(); | ||
| $('#annealingRestart').click(restart); | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,28 +1,30 @@ | ||
| var SimulatedAnnealing = function(x,k,T){ | ||
| this.x = x; // Starting state | ||
| this.k = k; // Boltzmann constant | ||
| this.T = T; // Initial temperature | ||
| class SimulatedAnnealing { | ||
| constructor(hill, initial, k) { | ||
| this.states = hill.getStates(); | ||
| this.initial = initial; | ||
| this.current = this.initial; | ||
| this.k = k; | ||
| } | ||
|
|
||
| this.anneal = function(f){ | ||
| if(this.T == 0) return x; | ||
| var new_x = this.getRandomInt(0,f.length); | ||
| if(f[new_x] > f[x]){ | ||
| // If the new chosen value is better | ||
| // then just move to new state | ||
| x = new_x; | ||
| } else { | ||
| // Calculate probability of transfer | ||
| var p = Math.exp((f[new_x] - f[x])/(k * T)); | ||
| // If a randomly chosen value is within p | ||
| // then move to the new state | ||
| if(Math.random() < p) | ||
| x = new_x; | ||
| } | ||
| this.T--; | ||
| return x; | ||
| }; | ||
|
|
||
| this.getRandomInt = function(min, max) { | ||
| return Math.floor(Math.random() * (max - min)) + min; | ||
| }; | ||
| }; | ||
| anneal(temperature) { | ||
| let nextState = this.getRandomState(); | ||
| let diff = this.states[nextState] - this.states[this.current]; | ||
| if (diff > 0) { | ||
| this.current = nextState; | ||
| } else { | ||
| let p = Math.exp((diff) / parseInt(this.k * temperature)); | ||
| if (Math.random() < p) { | ||
| this.current = nextState; | ||
| } | ||
| } | ||
| return { | ||
| state: this.current, | ||
| temp: temperature | ||
| }; | ||
| } | ||
| getRandomState() { | ||
| let mini = 0; | ||
| let maxi = this.states.length; | ||
| return Math.floor(Math.random() * (maxi - mini + 1)) + mini; | ||
| } | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Are you still using Two.js here?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
No I am not. The deleted part is from the past implementation.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Oh, silly me, I misread the diff :)