def diagramme_gant(liste_taches): durees =[] arivees =[] for tache in liste_taches: durees.append(tache.duree) arivees.append(tache.arivee) plt(arivees,"r",linewidth=10)
def make_CMD(short_w_file, long_w_file): """Links the two data sets it is given so the RA/Decs agree and plots a CMD. Compares second data set to first data set and assigns second data set the DataNum of first data set where the RA and Dec columns are within a reasonable range. Uses function from another module to do so. Removes the points not in both data sets so they can be ploted together and creates a CM Diagram of the data. Parameters ------ short_w_file, long_w_file: filename short_wave, long_wave: list short_w, long_w: astropy table """ short_wave = glob.glob(short_w_file) short_w = Table.read(short_wave[0]) long_wave = glob.glob(long_w_file) long_w = Table.read(long_wave[0]) # send through matching function in Sort module to make the DataNum's match long_w = assign_id(short_w, long_w, "AvgRA", "AvgDec") # print(long_w["DataNum", "AvgRA"], short_w["DataNum", "AvgRA"]) short_w = match(short_w, long_w) # long_w = match(long_w, short_w) # print(long_w["DataNum", "AvgRA"], short_w["DataNum", "AvgRA"]) # plot short - long vs instrumental mag plt(short_w["AvgFlux"] - long_w["AvgFlux"], short_w["InstruMag"])
def save_all_series(df): def plt(graph): graph.plot().save().close() cols = [x for x in dfm.columns if x not in ['year', 'month', 'qtr']] for col in cols: plt(Spline(col)) plt(Chart(col))
def render(self, renderObj, name): if self.ndims == 1: x_axis = np.linspace(-self.half_boxboundary, self.half_boxboundary, self.binNum) x_axis = np.delete(x_axis, -1 , 0) # prevent boundary error if hasattr(renderObj, '__call__'): # is function if renderObj.__name__ == "boltz1D" or renderObj.__name__ == "freeE1D": plt.plot(x_axis, renderObj(x_axis, self.temperature)) else: plt.plot(x_axis, renderObj(x_axis)) else: # is array plt(x_axis, renderObj) plt.xticks(np.linspace(-self.half_boxboundary, self.half_boxboundary, 8)) plt.savefig(name + ".png") plt.gcf().clear() if self.ndims == 2: x_axis = np.linspace(-self.half_boxboundary, self.half_boxboundary, self.binNum) y_axis = np.linspace(-self.half_boxboundary, self.half_boxboundary, self.binNum) x_axis = np.delete(x_axis, -1 , 0) # prevent boundary error y_axis = np.delete(y_axis, -1 , 0) # prevent boundary error A, B = np.meshgrid(x_axis, y_axis, indexing="ij") if hasattr(renderObj, '__call__'): if renderObj.__name__ == "boltz2D": #TODO freeE2D cs = plt.contourf(A, B, renderObj(A, B, self.temperature), 8, cmap=plt.cm.plasma) R = plt.contour(A, B, renderObj(A, B, self.temperature), 8, colors='black', linewidth=.25, linestyles="solid", extend="both") else: cs = plt.contourf(A, B, renderObj(A, B), 8, cmap=plt.cm.plasma) R = plt.contour(A, B, renderObj(A, B), 8, colors='black', linewidth=.25, linestyles="solid", extend="both") else: cs = plt.contourf(A, B, renderObj, 8, cmap=plt.cm.plasma) R = plt.contour(A, B, renderObj, 8, colors='black', linewidth=.25, linestyles="solid", extend="both") plt.clabel(R, inline=True, fontsize=8) plt.xlim(x_axis[0],x_axis[-1]) plt.ylim(y_axis[0],y_axis[-1]) plt.xticks(np.linspace(-self.half_boxboundary, self.half_boxboundary-2*self.half_boxboundary/(self.binNum-1), 6)) plt.yticks(np.linspace(-self.half_boxboundary, self.half_boxboundary-2*self.half_boxboundary/(self.binNum-1), 6)) plt.colorbar(cs) plt.savefig(name + ".png") plt.gcf().clear()
def winrate_statistics(self, dataset_df, mmr_info="1"): x_data, y_data = dataset_df wins = np.zeros(129) games = np.zeros(129) winrate = np.zeros(129) for idx, game in enumerate(x_data): for i in range(258): if game[i] == 1: games[i % 129] += 1 if y_data[idx] == 1: if i < 129: wins[i] += 1 else: if i >= 129: wins[i - 129] += 1 winrate = wins / games winrate_dict = dict() hero_dict = self.hero_id for i in range(129): try: winrate_dict[hero_dict[str(i)]] = winrate[i] except: continue sorted_winrates = sorted(winrate_dict.items(), key=operator.itemgetter(1)) x_plot_data = [x[0] for x in sorted_winrates] y_plot_data = [x[1] for x in sorted_winrates] title = 'Hero winrates at ' + mmr_info + ' MMR' data = [go.Bar(y=x_plot_data, x=y_plot_data, orientation='h')] layout = go.Layout(title=title, width=1000, height=1400, yaxis=dict(title='hero', ticks='', nticks=129, tickfont=dict(size=8, color='black')), xaxis=dict(title='win rate', nticks=30, tickfont=dict(size=10, color='black'))) fig = go.Figure(data=data, layout=layout) plt(data, filename='hero_win_1.html')
def main(): generator = Generator() discriminator = Discriminator() #setup the optimizer for two MLP networks D_solver = tf.train.AdadeltaOptimizer() G_solver = tf.train.AdadeltaOptimizer() out_path = os.path.join(config.OUTPUT_DIR, "conditional_gan") if not os.path.exists(out_path): os.makedirs(out_path) #training data i = 0 for it in range(100000): if it % 1000 == 0: n_sample = 16 z_sample = sample_z(n_sample, z_dim) y_sample = np.zeros(shape=[n_sample, y_dim]) y_sample[:, 6] = 1 samples = generator.forward(z_sample, y_sample) fig = plt(samples.numpy()) file_path = os.path.join(out_path, "{}.png".format(str(i).zfill(3))) plt.savefig(file_path, bbox_inches='tight') i += 1 plt.close(fig) images, labels = mnist.train.next_batch(batchSize) images = images.astpye(np.float32) labels = images.astpye(np.float32) z_sample = sample_z(batchSize, z_dim) with tf.GradientTape() as tape_d: g_sample = generator.forward(z_sample, labels) d_real, d_logit_real = discriminator.forward(images, labels) d_fake, d_logit_fake = discriminator.forward(g_sample, labels) d_loss = discriminator_loss(d_logit_real, d_logit_fake) # backward propagation of discriminator grad = tape_d.gradient(d_loss, discriminator.theta_D) D_solver.apply_gradients( zip(grad, discriminator.theta_D), global_step=tf.train.get_or_create_global_step()) with tf.GradientTape() as tape_g: g_sample = generator.forward(z_sample, labels) d_fake, d_logit_fake = discriminator.forward(g_sample, labels) g_loss = generator_loss(d_logit_fake) if it % 1000 == 0: print("Iter: {}".format(it)) print("D loss: {:.4}".format(d_loss)) print("G loss: {:.4}".format(g_loss)) print()
def learning_curve(model, inputs, inputs_val=None, train_args=None, metric='mse', ax=None, log=True, labels=None): if ax is None: _, ax = subplots(1, 1, size=figsize(1, 2)) if train_args is None: train_args = {} res = model.train(inputs, learning_curve=metric, **train_args) plt = ax.semilogy if log else ax.plot if labels is None: labels = ["Training Set", "Validation Set"] p = plt(res[0], res[1], label=labels[0]) if inputs_val is not None: plt(res[0], res[2], color=p[0].get_color(), linestyle='--', label=labels[1]) ax.set_xlabel("Epoch") metric_name = { 'mse': 'MSE', 'total': 'Total Error', }[metric] ax.set_ylabel(metric_name) ax.legend()
def DrawACC(t=None, Rec_ACC=None, *args, **kwargs): # varargin = DrawACC.varargin # nargin = DrawACC.nargin figure(5) plt.subplot(3, 1, 1) plt(t, Rec_ACC(1, arange()), '-bo') title('\theta1') xlabel('Sec') ylabel('Acc') plt.grid plt.subplt(3, 1, 2) plt(t, Rec_ACC(2, arange()), '-bo') title('\theta2') xlabel('Sec') ylabel('Acc') plt.grid plt.subplot(3, 1, 3) plt(t, Rec_ACC(3, arange()), '-bo') title('\theta3') xlabel('Sec') ylabel('Acc') plt.grid return
def DrawAngle(t=None, Rec_Ang=None, *args, **kwargs): # varargin = DrawAngle.varargin # nargin = DrawAngle.nargin figure(3) subplot(3, 1, 1) plt(t, Rec_Ang(1, arange())) title('\theta1') xlabel('Sec') ylabel('degree') plt.grid subplot(3, 1, 2) plt(t, Rec_Ang(2, arange())) title('\theta2') xlabel('Sec') ylabel('degree') plt.grid subplot(3, 1, 3) plt(t, Rec_Ang(3, arange())) title('\theta3') xlabel('Sec') ylabel('degree') plt.grid return
def DrawRPM(t=None, Rec_RPM=None, *args, **kwargs): # varargin = DrawRPM.varargin # nargin = DrawRPM.nargin figure(4) subplot(3, 1, 1) plt(t, Rec_RPM(1, arange()), '-bo') title('\theta1') xlabel('Sec') ylabel('RPM') plt.grid subplot(3, 1, 2) plt(t, Rec_RPM(2, arange()), '-bo') title('\theta2') xlabel('Sec') ylabel('RPM') plt.grid subplot(3, 1, 3) plt(t, Rec_RPM(3, arange()), '-bo') title('\theta3') xlabel('Sec') ylabel('RPM') plt.grid return
print('N_3e: |', 'count') for i in range(time_running): N_3e = find_out_3_coincidences(lmax, theta) #number of mu count += 1 print(N_3e, "|", count) L.append([N_3e]) if N_3e > 0: L_3e.append([N_3e]) if len(L_3e) == 0: print("Probability <", 1 / len(L)) else: print("probability =", len(L_3e) / len(L)) return len(L_3e), time_running '''L_dx = np.linspace(1,5,4) L_coincidence = [] for i in range(len(L_dx)): dx = L_dx[i] dy,dz = dx,dx N_coincidence, N_total = simulation_3_events(lmax = l, theta = angle, time_running=10**7) prob = N_coincidence/N_total L_coincidence.append(N_coincidence) plt(L_dx,L_coincidence) plt.xlabel('dx (mm)') plt.ylabel('N_coincidence')''' def estimate_prob_at_dx( dx, N ): # this function(method) require the high performance of computers which is not suitable for my laptop.
# coding: utf-8 import numpy import h5py import numpy as np np.read np.loadtxt('data/ecg_101.txt') a = np.loadtxt('data/ecg_101.txt') a a.shape import matplotlib import matplotlib.pyplot as plt plt(a[0], a[1]) plt.plot(a[0], a[1]) plt.show() a[0] a[] a[1] get_ipython().magic('pinfo plt.plot') plt.plot(a[1]) plt.show() plt.plot(a[0]) plt.show() a a[0] a[0][0] a[;0] a[,0] a[,:] a[:,] a.shape a[0][:]
if epoch >3: done_looping = True break end_time = timeit.default_timer() print(('Optimization complete. Best validation score of %f %% ' 'obtained at iteration %i, with test performance %f %%') % (best_validation_loss * 100., best_iter + 1, test_score * 100.)) print(('The code for file ' + os.path.split(__file__)[1] + ' ran for %.2fm' % ((end_time - start_time) / 60.)), file=sys.stderr) epoch_loss_np = np.reshape(epoch_loss_list,newshape=(len(epoch_loss_list),3)) plt(epoch_loss_np) epoch_val_np = np.reshape(epoch_loss_list,newshape=(len(epoch_val_list),3)) #trying to plot this this """ for i in range(10000): cost = train_model(Xtr_rows, Ytr) if cost_aux > cost: learning_rate.set_value(learning_rate.get_value()*1.1) else: learning_rate.set_value(learning_rate.get_value()*0.9) cost_aux = cost print("cost is: ", cost, "learning rate: ", learning_rate.get_value())
# -*- coding: utf-8 -*- """ Created on Thu May 10 16:10:56 2018 @author: sapta """ import matplotlib.pyplot as plt plt()
l_sec = df['total_seconds'].tolist() l_binsx =[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17] l_bins_n = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17] h = plt.hist2d(l_day, l_sec, bins=15) plt.grid(False) plt.xlabel("day of the month") plt.ylabel("seconds since midnight") plt.colorbar() plt.savefig("time_Vs_response.pdf") for i, group in df.groupby('statu'): plt.figure() group.plot(x='time', y='responsetime', title="status = "+str(i), legend=False) group.plot(df['responsetime'], bins=20, alpha=0.5, title="status = "+str(i), kind="hist") plt.ylabel("responsetime (s)") title=str(i)+".pdf" plt(marker='o') plt.savefig(title) print(df["stat_freq"]) for i, group, in df.groupby(['id']): print(group) print(group["status"]) count = group["status"].value_counts().sort_index(0).to_dict() o_count = collections.OrderedDict(sorted(count.items())) print(o_count) plt.bar(range(len(o_count)), o_count.values(), align='center') plt.xticks(range(len(o_count)), list(o_count.keys())) group["status"].plot(x='status', y=group['status'].value_counts(), title="user status - "+str(i), legend=False, kind="bar")
my['cat']='고양이' my['cat'] my['고양이'] dic={'1':1,'2':2,'3':3,'4':4,'5':5,'6':6} dic['1']+dic['6']==7 and dic['2']+dic['5']==7 and dic['3']+dic['4']==7 def max_min(a): print(max(a)) print(min(a)) my_list=[1,3,2,9,6,5,3] max_min(my_list) import matplotlib.pyplot as plt for i in range(0,6,0.1): print(i) plt(-(i-1)(i-3)(i-4)) x=[a for a in range(0,6)] y=[(-(b-1)(b-3)(b-4)) for b in range(6)] y=[a*a for a in x] plt.plot(x,y) import numpy as np x=np.arange(-1,6,0.1) y=-(x-1)*(x-3)*(x-4) plt.plot(x,y) x=np.arange(-1,11,0.1) y=-(x-1)*(x-6)*(x-9)
from scipy import optimize num_points = 150 Tx = linspace(5., 8., num_points) Ty = Tx tX = 11.86*cos(2*pi/0.81*Tx-1.32) + 0.64*Tx+4*((0.5-scipy.rand(num_points))*exp(2*scipy.rand(num_points)**2)) tY = -32.14*cos(2*pi/0.8*Ty-1.94) + 0.15*Ty+7*((0.5-scipy.rand(num_points))*exp(2*scipy.rand(num_points)**2)) # Fit the first set fitfunc = lambda p, x: p[0]*cos(2*pi/p[1]*x+p[2]) + p[3]*x # Target function errfunc = lambda p, x, y: fitfunc(p, x) - y # Distance to the target function p0 = [-15., 0.8, 0., -1.] # Initial guess for the parameters p1, success = optimize.leastsq(errfunc, p0[:], args=(Tx, tX)) time = linspace(Tx.min(), Tx.max(), 1000) plt(Tx, tX, "ro", time, fitfunc(p1, time), "r-") # Plot of the data and the fit # Fit the second set p0 = [-15., 0.8, 0., -1.] p2,success = optimize.leastsq(errfunc, p0[:], args=(Ty, tY)) time = linspace(Ty.min(), Ty.max(), 1000) plt(Ty, tY, "b^", time, fitfunc(p2, time), "b-") # Legend the plot plt.title("Oscillations in the compressed trap") plt.xlabel("time [ms]") plt.ylabel("displacement [um]") plt.legend(('x position', 'x fit', 'y position', 'y fit'))
maxchange = current > maxi - radius mini_h = (current - mini)[minchange] maxi_h = (maxi - current)[maxchange] vshell += np.sum(ne.evaluate("1/3.0*pi*(2*(radius**3 - inn**3) + 3*mini_h*(radius**2 - inn**2))")) vshell += np.sum(ne.evaluate("1/3.0*pi*(2*(radius**3 - inn**3) + 3*maxi_h*(radius**2 - inn**2))")) vshell += np.sum(((-minchange + -maxchange))*ne.evaluate("4/3.0*pi*(radius**3 - inn**3)")) count += np.sum((r<radius) * (r>inn)) gofrset[i,0] = radius gofrset[i,1] = count/(vshell*density) gofrset[i,2] = count gofrset[i,3] = vshell #print gofrset[i,1] #results.writerow(gofrset[:,0:1]) for i in range(len(gofrset[:])): plt(gofrset[i,0:1]) raw_input() print "I'm Done!" """ for m in range(num_part): if (current[m,0] - radius < mini[0]) | current[m,0] + radius > maxi[0]: continue elif (current[m,1] - radius < mini[1]) | current[m,1] + radius > maxi[1]: continue elif (current[m,2] - radius < mini[2]): h = current(m,2) - mini[2] vshell += ne.evaluate("1/3.0*np.pi*(2*(radius**3 - inn**3) + 3*h*(radius**2 - inn**2))")
def competition(t, state, parameters): # array # constants k = 0.11 m = 0.01 g = 0.1 n = 1 C = 0.99 q = 2 # state derivatives dw1 = (w1 ^ q/(w1 ^ q + C*w2 ^ q))*(k*(w1+w2)/(1 + g*(w1+w2) ^ n)) - m*w1 dw2 = (C*(w2 ^ q/(w1 ^ q + C*w2 ^ q))) * \ (k*(w1+w2)/(1 + g*(w1+w2) ^ n)) - m*w2 return [dw1, dw2] state0 = [0.20, 0.20] # initial state t = np.arange(.0, 10.0, 0.1) # timestep state = odeint(competition, state0, t) plt(t, state) xlabel('TIME (sec)') ylabel('STATES') title('2 Plant System') legend(('')) show()
# Checked OK, for the three ions independently, with fig.1 of Ercolano & Storey 2006 check_fb = False if check_fb : f = open('Ercolano_fig1_H.dat','r') # Datathiefed from fig.1 para HI, HeI and HeII. aa = f.readlines() f.close() lenaa = len(aa) xnu = np.zeros(lenaa) yfb = np.zeros(lenaa) for i in range(0,lenaa) : tt = string.split(aa[i]) xnu[i] = float(tt[0]) yfb[i] = float(tt[1]) Gamma_fb=gamma_fb_func('HI_t3_elec.ascii') plt(nu*1e-14,Gamma_fb,xnu,yfb*1e-40,'o') f = open('Ercolano_fig1_HeI.dat','r') # Datathiefed from fig.1 para HI, HeI and HeII. aa = f.readlines() f.close() lenaa = len(aa) xnu = np.zeros(lenaa) yfb = np.zeros(lenaa) for i in range(0,lenaa) : tt = string.split(aa[i]) xnu[i] = float(tt[0]) yfb[i] = float(tt[1]) Gamma_fb=gamma_fb_func('HeI_t5_elec.ascii') plt(nu*1e-14,Gamma_fb,'--',xnu,yfb*1e-40,'o')
# -*- coding: utf-8 -*- # <nbformat>3.0</nbformat> # <codecell> import matplotlib.pyplot as plt import numpy as np def lafunc(x): return np.exp(-(x**2)) minx = -5.0 maxx = 5.0 x = np.linspace(minx,maxx,1000) gausiana = lafunc(x) plt(x,gausiana) # <codecell> miny = 0.0 maxy = amax(gausiana) print miny, maxy # <codecell> nrandom = 10000 randomx = random.rand(nrandom) * (maxx - minx) + minx randomy = random.rand(nrandom) * (maxy - miny) + miny # <codecell> delta = lafunc(randomx) - randomy
import matplotlib.pyplot as plt Samples=100 #描画するサンプルパスの数 Steps=10000 #時間区切りの数 S_T=np.zeros((Samples,Steps)) # S_T[:,0]=S_t for i in range(1,Samples): for j in range(1,Steps): S_T[i,j]=gBM(S_T[i-1,j-1],sigma,r,T/Steps,random.gauss(0,1)) plt(S_T[:,Steps]) plt.show
dir_out = 'data' file_out= 'Hw4_1_fixed.png' N = 1000 f_Tm = 10 # mean T in C f_dA = 40 # in degree C w = 3600 ## noise / error f_sigma = 15.2 #======================================================================================= # create synthetic data #======================================================================================= a_t = np.linspace( 0, 7*w) # convert to martian days a_T = fct_T( a_t, f_Tm, f_dA, w) # add some noise a_T_noise = a_T + np.dot(np.random.randn( N, 1), (1, f_sigma) #======================================================================================= # save to file #======================================================================================= #fig, ax = plt.subplots() plt( a_t, a_T_noise, 'ko', ms = 2) plt( a_t, a_T, 'r-', lw = 1.5) # save this figure as .png plt.savefig( 'dir_out') plt.show()
def render(self, renderObj, name): if self.ndims == 1: x_axis = np.linspace(-self.half_boxboundary, self.half_boxboundary, self.binNum) x_axis = np.delete(x_axis, -1, 0) # prevent boundary error if hasattr(renderObj, '__call__'): # is function if renderObj.__name__ == "boltz1D": plt.plot(x_axis, renderObj(x_axis, self.temperature)) else: plt.plot(x_axis, renderObj(x_axis)) else: # is array plt(x_axis, renderObj) plt.xticks( np.linspace(-self.half_boxboundary, self.half_boxboundary, 8)) plt.savefig(name + ".png") plt.gcf().clear() if self.ndims == 2: x_axis = np.linspace(-self.half_boxboundary, self.half_boxboundary, self.binNum) y_axis = np.linspace(-self.half_boxboundary, self.half_boxboundary, self.binNum) x_axis = np.delete(x_axis, -1, 0) # prevent boundary error y_axis = np.delete(y_axis, -1, 0) # prevent boundary error A, B = np.meshgrid(x_axis, y_axis, indexing="ij") if hasattr(renderObj, '__call__'): if renderObj.__name__ == "boltz2D": cs = plt.contourf(A, B, renderObj(A, B, self.temperature), 6, alpha=.75, cmap=plt.cm.hot) R = plt.contour(A, B, renderObj(A, B, self.temperature), 6, colors='black', linewidth=.5) else: cs = plt.contourf(A, B, renderObj(A, B), 6, alpha=.75, cmap=plt.cm.hot) R = plt.contour(A, B, renderObj(A, B), 6, colors='black', linewidth=.5) else: cs = plt.contourf(A, B, renderObj, 6, alpha=.75, cmap=plt.cm.hot) R = plt.contour(A, B, renderObj, 6, colors='black', linewidth=.5) plt.clabel(R, inline=True, fontsize=10) plt.xlim(x_axis[0], x_axis[-2]) plt.ylim(y_axis[0], y_axis[-2]) plt.xticks( np.linspace(-self.half_boxboundary, self.half_boxboundary, 6)) plt.yticks( np.linspace(-self.half_boxboundary, self.half_boxboundary, 6)) plt.colorbar(cs) plt.savefig(name + ".png") plt.gcf().clear()
Noise power spectrum for angular frequency omega. """ return 0.5 * gamma1 * omega/(2*np.pi) # find the floquet modes for the time-dependent hamiltonian f_modes_0, f_energies = qt.floquet_modes(H, T, args) # precalculate mode table f_modes_table_t = qt.floquet_modes_table(f_modes_0, f_energies, np.linspace(0, T, 500 + 1), H, T, args) # solve the floquet-markov master equation output = qt.fmmesolve(H, psi0, tlist, [sigmax()], [], [noise_spectrum], T, args) # calculate expectation values in the computational basis p_ex = np.zeros(np.shape(tlist), dtype=complex) for idx, t in enumerate(tlist): f_modes_t = floquet_modes_t_lookup(f_modes_table_t, t, T) p_ex[idx] = expect(num(2), output.states[idx].transform(f_modes_t, True)) # For reference: calculate the same thing with mesolve output = qt.mesolve(H, psi0, tlist, [np.sqrt(gamma1) * qt.sigmax()], [num(2)], args) p_ex_ref = output.expect[0] # plot the results plt(tlist, real(p_ex), "r--", tlist, 1-real(p_ex), "b--") plt(tlist, real(p_ex_ref), "r", tlist, 1-real(p_ex_ref), "b") plt.xlabel("Time") plt.ylabel("Occupation probability") plt.legend(("Floquet $P_1$", "Floquet $P_0$", "Lindblad $P_1$", "Lindblad $P_0$")) plt.show()
import numpy as np from matplotlib.patches import Circle, Rectangle, Wedge, Polygon from matplotlib.collections import PatchCollection import matplotlib.pyplot as plt def atlok(szam): megoldás = (szam * (szam - 3)) / 2 return megoldás patches = [] for szám in range(100): #plt(0.1*szám, 0.1*atlok(szám)) patches.append(plt(0.2, 0.2)) p = PatchCollection(patches, alpha=0.4) plt.show()
def DrawRobotManipulator(DOF, JointPos, JointDir, FigNum, View): # varargin = DrawRobotManipulator.varargin # nargin = DrawRobotManipulator.nargin figure(FigNum) plt(JointPos(1, arange(1, end())), JointPos(2, arange(1, end())), JointPos(3, arange(1, end())), 'linewidth', 4) plt(JointPos(1, arange(1, end())), JointPos(2, arange(1, end())), JointPos(3, arange(1, end())), 'ro', 'linewidth', 7) xlabel('X axis') ylabel('Y axis') zlabel('Z axis') X = 10 Y = 10 Z = 20 BaseX = np.array([X, X, -X, -X, X]) BaseY = np.array([Y, -Y, -Y, Y, Y]) BaseZ = np.array([0, 0, 0, 0, 0]) patch(BaseX, BaseY, BaseZ, 'k') #------------------------------------- BaseX = np.array([X, X, X, X, X]) BaseY = np.array([Y, -Y, -Y, Y, Y]) BaseZ = np.array([0, 0, -Z, -Z, 0]) patch(BaseX, BaseY, BaseZ, 'k') #------------------------------------- BaseX = np.array([X, -X, -X, X, X]) BaseY = np.array([Y, Y, Y, Y, Y]) BaseZ = np.array([0, 0, -Z, -Z, 0]) patch(BaseX, BaseY, BaseZ, 'k') #------------------------------------- BaseX = np.array([-X, -X, -X, -X, -X]) BaseY = np.array([-Y, Y, Y, -Y, -Y]) BaseZ = np.array([0, 0, -Z, -Z, 0]) patch(BaseX, BaseY, BaseZ, 'k') #------------------------------------- BaseX = np.array([X, -X, -X, X, X]) BaseY = np.array([-Y, -Y, -Y, -Y, -Y]) BaseZ = np.array([0, 0, -Z, -Z, 0]) patch(BaseX, BaseY, BaseZ, 'k') for i in arange(1, DOF + 1): #----------------------------------------- nUnit_v = JointPos(arange(), i) + np.dot( 5, JointDir(arange(), np.dot(3, (i - 1)) + 1)) nBase = np.array([JointPos(arange(), i), nUnit_v]) plt(nBase(1, arange(1, end())), nBase(2, arange(1, end())), nBase(3, arange(1, end())), 'y', 'linewidth', 2) sUnit_v = JointPos(arange(), i) + np.dot( 5, JointDir(arange(), np.dot(3, (i - 1)) + 2)) sBase = np.array([JointPos(arange(), i), sUnit_v]) plt(sBase(1, arange(1, end())), sBase(2, arange(1, end())), sBase(3, arange(1, end())), 'g', 'linewidth', 2) aUnit_v = JointPos(arange(), i) + np.dot( 5, JointDir(arange(), np.dot(3, (i - 1)) + 3)) aBase = np.array([JointPos(arange(), i), aUnit_v]) plt(aBase(1, arange(1, end())), aBase(2, arange(1, end())), aBase(3, arange(1, end())), 'r', 'linewidth', 2) plt.show() view(View) #axis equal axis(np.array([-50, 50, -30, 80, -20, 80])) return
# coding: utf-8 get_ipython().magic(u'clear ') import numpy as np x = np.arange(0, 1, 50) x x = np.linspace(0, 1, 50) y = np.exp(-x) from matplotlib import pyplot as plt plt.plot(x, y) plt.show() plt.plot(x, y, '*') plt.show() x idx = np.arange(2, 48) idx dy = -0.5 * y[idx - 2] + y[idx - 1] - y[idx + 1] + 0.5 * y[idx + 2] dy x dy = dy / 0.02040816**3 plt(x, y, '*', x[idx], dy, 'o') plt.plot(x, y, '*', x[idx], dy, 'o') plt.show() plt.plot(x, y, '*', x[idx], dy, 'o') plt.legend('funcion', 'derivada') plt.legend(['funcion', 'derivada']) plt.show() get_ipython().magic(u'ls ') get_ipython().magic(u'save ejemplo_salon_clase.py 1-27')
plt.xscale('log') # Show plot plt.show() print('3 HISTOGRAM') print('use a histogram to show distribution ') print( 'range is diveded into bins and graph shows how many results are in each bin' ) print(' Too few bins will oversimplify reality and won' 't show you the details. ') print('prToo many bins will overcomplicate reality and won' 't show the bigger picture.') plt.clf() plt(life_exp, bins=10) print('customisations!!') print('lables for x and y') plt.ylabel('this is the x') plt.xlabel('this is the life expectency') print('title') plt.title('This is a crazy graph') print('Ticks = values for x and y axis - can use this to make it start at 0') print(' can also set lables for each tick') plt.xticks([0, 10, 20, 30, 40, 50, 60, 70, 80, 90]) plt.yticks([0, 4, 8, 12, 16, 20], ["None", "4 times", "8 times", "12 times", "16 times", "20 times"]) plt.grid(True) print('put text into the graph at given coordinates')
data.head() data.describe() data['bedrooms'].value_counts().plot(kind='bar') plt.title('number of Bedroom') plt.xlabel('Bedrooms') plt.ylabel('Count') sns.despine plt.figure(figsize=(10, 10)) sns.jointplot(x=data.lat.values, y=data.long.values, size=10) plt.ylabel('Longitude', fontsize=12) plt.xlabel('Latitude', fontsize=12) plt.show() plt1 = plt() sns.despine plt.scatter(data.price, data.sqft_living) plt.title("Price vs Square Feet") plt.scatter(data.bedrooms, data.price) plt.title("Bedroom and Price ") plt.xlabel("Bedrooms") plt.ylabel("Price") plt.show() sns.despine plt.scatter((data['sqft_living'] + data['sqft_basement']), data['price']) from sklearn.linear_model import LinearRegression
def tst7(look,xrange,velplotmin, velplotmax,amg_1666,\ nrcnm,tde,tbaseline,tbg,xd,zrocnm, taucnm, cencnm, widcnm, tspincnm, ordercnm,\ continuum_em, hgtwnm, cenwnm, widwnm, fwnm,\ zrocnmyn, taucnmyn, cencnmyn, widcnmyn, tspincnmyn,\ continuum_emyn, hgtwnmyn, cenwnmyn, widwnmyn, fwnmyn): # Tst 7 # zrocnmyn = 0 continuum_emyn = 0 taucnmyn = [0]*nrcnm cencnmyn = [0]*nrcnm widcnmyn = [0]*nrcnm ordercnm = [0]*nrcnm tdee = tde - tbaseline + tbg tb_cont, tb_wnm_tot, tb_cnm_tot, tb_tot, exp_tau_sum = tb_exp(xd, \ zrocnm, taucnm, cencnm, widcnm, tspincnm, ordercnm, \ continuum_em, hgtwnm, cenwnm, widwnm, fwnm) plt.plot(xd,tdee) plt.xlim(velplotmin, velplotmax) plt.plot(xd,tb_cnm_tot+tbg) plt(xd, tb_tot) # plt.show() tfita, sigma, \ zrocnm1, taucnm1, cencnm1, widcnm1, tspincnm1, \ sigzrocnm1, sigtaucnm1, sigcencnm1, sigwidcnm1, sigtspincnm1, \ continuum_em1, hgtwnm1, cenwnm1, widwnm1, fwnm1, \ sigcontinuum_em1, sighgtwnm1, sigcenwnm1, sigwidwnm1, sigfwnm1, \ cov, problem, nloop, \ tb_cont, tb_wnm_tot, tb_cnm_tot, \ exp_tau_sum, nloopmax, halfasseduse = fit.fit(look, xd, td, vrange, \ zrocnm, taucnm, cencnm, widcnm, tspincnm, ordercnm, \ zrocnmyn, taucnmyn, cencnmyn, widcnmyn, tspincnmyn, \ continuum_defln, hgtwnm, cenwnm, widwnm, fwnm, \ continuum_deflnyn, hgtwnmyn, cenwnmyn, widwnmyn, fwnmyn) tb_cont, tb_wnm_tot, tb_cnm_tot, tb_tot, exp_tau_sum = tb_exp(xd, \ zrocnm1, taucnm1, cencnm1, widcnm1, tspincnm1, ordercnm, \ continuum_em1, hgtwnm1, cenwnm1, widwnm1, fwnm1) plt.plot(xd, tb_tot) plt.plot(xd,tdee-tb_tot) nrgauss_wnm = len(hgtwnm1) nrg_wnm = nrgauss_wnm emg_1666 = {'sname':'', 'ell':0.0, 'bee':0.0, 'gaussnr':0, 'nrgauss':1, \ 'tbaseline':0.0, \ 'continuum':0.0, 'hgtwnm':0.0, 'cenwnm':0.0, 'widwnm':0.0, 'fwnm':0.0, \ 'sigcontinuum':0.0, 'sighgtwnm':0.0, 'sigcenwnm':0.0, 'sigwidwnm':0.0, 'sigfwnm':0.0,\ 'continuum_em':0.0} dassign(emg_1666,'sname', src, nrgauss_wnm) dassign(emg_1666,'ell', ell[n], nrgauss_wnm) dassign(emg_1666,'bee', bee[n], nrgauss_wnm) dassign(emg_1666,'gaussnr', list(range(nrg_wnm))) dassign(amg_1665,'nrgauss', nrg_wnm, nrgauss_wnm) dassign(emg_1666,'tbaseline', tbaseline, nrgauss_wnm) dassign(emg_1666,'continuum_em', continuum_em, nrgauss_wnm) dassign(emg_1666,'hgtwnm', hgtwnm1) dassign(emg_1666,'cenwnm', cenwnm1) dassign(emg_1666,'widwnm', widwnm1) dassign(emg_1666,'fwnm', fwnm1) dassign(emg_1666,'sighgtwnm', sighgtwnm1) dassign(emg_1666,'sigcenwnm', sigcenwnm1) dassign(emg_1666,'sigwidwnm', sigwidwnm1) dassign(emg_1666,'sigfwnm', sigfwnm1) amg_1666['tspincnm'] = tspincnm1 ## DAU DAY amg_1666['sigtspincnm'] = sigtspincnm1 ## DAU DAY # End - Tst 7 # return ''
ax2 = fig.add_subplot(2, 2, 2) ax3 = fig.add_subplot(2, 2, 3) plt.plot([1.5, 3.5, -2, 1.6]) plt.plot(rand(50).cumsum(), 'k--') _ = ax1.hist(randn(100), bins=20, color='k', alpha=0.3) ax2.scatter(np.arange(30), np.arange(30) + 3 * randn(30)) # Simple plot x = range(0, 100) y = [i * i for i in x] plt(x, y, '-') plt.plot(x, y, '-') plt.title('Plotting x * x') plt.xlabel('X axis') plt.ylabel('Y axis') plt.savefig('simple.png') # Plotting dates/times from matplotlib.dates import date2num from datetime import datetime, timedelta # Generate a series of timestamps from today to today + 100 years x = [date2num(datetime.today() + timedelta(days=365 * x)) for x in range(0, 100)] y = [i * i for i in range(0, 100)] plt(x, y, '-')
plt.title('Fed Tweets by Date') plt.xlabel('Date') plt.ylabel('Fed Tweets') plt.plot_date(datelistmod, incore, linestyle='-', marker='', color='blue') plt.show() plt.title('War Tweets by Date') plt.xlabel('Date') plt.ylabel('War Tweets') plt.plot_date(datelistmod, wacore, linestyle='-', marker='', color='blue') plt.show() objects = ('China \n Tweets', 'No \n China \n Tweets', 'Fed \n Tweets', 'No \n Fed \n Tweets', 'War \n Tweets', 'No \n War \n Tweets') y_pos = np.arange(len(objects)) plt.bar(y_pos, performance, align='center', alpha=0.5, color=['red', 'red', 'green', 'green', 'blue', 'blue']) plt.xticks(y_pos, objects) plt.ylabel('Average SPY Delta') plt.title('Average SPY Performance') plt(figsize=(10, 6)) plt.show() #When does trump tweet about china
import sys sys.path.append('/usr/local/anaconda3/lib/python3.6/site-packages') import sys import matplotlib.pyplot as plt import numpy as np from numpy import * x = linspace(0, 7, 70) y = cos(x) from matplotlib import pyplot as plt plt.grid() plt.xlabel('x') plt.ylabel('f(x)') plt.title('Funkcija $cos(x)$') plt.plot(x, y) plt(show)
c = conn.cursor() # c.execute('''CREATE TABLE POPULATION # (ID INT PRIMARY KEY NOT NULL, # EN_NAME TEXT NOT NULL, # ZH_NAME TEXT NOT NULL);''') # print("Population Table Created!") conn.commit() c.execute("select name from sqlite_master where type='table' order by name;") print(c.fetchall()) c.execute("PRAGMA table_info(POPULATION)") print(c.fetchall()) # make sure you already have the dict td in the memory for i, k in enumerate(td): sql = "INSERT INTO POPULATION (ID,EN_NAME,ZH_NAME) \ VALUES (%d, '%s', '%s');" % (i, k, td[k]) print(sql) c.execute(sql) print("Records created successfully") conn.close() x=[1999:1:2018] y=[tdplus] fig.ax = plt.subplots() plt(x,y) plt.savefig("static/image/graduate_figure.png") plt.show() __cpiplus__() crawl_graduate()
import csv import numpy as np filename = '/Users/MahdiMoslemi/Desktop/xyz_b' with open(filename) as csvfile: data = [ tuple(map(float, row)) for row in csv.reader(csvfile, delimiter=" ") ] points = np.array(data) from scipy.spatial import Voronoi, voronoi_plot_2d vor = Voronoi(points) import matplotlib.pyplot as plt plt(vor) plt.show()
plt.hist(sample, bins=100, orientation='horizontal') # bar-plot plt.bar(FCT.index, FCT['Volume']) # horizontal bar-plot plt.hbar(FCT.index, FCT['Volume']) # boxplot plt.boxplot([df['normal'], df['random'], df['gamma']]) # heatmap plt.hist2d(X, Y, bins=25) plt.colorbar() #add color range legend # error bars plt.errorbar(x, y, xerr=0.2) # OR.... use kind = graph_type plt(kind=bar, x, y) ### ADD HORIZONTAL/VERTICAL LINE, axhline--------------------------------------- df2.plot(figsize(15,5)).axhline(y = 0, color = "red", lw=1) #or just add to a new line plt.axhline(y = 0, color = "red", lw=1) plt.axvline(y = 0, color = "red", lw=1) #vertical lines ### ADD ANNOTATIONS--------------------------------------- plt.text('2015-10-23', 2.25, 'SMA 10-20',rotation=90) #(x, y, text, rotate-label) # http://matplotlib.org/users/annotations_guide.html#plotting-guide-annotation # label name, data points coord, annotation text coord, textcoords???, horizontal alignment, vertical alignment, arrow settings
def construct_boxplot(self, alpha=.05, k_a=1): """ This function constructs phase boxplot for functional data using the elastic square-root slope (srsf) framework. :param alpha: quantile value (e.g.,=.05, i.e., 95\%) :param k_a: scalar for outlier cutoff (e.g.,=1) """ if self.warp_data.rsamps: gam = self.warp_data.gams else: gam = self.warp_data.gam M, N = gam.shape t = np.linspace(0, 1, M) time = t lam = 0.5 # compute phase median median_x, psi_median, psi, vec = uf.SqrtMedian(gam) # compute phase distances dx = np.zeros(N) v = np.zeros((M, N)) for k in range(0, N): v[:, k], d = geo.inv_exp_map(psi_median, psi[:, k]) dx[k] = np.sqrt(trapz(v[:, k]**2, t)) dx_ordering = dx.argsort() CR_50 = dx_ordering[0:np.ceil(N / 2).astype('int')] tmp = dx[CR_50] m = tmp.max() # identify phase quartiles angle = np.zeros((CR_50.shape[0], CR_50.shape[0])) energy = np.zeros((CR_50.shape[0], CR_50.shape[0])) for i in range(0, CR_50.shape[0] - 1): for j in range(i + 1, CR_50.shape[0]): q1 = v[:, CR_50[i]] q3 = v[:, CR_50[j]] q1 /= np.sqrt(trapz(q1**2, time)) q3 /= np.sqrt(trapz(q3**2, time)) angle[i, j] = trapz(q1 * q3, time) energy[i, j] = (1 - lam) * (dx[CR_50[i]] / m + dx[CR_50[j]] / m) - lam * (angle[i, j] + 1) maxloc = energy.argmax() maxloc_row, maxloc_col = np.unravel_index(maxloc, energy.shape) Q1_index = CR_50[maxloc_row] Q3_index = CR_50[maxloc_col] Q1 = gam[:, Q1_index] Q3 = gam[:, Q3_index] Q1_psi = np.sqrt(np.gradient(Q1, 1 / (M - 1))) Q3_psi = np.sqrt(np.gradient(Q3, 1 / (M - 1))) # identify phase quantiles dx_ordering = dx.argsort() CR_alpha = dx_ordering[0:np.round(N * (1 - alpha)).astype('int')] tmp = dx[CR_alpha] m = tmp.max() angle = np.zeros((CR_alpha.shape[0], CR_alpha.shape[0])) energy = np.zeros((CR_alpha.shape[0], CR_alpha.shape[0])) for i in range(0, CR_alpha.shape[0] - 1): for j in range(i + 1, CR_alpha.shape[0]): q1 = v[:, CR_alpha[i]] q3 = v[:, CR_alpha[j]] q1 /= np.sqrt(trapz(q1**2, time)) q3 /= np.sqrt(trapz(q3**2, time)) angle[i, j] = trapz(q1 * q3, time) energy[i, j] = (1 - lam) * (dx[CR_alpha[i]] / m + dx[CR_alpha[j]] / m) - lam * (angle[i, j] + 1) maxloc = energy.argmax() maxloc_row, maxloc_col = np.unravel_index(maxloc, energy.shape) Q1a_index = CR_alpha[maxloc_row] Q3a_index = CR_alpha[maxloc_col] Q1a = gam[:, Q1a_index] Q3a = gam[:, Q3a_index] Q1a_psi = np.sqrt(np.gradient(Q1a, 1 / (M - 1))) Q3a_psi = np.sqrt(np.gradient(Q3a, 1 / (M - 1))) # check quartile and quantile going in same direction tst = trapz(v[:, Q1a_index] * v[:, Q1_index]) if tst < 0: Q1a = gam[:, Q3a_index] Q3a = gam[:, Q1a_index] # compute phase whiskers IQR = dx[Q1_index] + dx[Q3_index] v1 = v[:, Q3a_index] v3 = v[:, Q3a_index] upper_v = v3 + k_a * IQR * v3 / np.sqrt(trapz(v3**2, time)) lower_v = v1 + k_a * IQR * v1 / np.sqrt(trapz(v1**2, time)) upper_dis = np.sqrt(trapz(v3**2, time)) lower_dis = np.sqrt(trapz(v1**2, time)) whisker_dis = max(upper_dis, lower_dis) # identify phase outliers outlier_index = np.array([]) for i in range(0, N): if dx[dx_ordering[N - 1 - i]] > whisker_dis: outlier_index = np.append(outlier_index, dx_ordering[N + 1 - i]) # identify phase extremes distance_to_upper = np.full(N, np.inf) distance_to_lower = np.full(N, np.inf) out_50_CR = np.setdiff1d(np.arange(0, N), outlier_index) for i in range(0, out_50_CR.shape[0]): j = out_50_CR[i] distance_to_upper[j] = np.sqrt(trapz((upper_v - v[:, j])**2, time)) distance_to_lower[j] = np.sqrt(trapz((lower_v - v[:, j])**2, time)) max_index = distance_to_upper.argmin() min_index = distance_to_lower.argmin() minn = gam[:, min_index] maxx = gam[:, max_index] min_psi = psi[:, min_index] max_psi = psi[:, max_index] s = np.linspace(0, 1, 100) Fs2 = np.zeros((time.shape[0], 595)) Fs2[:, 0] = (1 - s[0]) * (minn - t) + s[0] * (Q1 - t) for j in range(1, 100): Fs2[:, j] = (1 - s[j]) * (minn - t) + s[j] * (Q1a - t) Fs2[:, 98 + j] = (1 - s[j]) * (Q1a - t) + s[j] * (Q1 - t) Fs2[:, 197 + j] = (1 - s[j]) * (Q1 - t) + s[j] * (median_x - t) Fs2[:, 296 + j] = (1 - s[j]) * (median_x - t) + s[j] * (Q3 - t) Fs2[:, 395 + j] = (1 - s[j]) * (Q3 - t) + s[j] * (Q3a - t) Fs2[:, 494 + j] = (1 - s[j]) * (Q3a - t) + s[j] * (maxx - t) d1 = np.sqrt(trapz(psi_median * Q1_psi, time)) d1a = np.sqrt(trapz(Q1_psi * Q1a_psi, time)) dl = np.sqrt(trapz(Q1a_psi * min_psi, time)) d3 = np.sqrt(trapz((psi_median * Q3_psi), time)) d3a = np.sqrt(trapz((Q3_psi * Q3a_psi), time)) du = np.sqrt(trapz((Q3a_psi * max_psi), time)) part1 = np.linspace(-d1 - d1a - dl, -d1 - d1a, 100) part2 = np.linspace(-d1 - d1a, -d1, 100) part3 = np.linspace(-d1, 0, 100) part4 = np.linspace(0, d3, 100) part5 = np.linspace(d3, d3 + d3a, 100) part6 = np.linspace(d3 + d3a, d3 + d3a + du, 100) allparts = np.hstack((part1, part2[1:100], part3[1:100], part4[1:100], part5[1:100], part6[1:100])) U, V = np.meshgrid(time, allparts) U = np.transpose(U) V = np.transpose(V) self.Q1 = Q1 self.Q3 = Q3 self.Q1a = Q1a self.Q3a = Q3a self.minn = minn self.maxx = maxx self.outlier_index = outlier_index self.median_x = median_x self.psi_media = psi_median plt = collections.namedtuple('plt', [ 'U', 'V', 'Fs2', 'allparts', 'd1', 'd1a', 'dl', 'd3', 'd3a', 'du', 'Q1_psi', 'Q3_psi' ]) self.plt = plt(U, V, Fs2, allparts, d1, d1a, dl, d3, d3a, du, Q1a_psi, Q3a_psi) return
# In[21]: sns.pairplot(data) # In[90]: import matplotlib.pyplot as plt import plotly.graph_objs as go import numpy as np x = np.random.randn(2000) y = np.random.randn(2000) plt([ go.Histogram2dContour(x=x, y=y, contours=dict(coloring='heatmap')), go.Scatter(x=x, y=y, mode='markers', marker=dict(color='white', size=3)) ], show_link=False) # In[5]: import plotly.offline as offline import plotly.graph_objs as go offline.plot( { 'data': [{ 'y': [14, 22, 30, 44] }], 'layout': { 'title': 'Offline Plotly', 'font': dict(size=16)
def construct_boxplot(self, alpha=.05, k_a=1): """ This function constructs the amplitude boxplot using the elastic square-root slope (srsf) framework. :param alpha: quantile value (e.g.,=.05, i.e., 95\%) :param k_a: scalar for outlier cutoff (e.g.,=1) """ if self.warp_data.rsamps: ft = self.warp_data.fs f_median = self.warp_data.fmean qt = self.warp_data.qs q_median = self.warp_data.mqn time = self.warp_data.time else: ft = self.warp_data.fn f_median = self.warp_data.fmean qt = self.warp_data.qn q_median = self.warp_data.mqn time = self.warp_data.time N = ft.shape[1] lam = 0.5 # compute amplitude distances dy = np.zeros(N) for i in range(0, N): dy[i] = np.sqrt(trapz((q_median - qt[:, i])**2, time)) dy_ordering = dy.argsort() CR_50 = dy_ordering[0:np.ceil(N / 2).astype('int')] tmp = dy[CR_50] m = tmp.max() # identify amplitude quartiles angle = np.zeros((CR_50.shape[0], CR_50.shape[0])) energy = np.zeros((CR_50.shape[0], CR_50.shape[0])) for i in range(0, CR_50.shape[0] - 1): for j in range(i + 1, CR_50.shape[0]): q1 = qt[:, CR_50[i]] - q_median q3 = qt[:, CR_50[j]] - q_median q1 = q1 / np.sqrt(trapz(q1**2, time)) q3 = q3 / np.sqrt(trapz(q3**2, time)) angle[i, j] = trapz(q1 * q3, time) energy[i, j] = (1 - lam) * (dy[CR_50[i]] / m + dy[CR_50[j]] / m) - lam * (angle[i, j] + 1) maxloc = energy.argmax() maxloc_row, maxloc_col = np.unravel_index(maxloc, energy.shape) Q1_index = CR_50[maxloc_row] Q3_index = CR_50[maxloc_col] Q1_q = qt[:, Q1_index] Q3_q = qt[:, Q3_index] Q1 = ft[:, Q1_index] Q3 = ft[:, Q3_index] # identify amplitude quantiles dy_ordering = dy.argsort() CR_alpha = dy_ordering[0:np.round(N * (1 - alpha)).astype('int')] tmp = dy[CR_alpha] m = tmp.max() angle = np.zeros((CR_alpha.shape[0], CR_alpha.shape[0])) energy = np.zeros((CR_alpha.shape[0], CR_alpha.shape[0])) for i in range(0, CR_alpha.shape[0] - 1): for j in range(i + 1, CR_alpha.shape[0]): q1 = qt[:, CR_alpha[i]] - q_median q3 = qt[:, CR_alpha[j]] - q_median q1 /= np.sqrt(trapz(q1**2, time)) q3 /= np.sqrt(trapz(q3**2, time)) angle[i, j] = trapz(q1 * q3, time) energy[i, j] = (1 - lam) * (dy[CR_alpha[i]] / m + dy[CR_alpha[j]] / m) - lam * (angle[i, j] + 1) maxloc = energy.argmax() maxloc_row, maxloc_col = np.unravel_index(maxloc, energy.shape) Q1a_index = CR_alpha[maxloc_row] Q3a_index = CR_alpha[maxloc_col] Q1a_q = qt[:, Q1a_index] Q3a_q = qt[:, Q3a_index] Q1a = ft[:, Q1a_index] Q3a = ft[:, Q3a_index] # compute amplitude whiskers IQR = dy[Q1_index] + dy[Q3_index] v1 = Q1_q - q_median v3 = Q3_q - q_median upper_q = Q3_q + k_a * IQR * v3 / np.sqrt(trapz(v3**2, time)) lower_q = Q1_q + k_a * IQR * v1 / np.sqrt(trapz(v1**2, time)) upper_dis = np.sqrt(trapz((upper_q - q_median)**2, time)) lower_dis = np.sqrt(trapz((lower_q - q_median)**2, time)) whisker_dis = max(upper_dis, lower_dis) # identify amplitude outliers outlier_index = np.array([]) for i in range(0, N): if dy[dy_ordering[N - i - 1]] > whisker_dis: outlier_index = np.append(outlier_index, dy[dy_ordering[N + 1 - i]]) # identify amplitude extremes distance_to_upper = np.full(N, np.inf) distance_to_lower = np.full(N, np.inf) out_50_CR = np.setdiff1d(np.arange(0, N), outlier_index) for i in range(0, out_50_CR.shape[0]): j = out_50_CR[i] distance_to_upper[j] = np.sqrt(trapz((upper_q - qt[:, j])**2, time)) distance_to_lower[j] = np.sqrt(trapz((lower_q - qt[:, j])**2, time)) max_index = distance_to_upper.argmin() min_index = distance_to_lower.argmin() min_q = qt[:, min_index] max_q = qt[:, max_index] minn = ft[:, min_index] maxx = ft[:, max_index] s = np.linspace(0, 1, 100) Fs2 = np.zeros((time.shape[0], 595)) Fs2[:, 0] = (1 - s[0]) * minn + s[0] * Q1 for j in range(1, 100): Fs2[:, j] = (1 - s[j]) * minn + s[j] * Q1a Fs2[:, 98 + j] = (1 - s[j]) * Q1a + s[j] * Q1 Fs2[:, 197 + j] = (1 - s[j]) * Q1 + s[j] * f_median Fs2[:, 296 + j] = (1 - s[j]) * f_median + s[j] * Q3 Fs2[:, 395 + j] = (1 - s[j]) * Q3 + s[j] * Q3a Fs2[:, 494 + j] = (1 - s[j]) * Q3a + s[j] * maxx d1 = np.sqrt(trapz((q_median - Q1_q)**2, time)) d1a = np.sqrt(trapz((Q1_q - Q1a_q)**2, time)) dl = np.sqrt(trapz((Q1a_q - min_q)**2, time)) d3 = np.sqrt(trapz((q_median - Q3_q)**2, time)) d3a = np.sqrt(trapz((Q3_q - Q3a_q)**2, time)) du = np.sqrt(trapz((Q3a_q - max_q)**2, time)) part1 = np.linspace(-d1 - d1a - dl, -d1 - d1a, 100) part2 = np.linspace(-d1 - d1a, -d1, 100) part3 = np.linspace(-d1, 0, 100) part4 = np.linspace(0, d3, 100) part5 = np.linspace(d3, d3 + d3a, 100) part6 = np.linspace(d3 + d3a, d3 + d3a + du, 100) allparts = np.hstack((part1, part2[1:100], part3[1:100], part4[1:100], part5[1:100], part6[1:100])) U, V = np.meshgrid(time, allparts) U = np.transpose(U) V = np.transpose(V) self.Q1 = Q1 self.Q3 = Q3 self.Q1a = Q1a self.Q3a = Q3a self.minn = minn self.maxx = maxx self.outlier_index = outlier_index self.f_median = f_median self.q_median = q_median plt = collections.namedtuple('plt', [ 'U', 'V', 'Fs2', 'allparts', 'd1', 'd1a', 'dl', 'd3', 'd3a', 'du', 'Q1q', 'Q3q' ]) self.plt = plt(U, V, Fs2, allparts, d1, d1a, dl, d3, d3a, du, Q1a_q, Q3a_q) return