forked from Rishav159/aima-javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Ch 4 - Add simulated annealing diagram
- Loading branch information
1 parent
9ddc4bb
commit f44dc39
Showing
5 changed files
with
183 additions
and
137 deletions.
There are no files selected for viewing
This file contains 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 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 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 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 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; | ||
} | ||
} |