def to_scale_sound(self, tuning, f0=440., num_harmonics=6, dur=0.5, sr=44100.): """ :: Realize given tuning system as a scale, starting at frequency f0=440., using num_harmonics=6 complex tones with duration dur=0.5 seconds, and default sample rate sr=44100Hz. """ p = default_signal_params() p['num_harmonics'] = num_harmonics p['sr'] = sr p['num_points'] = int(round(dur * sr)) p.pop('f0') x = [] num_samples = p['num_points'] ramp = pylab.r_[pylab.array(pylab.linspace(0, 1, 100)), pylab.linspace(1, 0, num_samples - 100)] for rat in tuning: x = pylab.r_[x, ramp * harmonics(f0=f0 * rat, **p)] return x
def plotModel2D(self,X=[],Y=[],xLabel="",yLabel="",title="",fName=""): #fig = plt.figure(figsize=(6,4),dpi=100) plt.close() # 真値のプロット(クラスごとにマーカーを変更) plt.plot(X[Y[:,0]==0,0],X[Y[:,0]==0,1],'cx',markersize=14,label="ラベル0") plt.plot(X[Y[:,0]==1,0],X[Y[:,0]==1,1],'m.',markersize=14,label="ラベル1") # 予測値のメッシュの計算 X1,X2 = plt.meshgrid(plt.linspace(np.min(X[:,0]),np.max(X[:,0]),50),plt.linspace(np.min(X[:,1]),np.max(X[:,1]),50)) Xmesh = np.hstack([np.reshape(X1,[-1,1]),np.reshape(X2,[-1,1])]) Pmesh,_,_ = self.predict(Xmesh) Pmesh = np.reshape(Pmesh,X1.shape) # 予測値のプロット CS = plt.contourf(X1,X2,Pmesh,linewidths=2,cmap="bwr",alpha=0.3,vmin=0,vmax=1) # カラーバー CB = plt.colorbar(CS) CB.ax.tick_params(labelsize=14) # 各軸の範囲とラベルの設定 plt.xlim([np.min(X[:,0]),np.max(X[:,0])]) plt.ylim([np.min(X[:,1]),np.max(X[:,1])]) plt.title(title,fontsize=14) plt.xlabel(xLabel,fontsize=14) plt.ylabel(yLabel,fontsize=14) plt.legend() # グラフの表示またはファイルへの保存 if len(fName): plt.savefig(fName) else: plt.show()
def main(datafile, err): # load a *.txt data file (see spinmob wiki for formatting rules) d = spinmob.data.load(datafile) # create a fitter object (with a reasonable guess for the Rutherford file) f = spinmob.data.fitter('a*(x-x0)**2+b', 'a,x0,b') # set the data and error bar ys = d.c('R_=_V/I_(ohm)') # Ohms xs = d.c('B_(mT)') / 1000 # T es = d.c('error_V5') # V es = [numpy.sqrt(e**2 + (y*1e-4)**2 + (y*1e-4)**2) for y, e in zip(ys, es)] es = pylab.array(es) / 1.2 a = -(ys[-1]-ys[0])/(xs[-1]**2-xs[0]**2) x0 = 0 b = 65 f.set_data(xs, ys, es) f.set(a=a, x0=x0, b=b) f.fit() res1 = f.results[0] fct1 = lambda x: res1[0] * (x - res1[1])**2 + res1[2] plt.clf() fig = pylab.figure() gs = gridspec.GridSpec(4, 4) TR = fig.add_subplot(gs[1:, :]) TR.errorbar(xs, ys, es, fmt=',') Xs = pylab.linspace(min(xs), max(xs)) TR.plot(Xs, fct1(Xs), '-', color='red') pylab.xlabel('Magnetic field ($\\times10^{-1}\\mathrm{T}$)') pylab.xticks(pylab.linspace(0, 0.5, 6), ['{:1.0f}'.format(i) for i in range(6)]) pylab.xlim(min(xs), max(xs)) pylab.ylabel('Resistance ($\\Omega$)') residual1 = fig.add_subplot(gs[0, :]) rs = [(y - fct1(x))/e for x, y, e in zip(xs, ys, es)] residual1.errorbar(xs, rs, 1, fmt=',', color='blue') xs = pylab.linspace(min(xs), max(xs), 3) residual1.plot(xs, [0 for x in xs], '-', color='red') residual1.xaxis.tick_top() pylab.xticks([]) pylab.xlim(min(xs), max(xs)) pylab.yticks([]) pylab.ylabel('Studentized\nresidual') plt.savefig('../Graphs/Magnetoresistance/Fit.png') plt.savefig('../Graphs/Magnetoresistance/Fit.pdf') return f
def plotImage(method): plt.figure() # linespace generate an array from start and stop value # with requested number of elements. Example 10 elements or 100 elements. x = plt.linspace(-10, 10, 100) if (method == "sigmoid"): plt.plot(x, sigmoid(x), 'b', label='linspace(-10,10,10)') elif (method == "dsigmoid"): plt.plot(x, dsigmoid(x), 'b', label='linspace(-10,10,10)') elif (method == "softmax"): plt.plot(x, softmax(x), 'b', label='linspace(-10,10,10)') elif (method == "ReLU"): plt.plot(x, ReLU(x), 'b') elif (method == "dReLU"): plt.plot(x, dReLU(x), 'b') else: return # Draw the grid line in background. plt.grid() # 顯現圖示的Title plt.title(method) # 顯現 the Sigmoid formula # plt.text(4, 0.8, r'$\sigma(x)=\frac{1}{1+e^{-x}}$', fontsize=15) # #resize the X and Y axes # plt.gca().xaxis.set_major_locator(plt.MultipleLocator(1)) # plt.gca().yaxis.set_major_locator(plt.MultipleLocator(0.1)) # create the graph plt.show()
def test(): time = plt.linspace(0,10,1000) #single-ball-simulation initials = [4,0,0,0] pos, vel = Cromer_1d(initials, singleforce, time) plt.plot(pos,vel)
def plot_rasters(event_locked, **kwargs): v_spacing = kwargs.get("vertical_spacing", 0.05) time_range = kwargs.get("time_range", (-0.100, 0.500)) n_bins = kwargs.get("n_bins", 25) bin_color = kwargs.get("bin_color", '0.5') n_events = len(event_locked) #print("Plotting %d events" % (n_events)) #plt.figure() plt.hold(True) plt.axvline(0.0, zorder=-500) #alpha=0.5) ts = [] for i in range(0, n_events): y = (n_events - i) evt = event_locked[i] for t in evt: plt.plot(t, y, '|k') ts.append(t) if len(ts) != 0: plt.hist(ts, bins=plt.linspace(time_range[0], time_range[1], n_bins), color=bin_color, zorder=-500) # bin into 24 bins plt.xlim(time_range)
def yPred(X, Y, M=1): pl.plot(X.T.tolist()[0], Y.T.tolist()[0], 'gs') phi = createTFeatures(X, M) w = OLS(X, Y, M) pts = np.array([[p] for p in pl.linspace(min(X), max(X), 100)]) yhat = np.dot(createTFeatures(pts, M), w) return yhat
def make_fig(Ts, Rs, es, a, b, c, d, fct1, fct2, outfile): fig = pylab.figure() gs = gridspec.GridSpec(4, 4) TR = fig.add_subplot(gs[:, :]) TR.errorbar(Ts, Rs, es, fmt=',', color='blue') #TR.plot(Ts, Rs, '.', color='blue') xs = pylab.linspace(a, b, 100) xs = pylab.linspace(c, d, 100) pylab.xlim(160, 400) pylab.yticks(list(pylab.linspace(0, 25e-2, 6)), ['{:.0f}'.format(i) for i in pylab.linspace(0, 25, 6)]) #pylab.ylim(0, 2e-1) pylab.xlabel('Temperature (K)') pylab.ylabel('Hall coefficient ($10^{-2}\\,\\mathrm{m}^3/\\mathrm{C}$)') #room_T, nominal_R_H, nRHe = 293, 1.47e-2*5e-3/1e-3, 1e-4 #TR.errorbar([room_T], [nominal_R_H], nRHe, fmt=',', color='red') if not outfile: outfile = 'Fits' fig.savefig('../Graphs/Hall/'+outfile+'.png') fig.savefig('../Graphs/Hall/'+outfile+'.pdf')
def plot_data(data): """ Creates a 2D plot of the input data. :param data: The data to be plotted :type data: list of [float | int] :return: """ x = plt.linspace(0, 1, len(data)) y = data figure() plt.plot(x, y, 'r')
def stochkit(model, start=0, finish=10, points=10, n_runs=20, path='/opt/conda/bin/'): set_path('stochkit_ssa', path) sims = StochKitSimulator(model, linspace(start, finish, points + 1)).run(n_runs=n_runs).dataframe sims = modes(sims, n_runs) return {'sims': sims['sims'], 'avrg': sims['avrg'], 'stdv': sims['stdv']}
def make_fig(Ts, Rs, Ges, a, b, c, d, fct1, fct2, outfile=None): fig = pylab.figure() gs = gridspec.GridSpec(4, 4) TR = fig.add_subplot(gs[1:, :]) TR.errorbar(Ts, 1/Rs, Ges[0], fmt=',') xs = pylab.linspace(a, b, 100) TR.plot(xs, 1/fct1(xs), '-', color='red') xs = pylab.linspace(c, d, 100) TR.plot(xs, 1/fct2(xs), '-', color='red') pylab.xlim(225, 400) pylab.ylim(0, 0.05) pylab.xlabel('Temperature (K)') pylab.ylabel('Conductance ($\\Omega^{-1}$)') residual1 = fig.add_subplot(gs[0, :2]) xs = [x for x in Ts if a <= x <= b] ys = [(1/y - 1/fct1(x))/e for x, y, e in zip(Ts, Rs, Ges[0]) if a <= x <= b] residual1.errorbar(xs, ys, 1, fmt=',', color='blue') xs = pylab.linspace(a, b, 100) residual1.plot(xs, [0 for x in xs], '-', color='red') residual1.xaxis.tick_top() pylab.xlim(a, b) pylab.xticks([a, b-1]) pylab.yticks([]) pylab.ylim(-3, 3) pylab.ylabel('Studentized\nresidual') residual2 = fig.add_subplot(gs[0, 2:]) xs = [x for x in Ts if c <= x <= d] ys = [(1/y - 1/fct2(x))/e for x, y, e in zip(Ts, Rs, Ges[1]) if c <= x <= d] residual2.errorbar(xs, ys, 1, fmt=',', color='blue') xs = pylab.linspace(c, d, 100) residual2.plot(xs, [0 for x in xs], '-', color='red') residual2.xaxis.tick_top() pylab.xticks([c+1, d]) pylab.yticks([]) pylab.ylim(-3, 3) pylab.xlim(c, d) if not outfile: outfile = 'Fits' fig.savefig('../Graphs/GvsT/'+outfile+'.png') fig.savefig('../Graphs/GvsT/'+outfile+'.pdf')
def bngNF(model, start=0, finish=10, points=10, n_runs=20, path='/opt/conda/bin/'): set_path('bng', path) sims = BngSimulator(model, linspace(start, finish, points + 1)).run(method='nf', n_runs=n_runs).dataframe sims = modes(sims, n_runs) return {'sims': sims['sims'], 'avrg': sims['avrg'], 'stdv': sims['stdv']}
def get_colors_pastel(n): """ Return n pastel colours. """ base = na.asarray([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) if n <= 3: return base[0:n] # how many new colours to we need to insert between # red and green and between green and blue? needed = (((n - 3) + 1) / 2, (n - 3) / 2) colours = [] for start in (0, 1): for x in mpl.linspace(0, 1, needed[start] + 2): colours.append((base[start] * (1.0 - x)) + (base[start + 1] * x)) return colours[0:n]
def plot(yhat): pts = np.array([[p] for p in pl.linspace(min(X), max(X), 100)]) true = np.sin(2 * np.pi * pts) DF = pd.DataFrame({ 'X': pd.Series(X.flatten()), 'Y': pd.Series(Y.flatten()), 'axis': pd.Series(pts.flatten()), 'yhat': pd.Series(yhat.flatten()), 'true': pd.Series(true.flatten()) }) mpl.rcParams["figure.figsize"] = "2, 4" print ggplot(DF, aes(x='axis', y='yhat')) + geom_line( color="red", size=4) + geom_line( aes(y='true'), color='green', size=2) + geom_point( aes(x='X', y='Y'), size=200, alpha=0.5) + xlim( -0.1, 1.1) + xlab('X') + ylab('Y')
def variable_phase_vocoder(D, times_steps, hop_length=None): n_fft = 2 * (D.shape[0] - 1) if hop_length is None: hop_length = int(n_fft // 4) # time_steps = P.arange(0, D.shape[1], rate, dtype=P.double) # time_steps = P.concatenate([ # P.arange(0, D.shape[1]/2, .5, dtype=P.double), # P.arange(D.shape[1]/2, D.shape[1], 2, dtype=P.double) # ]) # Create an empty output array d_stretch = P.zeros((D.shape[0], len(time_steps)), D.dtype, order='F') # Expected phase advance in each bin phi_advance = P.linspace(0, P.pi * hop_length, D.shape[0]) # Phase accumulator; initialize to the first sample phase_acc = P.angle(D[:, 0]) # Pad 0 columns to simplify boundary logic D = P.pad(D, [(0, 0), (0, 2)], mode='constant') for (t, step) in enumerate(time_steps): columns = D[:, int(step):int(step + 2)] # Weighting for linear magnitude interpolation alpha = P.mod(step, 1.0) mag = ((1.0 - alpha) * abs(columns[:, 0]) + alpha * abs(columns[:, 1])) # Store to output array d_stretch[:, t] = mag * P.exp(1.j * phase_acc) # Compute phase advance dphase = (P.angle(columns[:, 1]) - P.angle(columns[:, 0]) - phi_advance) # Wrap to -pi:pi range dphase = dphase - 2.0 * P.pi * P.around(dphase / (2.0 * P.pi)) # Accumulate phase phase_acc += phi_advance + dphase return d_stretch
def _ichroma(self, V, **kwargs): """ :: Inverse chromagram transform. Make a signal from a folded constant-Q transform. """ if not (self._have_hcqft or self._have_cqft): return None a, b = self.HCQFT.shape if self._have_hcqft else self.CQFT.shape complete_octaves = a / self.nbpo # integer division, number of complete octaves if P.remainder(a, self.nbpo): complete_octaves += 1 X = P.repeat(V, complete_octaves, 0)[:a, :] # truncate if necessary X /= X.max() X *= P.atleast_2d(P.linspace(1, 0, X.shape[0])).T # weight the spectrum self.x_hat = self._icqft(X, **kwargs) return self.x_hat
def test_interp(): # Testing interpolation nn = 33 # number of nodes ne = 65 # number of evaluation points x = cos(pi*(1+array(range(nn)))/(nn+1)) xp = linspace(-1,1,ne) rbf_list = ['mq','gauss','phs'] ep_list = [3.,5.,7.,9.] m = 3 for ep in ep_list: for ff in rbf_list: # 1D d = array([x]).T p = array([xp]).T rhs = testfunction(d) exact = testfunction(p) Pf = rbfinterp(d,rhs,p,ff,shapeparm = ep, power = m) err = norm(Pf-exact) print("1D interp, {}, shape = {}, L2 error = {:e}".format(ff,ep,err)) # 2D d = array([x,x]).T p = array([xp,xp]).T rhs = testfunction(d) exact = testfunction(p) Pf = rbfinterp(d,rhs,p,ff,shapeparm = ep, power = m) err = norm(Pf-exact) print("2D interp, {}, shape = {}, L2 error = {:e}".format(ff,ep,err)) # 3D d = array([x,x,x]).T p = array([xp,xp,xp]).T rhs = testfunction(d) exact = testfunction(p) Pf = rbfinterp(d,rhs,p,ff,shapeparm = ep, power = m) err = norm(Pf-exact) print("3D interp, {}, shape = {}, L2 error = {:e}".format(ff,ep,err)) print("----------------------------------------------------------")
def display_sigmoid(parameters): # plot the Sigmoid function using the parameter coefficient estimate from a logistic regression model print('\n') a = pylab.linspace(0, 160, 160) b1 = 1 / (1 + np.exp(-(parameters.values[0][1] + a * parameters.values[1][1]))) b2 = 1 / (1 + np.exp(-(parameters.values[0][1] + a * parameters.values[1][1] + parameters.values[2][1]))) pylab.rcParams['figure.figsize'] = 15, 10 pylab.xticks(size=15) pylab.yticks(size=15) pylab.plot(a, b1, label='Community Exposure') pylab.plot(a, b2, label='Travel Exposure') pylab.xlabel('Approximated Age in Years', fontsize=20) pylab.ylabel('Probability of COVID-19 Death', fontsize=20) pylab.legend(loc='upper left', prop={'size': 20}) pylab.text(50, 0.75, r'$\sigma(x)=\frac{1}{1+e^{-x}}$', fontsize=25) pylab.grid() pylab.title('Sigmoid Function', fontsize=20) pylab.show()
def plot_het_concordance(a): x = P.linspace(0, 1, a.shape[0]) y = a[:, 1] / (a[:, 0] + 1e-15) P.figure(1) P.clf() ax = P.subplot(111, title='IMPUTE2-PRIMAL Discordance Rate', xlabel='IMPUTE2 Confidence', ylabel='Discordance Rate') ax.plot(x, y, 'b.-') P.xlim([min(x[-20:]), 1.01]) P.grid(True) P.ylim([0, max(y[-20:])]) P.hold(True) f = np.polyfit(1 - x[-10:], y[-10:], 1) yFit = np.polyval(f, 1 - x) # ax.plot(x, 0.3 * (1 - x) + 0.005, 'g--') # Regression line ax.plot(x, yFit, 'g--') # Regression line for item in [ax.title, ax.xaxis.label, ax.yaxis.label]: item.set_fontsize(18) for item in (ax.get_xticklabels() + ax.get_yticklabels()): item.set_fontsize(14) return x, y, f
def gaussianFit2(self): """ It does not work """ data = P.hist(self.zMass, bins = 100) # Equation for Gaussian def f(x, a, b, c): return a * P.exp(-(x - b)**2.0 / (2 * c**2)) # Generate data from bins as a set of points x = [0.5 * (data[1][i] + data[1][i+1]) for i in xrange(len(data[1])-1)] y = data[0] popt, pcov = optimize.curve_fit(f, x, y) x_fit = P.linspace(x[0], x[-1], 100) y_fit = f(x_fit, *popt) P.plot(x_fit, y_fit, lw=4, color="r") P.show()
def test_dmatrix(): # Unit tests for the dmatrix function x = linspace(0,1,5) # Test 1D without formatting input, data is 1D, shape is (N,) data = x DM = dmatrix(data) print(DM) # Test 1D with x in wrong orientation (dim by N pts), data is 2D array data = array([x]) DM = dmatrix(data) print(DM) # Test 1D with x in correct orientation (N by dim pts), data is 2D array data = array([x]).T DM = dmatrix(data) print(DM) # Test 2D with x in wrong orientation (dim by N pts), data is 2D array data = array([x,x]) DM = dmatrix(data) print(DM) # Test 2D with x in correct orientation (N by dim pts), data is 2D array data = array([x,x]).T DM = dmatrix(data) print(DM) # Test 3D with x in wrong orientation (dim by N pts), data is 2D array data = array([x,x,x]) DM = dmatrix(data) print(DM) # Test 3D with x in correct orientation (N by dim pts), data is 2D array data = array([x,x,x]).T DM = dmatrix(data) print(DM)
def run(self, z, N = 2**14, self_steep = False): # euristic for setting the timescale dts = [p['dt'].to('ps').magnitude for p in self.pulses] timescale = max(dts)*5e2 self.t = np.linspace(-timescale,timescale,N) * ps t_step = self.t[1]-self.t[0] self.w = fftfreq(N,t_step)*2*pi w_step = self.w[2]-self.w[1] self.z = pl.linspace(0,z.to('m').magnitude,10)*Q_('m') print(self.init_report()) ## ToDo Verify all pulses are within the simulation self.a0 = np.sum(np.c_[[self.generate_pulse(**p) for p in self.pulses]],0) ## Generate operators dw = self.w dispersion = 1/2. *self.beta[1] * dw**2 + 1./6 *self.beta[2] * dw**3 nlinear = self.gamma if self_steep: self_steep = self.gamma/self.w0.to('1/ps').magnitude else: self_steep = 0 ## Start simulation self.sols = nl.split_step(self.a0, self.z, w_op = dispersion, nlin = nlinear, dt = t_step.to('ps').magnitude, self_steep = self_steep) self.results = Solution(self.sols, self.t, fftshift(self.w.to('GHz').magnitude)*Q_('GHz'), z = self.z) self.results.l0 = self.l0 return self.sols
print(brojac) #arr = numpy.array([tisina_int, zvuk_int]) tisina_sred = numpy.mean(tisina_int) print(tisina_sred) tisina_dev = numpy.std(tisina_int) print(tisina_dev) zvuk_sred = numpy.mean(zvuk_int) print(zvuk_sred) zvuk_dev = numpy.std(zvuk_int) print(zvuk_dev) brojevi = pl.linspace(5, 19, 15) time = pl.linspace(1, length, length) pl.subplot(211) pl.plot(time, desni) pl.subplot(212) pl.plot(time, proba) pl.show() #TODO # odvajanje intervala # aproksimacija sinusoide
#Sigmoid 數學函數表示方式 #sigmoid = lambda x: 1 / (1 + np.exp(-x)) def sigmoid(x): return (1 / (1 + np.exp(-x))) #Sigmoid 微分 def dsigmoid(x): return (x * (1 - x)) # linespace generate an array from start and stop value # with requested number of elements. Example 10 elements or 100 elements. x = plt.linspace(-10, 10, 100) # prepare the plot, associate the color r(ed) or b(lue) and the label plt.plot(x, sigmoid(x), 'b', label='linspace(-10,10,10)') # Draw the grid line in background. plt.grid() # 顯現圖示的Title plt.title('Sigmoid Function') # 顯現 the Sigmoid formula plt.text(4, 0.8, r'$\sigma(x)=\frac{1}{1+e^{-x}}$', fontsize=15) #resize the X and Y axes plt.gca().xaxis.set_major_locator(plt.MultipleLocator(1))
# -*- coding:utf-8 -*- # Author: hankcs # Date: 2019-02-26 15:16 # 《自然语言处理入门》13.2 深度学习与优势 # 配套书籍:http://nlp.hankcs.com/book.php # 讨论答疑:https://bbs.hankcs.com/ from matplotlib import pylab as plt import numpy as np sigmoid = lambda x: 1 / (1 + np.exp(-x)) x = plt.linspace(-10, 10, 10000) plt.plot(x, sigmoid(x), 'b') plt.grid() plt.title(r'$\sigma(x)=\frac{1}{1+e^{-x}}$') plt.xlabel('x') plt.ylabel('y') plt.savefig('sigmoid.png') plt.show()
def drawFig(self, img_grid): # figure properties fig = pb.figure(figsize=(10, 6)) row_length = len(out_row_vals) col_length = len(out_col_vals) gs = matplotlib.gridspec.GridSpec( row_length, col_length, wspace=.05, hspace=.05) # +1 for the colormap area """figure processing""" img_grid_list = img_grid.tolist() # get min and max to set up colormap scale, and loop all again to plot images MIN = pb.array(img_grid).min() MAX = pb.array(img_grid).max() for out_row_index in range(len(out_row_vals)): for out_col_index in range(len(out_col_vals)): ax = fig.add_subplot(gs[row_length - 1 - out_row_index, out_col_index]) ax.hold(True) img_grid_list[out_row_index][out_col_index] = ax.contourf( img_grid[out_row_index][out_col_index], levels=pb.linspace(MIN, MAX, 50), extent=[ in_col_vals.min(), in_col_vals.max(), in_row_vals.min(), in_row_vals.max() ], vmin=MIN, vmax=MAX) # set ticks and labels of axis (no number in legend for graphs not on borders): # for the x axis: xticks = in_col_vals ax.set_xticks(xticks) if (out_row_index > 0): #< row_length - 1): ax.set_xticklabels([]) else: ax.set_xlabel(in_col_label + "\n\n" + out_col_label + "=" + str(out_col_vals[out_col_index]) ) # , fontsize='xx-large') ax.set_xticklabels(map( str, xticks)) # , fontsize='xx-large') #in_col_val # for the y axis: yticks = in_row_vals # from in_row_val ax.set_yticks(yticks) if (out_col_index > 0): ax.set_yticklabels([]) else: ax.set_ylabel( "|" + out_row_label + "|=" + str(out_row_vals[out_row_index]) + ' ' + in_row_label, rotation='horizontal') # , fontsize='xx-large') ax.set_yticklabels(map( str, yticks)) # , fontsize='xx-large') #in_row_val # setup colorbar ax = pb.axes([0.92, 0.1, 0.01, 0.8]) # guess [left, bottom, width, heigth]. in percents cbar = pb.colorbar(img_grid_list[0][0], ax) # , ticks=ticksValues) pb.ion() return fig
def cons_vac(T): """ consentration is given by n(T)/N (vacant parrticle-spaces divided by total particle-spaces) """ k_b=8.617332478*1e-5;#[eV/K] boltzmanns constant deltaeps=1; #[eV] infitisemial energy for each "particle-jump" exponential = plt.exp( deltaeps/(T*k_b) ); #these values are way large. return 1.0/(exponential); try: pot = int(sys.argv[1]);#power of number of particles except: pot = input("give the power of the temperature you want in your system \n") tot_temp = 1*10**(pot); #total vacancies in system #plot_points = 1.0/float(tot_temp-1) x = plt.linspace(0,int(tot_temp),1001); n_cons = cons_vac(x); plt.plot(x,n_cons,"k-",label="n(T)/N"); plt.xlabel("temperature [K]"); plt.ylabel("consentration of vacancies"); plt.legend(numpoints=1, loc="lower right", borderpad=0.5); plt.savefig("exercise_g_img"+str(self_int)+".png"); plt.show();
def plotModel2D(self, X=[], Y=[], spptInds=[], xLabel="", yLabel="", title="", fName="", isLinePlot=False): plt.close() # 真値のプロット(クラスごとにマーカーを変更) plt.plot(X[Y[:, 0] == -1, 0], X[Y[:, 0] == -1, 1], 'cx', markerSize=14, label="カテゴリ-1") plt.plot(X[Y[:, 0] == 1, 0], X[Y[:, 0] == 1, 1], 'm.', markerSize=14, label="カテゴリ+1") # 予測値のメッシュの計算 X1, X2 = plt.meshgrid( plt.linspace(np.min(X[:, 0]), np.max(X[:, 0]), 50), plt.linspace(np.min(X[:, 1]), np.max(X[:, 1]), 50)) Xmesh = np.hstack([np.reshape(X1, [-1, 1]), np.reshape(X2, [-1, 1])]) _, Ymesh = self.predict(Xmesh) Ymesh = np.reshape(Ymesh, X1.shape) # contourプロット CS = plt.contourf(X1, X2, Ymesh, linewidths=2, cmap="bwr", alpha=0.3, vmin=-5, vmax=5) # カラーバー CB = plt.colorbar(CS) CB.ax.tick_params(labelsize=14) # サポートベクトルのプロット if len(spptInds): plt.plot(X[spptInds, 0], X[spptInds, 1], 'o', color='none', markeredgecolor='r', markersize=18, markeredgewidth=3, label="サポートベクトル") # 直線のプロット if isLinePlot: x1 = np.arange(np.min(X[:, 0]), np.max(X[:, 0]), (np.max(X[:, 0]) - np.min(X[:, 0])) / 100) x2 = -(x1 * self.w[0] + self.b) / self.w[1] plt.plot(x1, x2, 'r-', label="f(x)") # 各軸の範囲、タイトルおよびラベルの設定 plt.xlim([np.min(X[:, 0]), np.max(X[:, 0])]) plt.ylim([np.min(X[:, 1]), np.max(X[:, 1])]) plt.title(title, fontSize=14) plt.xlabel(xLabel, fontSize=14) plt.ylabel(yLabel, fontSize=14) plt.legend() # グラフの表示またはファイルへの保存 if len(fName): plt.savefig(fName) else: plt.show()
'custom_code' : ['custom_codes.hoc', 'biophys1.hoc'], } #Synaptic parameters, corresponding to a NetCon synapse built into NEURON synapseParameters = { 'idx' : 0, # insert synapse on index "0", the soma 'e' : 0., # reversal potential of synapse 'syntype' : 'Exp2Syn', # conductance based double-exponential synapse 'tau1' : 1.0, # Time constant, rise 'tau2' : 1.0, # Time constant, decay 'weight' : 0.05, # Synaptic weight 'record_current' : True, # Will enable synapse current recording } #Generate the grid in xz-plane over which we calculate local field potentials x = pl.linspace(-50, 50, 11) z = pl.linspace(-50, 50, 11) X, Z = pl.meshgrid(x, z) y = pl.zeros(X.size) #define parameters for extracellular recording electrode, using optional method electrodeParameters = { 'sigma' : 0.3, # extracellular conductivity 'x' : X.reshape(-1), # x,y,z-coordinates of contact points 'y' : y, 'z' : Z.reshape(-1), 'method' : 'som_as_point', #treat soma segment as sphere source } ################################################################################ # Main simulation procedure, setting up extracellular electrode, cell, synapse
else: return False try: savearg = int(sys.argv[1]) except IndexError: savearg = False except ValueError: savearg = False n = 1000 # number of datapoints V_0 = 0.4; V_end = 20.0 Rho_0 = 0.0; Rho_end = 2.0 T_hat = [1.15, 1.0, 0.85] # temperature [1] V_hat = plab.linspace(V_0, V_end, n) # volume [1] Rho_hat = plab.linspace(Rho_0, Rho_end, n) # density [1] P1_hat = plab.zeros((n,len(T_hat))) #P(V,T) pressure [1] P2_hat = plab.zeros((n,len(T_hat))) #P(Rho,T) pressure [1] for j in range(len(T_hat)): for i in range(n): P1_hat[i,j] = p_vt(v_=V_hat[i], t_=T_hat[j]) P2_hat[i,j] = p_rhot(rho_=Rho_hat[i], t_=T_hat[j]) #find out when the function is no longer unique if check_unique(y1=P2_hat[i-1,j], y2=P2_hat[i,j]): print "function is no longer unique for rho=%f, T=%f" %(Rho_hat[i],T_hat[j]) max_index = plab.argmax(P2_hat[0:n/2,2]) max_y = P2_hat[max_index,2] max_x = Rho_hat[max_index]
t0 = OLS(X, Y, 0) t1 = OLS(X, Y, 1) t3 = OLS(X, Y, 3) t9 = OLS(X, Y, 9) t0 = pd.Series(t0.flatten()) t1 = pd.Series(t1.flatten()) t3 = pd.Series(t3.flatten()) t9 = pd.Series(t9.flatten()) DF = pd.DataFrame({'0': t0, '1': t1, '3': t3, '9': t9}) print DF # 2.1 pts = np.array([[p] for p in pl.linspace(min(X), max(X), 100)]) Y0 = yPred(X, Y, 0) Y1 = yPred(X, Y, 1) Y3 = yPred(X, Y, 3) Y9 = yPred(X, Y, 9) plot(Y0) plot(Y1) plot(Y3) plot(Y9) # 2.2 random.seed(1)
x_label = "x-axis" #Text displayed on X axis y_label = "y-axis" #Text displayed on Y axis legend = ["Red", "Blue"] #Text displayed in "Legend" area respectively title = "Title" #Text displayed in "Title" area rows = 2 #Number of rows in subplot columns = 1 #Number of columns in subplot filename = "curve_plot.PNG" #The name of the file we will create #We can create a list to determine the scale of the graph #in the format [x-min,x-max,y-min,y-max] axis = [0, 10, 0, 150] x = mppl.linspace(start, stop, points) #We apply the previous #variables to create an #array of desired parameters y = mppl.zeros(len(x)) #We create an empty array of the same #dimensions as x for i in range(len(x)): #We fill up array y with the values y[i] = f(x[i]) #returned by f(x) mppl.plot(x, y, "r-") #Preparing the plot, the third argument #is divided into a letter and either a #'-' or a 'o' which represent a line #or a dot plot, respectively. r is for #red, b is for blue
def _plot_hdf5_model_vertical(f, component, output_filename, vmin=None, vmax=None): import matplotlib.cm import matplotlib.pylab as plt data = xarray.DataArray(f["data"][component][:], [("latitude", 90.0 - f["coordinate_0"][:]), ("longitude", f["coordinate_1"][:]), ("radius", f["coordinate_2"][:] / 1000.0)]) plt.style.use('seaborn-pastel') plt.figure(figsize=(32, 18)) plt.suptitle("Component %s - File %s" % (component, output_filename), fontsize=20) count = 12 lats = plt.linspace(data["latitude"].min(), data["latitude"].max(), count) lngs = plt.linspace(data["longitude"].min(), data["longitude"].max(), count) import lasif.colors my_colormap = lasif.colors.get_colormap("tomo_full_scale_linear_lightness") # Overwrite colormap things if given. if vmin is not None and vmax is not None: min_val_plot = vmin max_val_plot = vmax else: mean = data.mean() max_diff = max(abs(mean - data.min()), abs(data.max() - mean)) min_val_plot = mean - max_diff max_val_plot = mean + max_diff # Plotting essentially constant models. min_delta = 0.001 * abs(max_val_plot) if (max_val_plot - min_val_plot) < min_delta: max_val_plot = max_val_plot + min_delta min_val_plot = min_val_plot - min_delta for _i in range(count): plt.subplot(4, count // 2, _i + 1) x, y = np.meshgrid(data.longitude, data.radius) plot_data = data.sel(latitude=lats[_i], method="nearest") plot_data = np.ma.masked_invalid(plot_data.data) # Plot. plt.pcolormesh(x, y, plot_data.T, cmap=my_colormap, vmin=min_val_plot, vmax=max_val_plot, shading="flat") # make a colorbar and title plt.colorbar() plt.title("@Latitude: " + str(lats[_i])) for _i in range(count): plt.subplot(4, count // 2, count + _i + 1) x, y = np.meshgrid(data.latitude, data.radius) plot_data = data.sel(longitude=lngs[_i], method="nearest") plot_data = np.ma.masked_invalid(plot_data.data) # Plot. plt.pcolormesh(x, y, plot_data.T, cmap=my_colormap, vmin=min_val_plot, vmax=max_val_plot, shading="flat") # make a colorbar and title plt.colorbar() plt.title("@Longitude: " + str(lngs[_i])) plt.tight_layout(rect=(0, 0, 1, 0.95)) plt.savefig(output_filename, dpi=150) plt.close()
avgLoss *= -1 / len(height_test) print("Average loss (height): {}".format(avgLoss)) # compute accuracy accuracy = 0 for i in range(len(height_test)): prediction = 1 / (1 + np.exp(-1 * (height_test[i] * final_weights[1] + final_weights[0]))) target = basketball_test[i] if abs(target - prediction) < 0.5: accuracy += 1 accuracy *= 1 / len(height_test) print("Accuracy (height): {}".format(accuracy)) # function plot import matplotlib.pylab as pylab x = pylab.linspace(-3, 3,10) y = pylab.linspace(0,1,10) f = plt.figure() f.set_figwidth(10) f.set_figheight(6) pylab.plot(x, 1 / (1 + np.exp(-1 * (final_weights[1] * x + final_weights[0]))), 'r', label = ' x linspace(-10,10,10)') plt.scatter(height_train, basketball_train) plt.xlabel("Height (normalized)") plt.ylabel("Basketball player (true/false") plt.title("Basketball player data") plt.show() """**3.2:** Now train the model to be gender dependent by incorporating both the height and female features. Evaluate on the same test set with average loss and accuracy.
def cons_vac(T): """ consentration is given by n(T)/N (vacant parrticle-spaces divided by total particle-spaces) """ k_b=8.617332478*1e-5;#[eV/K] boltzmanns constant deltaeps=1; #[eV] infitisemial energy for each "particle-jump" exponential = plt.exp( deltaeps/(T*k_b) ); #these values are way large. return 1.0/(exponential); try: pot = int(sys.argv[1]);#power of number of particles except: pot = input("give the power of the temperature you want in your system") tot_temp = 1*10**(pot); #total vacancies in system plot_points = 1.0/float(tot_temp+1) x = plt.linspace(0,int(tot_temp), plt.ceil(plot_points)); n_cons = cons_vac(x); plt.plot(x,n_cons,"k-",label="n(T)/N"); plt.xlabel("temperature [K]"); plt.ylabel("consentration of vacancies"); plt.legend(numpoints=1, loc="lower right", borderpad=0.5); plt.savefig("exercise_g_img"+str(self_int)+".png"); plt.show();
def _plot_hdf5_model_vertical(f, component, output_filename, vmin=None, vmax=None): import matplotlib.cm import matplotlib.pylab as plt data = xarray.DataArray( f["data"][component][:], [ ("latitude", 90.0 - f["coordinate_0"][:]), ("longitude", f["coordinate_1"][:]), ("radius", f["coordinate_2"][:] / 1000.0)]) plt.style.use('seaborn-pastel') plt.figure(figsize=(32, 18)) plt.suptitle("Component %s - File %s" % (component, output_filename), fontsize=20) count = 12 lats = plt.linspace(data["latitude"].min(), data["latitude"].max(), count) lngs = plt.linspace(data["longitude"].min(), data["longitude"].max(), count) import lasif.colors my_colormap = lasif.colors.get_colormap( "tomo_full_scale_linear_lightness") # Overwrite colormap things if given. if vmin is not None and vmax is not None: min_val_plot = vmin max_val_plot = vmax else: mean = data.mean() max_diff = max(abs(mean - data.min()), abs(data.max() - mean)) min_val_plot = mean - max_diff max_val_plot = mean + max_diff # Plotting essentially constant models. min_delta = 0.001 * abs(max_val_plot) if (max_val_plot - min_val_plot) < min_delta: max_val_plot = max_val_plot + min_delta min_val_plot = min_val_plot - min_delta for _i in range(count): plt.subplot(4, count // 2, _i + 1) x, y = np.meshgrid(data.longitude, data.radius) plot_data = data.sel(latitude=lats[_i], method="nearest") plot_data = np.ma.masked_invalid(plot_data.data) # Plot. plt.pcolormesh( x, y, plot_data.T, cmap=my_colormap, vmin=min_val_plot, vmax=max_val_plot, shading="flat") # make a colorbar and title plt.colorbar() plt.title("@Latitude: " + str(lats[_i])) for _i in range(count): plt.subplot(4, count // 2, count + _i + 1) x, y = np.meshgrid(data.latitude, data.radius) plot_data = data.sel(longitude=lngs[_i], method="nearest") plot_data = np.ma.masked_invalid(plot_data.data) # Plot. plt.pcolormesh( x, y, plot_data.T, cmap=my_colormap, vmin=min_val_plot, vmax=max_val_plot, shading="flat") # make a colorbar and title plt.colorbar() plt.title("@Longitude: " + str(lngs[_i])) plt.tight_layout(rect=(0, 0, 1, 0.95)) plt.savefig(output_filename, dpi=150) plt.close()
def scipy(model, start=0, finish=10, points=10): return ScipyOdeSimulator(model, linspace(start, finish, points + 1)).run().dataframe
except: print "error in integer: exg_att#.py" def heat_capacity(Num,Temp): """ heat capacity is given by the partiaally derived energy on temperature. giving us the function: C_v = (delta_eps)**2*N*exp(-delta_eps/T*k)/(k*T**2) """ k_b=8.617332478*1e-5;#[eV/K] boltzmanns constant deltaeps=1; #[eV] infitisemial energy for each "particle-jump" exponential = plt.exp( -deltaeps/(Temp*k_b) ); #these values are way large. return Num*deltaeps**2*exponential/(k_b*Temp**2); T = plt.linspace(0,1000,1001); plt.figure("exercise h"); plt.hold(True); plt.xlabel("Temperature [K]"); plt.ylabel("Heat capacity [eV/K] (log-scale)"); #plt.title("system with N = %d"%N); for N in [10**i for i in range(3,7)]: Cv = heat_capacity(N,T); plt.plot(T,Cv,label="N=%d"%N); #plt.yscale("log") plt.legend(numpoints=1, loc="upper left", borderpad=0.5); plt.savefig("exercise_h_img"+str(self_int)+".png");
from matplotlib import rc import matplotlib.pylab as plt rc('font', **{'family': 'serif', 'serif': ['Computer Modern']}) rc('text', usetex=True) x = plt.linspace(0, 5) plt.plot(x, plt.sin(x)) plt.ylabel(r"This is $\sin(x)$", size=20) plt.show()
def bngODE(model, start=0, finish=10, points=10, path='/opt/conda/bin/'): set_path('bng', path) return BngSimulator(model, linspace(start, finish, points + 1)).run(method='ode').dataframe
def cupsoda(model, start=0, finish=10, points=10, path='/opt/conda/bin/'): set_path('cupsoda', path) return CupSodaSimulator(model, linspace(start, finish, points + 1)).run().dataframe
#!/usr/bin/env python from __future__ import print_function from pysb.simulator import ScipyOdeSimulator from matplotlib.pyplot import plot, legend, show from matplotlib.pylab import linspace from kinase_cascade import model tspan = linspace(0, 1200) print("Simulating...") yfull = ScipyOdeSimulator(model).run(tspan=tspan).all plot(tspan, yfull['ppMEK'], label='ppMEK') plot(tspan, yfull['ppERK'], label='ppERK') legend(loc='upper left') show()
def ex_k(savearg=False): n = 1000 T_hat = 0.9 rho_hat = plab.linspace(0.2, 2.0, n) V_hat = plab.linspace(0.2, 2.0, n) p_hat = p_rhot(rho_hat, T_hat)
from matplotlib import pylab as pl import math t = pl.linspace(0, 48, 49) y0 = 4.73 a = 0.65 y = y0 * math.e**-(a * t) pl.plot(t, y, label="Graph 1", linestyle="dashdot", color="red") pl.title("Fysssaaaaa") pl.legend() pl.grid() pl.show()
def get_colors(n): """ Return n shades of gray. """ return [[x, x, x] for x in mpl.linspace(0.3, 0.8, n)]
'tstopms' : 70., # stop simulation at 200 ms. 'passive' : True, 'v_init' : -65, # initial crossmembrane potential 'e_pas' : -65, # reversal potential passive mechs 'nsegs_method' : 'fixed_length', # 'fixed_length': 20, # method for setting number of segments, #'max_nsegs_length':5, #igy kapunk 52 szegmenst 'max_nsegs_length':20, #igy kapunk 27 szegmenst # 'max_nsegs_length':30, #igy kapunk 18 szegmenst # 'nsegs_method' : 'lambda_f', # 'lambda_f' : 1000, # segments are isopotential at this frequency 'custom_code' : ['/media/BA0ED4600ED416EB/agy/kCSD/progik/bs_futtat/bs_130509/active.hoc'], # will run this file } #Generate the grid in xz-plane over which we calculate local field potentials x = pl.linspace(d, d, elecnumb) z = pl.linspace(-150, 550, elecnumb) y = pl.linspace(0, 0, x.size) #define parameters for extracellular recording electrode, using optional method electrodeParameters = { 'sigma' : 0.5, # extracellular conductivity 'x' : x, # x,y,z-coordinates of contact points 'y' : y, 'z' : z, # 'method' : 'som_as_point', #treat soma segment as sphere source # 'method' : 'pointsource' 'method' : 'linesource' }
bundle = Theta_bundles[i] Theta_C[name].restore_from_bundle(bundle) items = [Golf_GPCM_IRF(params_hat[i], strokes[i], pars[i]) for i in range(18)] winners = {} for year in range(1937, 2019, 1): best = None for name in G.keys(): if year in G[name]: score = G[name][year].sum() if (best is None) or (score < best): best = score winners[year] = name P.figure(figsize=(5.5, 4)) theta = P.linspace(-6, 6, N) t = P.linspace(1937 - .5, 2018 + .5, N) i1 = 0 i2 = 0 temp = 0 for name, col in [("Arnold Palmer", 'red'), ("Jack Nicklaus", 'orange'), ("Tiger Woods", 'green')]: temp += 1 years = sorted(G[name].keys()) y1, y2 = years[0], years[-1] t = P.linspace(y1 - .5, y2 + .5, N) C = Theta_C[name] theta_hat = P.array(C.get_y_hat(t)) P.plot(t, theta_hat, linewidth=2, color=col, label=name) label = "Attended Masters" if temp == 1 else None P.scatter(years, P.array(C.get_y_hat(years)), color='blue', label=label)
def plotstuff(cell, electrode): #creating array of points and corresponding diameters along structure for i in xrange(cell.xend.size): if i == 0: xcoords = pl.array([cell.xmid[i]]) ycoords = pl.array([cell.ymid[i]]) zcoords = pl.array([cell.zmid[i]]) diams = pl.array([cell.diam[i]]) else: if cell.zmid[i] < 100 and cell.zmid[i] > -100 and \ cell.xmid[i] < 100 and cell.xmid[i] > -100: xcoords = pl.r_[xcoords, pl.linspace(cell.xstart[i], cell.xend[i], cell.length[i]*3)] ycoords = pl.r_[ycoords, pl.linspace(cell.ystart[i], cell.yend[i], cell.length[i]*3)] zcoords = pl.r_[zcoords, pl.linspace(cell.zstart[i], cell.zend[i], cell.length[i]*3)] diams = pl.r_[diams, pl.linspace(cell.diam[i], cell.diam[i], cell.length[i]*3)] #sort along depth-axis argsort = pl.argsort(ycoords) #plotting fig = pl.figure(figsize=[15, 10]) ax = fig.add_axes([0.1, 0.1, 0.533334, 0.8], frameon=False) ax.scatter(xcoords[argsort], zcoords[argsort], s=diams[argsort]**2*20, c=ycoords[argsort], edgecolors='none', cmap='gray') ax.plot(electrode.x, electrode.z, '.', marker='o', markersize=5, color='k') i = 0 limLFP = abs(electrode.LFP).max() for LFP in electrode.LFP: tvec = cell.tvec*0.6 + electrode.x[i] + 2 if abs(LFP).max() >= 1: factor = 2 color='r' elif abs(LFP).max() < 0.25: factor = 50 color='b' else: factor = 10 color='g' trace = LFP*factor + electrode.z[i] ax.plot(tvec, trace, color=color, lw = 2) i += 1 ax.plot([22, 28], [-60, -60], color='k', lw = 3) ax.text(22, -65, '10 ms') ax.plot([40, 50], [-60, -60], color='k', lw = 3) ax.text(42, -65, '10 $\mu$m') ax.plot([60, 60], [20, 30], color='r', lw=2) ax.text(62, 20, '5 mV') ax.plot([60, 60], [0, 10], color='g', lw=2) ax.text(62, 0, '1 mV') ax.plot([60, 60], [-20, -10], color='b', lw=2) ax.text(62, -20, '0.1 mV') ax.set_xticks([]) ax.set_yticks([]) ax.axis([-61, 150, -61, 400]) ax.set_title('Location-dependent extracellular spike shapes') #plotting the soma trace ax = fig.add_axes([0.75, 0.55, 0.2, 0.35]) ax.plot(cell.tvec, cell.somav) ax.set_title('Somatic action-potential') ax.set_ylabel(r'$V_\mathrm{membrane}$ (mV)')