def task2(): x = mlab.frange(-1, 1, 0.1) pylab.grid(True) for i in range(len(x) - 1): a = x[i] b = x[i + 1] x_local = mlab.frange(a, b, 0.01) y_local = [hermit(j, a, b, f(a), f(b), df(a), df(b)) for j in x_local] pylab.plot(x_local, y_local)
def _genticks(self, ta, precis='h'): '''Generating ticks and labels according to GMT time from unix time data, ta. One can set major and minor ticks via precis. ''' if precis[0] == 'h': mods = [12, 6, 4, 3, 2, 1] t = [0] * 51 # 4 ticks per inch is OK! while len(t) > 4 * self._req.figsize[0] and len(mods): mm = mods.pop() gm_1hour = tmu.upper_hour(ta[0], mod=mm) t = map(int, list(frange(gm_1hour, ta[-1], 3600 * mm))) if precis[1] == '0': zers = [] for tt in t: if time.localtime(tt).tm_hour == 0: zers.append(t.index(tt)) while len(zers): t.pop(zers.pop()) if len(t) > 4 * self._req.figsize[0]: l = [''] * len(t) else: l = [time.strftime('%H', time.localtime(int(ii))) for ii in t] elif precis[0] == 'd': if precis[1] == 'c': # at the center of a day gm_1day = tmu.upper_day(ta[0]) gm_1day = gm_1day - 12 * 3600 if gm_1day - 12 * 3600 > ta[ 0] else gm_1day + 12 * 3600 fmt = '%d.%m' elif precis[1] == 'l': gm_1day = tmu.upper_day(ta[0]) fmt = '%d' else: AttributeError('Precise code %s is incorrect' % precis) print 'Building day ticks from ts.%d to ts.%d' % (ta[0], ta[-1]) print 'First tick: %d' % gm_1day skip_days = 1 while (ta[-1] - gm_1day) / 3600. / 24. / skip_days > self._req.figsize[0]: skip_days += 1 #TODO: and something more curious! print 'DAYS skipping: %d days at %d inches' % ( skip_days, self._req.figsize[0]) t = map(int, list(frange(gm_1day, ta[-1], (3600 * 24 * skip_days)))) if len(t) > 0: if t[-1] > ta[-1]: t.pop() l = [time.strftime(fmt, time.localtime(int(ii))) for ii in t] print t, l else: # at least one tick :-) t = [(ta[0] + ta[1]) / 2.] l = [time.strftime(fmt, time.localtime(ta[0]))] else: raise NotImplementedError('Precis type ``%s'' not implemented' \ % precis) return t, l
def plot(self, policy): rows = len(policy) cols = len(policy[0]) X,Y = meshgrid(range(rows), range(cols)) # U, V give the x and y components of the arrow vectors U = [[0]*cols for _ in range(rows)] V = [[0]*cols for _ in range(rows)] for row,r in enumerate(policy): for col,c in enumerate(r): a = c[0] if a == 'N': U[row][col] = 0 V[row][col] = 1 elif a == 'S': U[row][col] = 0 V[row][col] = -1 elif a == 'E': U[row][col] = 1 V[row][col] = 0 elif a == 'W': U[row][col] = -1 V[row][col] = 0 else: raise ValueError ax = self.fig.add_subplot(111) ax.quiver(X, Y, U, V, pivot='middle') ax.grid(linestyle='-') ax.set_xticks(frange(0.5, cols)) ax.set_yticks(frange(0.5, rows)) ax.set_xticklabels([]) ax.set_yticklabels([]) xmin, xmax, ymin, ymax = ax.axis() ax.axis([xmin-0.5, xmax-1, ymin-0.5, ymax-1]) if self.world: #map = cdict = {'blue': ((0.0, 0.2, 0.2), (0.25, 1, 1), (1.0, 0, 0)), 'green': ((0.0, 0.2, 0.2), (0.25, 1, 1), (1.0, 1, 1)), 'red': ((0.0, 0.2, 0.2), (0.25, 1, 1), (1.0, 0, 0)) } cmap = LinearSegmentedColormap('fudge', cdict) ax.imshow(self.world, cmap=cmap, interpolation='nearest')
def Draw(func1, func2): # генирация точек графиков xlist = mlab.frange(a, b, 0.01) ylist = [func1(x) for x in xlist] ylist2 = [func2(x) for x in xlist] # Генирирум ось y0 = [0 for x in xlist] ############################################################# max1Y = max(ylist) min1Y = min(ylist) max2Y = max(ylist2) min2Y = min(ylist2) minmaxarrayY = [] minmaxarrayX = [] for i in range(len(ylist)): if ((max1Y == ylist[i]) or (min1Y == ylist[i])): minmaxarrayY.append(ylist[i]) minmaxarrayX.append(xlist[i]) for i in range(len(ylist2)): if ((max2Y == ylist2[i]) or (min2Y == ylist2[i])): minmaxarrayY.append(ylist2[i]) minmaxarrayX.append(xlist[i]) ################################################################ extremumX, extremumY = converter(korn, 0, 3, 4, func1) inflectionX, inflectionY = converter(korn1, 0, 3, 4, func1) kornsX, kornsY = converter(table, 1, 3, 4, func1) pylab.plot(extremumX, extremumY, 'go', label='extremum', color='red') pylab.plot(inflectionX, inflectionY, 'go', label='inflection point', color='yellow') pylab.plot(minmaxarrayX, minmaxarrayY, 'go', label='min/max', color='green') pylab.plot(kornsX, kornsY, 'go', label='Korn', color='black') pylab.plot(xlist, ylist, label='$sin(x)/x$') pylab.plot(xlist, y0, color='pink') pylab.plot(xlist, ylist2, label='$0.02*x* x - 4$', color='pink') pylab.legend() # Включаем рисование сетки pylab.grid(True) xlist1 = mlab.frange(float(table2[0][3]), float(table2[len(table2) - 1][3]), 0.01) pylab.fill_between(xlist1, [func1(x) for x in xlist1], [func2(x) for x in xlist1], color='green', alpha=0.25) # если мало разбиений, то переопереляем сетку под шаг if ((round((b - a) / h)) < 25): pylab.xticks([a + i * h for i in range(round((b - a) / h) + 1)]) print() print() print("Минимумы и максимумы:") print("X", "Y", sep="\t") for i in range(len(minmaxarrayY)): print('{:3.5g}'.format(minmaxarrayX[i]), '{:3.5g}'.format(minmaxarrayY[i]), sep='\t\t') # Рисуем фогрму с графиком pylab.show()
def search_best_parameter(filename): a, b, y_title, x_title, table = filehandling.bonus_file_handling(filename) b_range = frange(b[0], b[1], b[2]) a_range = frange(a[0], a[1], a[2]) # Calculate chi for each pair of values. chi_values = [] for b_value in b_range: for a_value in a_range: chi_values.append([ b_value, a_value, fitgui.bonus_chi_squared(table, my_function, (0, a_value, b_value)) ]) # Minimize chi best = chi_values[0] for b_value, a_value, chi in chi_values: if (chi < best[2]): best = (b_value, a_value, chi) print( output_format.format(a_value=best[1], a_error=a[2], b_value=best[0], b_error=b[2], chi_squared=best[2], chi_reduced=fitgui._chi_reduced( best[2], len(table["x"])))) # Create graph. pyplot.figure() pyplot.title("Generated custom fit") pyplot.ylabel("chi2(a,b = {best_b})".format(best_b=best[0])) pyplot.xlabel('a') # Set data and graph. plot_fitted_graph(min(table["x"]), max(table["x"]), (0, best[1], best[0]), my_function, c="blue") plot_data_points(table) a_values = [a for (b, a, chi) in chi_values if b == best[0]] chi_values = [chi for (b, a, chi) in chi_values if b == best[0]] slope = (max(chi_values) - min(chi_values)) / (max(a_values) - min(a_values)) intercept = max(chi_values) + (slope * max(a_values)) # save and show bonus function save_graph("numeric_sampling") pyplot.show()
def plot(self, policy): rows = len(policy) cols = len(policy[0]) X, Y = meshgrid(range(rows), range(cols)) # U, V give the x and y components of the arrow vectors U = [[0] * cols for _ in range(rows)] V = [[0] * cols for _ in range(rows)] for row, r in enumerate(policy): for col, c in enumerate(r): a = c[0] if a == 'N': U[row][col] = 0 V[row][col] = 1 elif a == 'S': U[row][col] = 0 V[row][col] = -1 elif a == 'E': U[row][col] = 1 V[row][col] = 0 elif a == 'W': U[row][col] = -1 V[row][col] = 0 else: raise ValueError ax = self.fig.add_subplot(111) ax.quiver(X, Y, U, V, pivot='middle') ax.grid(linestyle='-') ax.set_xticks(frange(0.5, cols)) ax.set_yticks(frange(0.5, rows)) ax.set_xticklabels([]) ax.set_yticklabels([]) xmin, xmax, ymin, ymax = ax.axis() ax.axis([xmin - 0.5, xmax - 1, ymin - 0.5, ymax - 1]) if self.world: #map = cdict = { 'blue': ((0.0, 0.2, 0.2), (0.25, 1, 1), (1.0, 0, 0)), 'green': ((0.0, 0.2, 0.2), (0.25, 1, 1), (1.0, 1, 1)), 'red': ((0.0, 0.2, 0.2), (0.25, 1, 1), (1.0, 0, 0)) } cmap = LinearSegmentedColormap('fudge', cdict) ax.imshow(self.world, cmap=cmap, interpolation='nearest')
def box_grid(xlimp, ylimp): """box_grid generate list of points on edge of box list = box_grid([xmin xmax xnum], [ymin ymax ynum]) generates a list of points that correspond to a uniform grid at the end of the box defined by the corners [xmin ymin] and [xmax ymax]. """ sx10 = frange(xlimp[0], xlimp[1], float(xlimp[1] - xlimp[0]) / xlimp[2]) sy10 = frange(ylimp[0], ylimp[1], float(ylimp[1] - ylimp[0]) / ylimp[2]) sx1 = np.hstack((0, sx10, 0 * sy10 + sx10[0], sx10, 0 * sy10 + sx10[-1])) sx2 = np.hstack((0, 0 * sx10 + sy10[0], sy10, 0 * sx10 + sy10[-1], sy10)) return np.transpose(np.vstack((sx1, sx2)))
def box_grid(xlimp, ylimp): """box_grid generate list of points on edge of box list = box_grid([xmin xmax xnum], [ymin ymax ynum]) generates a list of points that correspond to a uniform grid at the end of the box defined by the corners [xmin ymin] and [xmax ymax]. """ sx10 = frange(xlimp[0], xlimp[1], float(xlimp[1]-xlimp[0])/xlimp[2]) sy10 = frange(ylimp[0], ylimp[1], float(ylimp[1]-ylimp[0])/ylimp[2]) sx1 = np.hstack((0, sx10, 0*sy10+sx10[0], sx10, 0*sy10+sx10[-1])) sx2 = np.hstack((0, 0*sx10+sy10[0], sy10, 0*sx10+sy10[-1], sy10)) return np.transpose( np.vstack((sx1, sx2)) )
def __init__(self, funct, xmin, xmax, dx, nx=False): self.xes = list(mlab.frange(xmin, xmax, dx)) if nx != False: for m_y in nx: if m_y not in self.xes: self.xes.append(m_y) self.yes = [funct(x) for x in self.xes]
def main(args): # y = a*x + b x = frange(-1, 2, 0.15) # f(x) = x / (x+ 2) dla x > 0 # f(x) = x * x/3 dla x > 0 i x < 1 # f(x) = x / -3 dla x <= 0 y = [] for el in x: if el <= 0: y.append(el / -3) elif el < 1: y.append(el * el / 3) else: y.append(el / (el + 2)) print(x) plt.plot(x, y) plt.title('Wykres f(x') plt.grid(True) plt.show() return 0
def hw_6_2(): D = [] for i in range(10000): smp = np.random.uniform(0, 1, 50) stat = np.max(smp) D.append(stat) sample = np.random.uniform(0, 1, 50) bootstrap_D = do_bootstrap(sample, 10000, lambda array: np.max(array)) xlist = mlab.frange(0, 1, 0.001) ylist = [magic(x) for x in xlist] # sns.distplot(D) # plt.hist(D, bin_number(10000), color='red', alpha=0.5) # plt.hist(bootstrap_D, bin_number(10000), color='blue', alpha=0.5) my_cdf(D, 'blue') my_cdf(bootstrap_D, 'red') plt.plot(xlist, ylist) print('Квантиль 0.025: ', find_quantile(bootstrap_D, 0.025)) print('Квантиль 0.975: ', find_quantile(bootstrap_D, 0.975)) print(se_boot(bootstrap_D)) plt.show()
def showT(): '''Utility function to show T distributions''' t = frange(-5, 5, 0.05) TVals = [1,5] normal = stats.norm.pdf(t) t1 = stats.t.pdf(t,1) t5 = stats.t.pdf(t,5) plt.plot(t,normal, '--', label='normal') plt.plot(t, t1, label='df=1') plt.plot(t, t5, label='df=5') plt.legend() plt.xlim(-5,5) plt.xlabel('X') plt.ylabel('pdf(X)') plt.axis('tight') outDir = r'..\Images' outFile = 'dist_t.png' saveTo = os.path.join(outDir, outFile) plt.savefig(saveTo, dpi=200) print('OutDir: {0}'.format(outDir)) print('Figure saved to {0}'.format(outFile)) plt.show() plt.close()
def Draw(func1, func2): # генирация точек графика xlist = mlab.frange(a, b, 0.01) ylist = [func1(x) for x in xlist] ylist2 = [func2(x) for x in xlist] # Генирирум ось y0 = [0 for x in xlist] pylab.plot(xlist, ylist) #pylab.plot(xlist, y0, label='line1', color='blue') pylab.plot(xlist, ylist2, label='$sin(x)/x)$', color='red') pylab.legend() # Включаем рисование сетки pylab.grid(True) pylab.fill_between(xlist, ylist, ylist2, color='green', alpha=0.25) # если мало разбиений, то переопереляем сетку под шаг if ((round((b - a) / h)) < 25): pylab.xticks([a + i * h for i in range(round((b - a) / h) + 1)]) # рисуем корни, промерка того что корень не содержит ошибок for i in range(1, len(table)): if (table[i][4] != ':-('): pylab.scatter(table[i][3], table[i][4]) # Рисуем фогрму с графиком pylab.show()
def showExp(): '''Utility function to show exponential distributions''' t = frange(0, 3, 0.01) lambdas = [0.5, 1, 1.5] for par in lambdas: plt.plot(t, stats.expon.pdf(t, 0, par), label='$\lambda={0:3.1f}$'.format(par)) plt.legend() plt.xlim(0, 3) plt.xlabel('X') plt.ylabel('pdf(X)') plt.axis('tight') plt.legend() outDir = r'..\Images' outFile = 'dist_exp.png' saveTo = os.path.join(outDir, outFile) plt.savefig(saveTo, dpi=200) print('OutDir: {0}'.format(outDir)) print('Figure saved to {0}'.format(outFile)) plt.show() plt.close()
def integrate(func, mim_lim, max_lim, n): integral = 0.0 step = (max_lim - mim_lim) / n for x in mlab.frange(mim_lim + step / 2, max_lim - step / 2, step): integral += step / 6 * (func(x - step / 2) + 4 * func(x) + func(x + step / 2)) return integral
def showT(): '''Utility function to show T distributions''' t = frange(-5, 5, 0.05) TVals = [1, 5] normal = stats.norm.pdf(t) t1 = stats.t.pdf(t, 1) t5 = stats.t.pdf(t, 5) plt.plot(t, normal, '--', label='normal') plt.plot(t, t1, label='df=1') plt.plot(t, t5, label='df=5') plt.legend() plt.xlim(-5, 5) plt.xlabel('X') plt.ylabel('pdf(X)') plt.axis('tight') outDir = r'..\Images' outFile = 'dist_t.png' saveTo = os.path.join(outDir, outFile) plt.savefig(saveTo, dpi=200) print('OutDir: {0}'.format(outDir)) print('Figure saved to {0}'.format(outFile)) plt.show() plt.close()
def showChi2(): '''Utility function to show Chi2 distributions''' t = frange(0, 8, 0.05) Chi2Vals = [1, 2, 3, 5] for chi2 in Chi2Vals: plt.plot(t, stats.chi2.pdf(t, chi2), label='k={0}'.format(chi2)) plt.legend() plt.xlim(0, 8) plt.xlabel('X') plt.ylabel('pdf(X)') plt.axis('tight') outDir = r'..\Images' outFile = 'dist_chi2.png' saveTo = os.path.join(outDir, outFile) plt.savefig(saveTo, dpi=200) print('OutDir: {0}'.format(outDir)) print('Figure saved to {0}'.format(outFile)) plt.show() plt.close()
def shifted_normal(): '''PDF, scatter plot, and histogram.''' # Generate the data # Plot a normal distribution: "Probability density functions" myMean = [0,0,0,-2] mySD2 = [0.2,1,5,0.5] t = frange(-5,5,0.02) sns.set_palette('husl', 4) for mu,sigma in zip(myMean, np.sqrt(mySD2)): y = stats.norm.pdf(t, mu, sigma) plt.plot(t,y, label='$\mu={0}, \; \t\sigma={1:3.1f}$'.format(mu,sigma)) plt.legend() plt.xlim([-5,5]) plt.title('Normal Distributions') outFile = 'Normal_Distribution_PDF.png' saveTo = os.path.join(outDir, outFile) plt.savefig(saveTo, dpi=200) print('OutDir: {0}'.format(outDir)) print('Figure saved to {0}'.format(outFile)) plt.show() # Generate random numbers with a normal distribution myMean = 0 mySD = 3 numData = 500 data = stats.norm.rvs(myMean, mySD, size = numData) plt.scatter(np.arange(len(data)), data) plt.title('Normally distributed data') plt.xlim([0,500]) plt.ylim([-10,10]) plt.show() plt.close()
def showF(): '''Utility function to show F distributions''' t = frange(0, 3, 0.01) d1s = [1, 2, 5, 100] d2s = [1, 1, 2, 100] for (d1, d2) in zip(d1s, d2s): plot(t, stats.f.pdf(t, d1, d2), label='F({0}/{1})'.format(d1, d2)) plt.legend() plt.xlim(0, 3) plt.xlabel('X') plt.ylabel('pdf(X)') plt.axis('tight') plt.legend() outDir = r'..\Images' outFile = 'dist_f.png' saveTo = os.path.join(outDir, outFile) plt.savefig(saveTo, dpi=200) print('OutDir: {0}'.format(outDir)) print('Figure saved to {0}'.format(outFile)) plt.show() plt.close()
def showChi2(): '''Utility function to show Chi2 distributions''' t = frange(0, 8, 0.05) Chi2Vals = [1,2,3,5] for chi2 in Chi2Vals: plt.plot(t, stats.chi2.pdf(t, chi2), label='k={0}'.format(chi2)) plt.legend() plt.xlim(0,8) plt.xlabel('X') plt.ylabel('pdf(X)') plt.axis('tight') outDir = r'..\Images' outFile = 'dist_chi2.png' saveTo = os.path.join(outDir, outFile) plt.savefig(saveTo, dpi=200) print('OutDir: {0}'.format(outDir)) print('Figure saved to {0}'.format(outFile)) plt.show() plt.close()
def showF(): '''Utility function to show F distributions''' t = frange(0, 3, 0.01) d1s = [1,2,5,100] d2s = [1,1,2,100] for (d1,d2) in zip(d1s,d2s): plot(t, stats.f.pdf(t, d1, d2), label='F({0}/{1})'.format(d1,d2)) plt.legend() plt.xlim(0,3) plt.xlabel('X') plt.ylabel('pdf(X)') plt.axis('tight') plt.legend() outDir = r'..\Images' outFile = 'dist_f.png' saveTo = os.path.join(outDir, outFile) plt.savefig(saveTo, dpi=200) print('OutDir: {0}'.format(outDir)) print('Figure saved to {0}'.format(outFile)) plt.show() plt.close()
def showExp(): '''Utility function to show exponential distributions''' t = frange(0, 3, 0.01) lambdas = [0.5, 1, 1.5] for par in lambdas: plt.plot(t, stats.expon.pdf(t, 0, par), label='$\lambda={0:3.1f}$'.format(par)) plt.legend() plt.xlim(0,3) plt.xlabel('X') plt.ylabel('pdf(X)') plt.axis('tight') plt.legend() outDir = r'..\Images' outFile = 'dist_exp.png' saveTo = os.path.join(outDir, outFile) plt.savefig(saveTo, dpi=200) print('OutDir: {0}'.format(outDir)) print('Figure saved to {0}'.format(outFile)) plt.show() plt.close()
def generate_heatmap_data(Tmin, Tmax, Smin, Smax, Lmin, Lmax, scale, log=True): data = dict() if log == True: Tmin, Tmax = np.log10(Tmin), np.log10(Tmax) Smin, Tmax = np.log10(Smin), np.log10(Smax) from matplotlib.mlab import frange print(Tmin, Tmax) for i, item in enumerate(frange(Tmin, Tmax, (Tmax - Tmin) / scale)): for j, jtem in enumerate(frange(Lmin, Lmax, (Lmax - Lmin) / scale)): for k, ktem in enumerate(frange(Smin, Smax, (Smax - Smin) / scale)): if log == True: data[(i, j, k)] = tc_gelhar(10**(item), jtem, 10**(ktem)) else: data[(i, j, k)] = tc_gelhar(item, jtem, ktem) return data
def plot(func): x_min = ARRAY_X[0] x_max = ARRAY_X[-1] dx = 0.001 x_list = mlab.frange(x_min, x_max, dx) y_list = [func(arg) for arg in x_list] pylab.plot(x_list, y_list) pylab.show()
def plot(a, b, c): x_min = ARGS[0] x_max = ARGS[-1] dx = 0.001 x_list = mlab.frange(x_min, x_max, dx) y_list = [a * arg + b * math.exp(arg) + c for arg in x_list] pylab.scatter(ARGS, VALUES) pylab.plot(x_list, y_list) pylab.show()
def search_best_parameter(filename): a, b, y_title, x_title, table = filehandling.bonus_file_handling(filename) b_range = frange(b[0], b[1], b[2]) a_range = frange(a[0], a[1], a[2]) # Calculate the chi for each pair. chi_values = [] for b_value in b_range: for a_value in a_range: chi_values.append([ b_value, a_value, fitgui.bonus_chi_squared(table, myfunc, (0, a_value, b_value)) ]) # Find the best chi. best = chi_values[0] for b_value, a_value, chi in chi_values: if chi < best[2]: best = (b_value, a_value, chi) print( OUTPUT_FORMAT.format(a_value=best[1], a_error=a[2], b_value=best[0], b_error=b[2], chi_squared=best[2], chi_reduced=fitgui._chi_reduced( best[2], len(table["x"])))) # Create graph. pyplot.figure() pyplot.title("Generated custom fit") pyplot.ylabel(y_title) pyplot.xlabel(x_title) # Set the data and graph. plot_fitted_graph(min(table["x"]), max(table["x"]), (0, best[1], best[0]), myfunc, c="blue") plot_data_points(table) pyplot.show()
def __init__(self, name='drawSinus'): print name, 'started!\n' # Интервал изменения переменной по оси X self.xmin = -20.0 self.xmax = 20.0 # Шаг между точками self.dx = 0.01 #Создадим список координат по оси X #на отрезке [-xmin; xmax], включая концы self.xlist = mlab.frange (self.xmin, self.xmax, self.dx)
def task1(): rndx = [-1, -0.5, 0, 0.5, 1] rndy = [random.uniform(0, 1) for i in range(5)] rndlagrx = mlab.frange(-1, 1, 0.01) rndlagry = [lagr1(x, rndx, rndy) for x in rndlagrx] pylab.subplot(2, 3, 1) pylab.title('1.1') pylab.grid(True) pylab.plot(rndlagrx, rndlagry, color='green') pylab.plot(rndx, rndy, 'go', color='red', marker='x')
def find_dots(x1, x2, n, x, q, f): h = (x2 - x1) / (n) print("h = " + str(h)) xlist = mlab.frange(x1, x2, h) print("X's:") print(len(xlist)) print(xlist) # y" = -(1 + x^2)y - 1 # ay" + (1 + bx^2)y = -1 yks = [] for i in range(n + 1): yks.append(Symbol("y_d" + str(i + 1))) q = lambdify(x, q, 'numpy') f = lambdify(x, f, 'numpy') system = [] # for i in range(n - 2): # system.append((yks[i + 2] - 2 * yks[i + 1] + yks[i])/(h**2) - q(xlist[i + 1]) * yks[i + 1] - f(xlist[i + 1])) # #system.append(yks[i] - (2 + h ** 2 * q(xlist[i + 1])) * yks[i + 1] + yks[i + 2] - h ** 2 * f(xlist[i + 1])) #^^^^^деление на нолb k = 1 while k != n: system.append(yks[k - 1] - (2 - h**2 * q(xlist[k])) * yks[k] + yks[k + 1] - f(xlist[k]) * h**2) k += 1 print("\nGain system:") for el in system: print(el) system[0] = system[0].subs(yks[0], 0) system[-1] = system[-1].subs(yks[-1], 0) print("\nThen we substitute the boundary points and get solvable system :") for el in system: print(el) coeffs = linsolve(system, yks[1:n]) coeffs = next(iter(coeffs)) print("\nAnswer:") print(coeffs) ylist = [0] for el in coeffs: ylist.append(el) ylist.append(0) print("\nYk's :") print(ylist) return xlist, ylist
def run(self, c, path): # c = "LSKETH" with open(path + c + ".log", "w") as f: print(str(self.start_date) + " " + str(self.stop_date)) time_delta = self.MAX_STEP * self.tickers["1m"] time_spans = frange(self.start_date, self.stop_date, time_delta) for index, span in enumerate(time_spans): print("loop " + str(index) + "/" + str(len(time_spans))) data = Stock.get_klines(c, "1m", span) for e in data: f.write(str(e) + "\n") f.flush()
def skewness(ax): '''Normal and skewed distribution''' t = frange(-6,10,0.1) # generate the desirded x-values normal = stats.norm.pdf(t,1,1.6) chi2 = stats.chi2.pdf(t,3) ax.plot(t, normal, '--', label='normal') ax.plot(t, chi2, label='positive skew') ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') ax.legend()
def Shooting(N): y0 = 0 x0 = 0 h = 1 / N xlist = mlab.frange(0, 1, h) #описание метода def RungeKutta(f, x, y): def k1(): return h * f(x, y) def k2(): return h * f(x + h / 2, y + k1() / 2) def k3(): return h * f(x + h / 2, y + k2() / 2) def k4(): return h * f(x + h, y + k3()) return y + 1 / 6 * k1() + 2 / 6 * k2() + 2 / 6 * k3() + 1 / 6 * k4() #решение краевой задачи не зависит от параметра, поэтому вынес из цикла u = 0 w = 1 def difw(x, y): return u def difu(x, y): return w for i in range(N): w = RungeKutta(difw, x0 + i * h, w) u = RungeKutta(difu, x0 + i * h, u) #решение основной задачи def dify(x, y): return z def difz(x, y): return dif2y(x, y) for i in range(N + 1): y = y0 z = -3.1 ylist = [y0] for j in range(N): z = RungeKutta(difz, x0 + j * h, z) y = RungeKutta(dify, x0 + j * h, y) ylist.append(y) y0 = y0 - (y - math.e - 1 / math.e + 2) / w return plt.plot(xlist, ylist)
def __call__(self): 'Return the locations of the ticks' self.verify_intervals() vmin, vmax = self.viewInterval.get_bounds() if vmax<vmin: vmin, vmax = vmax, vmin vmin = self._base.ge(vmin) locs = frange(vmin, vmax+0.001*self._base.get_base(), self._base.get_base()) return locs
def plot_graphic(linear_combination, x, xmin, xmax, dx): f = lambdify(x, linear_combination, 'numpy') # xmin = -10000 # xmax = 10000 # dx = 0.1 xlist = mlab.frange(xmin, xmax, dx) ylist = [f(x) for x in xlist] # pylab.plot(xlist, ylist) # # pylab.axhline(0, color='black') # pylab.axvline(0, color='black') # pylab.show() return xlist, ylist
def test(): min, max, dx = 0, 16, 0.01 for d in containerDot: a = listA(d) b = listB(d) h = np.linalg.solve(a, b) h = list(h) xlist = mlab.frange(min, max, dx) ylist = [f(x) for x in xlist] yrlist = [g(x, h) for x in xlist] pylab.plot(xlist, yrlist) pylab.plot(xlist, ylist) pylab.show()
def figure(): def realfunction(x): return math.exp(x) * math.sin(x) - 1 xlist = mlab.frange(bot, top, 0.001) ylist = [realfunction(x) for x in xlist] pylab.plot(xlist, ylist) # axis ax = pylab.gca() ax.axhline(y=0, color='k') ax.axvline(x=0, color='k') ax.set_ylim([-5, 5]) pylab.show()
def func(x, d_lambda, n): mass1 = [] xlist = mlab.frange(1, 500, 1) w = complex(1, 0) fi = 2 * math.pi * d_lambda * math.sin(math.pi / 180.0 * x) for i in range(1, n + 1): x = complex(random.normalvariate(0, 10), random.normalvariate(0, 10)) x2 = x * complex(math.cos(-math.pi / 4), math.sin(-math.pi / 4)) e = x + w * x2 w = w - 2 * 0.00005 * e * x2.conjugate() w = w + complex(math.cos(fi * (i - 1)), math.sin(fi * (i - 1))) a = abs(w) mass1.append(e * e.conjugate()) return mass1
def task(): a = -1 b = 1 fa = random.uniform(-1, 1) fb = random.uniform(-1, 1) dfb = random.uniform(-1, 1) x = mlab.frange(-1, 1, 0.01) for i in range(2): for j in range(3): dfa = random.uniform(-1.0, 1.0) y = [hermit(i, a, b, fa, fb, dfa, dfb) for i in x] pylab.subplot(2, 3, i * 3 + j + 1) pylab.title('f\'(a)=%.2f f\'(b) = %.2f' % (dfa, dfb)) pylab.grid(True) pylab.plot(x, y)
def CheckElevation(vec): #print vec step = 1.0/len(vec) vec_after_polyfit = createElevationVectorAfterPolyfit(mlab.frange(0,1-step,step),vec) vec_diff = np.diff(np.array(vec_after_polyfit)) elChange = vec_after_polyfit[-1] - vec_after_polyfit[1]; if (elChange > ELEVATION_THRESHOLD): #print 'DOWN' if (mlab.find(vec_diff >= 0).size > VECTOR_SIZE*ELEVATION_TREND_PRECENT): return elChange,HAND_DOWN elif (elChange < -ELEVATION_THRESHOLD): #print 'UP' if (mlab.find(vec_diff <= 0).size > VECTOR_SIZE*ELEVATION_TREND_PRECENT): return elChange,HAND_UP return 0,HAND_UNKWON
def kurtosis(ax): ''' Distributions with different kurtosis''' # Generate the data t = frange(-3,3,0.1) # generate the desirded x-values platykurtic = stats.laplace.pdf(t) wigner = np.zeros(np.size(t)) wignerIndex = np.abs(t) <= 1 wigner[wignerIndex] = 2/np.pi * np.sqrt(1-t[wignerIndex]**2) ax.plot(t, platykurtic, label='kurtosis=3') ax.plot(t, wigner, '--', label='kurtosis=-1') ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') ax.legend()
def __call__ (self) : binner = self.binner delta = self.delta phase = self.phase vmin, vmax = self.viewInterval wmin = binner.value (vmin, False) wmax = binner.value (vmax, False) if phase is not None : wmin -= (wmin % delta - phase) return \ [ i for i in ( binner.index_f (v) for v in frange (wmin, wmax + 0.001 * delta, delta) ) if vmin <= i <= vmax ]
def showChi2(): '''Utility function to show Chi2 distributions''' t = frange(0, 8, 0.05) Chi2Vals = [1,2,3,5] for chi2 in Chi2Vals: plt.plot(t, stats.chi2.pdf(t, chi2), label='k={0}'.format(chi2)) plt.legend() plt.xlim(0,8) plt.xlabel('X') plt.ylabel('pdf(X)') plt.axis('tight') outFile = 'dist_chi2.png' C2_8_mystyle.printout_plain(outFile)
def showExp(): '''Utility function to show exponential distributions''' t = frange(0, 3, 0.01) lambdas = [0.5, 1, 1.5] for par in lambdas: plt.plot(t, stats.expon.pdf(t, 0, par), label='$\lambda={0:3.1f}$'.format(par)) plt.legend() plt.xlim(0,3) plt.xlabel('X') plt.ylabel('pdf(X)') plt.axis('tight') plt.legend() outFile = 'dist_exp.png' C2_8_mystyle.printout_plain(outFile)
def showF(): '''Utility function to show F distributions''' t = frange(0, 3, 0.01) d1s = [1,2,5,100] d2s = [1,1,2,100] for (d1,d2) in zip(d1s,d2s): plt.plot(t, stats.f.pdf(t, d1, d2), label='F({0}/{1})'.format(d1,d2)) plt.legend() plt.xlim(0,3) plt.xlabel('X') plt.ylabel('pdf(X)') plt.axis('tight') plt.legend() outFile = 'dist_f.png' C2_8_mystyle.printout_plain(outFile)
def showWeibull(): '''Utility function to show Weibull distributions''' t = frange(0, 2.5, 0.01) lambdaVal = 1 ks = [0.5, 1, 1.5, 5] for k in ks: wd = stats.weibull_min(k) plt.plot(t, wd.pdf(t), label='k = {0:.1f}'.format(k)) plt.xlim(0,2.5) plt.ylim(0,2.5) plt.xlabel('X') plt.ylabel('pdf(X)') plt.legend() outFile = 'Weibull_PDF.png' showData(outFile)
def shifted_normal(): '''PDF and scatter plot''' # Plot 3 PDFs (Probability density functions) for normal distributions ---------- # Select 3 mean values, and 3 SDs myMean = [0,0,0,-2] mySD = [0.2,1,5,0.5] t = frange(-5,5,0.02) # Plot the 3 PDFs, using the color-palette "hls" with sns.color_palette('hls', 4): for mu,sigma in zip(myMean, np.sqrt(mySD)): y = stats.norm.pdf(t, mu, sigma) plt.plot(t,y, label='$\mu={0}, \; \t\sigma={1:3.1f}$'.format(mu,sigma)) # Format the plot plt.legend() plt.xlim([-5,5]) plt.title('Normal Distributions') # Show the plot, and save the out-file outFile = 'Normal_Distribution_PDF.png' showData(outFile) # Generate random numbers with a normal distribution ------------------------ myMean = 0 mySD = 3 numData = 500 data = stats.norm.rvs(myMean, mySD, size = numData) # Plot the data plt.scatter(np.arange(len(data)), data) # Format the plot plt.title('Normally distributed data') plt.xlim([0,500]) plt.ylim([-10,10]) plt.show() plt.close()
def showT(): '''Utility function to show T distributions''' t = frange(-5, 5, 0.05) TVals = [1,5] normal = stats.norm.pdf(t) t1 = stats.t.pdf(t,1) t5 = stats.t.pdf(t,5) plt.plot(t,normal, '--', label='normal') plt.plot(t, t1, label='df=1') plt.plot(t, t5, label='df=5') plt.legend() plt.xlim(-5,5) plt.xlabel('X') plt.ylabel('pdf(X)') plt.axis('tight') outFile = 'dist_t.png' C2_8_mystyle.printout_plain(outFile)
def DrawPlot(self): from matplotlib import pyplot as plt from matplotlib.mlab import frange import numpy xBegin = -1 xEnd = 1 xRange = frange(xBegin, xEnd, self._drawingStep) y1Points = [ self._f1(x) for x in xRange ] y2Points = [ self._f2(x) for x in xRange ] top, = plt.plot(xRange, y1Points, color="red", linewidth=2.5) bottom, = plt.plot(xRange, y2Points, color="red", linewidth=2.5) plt.fill_between(xRange, y1Points, y2Points, color="red", alpha=0.25) plt.xlim(-2, 2) plt.title("♥") plt.show()
for i in xrange(0, n): array_x_y[0] = [-3.,-2.,-1.,1.,2.,4.] array_x_y[1] = [-2.1,-1.,2.,2.,1.,-2.] #for i in xrange(0, n): array_x_y[0] = [-3.,-2.,0.,0.,0.,0.] array_x_y[1] = [-2.,-1.,0.,0.,0.,0.] array_x_y[2] = [-1.,2.,0.,0.,0.,0.] array_x_y[3] = [1.,2.,0.,0.,0.,0.] array_x_y[4] = [2.,1.,0.,0.,0.,0.] array_x_y[5] = [4.,-2.,0.,0.,0.,0.] from matplotlib import mlab zlist = mlab.frange (-5, 5, 0.01) res = get_coefficient(array_x_y) import pylab pylab.grid() #pylab.plot(zlist, [f(x) for x in zlist ], label='График функции'.decode("utf8")) pylab.plot(zlist, [approx_function(res, x/0.85)-2.1 for x in zlist ], label='Аппроксимация'.decode("utf8")) #pylab.plot(glist, [approx_function(res,x) for x in glist ], "ro") pylab.plot([-3.,-2.,-1.,1.,2.,4.], [-2.1,-1.,2.,2.,1.,-2.], "ro") pylab.legend(loc='lower left').draggable() pylab.show()
__author__ = 'maxim' from math import log from math import cos from math import sin from matplotlib import mlab import pylab as plt e1, e2, e3 = 10 ** (-3), 10 ** (-6), 10 ** (-9) x_min = 0.0 x_max = 10.0 n = 200 h = (x_max - x_min) / n x = mlab.frange(x_min, x_max, h) x1 = list(x) fig = plt.figure() axes = fig.add_subplot(1, 1, 1) def f(z): return log(z ** 2 + 3 * z + 1) - cos(2 * z - 1) y = map(lambda z: log(z ** 2 + 3 * z + 1) - cos(2 * z - 1), x) def u(z): return (2 * z + 3) / (z ** 2 + 3 * z + 1) + 2 * sin(2 * z - 1) # М Е Т О Д Н Ь Ю Т О Н А
import numpy as np import math import pylab from matplotlib import mlab tmin = -10 tmax = 10 dt = 0.01 tlist = mlab.frange(tmin, tmax, dt) pylab.ion() for i in range(100): xlist = [math.sin(t + i) for t in tlist] ylist = [math.cos(2*t) for t in tlist] pylab.clf() pylab.plot(xlist, ylist) pylab.draw() pylab.close()
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from __future__ import division from matplotlib.artist import Artist import matplotlib.mlab as mlab import matplotlib.font_manager as fm import matplotlib.colors as mc import numpy as np import colorsys # from http://matplotlib.org/examples/pylab_examples/demo_agg_filter.html plot_colors = [ mc.rgb2hex(colorsys.hsv_to_rgb(x, 0.58, 1)) for x in mlab.frange(0, 1, 0.05) ] plot_colors = plot_colors[0::2] + plot_colors[1::2] class FilteredArtistList(Artist): def __init__(self, artist_list, filter): self._artist_list = artist_list self._filter = filter Artist.__init__(self) def draw(self, renderer): renderer.start_rasterizing() renderer.start_filter() for a in self._artist_list: a.draw(renderer)
# functii neprerivnoy sluchaynoy velichini pyplot.subplot(1, 1, 1) y1.sort() F1 = [i / float(len(y1)) for i in xrange(len(y1))] pyplot.title("exponential function with parameter lambda : {0} and volume sample : {1}".format(_lambda, len(y1))) pyplot.plot(y1, F1) pyplot.plot(x, F) pyplot.show() pyplot.subplot(1, 1, 1) y2.sort() F2 = [i / float(len(y2)) for i in xrange(len(y2))] pyplot.title("exponential function with parameter lambda : {0} and volume sample : {1}".format(_lambda, len(y2))) pyplot.plot(y2, F2) pyplot.plot(x, F) pyplot.show() # kolmogorov kriterii soglasia F1_teor = [1 - math.e ** (-_lambda * y1[i]) for i in xrange(len(y1))] F2_teor = [1 - math.e ** (-_lambda * y2[i]) for i in xrange(len(y2))] print math.sqrt(n) * max(abs(F2[i] - F2_teor[i]) for i in xrange(len(y2))) x_min = 0.01 x_max = 0.99 dx = 0.01 xlist = frange(x_min, x_max, dx) ylist = [st.norm.ppf((i + 1) / 2) * 2 * math.sqrt(D1) / math.sqrt(n - 1) for i in xlist] pyplot.plot(xlist, ylist, 'b') pyplot.show()
return (exp(z) - exp(-z)) / 2.0 def ch(z): return (exp(z) + exp(-z)) / 2.0 def ch1(v1, v): return (exp(v1 - v) + exp(v - v1)) / 2.0 # Задание сетки по х x_min = 0.0 x_max = 1.0 n = 20 h = (x_max - x_min) / n x = mlab.frange(x_min, x_max, h) N = len(x) - 1 # Задание сетки по t t_min = 0.0 print("Хотите Задать Время Окончания Расчета (1/0) ?") a = (input()) if a == 1: print("t_max = ") t_max = input() if a == 0: t_max = 1.0 print("Хотите Задать Шаг ? (1/0)") a = (input())
if (k & 1): res *= t k = k >> 1 if k == 0: break t *= t return res def bernulli(n, k, p0): koef = math.factorial(n) / ((math.factorial(k))*(math.factorial(n - k))) return koef * math.pow(p0, k) * math.pow(1 - p0, (n - k)) while j < len(n): i = math.floor((d[j] - 1)/2) s = i + 1 summ = 0 while s < n[j]: summ += bernulli(n[j], s, p0 = 0.01) s += 1 result.append(summ) j += 1 f1=open('./testfile.txt', 'w+') print (result, f1) xlist = mlab.frange (2, 24, 2) ylist = result pylab.plot (xlist, ylist) pylab.show()