Created
November 3, 2016 20:09
-
-
Save kingoflolz/cd8f61520f68e09eeefae3514fa98cd2 to your computer and use it in GitHub Desktop.
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
import json | |
import operator | |
import random | |
import re | |
import statistics | |
import requests | |
import time | |
from functools import reduce | |
from simanneal import Annealer | |
class ZRSimulator: | |
# HTTP Session | |
session = None | |
timeout = 1 | |
base_uri = 'http://zerorobotics.mit.edu/ide/' | |
simulate_uri = '/simulate' | |
status_uri = '/simulate/status/' | |
simulation_uri = '/simulation/json/' | |
cookies = { | |
'session': '.eJw9kMtugkAARX-lmXUXMGJTSLqoCBTaGeIAA8PG8Bh5DWgQRDD-e41Ju7_35Nx7A_tDz88l0IZ-5K9gX-VAu4GXFGgA10hGrS0zSAWqHcFaBtnCJAzZjC3SuL5TuyGa8db4APdH98T7Nul4N_zRhmPDu38en52SQSyyFT7kltrHoVK51WfFQ2N2vfU2adSfnU--kXCUvCFNGsU1WrIJGdcu9R0crIgXSMIk1JyQRS-JXAxkKyTim3IoiB4bWKFhs-bUDJGBrjEsIxyVp8CTh3y2z7buCP61OWUtXSIoRrs-FmhhE9Knwu7IJYF0jFZknVnB02vX0vKRne1Oeu4bz7x__vP-pqj3X2QLaEc.Cvyq-Q.upvyjwcLesDU4DFs4YspW8DU_7E' } | |
headers = { | |
'Pragma': 'no-cache', | |
'Origin': 'http://zerorobotics.mit.edu', | |
'Accept-Encoding': 'gzip, deflate', | |
'Accept-Language': 'en-US,en;q=0.8,fr;q=0.6,zh-CN;q=0.4,zh;q=0.2,zh-TW;q=0.2', | |
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36', | |
'Content-Type': 'application/json;charset=UTF-8', | |
'Accept': 'application/json, text/plain, */*', | |
'Cache-Control': 'no-cache', | |
'authorization': 'ya29.CjOKA4J2RxvDdmvc3700Lgm2MStRSIEEQp0eokX-D9tE1uZTBdCxUi9yQV0C1ghW5xiQ-mw', | |
'Connection': 'keep-alive', | |
'Referer': 'http://zerorobotics.mit.edu/ide/0B-Oky5UE3YgiRW81TG1EdG52dEU//', | |
'DNT': '1', | |
} | |
data = { | |
"gameId": 19, | |
"snapshot1": 94857, | |
"snapshot2": 203458, | |
"simConfig": { | |
"timeout": 213, | |
"state1": [0, 0.15, 0, 1, 0, 0], | |
"state2": [0, -0.15, 0, -1, 0, 0], | |
"gameVariables": [{"name": "zoneX_cm", "value": 0}, {"name": "zoneY_cm", "value": 0}, | |
{"name": "zoneZ_cm", "value": 0}] | |
}, | |
"code1": "{}", | |
"code2": "{}" | |
} | |
last_simulation_id = 0 | |
def __init__(self): | |
# Init a session | |
self.session = requests.Session() | |
# Setup cookies | |
for key, val in self.cookies.items(): | |
self.session.cookies.set(key, val) | |
# Setup headers | |
self.session.headers.update(self.headers) | |
# Is the http response 200? | |
def validate_response(self, resp): | |
if resp.status_code == 200: | |
return True | |
else: | |
print(resp.status_code) | |
return False | |
# Dispatches a sim request and returns the simid | |
def simulate(self, code1, code2): | |
d = self.data.copy() | |
d["code1"] = d["code1"].format(code1) | |
d["code2"] = d["code2"].format(code2) | |
resp = self.session.post(self.base_uri + self.simulate_uri, json=d) | |
while not self.validate_response(resp): | |
resp = self.session.post(self.base_uri + self.simulate_uri, d) | |
self.last_simulation_id = int(resp.text) | |
return int(resp.text) | |
# Gets the status of the sim | |
def get_sim_status(self, simid=None): | |
if simid is None: | |
simid = self.last_simulation_id | |
resp = self.session.get(self.base_uri + self.status_uri + str(simid)) | |
while not self.validate_response(resp): | |
resp = self.session.get(self.base_uri + self.status_uri + str(simid)) | |
return resp.json() | |
# Gets the sim data of sim id | |
def get_sim_data(self, simid=None): | |
if simid is None: | |
simid = self.last_simulation_id | |
resp = self.session.get(self.base_uri + self.simulation_uri + str(simid)) | |
self.validate_response(resp) | |
return resp.json() | |
def get_sim_data_blocking(self, simid): | |
status = self.get_sim_status(simid)['status'] | |
while status != 'SUCCEEDED': | |
if status == 'FAILED': | |
raise TypeError("Failed to compile code" + self.get_sim_status(simid)['message']) | |
time.sleep(self.timeout) | |
status = self.get_sim_status(simid)['status'] | |
return self.get_sim_data(simid) | |
def run(self, code): | |
simids = [] | |
for i in code: | |
simids.append(self.simulate(i[0], i[1])) | |
results = [] | |
for i in simids: | |
results.append(self.get_sim_data_blocking(i)) | |
return results | |
targets_1 = [ | |
"0.0, 0.2, 0.0", | |
"0.0, 0.3, 0.0", | |
"0.0, 0.4, 0.0", | |
"0.0, 0.5, 0.0", | |
"0.0, 0.6, 0.0", | |
] | |
targets_2 = [ | |
"0.0, -0.2, 0.0", | |
"0.0, -0.3, 0.0", | |
"0.0, -0.4, 0.0", | |
"0.0, -0.5, 0.0", | |
"0.0, -0.6, 0.0", | |
] | |
def geometric_mean(iterable): | |
return (reduce(operator.mul, iterable)) ** (1.0/len(iterable)) | |
class GainsOpt(Annealer): | |
def __init__(self, initial_state): | |
super().__init__(initial_state) | |
self.copy_strategy = 'slice' | |
self.base_code = open('code.cpp', 'r').read() | |
self.ZRSim = ZRSimulator() | |
self.Tmax = 25000.0 | |
self.Tmin = 2.5 | |
self.steps = 1000 | |
self.updates = 1000 | |
def move(self): | |
print(self.state) | |
id = random.randint(0, len(self.state) - 1) | |
self.state[id] *= (1 + 0.01 * (random.randint(0, 1) * 2 - 1)) | |
def energy(self): | |
code = [] | |
for i in range(len(targets_1)): | |
gains = "{}f, {}f, {}f".format(self.state[0], self.state[1], self.state[2]) | |
code1 = self.base_code.replace("<target>", targets_1[0]).replace("<gains>", gains) | |
code2 = self.base_code.replace("<target>", targets_2[0]).replace("<gains>", gains) | |
code.append([code1, code2]) | |
results = self.ZRSim.run(code) | |
times = [] | |
for i in results: | |
times.append(statistics.mean([int(s) for s in re.findall(r'DONE ON TICK (\d+)', json.dumps(i))])) | |
print(geometric_mean(times), self.state) | |
return geometric_mean(times) | |
g = GainsOpt([0.12 ,0.0 ,1.55]) | |
r, c = g.anneal() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment