def compute_cost(start, goal): #create problem.pddl file, run FD and return solution cost problem(start, goal) os.system( ' ./downward/fast-downward.py domain.pddl problem.pddl --search "astar(lmcut())" > /dev/null' ) if os.path.isfile('sas_plan'): solution = open('sas_plan', 'r') last_line = solution.readlines()[-1].split() cost = int(last_line[3]) solution.close() else: cost = 'inf' #if does not exists a solution return cost
def test_rand(self): import random x = random.randint(1, 500) for _ in range(30): x = random.randint(1, 500) self.assertEqual(problem(x), x * 50 + 6)
def GET(self): top() data=web.input() web.ctx.session.idp=data['idp'] web.ctx.session.hintlevel=0 web.ctx.session.hint='' problemdata=db.select('description',data,where='id=$idp') problemdata=problemdata[0] constants=randomgenerator.getRandomConstants(problemdata.constants) arrays=randomgenerator.getRandomArrays(problemdata.arrays) if problemdata.hints is not None: hinttext='hints='+problemdata.hints exec(hinttext) else: hints=None if problemdata.video is not None: videotext='video='+problemdata.video exec(videotext) else : video=None t=problem('<p>'+problemdata.description,arrays,constants,(problemdata.dimension_y,20),problemdata.solutiontext,problemdata.tableexplanation,hints,video) web.ctx.session.instance=t web.ctx.session.problemstatus=2; web.ctx.session.solutionindex=0; commands=re.split('[\n\r]+',problemdata.recurrence) comments=db.query('select * from example_users eu join comment c on c.user_id=eu.id where c.problem_id='+web.ctx.session.idp) mysolution=solutioninstance(solver2.solve(web.ctx.session.instance.lists,web.ctx.session.instance.constants,commands,web.ctx.session.instance.dimensions[0],web.ctx.session.instance.dimensions[1])) render = web.template.render(config.templatedir,base='layout',globals={'context': web.ctx.session}) return render.problemtable(web.ctx.session.instance,mysolution,None,comments)
def test(self): self.assertEqual(problem("hello"), "Error") self.assertEqual(problem(1), 56) self.assertEqual(problem(5), 256) self.assertEqual(problem(0), 6) self.assertEqual(problem(1.2), 66) self.assertEqual(problem(3), 156) self.assertEqual(problem("RyanIsCool"), "Error") self.assertEqual(problem(x), x * 50 + 6)
def create_problem (parsed_problem_description, output): path_planner = distances_calculator.distances_calculator(parsed_problem_description['image'], parsed_problem_description['pathPlan']['grid_size'], parsed_problem_description['pathPlan']['algorithm'], parsed_problem_description['pathPlan']['heuristic'], parsed_problem_description['pathPlan']['scale']) prob = problem.problem(parsed_problem_description,path_planner) if not os.path.exists(f'{head_path}{output}'): os.makedirs(f'{head_path}{output}') with open(f'{head_path}{output}{problem_path}', 'w+') as problem_output: problem_output.write(str(prob)) return path_planner, prob
def recommend_most_recent_bckdr(self): bkd = problem(self.pid) res = "\nShowing recommendations for problem: " + self.pid + "\n" os.write(self.log_file,res) print res res = json.dumps(bkd.find_similar_bckdr(self.status), indent=4, separators=(',', ': ')) os.write(self.log_file,res) os.write(self.result_file,res) print res
def setUp(self): np.random.seed(0) n = 10 p = 5 A1 = np.zeros((n, p)) C1 = np.zeros((n, p)) b = np.zeros(n) e = np.zeros(n) A2 = np.random.randn(n, p) C2 = np.random.randn(n, p) self.pr1 = problem(n, A1, b, C1, e) self.pr2 = problem(n, A2, b, C2, e) self.n = n self.p = p self.theta1 = np.random.randn(p) self.theta2 = np.zeros(p) self.theta = np.zeros((n, p))
def setUp(self, lambda_1=None, lambda_2=None): if lambda_1 is None: lambda_1 = -1.0 if lambda_2 is None: lambda_2 = -0.1 self.prob = problem(lambda_1, lambda_2) self.M = 2 self.P = 3 tstart = 0.0 tend = 0.5 self.sdc = sdc_step(self.M, self.P, tstart, tend, self.prob)
def setUp(self, lambda_1=None, lambda_2=None): if lambda_1 is None: lambda_1 = -1.0 if lambda_2 is None: lambda_2 = -0.1 self.prob = problem(lambda_1, lambda_2) self.M = 2 self.P = 3 tstart = 0.0 tend = 0.5 self.sdc = sdc_step(self.M, self.P, tstart, tend, self.prob)
def recommend_most_recent_cfs(self): cfs = problem(self.pid) res = "\nShowing recommendations for problem: " + self.pid + "\n" os.write(self.log_file, res) print res res = json.dumps(cfs.find_similar_cfs(self.status), indent=4, separators=(',', ': ')) os.write(self.log_file, res) os.write(self.result_file, res) print res
def checksolution(idp, theircommands): checks = [] data = {} answer = True data['idp'] = idp problemdata = db.select('description', data, where='id=$idp') problemdata = problemdata[0] commands = re.split('[\n\r]+', problemdata.recurrence) text = '\n'.join(theircommands) for i in range(10): constants = randomgenerator.getRandomConstants(problemdata.constants) arrays = randomgenerator.getRandomArrays(problemdata.arrays) t = problem('<p>' + problemdata.description, arrays, constants, (problemdata.dimension_y, 20), problemdata.solutiontext, problemdata.tableexplanation) mysolution = solutioninstance(solver2.solve(t.lists, t.constants, commands, t.dimensions[0], t.dimensions[1])) theirsolution = solutioninstance( solver2.solve(t.lists, t.constants, theircommands, t.dimensions[0], t.dimensions[1])) #both answers are none-just output tables if mysolution.answer is None and theirsolution.answer is None: if mysolution.table == theirsolution.table: print "Try " + str(i) + ":", "TRUE TRUE TRUE!!!!!!!!!!!" checks.append(["Succeeded with input:", constants, arrays, mysolution.table, theirsolution.table]) else: checks.append(["Failed with input:", constants, arrays, mysolution.table, theirsolution.table]) print "FALSE FALSE FALSE!!!!" print "mine:" + str(mysolution.table) print "theirs:" + str(theirsolution.table) answer = False #if one answer is None, return false. TODO: make them separate when you get messages elif (mysolution.answer is not None and theirsolution.answer is None) or ( mysolution.answer is None and theirsolution.answer is not None): checks.append(["You should specify an answer with the answer keyword",constants,arrays,mysolution.table,theirsolution.table,mysolution.answer,theirsolution.answer]) answer = False elif mysolution.answer != theirsolution.answer: checks.append(["Wrong answer for input:", constants, arrays, mysolution.table,theirsolution.table, mysolution.answer, theirsolution.answer]) answer = False elif mysolution.answer == theirsolution.answer: checks.append( ["Succeeded with input:", constants, arrays, mysolution.table, theirsolution.table, mysolution.answer, theirsolution.answer]) try: db.insert('user_input', id_user=int(web.ctx.session.userid), attempt=text, id_problem=idp, correct=answer) except Exception as e: print e if answer: try: db.insert('user_problems', id_user=int(web.ctx.session.userid), id_problem=idp) except Exception as e: pass return answer, checks
def fetch_user_activity_erd(uid="", handle=""): ''' | Fetch User's activity from Erdos ''' url = "http://erdos.sdslabs.co/activity/users/" + handle[3:] + ".json" print url sql = "SELECT MAX(created_at) FROM activity WHERE handle = \'" + handle + "\'" print sql res = db.read(sql, cursor) # print res if res[0][0] is None: last_activity = 0 else: last_activity = int(res[0][0]) # last_activity = int(last_activity) payload = {} payload['start_time'] = last_activity r = requests.get(url, params = payload) if(r.status_code != 200 ): print r.status_code, " returned from ", r.url else: result = r.json()['list'] result.reverse() for act in result: if int(act['created_at']) > last_activity: sql = "SELECT pid FROM activity WHERE pid = \'erd" + act['problem_id'] + "\' AND handle = \'" + handle + "\'" check = db.read(sql, cursor) difficulty = 0 if check == (): sql = "INSERT INTO activity (handle, pid, attempt_count, status, difficulty, uid, created_at) VALUES ( \'" + handle + "\', \'erd" + act['problem_id'] + "\', '1', " + str(act['status']) + ", " + str(difficulty) + ", " + uid + ", " + str(act['created_at']) + " )" db.write(sql, cursor, conn) p = problem("erd" + act['problem_id']) if p.exists_in_db != -1: tag_data = p.tag for tag in tag_data: sql = "SELECT tag FROM user_tag_score WHERE tag = \'" + tag + "\' AND handle = \'" + handle + "\'" tag_check = db.read(sql, cursor) if tag_check == (): sql = "INSERT INTO user_tag_score (handle, tag, score) VALUES ( \'" + handle + "\' , \'" + tag + "\' , " + str(tag_data[tag]) + " )" db.write(sql, cursor, conn) else: sql = "UPDATE user_tag_score SET score = score +" + str(tag_data[tag]) + " WHERE tag = \'" + tag + "\' AND handle = \'" + handle + "\'" db.write(sql, cursor, conn) else: sql = "UPDATE activity SET attempt_count = attempt_count + 1, status = " + str(act['status']) + ", difficulty = " + str(difficulty) + ", created_at = " + str(act['created_at']) + " WHERE pid = \'erd" + act['problem_id'] + "\' AND handle = \'" + handle + "\'" db.write(sql, cursor, conn) print sql
def main(): filename, strategy, depthl, pruning, stat, heu = askInfo() if(strategy == 3): depthi = int(input('depth increment: ')) p = problem('%s.json' % filename) print(p._state_space._path.lower()) itime = time.time() #run algorithms if(strategy == 3): sol, num_f = search(p, strategy, depthl, depthi, pruning, heu) else: sol, num_f = limSearch(p, strategy, depthl, pruning, heu) etime = time.time() createSolution(sol, itime, etime, num_f) createGpx(p, sol, itime, etime, num_f, stat) call(['solu/gpx2svg', '-i', 'solu/out.gpx', '-o', 'solu/out.svg'])
def fetch_user_activity_cfs(handle=""): ''' | Fetch User's activity from Codeforces ''' cfs_url = "http://codeforces.com/api/user.status" payload = {} payload['handle'] = handle handle = 'cfs' + handle sql = "SELECT created_at FROM activity WHERE handle = \'" + handle + "\' ORDER BY created_at DESC LIMIT 1;" res = db.read(sql, cursor) if res == (): last_activity = 0 else: last_activity = res[0][0] last_activity = int(last_activity) r = requests.get(cfs_url, params=payload) if(r.status_code != 200 ): print r.status_code, " returned from ", r.url else: result = r.json()['result'] result.reverse() for act in result: if int(act['creationTimeSeconds']) > last_activity: sql = "SELECT pid FROM activity WHERE pid = \'cfs" + str(act['problem']['contestId']) + str(act['problem']['index']) + "\' AND handle = \'" + handle + "\'" check = db.read(sql, cursor) difficulty = 0 if act['verdict'] == "OK": status = 1 else: status = 0 if check == (): sql = "INSERT INTO activity (handle, pid, attempt_count, status, difficulty, created_at) VALUES ( \'" + handle + "\', \'cfs" + str(act['problem']['contestId']) + str(act['problem']['index']) + "\', '1', " + str(status) + ", " + str(difficulty) + ", " + str(act['creationTimeSeconds']) +" )" db.write(sql, cursor, conn) p = problem("cfs" + str(act['problem']['contestId']) + str(act['problem']['index'])) if p.exists_in_db != -1: tag_data = p.tag for tag in tag_data: sql = "SELECT tag FROM user_tag_score WHERE tag = \'" + tag + "\' AND handle = \'" + handle + "\'" tag_check = db.read(sql, cursor) if tag_check == (): sql = "INSERT INTO user_tag_score (handle, tag, score) VALUES ( \'" + handle + "\' , \'" + tag + "\' , " + str(tag_data[tag]) + " )" db.write(sql, cursor, conn) else: sql = "UPDATE user_tag_score SET score = score + " + str(tag_data[tag]) + " WHERE tag = \'" + tag + "\' AND handle = \'" + handle + "\'" db.write(sql, cursor, conn) else: sql = "UPDATE activity SET attempt_count = attempt_count + 1, status = " + str(status) + ", difficulty = " + str(difficulty) + ", created_at = " + str(act['creationTimeSeconds']) + " WHERE pid = \'cfs" + str(act['problem']['contestId']) + str(act['problem']['index']) + "\' AND handle = \'" + handle + "\'" db.write(sql, cursor, conn)
def fetch_user_activity_cfs(handle=""): ''' | Fetch User's activity from Codeforces ''' cfs_url = "http://codeforces.com/api/user.status" payload = {} payload['handle'] = handle handle = 'cfs' + handle sql = "SELECT created_at FROM activity WHERE handle = \'" + handle + "\' ORDER BY created_at DESC LIMIT 1;" res = db.read(sql, cursor) if res == (): last_activity = 0 else: last_activity = res[0][0] last_activity = int(last_activity) r = requests.get(cfs_url, params=payload) if(r.status_code != 200 ): print r.status_code, " returned from ", r.url else: result = r.json()['result'] result.reverse() for act in result: if int(act['creationTimeSeconds']) > last_activity: sql = "SELECT pid FROM activity WHERE pid = \'cfs" + str(act['problem']['contestId']) + str(act['problem']['index']) + "\' AND handle = \'" + handle + "\'" check = db.read(sql, cursor) difficulty = 0 if act['verdict'] == "OK": status = 1 else: status = 0 if check == (): sql = "INSERT INTO activity (handle, pid, attempt_count, status, difficulty, created_at) VALUES ( \'" + handle + "\', \'cfs" + str(act['problem']['contestId']) + str(act['problem']['index']) + "\', '1', " + str(status) + ", " + str(difficulty) + ", " + str(act['creationTimeSeconds']) +" )" db.write(sql, cursor, conn) p = problem("cfs" + str(act['problem']['contestId']) + str(act['problem']['index'])) if p.exists_in_db != -1: tag_data = p.tag for tag in tag_data: sql = "SELECT tag FROM user_tag_score WHERE tag = \'" + tag + "\' AND handle = \'" + handle + "\'" tag_check = db.read(sql, cursor) if tag_check == (): sql = "INSERT INTO user_tag_score (handle, tag, score) VALUES ( \'" + handle + "\' , \'" + tag + "\' , " + str(tag_data[tag]) + " )" db.write(sql, cursor, conn) else: sql = "UPDATE user_tag_score SET score = score + " + str(tag_data[tag]) + " WHERE tag = \'" + tag + "\' AND handle = \'" + handle + "\'" db.write(sql, cursor, conn) else: sql = "UPDATE activity SET attempt_count = attempt_count + 1, status = " + str(status) + ", difficulty = " + str(difficulty) + ", created_at = " + str(act['creationTimeSeconds']) + " WHERE pid = \'cfs" + str(act['problem']['contestId']) + str(act['problem']['index']) + "\' AND handle = \'" + handle + "\'" db.write(sql, cursor, conn)
def rank_erdos_users(self): ''' | Rank erdos users based on the sum of difficulty of problems solved by them ''' score = {} for user in self.difficulty_matrix: if( user[:3] == "erd" ): score[user] = 0 #print user + ": " for prob in self.difficulty_matrix[user]: p = problem(prob) if p.exists_in_db != -1: score[user] += p.difficulty #p.print_info() #print "\n" return sorted(score.items(), key=operator.itemgetter(1), reverse = 1)
def __init__(self, sub_id, cfg, cursor): self.cfg = cfg self.cursor = cursor self.id = sub_id self.cursor.execute('SELECT * FROM `submissions` WHERE id=%s', (self.id, )) datas = self.cursor.fetchone() self.problem = problem(datas['problem_id'], self.cfg) datadir = Path(self.cfg.get('oj', 'datadir')) self.path = datadir / 'submissions' / str(self.id) self.cursor.execute('SELECT * FROM `langs` WHERE id=%s', (datas['lang_id'], )) self.lang = self.cursor.fetchone() self.sandbox_enabled = self.cfg.getboolean('sandbox', 'enabled') self.compile_required = self.lang['compile'] is not None source_dir = '/' if self.sandbox_enabled else str(self.path) if (self.compile_required): self.compilecmd = self.lang['compile'].replace( '{path}', source_dir).split()
import testfuncs_semenkina as tfunc from SR_Population import SR_Population from SR_animate import SR_animate import numpy as np if __name__ == '__main__': #gp = GeneticProgramming(objective_function=objective_function,variables=variables) #test = tests.Test(runs=4) dims = [1] #allfuncnames = tfunc.funcnames_minus() #allfuncs = [problem(func) for func in tfunc.allfuncs_minus()] allfuncs = [problem(func, 1) for func in tfunc.getfuncs(names="I1")] allfuncs *= len(dims) params = [["dynamic", True, "rank", "standard", "weak"], ["standard", True, "rank", "standard", "weak"]] # t1=time.time() # test.gp_start_parallel_by_runs(allfuncs,params) # print(time.time()-t1) gp = genalgorithm.GeneticAlgorithm(algorithm="gp", class_population=SR_Population, objective_function=allfuncs[0], variables=allfuncs[0].variables, selfconfiguration=True, scheme="dynamic", size_of_population=200, iterations=100, max_depth=10,
M = 3 P = 3 tstart = 0.0 tend = 2.25 nsteps = [4, 6, 8, 10, 12, 14, 16, 18, 20] K_iter = [1, 2, 3] err = np.zeros((np.size(K_iter),np.size(nsteps))) order = np.zeros((np.size(K_iter),np.size(nsteps))) err_ros = np.zeros(np.size(nsteps)) fs = 8 lambda_1 = -0.1 lambda_2 = -1.0 prob = problem(lambda_1, lambda_2) for kk in range(np.size(K_iter)): order_p = np.min([K_iter[kk], 2*M-1, 2*P-1]) for ll in range(np.size(nsteps)): dt = (tend - tstart)/float(nsteps[ll]) u0 = 2.0 u0_ros = u0 u_ex = u0*np.exp(tend*(lambda_1+lambda_2)) for n in range(nsteps[ll]): t_n = float(n)*dt t_np1 = float(n+1)*dt
#print(a.is_overlapped(b,0,3,0,2)) #piece.mergeデバッグ #import piece #a=piece.piece(numpy.array([[0,0],[10,0],[10,10],[0,10]])) #b=piece.piece(numpy.array([[0,0],[10,0],[10,10],[0,10]])) #print(a.merge(b,1,2,0,3).vertexes) #piece.is_mergeデバッグ #import piece #a=piece.piece(numpy.array([[0,0],[10,0],[10,10],[0,10]])) #b=piece.piece(numpy.array([[0,0],[10,0],[10,10],[0,10]])) #print(a.is_merge(b,1,2,0,3)) import QR root_problem=problem.problem(*QR.read_QR()) gui=GUI.GUI(root_problem) root_problem.gui_api=gui #GUIデバッグ #import copy #root_problem.merge_history.append((copy.deepcopy(root_problem.frame),root_problem.pieces[0],0,1,0,1)) #root_problem.frame.vertexes[0]=numpy.array([5,5]) #root_problem.pieces.pop(0) #root_problem.merge_history.append((copy.deepcopy(root_problem.frame),root_problem.pieces[0],0,1,0,1)) #gui.draw_history(root_problem) def search(): root_problem.dfs_corner([(root_problem.frame,[])],[],0)
sql = "CREATE table IF NOT EXISTS problem_reco_new LIKE problem_reco" db.write(sql, remote_cursor, remote_conn) sql = "SELECT pid FROM problem WHERE MID(pid, 1, 3)='erd' " problem_result = db.read(sql, cursor) count = 0 sql = "INSERT INTO problem_reco_new (uid, base_pid, status, reco_pid, score, time_created, time_updated, state, is_deleted) VALUES " for i in problem_result: pid = str(i[0]) a = problem(pid=pid, erd_problem_difficulty=erd_problem_difficulty, conn=conn, cfs_max_score=cfs_max_score, lower_threshold=lower_threshold, upper_threshold=upper_threshold, number_to_recommend=number_to_recommend, batchmode=1) for j in user_result: #erdos recommendations sql += a.find_similar_erdos(uid=str(j[0]), user_difficulty=float(j[1])) count += 1 # print count if (count % 20000 == 0): sql = sql[:-2] if (sql[-1] == ')'): db.write(sql, remote_cursor, remote_conn) sql = "INSERT INTO problem_reco_new (uid, base_pid, status, reco_pid, score, time_created, time_updated, state, is_deleted) VALUES " print count, " insertions done"
# np.random.seed() theta_1 = 1 * np.random.randn(size, dim) #------------------------------------------------------------------------------- #------------------------------------------------------------------------------- # constrianed, my modification to my step_size step_size4 = 0.05 rho4 = 0.05 alpha4 = 0.5 mu4 = 1.0 # DDPS p --> decaying power, eps: parameter eps = 0.05 p = 0.5 #------------------------------------------------------------------------------- #------------------------------------------------------------------------------- lr_1 = problem(size, AA, bb, CC, ee) error_lr_1 = error(lr_1, np.zeros(size), 0) #------------------------------------------------------------------------------- #------------------------------------------------------------------------------- pseudo_adj = Random(size, Edge_prob).directed() ZR, ZC, RS, CS = graph_matrices(pseudo_adj, size, LDF) graph_check(pseudo_adj, size) # Introduce assertion #------------------------------------------------------------------------------- #------------------------------------------------------------------------------- theta_ddps = dopt.DDPS(lr_1, RS, CS, p, int(depoch), theta_1, eps) res_F_ddps = error_lr_1.cost_gap_path(np.sum(theta_ddps, axis=1) / size) fesgp_ddps = error_lr_1.feasibility_gap(np.sum(theta_ddps, axis=1) / size) theta_DAGP = dopt.ADDOPT(lr_1, ZR, ZC, step_size4, int(depoch), theta_1) res_F_DAGP = error_lr_1.cost_path(np.sum(theta_DAGP, axis=1) / size) fesgp_DAGP = error_lr_1.feasibility_gap(np.sum(theta_DAGP, axis=1) / size)
from problem import problem from sdc import sdc_step import numpy as np import copy M = 5 P = 4 tstart = 0.0 tend = 10.0 nsteps = 4 dt = (tend - tstart) / float(nsteps) lambda_1 = -0.1 lambda_2 = -1.0 prob = problem(lambda_1, lambda_2) K_iter = 12 u_ = np.zeros((M, 1, 1)) usub_ = np.zeros((M, P, 1)) u = np.zeros((M, 1, 1)) usub = np.zeros((M, P, 1)) u0 = 2.0 u_ex = u0 * np.exp(tend * (lambda_1 + lambda_2)) for n in range(nsteps): tstart = float(n) * dt tend = float(n + 1) * dt sdc = sdc_step(M, P, tstart, tend, prob) # reset buffers to zero u = np.zeros((M, 1, 1))
sql = "UPDATE problem_reco SET is_deleted = 1" db.write(sql, cursor, conn) sql = "CREATE table IF NOT EXISTS problem_reco_new LIKE problem_reco" db.write(sql, remote_cursor, remote_conn) sql = "SELECT pid FROM problem WHERE MID(pid, 1, 3)='erd' " problem_result = db.read(sql, cursor) count = 0 sql = "INSERT INTO problem_reco_new (uid, base_pid, status, reco_pid, score, time_created, time_updated, state, is_deleted) VALUES " for i in problem_result: pid = str(i[0]) a = problem(pid = pid, erd_problem_difficulty = erd_problem_difficulty, conn = conn, cfs_max_score = cfs_max_score, lower_threshold = lower_threshold, upper_threshold = upper_threshold, number_to_recommend = number_to_recommend, batchmode = 1) for j in user_result: #erdos recommendations sql+=a.find_similar_erdos(uid = str(j[0]), user_difficulty = float(j[1])) count+=1 # print count if(count%20000 == 0): sql = sql[:-2] if(sql[-1] == ')'): db.write(sql, remote_cursor, remote_conn) sql = "INSERT INTO problem_reco_new (uid, base_pid, status, reco_pid, score, time_created, time_updated, state, is_deleted) VALUES " print count," insertions done" if(sql[-1] == ')'):
P = 4 tstart = 0.0 tend = 1.0 lambda_1 = np.linspace(-1.0, 0.0, 25) lambda_2 = np.linspace(-5.0, 0.0, 20) err = np.zeros((np.size(lambda_1), np.size(lambda_2))) K_iter = 4 u0 = 2.0 for kk in range(np.size(lambda_1)): for ll in range(np.size(lambda_2)): prob = problem(lambda_1[kk], lambda_2[ll]) sdc = sdc_step(M, P, 0.0, 1.0, prob) u_ex = u0 * np.exp((lambda_1[kk] + lambda_2[ll])) # reset buffers to zero u = np.zeros((M, 1)) usub = np.zeros((M, P)) fu = np.zeros((M, prob.dim)) fu_sub = np.zeros((M, P, prob.dim)) sdc.predict(u0, u, usub, fu, fu_sub) for k in range(K_iter): sdc.sweep(u0, u, usub, fu, fu_sub) err[kk, ll] = abs(u[M - 1] - u_ex) / abs(u_ex)
import mapreader import solver import problem import sys from matplotlib import pyplot as plt import numpy as np mapfile = open(sys.argv[1]) reader = mapreader.mapreader(mapfile) mapvals = reader.read() prob = problem.problem(mapvals) prob.setSrc(0, 0) prob.setDst(len(mapvals)-1, len(mapvals[0])-1) oracle = solver.OracleSolver(prob) cost, path = oracle.search() plt.pcolormesh(np.array(mapvals)) for i in range(len(path)-1): x1,y1 = path[i+1] x2,y2 = path[i] plt.plot([x1,x2], [y1,y2], 'k-', lw=5) plt.savefig('test.png') for visibility in [5,10,20,50,100,200,500,1000,2000]: baseline = solver.BaselineSolver(prob, visibility)
P = 4 tstart = 0.0 tend = 1.0 lambda_1 = np.linspace(-1.0, 0.0, 25) lambda_2 = np.linspace(-5.0, 0.0, 20) err = np.zeros((np.size(lambda_1), np.size(lambda_2))) K_iter = 4 u0 = 2.0 for kk in range(np.size(lambda_1)): for ll in range(np.size(lambda_2)): prob = problem(lambda_1[kk], lambda_2[ll]) sdc = sdc_step(M, P, 0.0, 1.0, prob) u_ex = u0*np.exp((lambda_1[kk]+lambda_2[ll])) # reset buffers to zero u = np.zeros((M,1)) usub = np.zeros((M,P)) fu = np.zeros((M,prob.dim)) fu_sub = np.zeros((M,P,prob.dim)) sdc.predict(u0, u, usub, fu, fu_sub) for k in range(K_iter): sdc.sweep(u0, u, usub, fu, fu_sub) err[kk,ll] = abs(u[M-1] - u_ex)/abs(u_ex)
def make_problem(shape=gm.ushape, mu=1.5): prob = problem(gm.compose_track(shape)) prob.set_mu( mu, 1.2).set_top_speed().set_acc_and_brake_factors().set_road_width() prob.set_nominal_speed() return prob