Skip to content

Instantly share code, notes, and snippets.

@branw
Last active August 29, 2015 14:10
Show Gist options
  • Save branw/ca56b4550413b7e2d6c5 to your computer and use it in GitHub Desktop.
Save branw/ca56b4550413b7e2d6c5 to your computer and use it in GitHub Desktop.
A bookmarklet JavaScript snippet to automate the process of running several simulations in the Zero Robotics 2014-15 IDE and averaging their scores.

zr-batch-simulate.js

A bookmarklet JavaScript snippet to automate the process of running several simulations in the Zero Robotics 2014-15 IDE and averaging their scores.

Usage

Through a bookmark

  1. Copy the contents of bookmarklet.js below
  2. In a new bookmark, type javascript: followed by the copied text if bookmarklet.js; save the bookmark
  3. Once the IDE is fully loaded, click the bookmark and, when prompted, enter the number of simulations to run
  4. Wait patiently a dozen or so seconds for the simulations to complete; a item will appear in the left-hand list titled "Log" detailing all of the simulations

Through the address bar

  1. Copy the contents of bookmarklet.js below
  2. In the address bar, type javascript: followed by the copied text if bookmarklet.js
  3. When the IDE is fully loaded, press enter in the address bar to run the script and, when prompted, enter the number of simulations to run
  4. Wait patiently a dozen or so seconds for the simulations to complete; a item will appear in the left-hand list titled "Log" detailing all of the simulations

License

The MIT License (MIT)

Copyright (c) 2014 Brandon Walker

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

$.getScript('https://rawgit.com/summerset/ca56b4550413b7e2d6c5/raw/zr-batch-simulate.min.js')
var sim_info = {};
var batch_simulations = function(code, runs, callback) {
var index = Object.keys(sim_info).length;
sim_info[index] = {
'total_runs': runs,
'runs_completed': 0,
'scores': [],
'scores_sum': 0,
'id': 0,
'code': code,
'callback': callback
};
for (var i = 0; i < runs; i++) {
_create_simulation(sim_info[index]);
}
};
var _create_simulation = function(info) {
$.ajax({
type: 'POST',
url: '/ide/simulate',
data: JSON.stringify({
'gameId': 11,
'snapshot1': 94857,
'snapshot2': 203458,
'simConfig': {
'timeout': 300,
'state1': [0,0.6,0,0,0.6,0],
'state2': [0,-0.6,0,0,-0.6,0],
'gameVariables': []
},
'code1': info['code'],
'code2': 'void init() {} void loop() {}'
}),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(content) {
setTimeout(function() {
_check_status(info, content);
}, 1000);
},
failure: function(error) {
console.log(error);
}
});
};
var _check_status = function(info, id){
$.ajax({
type: 'GET',
url: '/ide/simulate/status/' + id,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(data) {
var status = data['status'];
if (status == 'SIMULATING') {
setTimeout(function() {
_check_status(info, id);
}, 1000);
} else if (status == 'SUCCEEDED') {
_load_page(info, id);
} else {
alert(id + ' ' + status);
}
}
});
};
var _load_page = function(info, id) {
$.get('/ide/simulation/' + id + '/', function(data) {
_check_score(info, id, data);
});
};
var _check_score = function(info, id, data) {
var simdata = $(data).filter('script')[17].text;
simdata = simdata.substring(18, simdata.length - 2);
simdata = $.parseJSON(simdata);
var score = parseFloat(simdata['satData']['0']['dF']['0']['250']);
console.log(id + ' ' + score);
info['scores'].push(score);
info['scores_sum'] += score;
info['runs_completed']++;
if (info['runs_completed'] == info['total_runs']) {
info['callback'](info);
}
};
$('.ace_editor').attr('id', 'editor');
var code = ace.edit("editor").getSession().getValue();
var runs = parseInt(prompt('Number of simulations to run:', '20'));
var callback = function(info) {
var mean = info['scores_sum'] / info['total_runs'];
var max = Math.max.apply(null, info['scores']);
var min = Math.min.apply(null, info['scores']);
var list_item = '<a class="list-group-item ng-scope ng-binding">' + new Date($.now()) + '<br/>Average score across ' + info['runs_completed'] + ' attempts: <b>' + mean.toFixed(2) + '</b><br/>with a max and min of ' + max + ' and ' + min + '<br/>(' + info['scores'].join(', ') + ')<br/></a>';
$('#log-list').prepend(list_item);
};
batch_simulations(code, runs, callback);
var sim_info={};var batch_simulations=function(c,d,e){var a=Object.keys(sim_info).length;sim_info[a]={total_runs:d,runs_completed:0,scores:[],scores_sum:0,id:0,code:c,callback:e};for(var b=0;b<d;b++){_create_simulation(sim_info[a])}};var _create_simulation=function(a){$.ajax({type:"POST",url:"/ide/simulate",data:JSON.stringify({gameId:11,snapshot1:94857,snapshot2:203458,simConfig:{timeout:300,state1:[0,0.6,0,0,0.6,0],state2:[0,-0.6,0,0,-0.6,0],gameVariables:[]},code1:a.code,code2:"void init() {} void loop() {}"}),contentType:"application/json; charset=utf-8",dataType:"json",success:function(b){setTimeout(function(){_check_status(a,b)},1000)},failure:function(b){console.log(b)}})};var _check_status=function(a,b){$.ajax({type:"GET",url:"/ide/simulate/status/"+b,contentType:"application/json; charset=utf-8",dataType:"json",success:function(d){var c=d.status;if(c=="SIMULATING"){setTimeout(function(){_check_status(a,b)},1000)}else{if(c=="SUCCEEDED"){_load_page(a,b)}else{alert(b+" "+c)}}}})};var _load_page=function(a,b){$.get("/ide/simulation/"+b+"/",function(c){_check_score(a,b,c)})};var _check_score=function(c,e,b){var a=$(b).filter("script")[17].text;a=a.substring(18,a.length-2);a=$.parseJSON(a);var d=parseFloat(a.satData["0"]["dF"]["0"]["250"]);console.log(e+" "+d);c.scores.push(d);c.scores_sum+=d;c.runs_completed++;if(c.runs_completed==c.total_runs){c.callback(c)}};$(".ace_editor").attr("id","editor");var code=ace.edit("editor").getSession().getValue();var runs=parseInt(prompt("Number of simulations to run:","20"));var callback=function(e){var b=e.scores_sum/e.total_runs;var a=Math.max.apply(null,e.scores);var d=Math.min.apply(null,e.scores);var c='<a class="list-group-item ng-scope ng-binding">'+new Date($.now())+"<br/>Average score across "+e.runs_completed+" attempts: <b>"+b.toFixed(2)+"</b><br/>with a max and min of "+a+" and "+d+"<br/>("+e.scores.join(", ")+")<br/></a>";$("#log-list").prepend(c)};batch_simulations(code,runs,callback);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment