def modelprediction(obj,x0,W,U,*varargin): # extract optimal control input traj for x[0]=x0 x=nan*random.random((obj.Np+1,1)) UTR=nan*random.random((obj.Np,1)) phik=nan*random.random((obj.Np,1)) x[0]=x0; T=arange(0,obj.Np+1,1) for k in range(obj.Np): wk=W[k,:].T UTR[k]=U[k]; ##<< the only difference x[k+1]=obj.f(x[k],UTR[k],wk) phik[k]=obj.phi(x[k],UTR[k],wk) if len(varargin) is not 0: figure(2) subplot(211) plot(T,x,'o-');grid(True); title('MPCthink') subplot(212) pp.step(T[:-1],kW2ton(UTR),'-o',where='post');#ylim([-1,1.5]) grid(True) figure(3) subplot(211) plot(T[:-1],hstack((kW2ton(H_iscolumn(W[:,0])),kW2ton(UTR))),'-o') legend(['QBL','QDIS']) title('MPCthink') print(phik.shape) subplot(212) plot(T[:-1],hstack((H_iscolumn(W[:,2]),H_iscolumn(W[:,3]),phik)),'-o') legend(['Pnonhvac','Psolar','phik $']) #print(phik.sum()) return x, phik
def testlivePlot(): a = livePlot(getData()) figure(figsize=(7, 7 / 2)) for k in range(100): a.data = getData() drawnow(a.draw, stop_on_close=True)
def controller(obj, x0, W, *varargin): # solve Bellman equation (Vok, Uok) = obj.BellmanEq(W) # extract optimal control input traj for x[0]=x0 x = nan * random.random((obj.Np + 1, obj.n)) UTR = nan * random.random((obj.Np, obj.m)) phik = nan * random.random((obj.Np, 1)) QCHL = nan * random.random((obj.Np, 1)) x[0, :] = x0.T T = arange(0, obj.Np + 1, 1) for k in range(obj.Np): wk = W[k, :].T for j in range(obj.m): Uoptfuncofx = RegularGridInterpolator(obj.ix_grid, Uok[j][k], bounds_error=False) UTR[k, j] = Uoptfuncofx(obj.xcut(mat(x[k, :]).T)) x[k + 1, :] = obj.f(mat(x[k, :]).T, mat(UTR[k, :]).T, wk).T phik[k] = obj.phi(mat(x[k, :]).T, mat(UTR[k, :]).T, wk) QCHL[k] = obj.Transform(mat(x[k, :]).T, mat(UTR[k, :]).T, wk) if len(varargin) is not 0: figure(2) subplot(211) plot(T, x[:, 0], 'o-') grid(True) ylabel('state of charge [%]') title('MPCthink') subplot(212) pp.step(T[:-1], kgs2gpm(UTR[:, 1]), '-o', where='post') #ylim([-1,1.5]) ylabel('optimal gpm') grid(True) figure(3) subplot(211) plot(T[:-1], hstack((kW2ton(H_iscolumn(W[:, 0])), kW2ton(QCHL))), '-o') legend(['QBL', 'QCHL']) ylabel('ton') title('MPCthink') grid(True) print phik.shape subplot(212) plot(T[:-1], hstack((H_iscolumn(QCHL / obj.COP), H_iscolumn(W[:, 3]))), '-o') legend(['P_{HVAC}', 'P_{solar}']) ylabel('kW') xlabel('hour') grid(True) print phik.sum() return UTR, phik.sum()
def VAE_trainer(loader_mix, train_loader, generator, EP = 5, **kwargs): arguments = kwargs['arguments'] criterion = kwargs['criterion'] conditional_gen = kwargs['conditional_gen'] generator.train() L1 = generator.L1 L2 = generator.L2 K = generator.K if arguments.optimizer == 'Adam': optimizerG = optim.Adam(generator.parameters(), lr=arguments.lr, betas=(0.9, 0.999)) elif arguments.optimizer == 'RMSprop': optimizerG = optim.RMSprop(generator.parameters(), lr=arguments.lr) if not arguments.cuda and arguments.plot_training: figure(figsize=(4,4)) true, false = 1, 0 for ep in range(EP): for (ft, tar, lens), mix in zip(train_loader, loader_mix): if arguments.cuda: tar = tar.cuda() ft = ft.cuda() lens = lens.cuda() # sort the tensors within batch if arguments.task == 'images': tar = tar.contiguous().view(-1, arguments.L2) tar, ft = Variable(tar), Variable(ft) else: ft, tar = ut.sort_pack_tensors(ft, tar, lens) tar = Variable(tar[0]) #if conditional_gen: # inp = mix.contiguous().view(-1, L) #else: # inp = ft_rshape # fixed_noise.contiguous().view(-1, L) # generator gradient generator.zero_grad() out_g, mu, logvar = generator.forward(ft) err_G = criterion(out_g, tar, mu, logvar) err_G.backward() # step optimizerG.step() print(err_G) print(ep)
def analysis(obj): times=np.unique(obj.PRED['cur_t'].values) for t in times: ydf=obj.PRED[obj.PRED['cur_t']==t] hr=(t+arange(0,ydf.shape[0])*obj.Ts*1.)/3600 print(t, hr.size) figure(10) subplot(311) plot(hr,ydf['Uop']);grid(True);title('Uop') subplot(312) plot(hr,ydf['x']);grid(True);title('x') subplot(313) plot(hr,ydf['phi']);grid(True);title('phi')
def capture(): cap_1 = cv2.VideoCapture(int(sys.argv[1])) cap_2 = cv2.VideoCapture(int(sys.argv[2])) cap_3 = cv2.VideoCapture(int(sys.argv[3])) time = 0 count_time = 0 fig = figure() def draw(): plt.plot(range(100),ave_gaze[1,:]) while True: frame_got_1, frame_1 = cap_1.read() frame_got_2, frame_2 = cap_2.read() frame_got_3, frame_3 = cap_3.read() if frame_got_1 is False: break else: f_1 = cv2.flip(frame_1, 2) f_2 = cv2.flip(frame_2, 2) f_3 = cv2.flip(frame_3, 2) g_1 = cv2.cvtColor(f_1, cv2.COLOR_BGR2GRAY) g_2 = cv2.cvtColor(f_2, cv2.COLOR_BGR2GRAY) g_3 = cv2.cvtColor(f_3, cv2.COLOR_BGR2GRAY) r_1 = cv2.resize(g_1,(width,height)) r_2 = cv2.resize(g_2,(width,height)) r_3 = cv2.resize(g_3,(width,height)) a_1 = np.array(r_1,dtype=np.uint8) a_2 = np.array(r_2,dtype=np.uint8) a_3 = np.array(r_3,dtype=np.uint8) frame = np.hstack((g_1,g_2,g_3)) count_time = count_time + 1 name = "./pic/test7"+str(datetime.datetime.now()) + "-cap.png" print name #cv2.imwrite(name,frame) #print datetime.datetime.today() cv2.imshow("pic",frame) if cv2.waitKey(1) == 27: break
from scipy.spatial import distance from imutils import face_utils import imutils import dlib import cv2 import matplotlib.pyplot as plt from drawnow import drawnow, figure i = 0 x = [] y = [] fig = figure() flag = 0 def eye_aspect_ratio(eye): A = distance.euclidean(eye[1], eye[5]) B = distance.euclidean(eye[2], eye[4]) C = distance.euclidean(eye[0], eye[3]) ear = (A + B) / (2.0 * C) return ear def draw(): plt.plot(x, y) plt.title("The relationship between EAR and the time") plt.xlabel("time") plt.ylabel("EAR") thresh = 0.25
dy[2] = y[3] dy[3] = (1 / D) * ((m + M) * m * g * L * Sy - m * L * Cy * (m * L * y[3]**2 * Sy - d * y[1])) - m * L * Cy * ( 1 / D) * u + .01 * np.random.randn() return dy # From here, sim_cartpend.m m = 1 M = 5 L = 2 g = -10 d = 1 tspan = np.arange(0, 10, 0.1) y0 = [0, 0, np.pi, .5] # t0 of [0, 15] is an arbitrary one. # It can be any tuple whose width is greater than range(10) sol = solve_ivp(cartpend, [0, 15], y0, t_eval=tspan, args=(m, M, L, g, d, 0)) y = sol.y.T # Iteratively drawing to make it look like an animation figure() for i in range(100): drawcartpend(y[i, ], m, M, L) plt.pause(0.01) plt.clf()
is_infected = True # Mit einer gewählten Wahrscheinlichkeit ist die Person infiziert. if temp < params.superspreader: is_superspread = True # Mit einer gewählten Wahrscheinlichkeit ist die Person superspreader. new_person = Person( is_isolated, is_infected, is_immune, is_heavy, is_infected, is_superspread ) #Erstellen eines Objekts Person mit den oben genannten Eigenschaften params.end_dist['Age'][i] = new_person.age new_person.ps = new_person.ps.move( new_person.left * 10, new_person.top * 10) # Setzen der Personen auf das Spielfeld population.append(new_person) people_infected[0] = params.infected / params.popsize start = timer() figure() #erstellt das Figure aus der drawnow-Bibliothek für Liveplot # Creating the Simulation while sim_continue(population): count += 1 #Abfrage der GUI und auslösen von Events #params.isolation ist während des Programms über die Pfeiltasten rechts und links steuerbar. for event in pygame.event.get(): # check if Pause button is pressed clickPauseEvent(event, population) if event.type == KEYDOWN and event.key == K_RIGHT: for people in population:
from __future__ import division from pylab import * from drawnow import drawnow, figure from time import sleep def draw_fig(): #figure() # don't call figure or show each time! imshow(x, interpolation='nearest') title('Iteration %d' % i) #show() N = 10 seed(41) figure(figsize=(4, 4)) x = eye(N) * 1 + randn(N,N) / 40 for i in arange(N): r = rand()*(1-0.3) + 0.3 x[i, i-5] += r drawnow(draw_fig, confirm=False, show_once=False) sleep(0.1)
def run_test(self, testname, param=None, filename=None, display='pbar', timeunit='s'): """Runs the test with specified test name and returns the time, voltage and current data. """ self.stop_test() mux_enabled = False channel_list = [0] # try/except to handle lack of mux implementation for ECL device (GVR) #if self.firmware_version >= MinimumFirmwareVersionForMux: # mux_enabled = self.get_mux_enabled() mux_enabled = False if mux_enabled: channel_list = self.get_enabled_mux_channels() if timeunit not in TimeUnitToScale: raise RuntimeError('uknown timeunit option {0}'.format(timeunit)) if display not in (None, 'pbar', 'data', 'plot'): raise RuntimeError('uknown display option {0}'.format(display)) if param is not None: self.set_param(testname, param) if display in ('pbar', 'data'): #print('\ntest: {0}'.format(testname)) display_print = True else: display_print = False if display == 'pbar': test_done_tval = self.get_test_done_time(testname, timeunit=timeunit) widgets = [progressbar.Percentage(), progressbar.Bar()] pbar = progressbar.ProgressBar(widgets=widgets, maxval=test_done_tval) pbar.start() data_dict = { chan: { TimeKey: [], VoltKey: [], CurrKey: [], PhotoCurrKey: [] } for chan in channel_list } # added PhotoCurr if display == 'plot': # added GVR plotActive = livePlot(data_dict) figure(figsize=(7, 7 / 2)) # Determine output file type and open if required if filename is not None: filename_base, filename_ext = os.path.splitext(filename) if filename_ext == '.pkl': output_filetype = PklOutputFileType else: output_filetype = TxtOutputFileType fid = open(filename, 'w') # write parameters to file as header (added GVR) if (filename is not None) and (output_filetype == TxtOutputFileType): param['Test'] = testname #param['Date'] = datetime.today().strftime('%Y-%m-%d') fid.write(json.dumps(param) + '\n') # Start voltammetric test cmd_dict = {CommandKey: RunTestCmd, TestKey: testname} msg_dict = self.send_cmd(cmd_dict) self.test_running = True print('Estimated time for test: ', format(self.testDuration)) done = False samples = 0 endPattern = re.compile( "EndOfTest" ) # DE 15.3 GVR todo: modify to avoid exceptional handling of endoftest while not done: if self.RawMode: v = self.readline() if endPattern.search(str(v)): print("End of Test") sample_dict = {} else: vals = [float(i) for i in v.split()] # in raw mode we expect 2 or 3 floats in order determined they are listed in self.measure sample_dict = dict.fromkeys( self.measure) # initialise dictionary w try: for key in self.measure: sample_dict[key] = vals.pop(0) except: sample_dict = {} samples += 1 if self.debug: print("Sample dictionary: ", sample_dict) else: sample_json = self.readline() sample_json = sample_json.strip() sample_dict = json.loads(sample_json.decode()) if len(sample_dict) > 0: chan = 0 # Dummy channel used when mux isn't running if mux_enabled: chan = sample_dict[ChanKey] tval = sample_dict[TimeKey] * TimeUnitToScale[timeunit] data_dict[chan][TimeKey].append(tval) try: volt = sample_dict[VoltKey] except: volt = None else: data_dict[chan][VoltKey].append(volt) try: curr = sample_dict[CurrKey] except: curr = None else: data_dict[chan][CurrKey].append(curr) try: phot = sample_dict[PhotoCurrKey] except: phot = None else: data_dict[chan][PhotoCurrKey].append(phot) #for k,v in [(TimeKey,tval),(VoltKey,volt),(CurrKey,curr),(PhotoCurrKey,phot)]: # data_dict[chan][k].append(v) # Write data to file if (filename is not None) and (output_filetype == TxtOutputFileType): if chan == 0: #fid.write('{0:1.3f}, {1:1.4f}, {2:1.4f}\n'.format(tval,volt,curr)) fid.write('{},{},{},{}\n'.format( tval, volt, curr, phot)) else: fid.write( '{0}, {1:1.3E}, {2:1.4E}, {3:1.4E}, {3:1.4E}\n'. format(chan, tval, volt, curr, phot)) # Handle diplay options if display == 'data': if chan == 0: fmt = PartialFormatter(bad=' ~', missing=' !') data = { 't': tval, 'prog': int(100 * tval / self.testDuration), 'v': volt, 'i': curr, 'l': phot } print(fmt.format( 'Time: {t:1.3f} s ({prog:03d}%) Potential: {v:+1.4f} V, Current: {i:+1.4f} A, Photocurrent: {l:1.4f}', **data), end="\r", flush=True) else: print( 'ch{0}: {1:1.3f}, {2:+1.4f}, {3:+1.4f}, {3:1.4f}'. format(chan, tval, volt, curr, phot), end="\r", flush=True) else: #display minimal progress information: print('Sample: {} of {}'.format(samples, self.testLength), end="\r") if display == 'plot': plotActive.data = data_dict # need to append not replace! drawnow(plotActive.draw, stop_on_close=True) # if chan == 0: # y_vec.append(sample_dict[self.measure[2]]) # x_vec.append(sample_dict[self.measure[0]]) # #line1 = live_plotter(x_vec,y_vec,line1,identifier='',ylabel=self.measure[2],xlabel=self.measure[0]) # else: # pass # case not implemented elif display == 'pbar': pbar.update(tval) else: done = True self.test_running = False if display_print: print() print() if filename is not None: if output_filetype == PklOutputFileType: with open(filename, 'w') as fid: if mux_enabled: cPickle.dump(data_dict, fid) else: cPickle.dump(data_dict[0], fid) else: fid.close() print('Data written to file: {}'.format(filename)) if mux_enabled: out = data_dict else: #return data_dict[0][TimeKey], data_dict[0][VoltKey], data_dict[0][CurrKey] #return data_dict[0][TimeKey], data_dict[0][VoltKey], data_dict[0][CurrKey], data_dict[0][PhotoCurrKey] out = data_dict[0] self.flush( ) # included in attempt to fix communication error after experiment return out
from __future__ import division from pylab import * from drawnow import drawnow, figure from time import sleep def draw_fig(): #figure() # don't call figure or show each time! imshow(x, interpolation='nearest') title('Iteration %d' % i) #show() N = 10 seed(41) figure(figsize=(4, 4)) x = eye(N) * 1 + randn(N, N) / 40 for i in arange(N): r = rand() * (1 - 0.3) + 0.3 x[i, i - 5] += r drawnow(draw_fig, confirm=False, show_once=False) sleep(0.1)
def maxlikelihood_separatesources(generators, loader_mix, EP, **kwargs): generator1, generator2 = generators arguments = kwargs['arguments'] loss = kwargs['loss'] L1 = generator1.L1 L2 = generator1.L2 x1hat, x2hat = [], [] mixes = [] for i, (mix, _ ) in enumerate(islice(loader_mix, 0, 1, 1)): if arguments.cuda: mix = mix.cuda() print('Processing source ',i) Nmix = mix.size(0) if arguments.cuda: x1 = Variable(torch.rand(Nmix, L1).cuda(), requires_grad=True) x2 = Variable(torch.rand(Nmix, L1).cuda(), requires_grad=True) else: x1 = Variable(torch.rand(Nmix, L1), requires_grad=True) x2 = Variable(torch.rand(Nmix, L1), requires_grad=True) optimizer_sourcesep = optim.Adam([x1, x2], lr=1e-3, betas=(0.5, 0.999)) for ep in range(EP): mix_sum = generator1.forward(x1) + generator2.forward(x2) if loss == 'Euclidean': err = torch.mean((Variable(mix) - mix_sum)**2) elif loss == 'Poisson': eps = 1e-20 err = torch.mean(-Variable(mix)*torch.log(mix_sum+eps) + mix_sum) err.backward() optimizer_sourcesep.step() x1.grad.data.zero_() x2.grad.data.zero_() print('Step in batch [{:d}\{:d}]'.format(ep+1, EP)) print('The error is ', err) x1hat.append(generator1.forward(x1).data.cpu().numpy()) x2hat.append(generator2.forward(x2).data.cpu().numpy()) mixes.append(mix.cpu().numpy()) print('sum is:', x1hat[0].sum()) num_ims, c = 30, 2 figure(num=None, figsize=(3*c, num_ims*c), dpi=80, facecolor='w', edgecolor='k') sqrtL2 = int(np.sqrt(L2)) for i in range(num_ims): plt.subplot(num_ims, 3, 3*i + 1) plt.imshow(x1hat[0][i].reshape(sqrtL2, sqrtL2)) plt.title('Estimated Source 1') plt.subplot(num_ims, 3, 3*i + 2) plt.imshow(x2hat[0][i].reshape(sqrtL2, sqrtL2)) plt.title('Estimated Source 2') plt.subplot(num_ims, 3, 3*i + 3) plt.imshow(mixes[0][i].reshape(sqrtL2, sqrtL2)) plt.title('Mixture') curdir = os.getcwd() figdir = os.path.join(curdir, 'figures') if not os.path.exists(figdir): os.mkdir(figdir) figname = '_'.join([kwargs['data'], kwargs['tr_method'], 'conditional', str(kwargs['conditional']), 'smooth_output', str(kwargs['arguments'].smooth_output), 'sourceseparation']) plt.savefig(os.path.join(figdir, figname))
def generative_trainer(loader_mix, train_loader, generator, EP = 5, **kwargs): arguments = kwargs['arguments'] criterion = kwargs['criterion'] conditional_gen = kwargs['conditional_gen'] L1 = generator.L1 L2 = generator.L2 K = generator.K def drawgendata(): I = 1 N = 3 if arguments.task == 'mnist' else 2 for i in range(I): plt.subplot(N, I, i+1) plt.imshow(out_g[i].view(arguments.nfts, arguments.T).data.numpy()) plt.subplot(N, I, I+i+1) plt.imshow(tar[i].view(arguments.nfts, arguments.T).numpy()) if arguments.task == 'mnist': plt.subplot(N, I, 2*I+i+1) plt.imshow(ft[i].view(arguments.nfts, arguments.T).numpy()) def drawgendata_atomic(): I = 1 N = 5 genspec = out_g.data.numpy().transpose()[:, :200] target = tar.data.numpy().transpose()[:, :200] feat = ft[0].numpy().transpose()[:, :200] #genspec = out_g[].data.numpy().transpose() #target = tar.permute(0,2,1).contiguous().view(-1, L2).numpy().transpose() for i in range(I): plt.subplot(N, I, i+1) plt.imshow(genspec) plt.subplot(N, I, I+i+1) plt.imshow(target) plt.subplot(N, I, I+i+2) lrd.specshow(genspec, y_axis='log', x_axis='time') plt.subplot(N, I, I+i+3) lrd.specshow(target, y_axis='log', x_axis='time') plt.subplot(N, I, I+i+4) lrd.specshow(feat, y_axis='log', x_axis='time') if arguments.optimizer == 'Adam': optimizerG = optim.Adam(generator.parameters(), lr=arguments.lr, betas=(0.9, 0.999)) elif arguments.optimizer == 'RMSprop': optimizerG = optim.RMSprop(generator.parameters(), lr=arguments.lr) if not arguments.cuda and arguments.plot_training: figure(figsize=(4,4)) true, false = 1, 0 for ep in range(EP): for (ft, tar, lens), mix in zip(train_loader, loader_mix): if arguments.cuda: tar = tar.cuda() ft = ft.cuda() lens = lens.cuda() # sort the tensors within batch if arguments.task == 'images': tar = tar.contiguous().view(-1, arguments.L2) tar, ft = Variable(tar), Variable(ft) else: ft, tar = ut.sort_pack_tensors(ft, tar, lens) tar = Variable(tar[0]) #if conditional_gen: # inp = mix.contiguous().view(-1, L) #else: # inp = ft_rshape # fixed_noise.contiguous().view(-1, L) # generator gradient generator.zero_grad() out_g = generator.forward(ft) err_G = criterion(out_g, tar) err_G.backward() # show the current generated output if not arguments.cuda: if arguments.task == 'atomic_sourcesep': drawnow(drawgendata_atomic) else: drawnow(drawgendata) optimizerG.step() print(err_G) print(ep)
plt.title('Gradient descent methods visualized') plt.title('Objective function') plt.xlabel('x') plt.ylabel('Cost') if initial: plt.savefig('objective_function.png') plt.show() def grad_descent(x_k, tau): return x_k - tau * num_eval(grad(f), x_k) def ball_acceleration(x, c): t = x[0] x[0] = x[0] - c[0]*num_eval(grad(f), x[0]) + c[1]*(x[0] - x[1]) x[1] = t return x x_ball = [2, 2] x_grad = 2 tau = 0.02 drawnow.figure(figsize=(7, 7)) drawnow.drawnow(plot_descent, confirm=False, initial=True) for k in range(40): #weight = 1 - 2 / (k+2) #weight *= 1.05 weight = 0.8 x_ball = ball_acceleration(x_ball, [tau, weight]) x_grad = grad_descent(x_grad, tau) drawnow.drawnow(plot_descent, confirm=False) time.sleep(0.01)
def controller(obj,x0,W,*varargin): # solve Bellman equation #print("Np:",obj.Np, "W:", W.shape) (Vok,Uok)=obj.BellmanEq(W) # extract optimal control input traj for x[0]=x0 x=nan*random.random((obj.Np+1,1)) UTR=nan*random.random((obj.Np,1)) phik=nan*random.random((obj.Np,1)) x[0]=x0; T=arange(0,obj.Np+1,1) for k in range(obj.Np): wk=W[k,:].T UTR[k]=interp(x[k],obj.X,Uok[:,k]);#,right=1e10) x[k+1]=obj.f(x[k],UTR[k],wk) phik[k]=obj.phi(x[k],UTR[k],wk) if len(varargin) is not 0: if varargin: QCHL=H_iscolumn(W[:,0])-H_iscolumn(UTR) figure(2) subplot(311) if mean(W[:,3])==0: plot(T[:-1],kW2ton(QCHL),'ro-') plot(T[:-1],kW2ton(H_iscolumn(W[:,0])),'go-') legend(['QCHL$_{before}$','QBL']) else: plot(T[:-1],kW2ton(QCHL),'bo-',linewidth=2) legend(['QCHL$_{before}$','QBL','QCHL$_{after}$']) ylabel('Cooling ton') xlim([0,24]) ylim([0,3000]) grid(True) subplot(312) if mean(W[:,3])==0: plot(T[:-1],H_iscolumn(QCHL/obj.COP),'ro-') else: plot(T[:-1],H_iscolumn(QCHL/obj.COP),'bo-',linewidth=2) plot(T[:-1],H_iscolumn(W[:,3]),'go-') legend(['P$_{before}$','P$_{after}$','P$_{solar}$']) ylabel('Power [kW]') xlim([0,24]) ylim([0,2000]) grid(True) subplot(313) if mean(W[:,3])==0: plot(T,x,'ro-');grid(True); else: plot(T,x,'bo-',linewidth=2);grid(True); ylabel('State of Charge [%]') grid(True) xlabel('hour') xlim([0,24]) ylim([0.4,1]) #print(phik.sum()) return UTR, phik.sum()
for i, x_hat in enumerate([x_ball, x_grad]): circle = plt.Circle((x_hat, f(x_hat)), RADIUS, color=colors[i]) plt.gcf().gca().add_artist(circle) handles = [mpatches.Patch(color=c, label=l) for c, l in zip(colors, labels)] plt.legend(loc='best', handles=handles) def ball_acceleration(x, f_p1, c=[0.1, 0.1]): f_p = f_prime(x) return x - c[0]*(c[1]*f_p1 + f_p*(1-c[1])), f_p def grad_descent(x, tau=0.1): return x - tau*f_prime(x) N = 1e3 x = np.linspace(-1.5, 2, num=N) y = f(x) x_ball = 2.0 x_grad = 2.0 tau, f_p1 = 0.15, 0 drawnow.figure(figsize=(5, 5)) drawnow.drawnow(animate_plot) for i in range(int(2e1)): x_ball, f_p1 = ball_acceleration(x_ball, f_p1, c=[tau, 0.86]) x_grad = grad_descent(x_grad, tau=tau) print(x_ball, x_grad) drawnow.drawnow(animate_plot) #time.sleep(0.1)
var = STREAM_ID[key] # sensor_data[var] = [float(x) for x in dat[i+1:i+4]] sensor_data[var[0]] = list(map(float, dat[3:(3 + var[1])])) return sensor_data UDP_IP = "192.168.0.122" UDP_PORT = 5555 sock = socket.socket( socket.AF_INET, # Internet socket.SOCK_DGRAM) # UDP sock.bind((UDP_IP, UDP_PORT)) figure(figsize=(7, 7 / 2)) fig = plt.gcf() # x=[] # t=[] xx = yy = zz = 0 def draw_fig(): ax = fig.add_subplot(111, projection='3d') # ax.set_xlim(-100,100) # ax.set_ylim(-100,100) # ax.set_zlim(-100,100) ax.set_xlim(-1, 1) ax.set_ylim(-1, 1)
#p4 plt.subplot(grid[1, 3]) plt.plot(board.players[3].cash_history, "k--") plt.plot(board.players[3].net_asset_history, "b") plt.title("Player 4 assets (net and cash)") # Initialize players p1 = Player(1, board, RandBot) p2 = Player(2, board, FrugalBot) p3 = Player(3, board, LeftBot) p4 = Player(4, board, BrandBot) board.players.extend([p1, p2, p3, p4]) drawnow.figure(figsize=(13, 5)) # Play the game! while not board.gameCompleted: for player in board.players: ## Play tile possible_tiles = player.getValidPlays() # TODO: Provide tile replacement for dead tiles if len(possible_tiles) >= 1: ### INSERT AI CHOICE HERE: Which tile to play ### chosen_play = player.ai.choosePlayTile(possible_tiles) player.tiles.remove(chosen_play) board.playTile(player, chosen_play)