def generate(): global count, defender, attacker, x_axis, generated_values # check time if count == seconds + 1: raise a, u, y, B, G, R, V, E, H = get_random_value(count) Ud = case_3_get_pay_off_defender(a, u, y, B, G, R, V, E, H) Ua = case_3_get_pay_off_attacker(a, u, y, B, G, R, V, E, H) if check_constraint(count, a, u, y, B, G, R, V, E, H): # update x axis x_axis.append(count) # update graph defender.append(Ud) attacker.append(Ua) drawnow(create_plot) generated_values = { 'a': a, 'u': u, 'y': y, 'B': B, 'G': G, 'R': R, 'V': V, 'E': E, 'H': H } count += 1
def plot(self, all_rewards, epsilon): self.all_rewards = all_rewards self.epsilon = round(epsilon, 4) try: drawnow(self.plot_rewards) except: print("Break")
def update_detection(data): global cur_pos global cur_det cur_det = data.data positions.append(cur_pos) detections.append(cur_det) drawnow(draw_cur_pos)
def plot_realtime(self): plt.ion() count = 0 while True: conta = 0 while (self.usb.inWaiting() == 0): conta += 1 if (conta > 1000): print 'Conexão falha!' break pass self.leitura = self.usb.readline() print self.leitura self.leitura = float(self.leitura) self.valor.append(self.leitura) drawnow(self.plotar_grafico) plt.pause(.00005) count += 1 if (count > 50): self.valor.pop(0) if (self.flag != 0): break pass
def visualize(self, sess, showonlysol=False, i=None, savefig=None): x = np.linspace(0, 1, self.refn) uh = sess.run(self.u, feed_dict={self.x: self.refnX}) def draw(): fig = plt.figure() if not showonlysol: plt.plot(x, self.exactsol(x), label='analytical soln') plt.plot(self.sol.t, self.sol.y[0].T, 'g-.', label='scipy solution') plt.plot(x, uh, label='soln') plt.xlabel('$time$') plt.ylabel('$y$') plt.legend() if i: # plt.title('Loss={}\nIteration {}'.format(self.rloss, i)) plt.title( 'Solutions when c=31 and k=30\nLoss={}\nIteration {}'.format(self.rloss, i)) if savefig: plt.savefig("{}/fig{}".format(savefig, 0 if i is None else i)) drawnow(draw)
def show_fig(self): if self.actual_generation % self.REDRAW_STEP == 0: self.x = self.x[-self.MAX_TO_SHOW:] self.y = self.y[-self.MAX_TO_SHOW:] self.y2 = self.y2[-self.MAX_TO_SHOW:] drawnow(self.draw_fig)
def visualize(self, sess, showonlysol=False, i=None, savefig=None): x = np.linspace(0, 1, self.refn) y = np.linspace(0, 1, self.refn) [X, Y] = np.meshgrid(x, y) uh = sess.run(self.u, feed_dict={self.x: self.refnX}) Z = uh.reshape((self.refn, self.refn)) uhref = self.exactsol(X, Y) def draw(): ax = self.fig.gca(projection='3d') if not showonlysol: ax.plot_surface(X, Y, uhref, rstride=1, cstride=1, cmap=cm.autumn, linewidth=0, antialiased=False, alpha=0.3) ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.summer, linewidth=0, antialiased=False, alpha=0.8) ax.set_xlabel('$x$') ax.set_ylabel('$y$') if i: plt.title('Loss={}\nIteration {}'.format(self.rloss, i)) if savefig: plt.savefig("{}/fig{}".format(savefig, 0 if i is None else i)) drawnow(draw)
def main(): stats = [] for i_episode in range(cfg.max_episode): state = env.reset() episode_score = 0 for t in count(): action = get_action(state) next_state, reward, done, _ = env.step([action]) episode_score += reward # env.render() target = reward + cfg.gamma * get_state_value(next_state) td_error = target - get_state_value(state) update_actor(state, action, advantage=td_error) update_critic(state, target) if done: avg_score_plot.append(avg_score_plot[-1] * 0.99 + episode_score * 0.01) last_score_plot.append(episode_score) drawnow(draw_fig) break state = next_state stats.append(episode_score) if np.mean(stats[-100:]) > 90 and len(stats) >= 101: print(np.mean(stats[-100:])) print("Solved") print("Episode: {}, reward: {}.".format(i_episode, episode_score)) return np.mean(stats[-100:])
def two_layer_drawnow_session(fignum): global errors, mse, validx, validy, result plt.ion() errors = [] plt.figure(fignum) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for i in range(NUM_EPOCHS): # start step stop # e.g. 0 100 800 starts = range(0, len(trainx), MINI_BATCH_SIZE) ends = range(MINI_BATCH_SIZE, len(trainx), MINI_BATCH_SIZE) for start, end in zip(starts, ends): sess.run( train_op_2, feed_dict={X: trainx[start:end], Y: trainy[start:end]}) mse = sess.run( tf.nn.l2_loss(yhat_2 - validy), feed_dict={X: validx}) errors.append(mse) if i % DRAWNOW_INTERVAL == 0 or i == NUM_EPOCHS - 1: result = sess.run(the_model_2, feed_dict={X: validx}) drawnow.drawnow(make_fig) print(f"epoch {i}, validation MSE {mse:6.2f}") return fignum + 1
def plot_data(sample): if 0 != sample.id: global count x.append(count) y.append(sample.channel_data) drawnow(make_fig) count = count + 1
def sound_serial_plot_realtime(com_port): ser = transfer_to_initiator.myserial.serial_send.config_port(com_port) i = 0 while True: line = ser.readline().decode('ascii').strip() # skip the empty data audio = 0 envelope = 0 gate = 0 if line: if line.startswith("audio"): try: strings = line.split(',') audio = float(strings[0].split("audio:", 1)[1]) envelope = float(strings[1].split("envelope:", 1)[1]) gate = float(strings[2].split("gate:", 1)[1]) x_audio.append(i) y_audio.append(audio) envelope = math.log10(envelope) x_envelope.append(i) y_envelope.append(envelope) x_gate.append(i) y_gate.append(gate) i += 1 if (i % 20 == 0): drawnow(make_fig) except: pass
def anneal(path, X, Y, n_iter=100000, pmelt=0.7, tgt=0.01, stagfactor=0.05, procplt=False, realtime=False, color='dimgray', lw=2): n_cities = len(path) initial_distance = calc_distance(path, X, Y) min_distance, max_distance = initial_distance, initial_distance optimized_distances = [] distances = [] optimized_distances.append(initial_distance) distances.append(initial_distance) for i in range(max([0.01 * n_cities, 2])): path_, distance = _metropolis(path, X, Y, 10**10) if distance < min_distance: min_distance = distance if max_distance < distance: max_distance = distance range_ = (max_distance - min_distance) * pmelt temp = tgt**(1 / n_iter) optimized_distance = initial_distance optimized_step = 1 optimized_path = path path_ = np.copy(path) for i in range(1, n_iter): if realtime: drawnow(showmap, path=path_, X=X, Y=Y) sys.stdout.write('\r{} / {} processing...'.format(i + 1, n_iter)) sys.stdout.flush() T = range_ * (temp**i) path_, distance = _metropolis(path_, X, Y, T) if distance < optimized_distance: optimized_distance = distance optimized_path = path_ optimized_step = i optimized_distances.append(optimized_distance) distances.append(distance) # Reheat if i - optimized_step == stagfactor * n_iter: temp = temp**(0.05 * i / n_iter) if procplt: plt.plot(distances, color='dimgray', lw=1) plt.plot(optimized_distances, color='black', lw=2) return optimized_path
def main(): state = env.reset() episode = 0 episode_score = 0 episode_steps = 0 states = [] actions = [] rewards = [] start_time = time.perf_counter() while episode < cfg.max_episode: action = get_action(torch.from_numpy(state).float()[None, :]) next_state, reward, done, _ = env.step(action) states.append(state) actions.append(action) rewards.append(reward) episode_score += reward episode_steps += 1 if done: # calculate discounted reward returns = [rewards[-1]] for r in rewards[-2::-1]: returns.append(r + cfg.gamma * returns[-1]) state_batch = torch.tensor(states).float() action_batch = torch.tensor(actions).float() return_batch = torch.tensor(returns[::-1]).float() return_batch = (return_batch - return_batch.mean()) / return_batch.std() update_policy(state_batch, action_batch[:, None], return_batch) print('episode: %d score %.5f, steps %d, (%.2f sec/eps)' % (episode, episode_score, episode_steps, time.perf_counter() - start_time)) last_score_plot.append(episode_score) if len(avg_score_plot) == 0: avg_score_plot.append(episode_score) else: avg_score_plot.append(avg_score_plot[-1] * 0.99 + episode_score * 0.01) drawnow(draw_fig) start_time = time.perf_counter() episode += 1 episode_score = 0 episode_steps = 0 state = env.reset() states.clear() actions.clear() rewards.clear() else: state = next_state env.close()
def runPlot(): i = 0 for i in range(1000): temp_y = np.random.random() x.append(i) y.append(temp_y) # or any arbitrary update to your figure's data i += 1 drawnow(make_fig)
def run(self): np.random.seed(13) mean = (2, 17) cov = [[10., 0], [0, 4.]] drawnow(self.draw_fig1, show_once=True, confirm=False) print (np.cov([self.sc1X,self.sc1Y], [self.sc2X,self.sc2Y]))
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 plot_func(next_time, next_obs, flag): time_seq.append(next_time) observe_seq.append(next_obs) #print(str(next_time) + " " + str(next_obs)) if flag == 1: drawnow(plot_new, x=time_seq, y=observe_seq) else: pass
def plot(self, all_rewards, epsilon): "Live plot of the reward" self.all_rewards = all_rewards self.epsilon = round(epsilon, 4) try: drawnow(self.plot_rewards) except KeyboardInterrupt: print("Break")
def render(self, filename=None, stop_on_close=True): """ Creates an image of the map to plot or save.""" if filename is None: drawnow.drawnow(self.update_drawnow, stop_on_close=stop_on_close) else: rgb_arr = self.get_rgb() plt.imshow(rgb_arr, interpolation='nearest') plt.savefig(filename)
def draw_array_xy(self, x1, x2, x3, x4, y1, y2, y3, y4): self.x1 = x1[:] self.x2 = x2[:] self.x3 = x3[:] self.x4 = x4[:] self.y1 = y1[:] self.y2 = y2[:] self.y3 = y3[:] self.y4 = y4[:] drawnow(self.make_fig_xy)
def run(self): np.random.seed(13) self.sc1X = randn(1000) self.sc1Y = randn(1000) self.sc2X = randn(1000) self.sc2Y = randn(1000) drawnow(self.draw_fig1, show_once=True, confirm=False) print(np.cov([self.sc1X, self.sc1Y], [self.sc2X, self.sc2Y]))
def payload_status(conn): """ Gathers the raw data of payload speed, and time Filters out payload and status :param conn: the Connection object :return: """ time_old = 0 global _status_old cur = conn.cursor() cur.execute("SELECT * FROM PLFDataLog") rows = cur.fetchall() for row in rows: status = (row[2][23] << 24)|(row[2][22] << 16)|(row[2][21] << 8)|(row[2][20]) speed = (row[2][19] << 24) | (row[2][18] << 16) | (row[2][17] << 8) | (row[2][16]) filter = (row[2][15] << 24) | (row[2][14] << 16) | (row[2][13] << 8) | (row[2][12]) ton = (row[2][11] << 24) | (row[2][10] << 16) | (row[2][9] << 8) | (row[2][8]) time_stamp = (row[2][7] << 56) | (row[2][6] << 48) | (row[2][5] << 40) | (row[2][4]|row[2][23] << 32) | (row[2][3] << 24) | (row[2][2] << 16) | (row[2][1])<<8 |(row[2][0]) if status == 0: st_status = 'STATE_UNKNOWN' elif status ==1: st_status = 'EMPTY_STOP' elif status ==2: st_status = 'EMPTY_MOVE' elif status ==3: st_status = 'LOADING' elif status ==4: st_status = 'LOADED_MOVE' elif status ==5: st_status = 'LOADED_STOP' elif status ==6: st_status = 'DUMPING' time_stamp=round((time_stamp/1000.),2) time_diff=round(((time_stamp-time_old)),2) ton = (ton/1000) filter = (filter/1000) speed = (speed/1000) slopecal(ton)#get the slope curve tonfilter(ton,speed)#get the right tonnage and status print("time_stamp (seg): ", time_stamp," time_diff: ",time_diff," tons: ", ton," ton filtered: ", filter," speed: ",speed ," status: ", st_status," filter ton: ", _ton," new status: ", _status, " slope: ", _slope ) _time.append(time_stamp) _raw_ton.append(ton) _filt_ton.append(_ton) _filt_status.append(_status) with open('/Users/jav/Desktop/komatsu.csv', 'a', newline='') as file: writer = csv.writer(file) writer.writerow(["time_stamp (seg): ", time_stamp," time_diff: ",time_diff," tons: ", ton," ton filtered: ", filter," speed: ", speed," status: ", st_status, " Filter ton: ",_ton, " new Status: ", _status, " slope: ", _slope]) time_old = time_stamp #drawnow(makeFig) #break drawnow(makeFig) plt.pause(30)
def on_epoch_end(self, epoch, logs={}): self.counter += 1 if self.slowlyCutBeginning and self.counter % 10 == 0: self.logs = self.logs[1:] self.x = self.x[1:] self.acc = self.acc[1:] self.logs.append(logs) self.x.append(self.i) self.acc.append(logs.get('acc')) self.i += 1 drawnow(self.paintPlot)
def wave_no_lineal(self, nx=41, nt=25, Lx=2., dt=0.025): super().__init__(nx, nt, Lx) self.dt = dt import matplotlib.pyplot as plt from drawnow import drawnow import numpy as np import time, sys import copy def makeFig(): plt.plot(xList, yList) plt.plot(1, Lx) plt.xlabel('X (m)') plt.ylabel('Y (m)') plt.title( "ECUACION DE LA ONDA\n No Lineal \n Tiempo{:.3f} s".format( inter)) plt.grid(True) plt.annotate(s=u"Celeridad ", xy=(0.95, 1.8), xytext=(0.2, 1.8), arrowprops=dict(arrowstyle="->")) plt.savefig("Onda_no_lineal.png") #Grafico de la Onda en PNG plt.savefig("Onda_no_lineal.jpg") #Grafico de la Onda en JPG plt.savefig("Onda_no_lineal.pdf") #Grafico de la Onda en PDF plt.show() plt.ion() fig = plt.figure() dx = Lx / (nx - 1) u = np.ones(nx) A = np.zeros((nt, nx)) u[int(.5 / dx): int(1. / dx + 1)] = 2 # Para valores dentro de un array siempre poner enteros # u0 = copy.copy(u) un = np.ones(nx) for n in range(nt): un[:] = u[:] for i in range(1, nx): u[i] = un[i] - un[i] * (dt / dx) * (un[i] - un[i - 1]) A[n, :] = u for i in range(nt): xList = np.linspace(0, Lx, nx) yList = A[i, :] inter = i * dt drawnow(makeFig) plt.pause(0.1) drawnow(makeFig) plt.show('hold')
def on_epoch_end(self, epoch, logs={}): self.counter+=1 if self.counter%10==0: self.logs=self.logs[1:] self.x=self.x[1:] self.losses=self.losses[1:] self.val_losses=self.val_losses[1:] self.logs.append(logs) self.x.append(self.i) self.losses.append(logs.get('loss')) self.val_losses.append(logs.get('val_loss')) self.i += 1 drawnow(self.paintPlot)
def run(): global file global plots_legend plt.ion() # enable interactivity fig=plt.figure() # make a figure plots_legend = ['Training loss', 'Validation loss', 'Accuracy'] #for line in fileinput.input(): file_list = [] file_id = -1 if len(sys.argv) > 2: file_list = sys.argv[2:] file_id = 0 while 1: if file_id > -1: if file == None: print "Opening file: ",file_list[file_id] file = open(file_list[file_id], 'rt') line = file.readline() if not line: file.close() file = None file_id+=1 if file_id == len(file_list): file_id = -1 else: timeout = 0.1 rlist, _, _ = select([sys.stdin], [], [], timeout) if rlist: line = sys.stdin.readline() else: #print "waiting" #plt.show() drawnow(makeFig) plt.pause(0.2) continue parseLine(line) pass
def main(): env.reset() for episode in range(MAX_EPISODES): episode_rewards = 0. end_of_episode = False while not end_of_episode: state = torch.FloatTensor(env.env.state) trajectory = [] for step in range(MAX_STEPS_BEFORE_UPDATE): action_probabilities, *_ = actor_critic_(state) action = action_probabilities.multinomial(1) exploration_statistics = action_probabilities.data.view(1, -1) next_state, reward, done, _ = env.step(action.numpy()[0]) next_state = torch.from_numpy(next_state).float() if render: env.render() transition = Transition(states=state.view(1, -1), actions=action.view(1, -1), rewards=torch.FloatTensor([[reward]]), next_states=next_state.view(1, -1), done=torch.FloatTensor([[done]]), exploration_statistics=exploration_statistics) buffer.add(transition) trajectory.append(transition) if done: env.reset() break else: state = next_state learning_iteration(trajectory) end_of_episode = trajectory[-1].done[0, 0] episode_rewards += sum([transition.rewards[0, 0] for transition in trajectory]) for trajectory_count in range(np.random.poisson(REPLAY_RATIO)): if len(buffer.episodes) > 1: trajectory = buffer.sample(OFF_POLICY_MINIBATCH_SIZE, MAX_REPLAY_SIZE) if trajectory: learning_iteration(trajectory) if verbose: print("Episode #%d, episode rewards %d" % (episode, episode_rewards)) last_score_plot.append(episode_rewards) if len(avg_score_plot) == 0: avg_score_plot.append(episode_rewards) else: avg_score_plot.append(avg_score_plot[-1] * 0.99 + episode_rewards * 0.01) drawnow(draw_fig)
def update(self, est_init2m): # pose est_init2m[:, :3, 3] *= self.scale[:, None] # equiv. to: est_m2c = metrics.invert_tensor(est_init2m @ metrics.invert_tensor(self.init_m2c)) est_m2init = torch.eye(4, device=est_init2m.device).repeat( est_init2m.shape[0], 1, 1) est_m2init[:, :3, :3] = est_init2m[:, :3, :3].transpose(2, 1) est_m2init[:, :3, 3] = -(est_m2init[:, :3, :3] @ est_init2m[:, :3, 3].view( -1, 3, 1)).view(-1, 3) est_m2c = self.init_m2c @ est_m2init # plot drawnow(self.plot, est_m2c=est_m2c) time.sleep(self.t_sleep)
def livePlot(self, data): """Creates a plot that updates in real time Parameters ---------- data: str datastream from serial""" self.values.append(data) use("seaborn") def makeFig(): plt.plot(self.values) drawnow(makeFig) plt.pause(0.00001)
def discrete_bayes_sim(self, kernel, zs, z_prob_correct, sleep=0.25): N = len(self.hallway) for i, z in enumerate(zs): self.loopIdx = i self.prior = predict(self.posterior, 1, kernel) drawnow(self.draw_fig_prior, show_once=False, confirm=False) time.sleep(sleep) likelihood = self.lh_hallway(self.hallway, z, z_prob_correct) print(self.hallway) print(likelihood) self.posterior = update(likelihood, self.prior) drawnow(self.draw_fig_posterior, show_once=False, confirm=False) time.sleep(sleep)
def plotValue(plot, x, y): global plots while len(plots) <= plot: plots.append([list(), list()]) plots[plot][0].append(x) plots[plot][1].append(y) if file == None: drawnow(makeFig) plt.pause(0.000000000001) pass
def plotLive(combine_Type, combine_Name, lat_Name, long_Name, massFlow_Name, filename): data = pd.read_csv(filename) if combine_Type != 0: comb_df = data[data[combine_Name] == combine_Type] lat_df = comb_df[lat_Name] lon_df = comb_df[long_Name] y = comb_df[massFlow_Name] else: lat_df = data[lat_Name] lon_df = data[long_Name] y = data[massFlow_Name] e,n = convertToUTM(lat_df, lon_df) def makeFig(): plt.plot(x,y) plt.ylabel('Easting') plt.xlabel('Northing') plt.ion() # enable interactivity plt.grid() fig = plt.figure() # make a figure x=list() y=list() for i in arange(len(n)): x.append(n[i]) y.append(e[i]) i+=1 drawnow(makeFig)
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)
import numpy as np import drawnow import matplotlib as mpl import matplotlib.pyplot as plt import time def draw_figs(): plt.plot(x, y) x = np.linspace(0, 1) #drawnow.figure() plt.figure() mpl.interactive = True for p in [0, 1, 2, 3, 4, 5, 6]: print('p = {}'.format(p)) y = x**p drawnow.drawnow(draw_figs) time.sleep(1)
i = arange(1,N_MAX) i = pow(i, 2) j = arange(1, N_MAX, dtype=int) for jj in j: if jj in i: j = j[j != jj] def fig_show(): figure() plot(periods) #show() periods = [] drawnow_init() for i in j: if i%(N_MAX//10) == 0: print i sys.stdout.flush() periods += [ find_period_sqrt(i) ] drawnow(fig_show, wait_secs=1) periods = asarray(periods) #def p65(): #same thing as p64()
print "Start Logging" try: while True : while (ser.inWaiting()==0): pass try: data=ser.readline() # read data dataArray = data.split('\t') tmpT = float( dataArray[0]) tmpA = float( dataArray[1]) T.append(tmpT) A.append(tmpA) if plotok : drawnow(makeFig,show_once=True) cnt += 1 # important until plot buffer is filled up # safe data f.write(data) # write to file f.close() f=open('datafile.txt','a') # keep plot vector tidy if plperf: cnt_max = 40 else: cnt_max = 20 if(cnt>cnt_max): T.pop(0) A.pop(0)
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)
# -*- coding: utf-8 -*- """ Created on Thu Nov 27 13:41:48 2014 @author: Camilo """ from drawnow import drawnow x = zeros((N,N)) def function_to_draw_figure(): #figure() # don't call, otherwise new window opened imshow(x) # python's global scope #show() # don't call show()! ion() # enable interactivity, can be default figure() for i in arange(x): x.flat[i] = 1 drawnow(function_to_draw_figure)
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)
resized = imresize(comic, 0.25) resized /= resized.max() rn, rm = resized.shape base_x, base_y = (80, 530) comic[base_x:base_x+rn, base_y:base_y+rm] = resized if __name__ == "__main__": panels = 3 WIDTH = 246 BLACK = 0.2 comic = imread('base.png') comic = 1 - comic HEIGHT = comic.shape[0] n = comic.shape[0] * comic.shape[1] # for drawnow S = 12 ion() figure(figsize=(S, S/3)) def update_image(): set_cmap('binary') imshow(comic)#, interpolation='nearest') axis('off') title('Iteration %d' % (i+1)) for i in arange(7): draw_figure() drawnow(update_image) sleep(1)
def draw(self): xx = [p.x for p in self.points] yy = [p.y for p in self.points] drawnow(lambda : Route.__draw_plot(xx, yy))
def pltFig(self): if self.device.flag != 0: drawnow.drawnow(self.makeFig)
from __future__ import division from pylab import zeros, arange, figure, ion, colorbar, imshow from drawnow import drawnow def draw_fig_real(): imshow(z, interpolation='nearest') colorbar() N = 16 z = zeros((N,N)) ion() figure() for i in arange(4*N): z.flat[i] = i+1 drawnow(draw_fig_real, show_once=False, confirm=False)
t = 0 fig = plt.figure() while True: #humidity = sense.get_humidity() te = os.popen('/opt/vc/bin/vcgencmd measure_temp') cputemp = te.read() cputemp = cputemp.replace('temp=','') cputemp = cputemp.replace('\'C\n','') cputemp = float(cputemp) temperature = sense.get_temperature_from_pressure() temperature = temperature - ((cputemp - temperature)/2) t += dt pressure = sense.get_pressure()*0.001 #temp = sense.get_temperature() humidity = sense.get_humidity() calctemp = temperature #0.0071*temp*temp+0.86*temp-10.0 calchum = humidity #humidity*(2.5-0.029*temperature) stringval1 = " H: %2.1f %%rH" % calchum stringval2 = " T: %2.1f C" % calctemp stringval3 = " P: %2.3f bar" % pressure timestamp = strftime("%d/%m/%Y %H:%M:%S") #timestampd = datetime.strptime(str(timestamp),'%d/%m/%Y %H:%M:%S') print(timestamp+stringval1) print(timestamp+stringval2) print(timestamp+stringval3) dateList.append(timestamp) timeList.append(t) tempList.append(calctemp) drawnow(makeFig) sleep(dt)