Skip to content

Instantly share code, notes, and snippets.

@Ygenks
Last active May 21, 2016 13:50
Show Gist options
  • Save Ygenks/b1baecaa03fd7e471f42613a3309eb4b to your computer and use it in GitHub Desktop.
Save Ygenks/b1baecaa03fd7e471f42613a3309eb4b to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
# 0 -> install matplotlib & numpy & sympy
# tut vse napisano http://matplotlib.org/users/installing.html
# 1 -> Pastnite vashi data iz faila s tipovim v proizvolnu
# 2 -> Kinte fail v papku so skriptom
# 3 -> vizovite skript v duhe ./script_name <poryadkovy nomer grafika iz 10 zadania> <imya faila s dannimy>
# -> gde:
# 1 - F*(x)
# 2 - r'avnointervalnaya functsiya
# 3 - gavnoveroyatnostnaya functsiya
# 4 - 11 nomer
# 5 - 10 nomer posle grafika - gavnomerka
# 6 - 10 nomer posle grafika - belexpa
# 7 - 10 nomer posle grafika - ETO NORMA (budet dolgo)
import matplotlib.pyplot as plt
import numpy as np
import sys
from math import sqrt, exp, pi
from itertools import chain
from sympy import *
def get_x_coordinates(file):
try:
file = open(file, "r")
except Exception:
print("Vrong fail neim")
sys.exit(-1)
x_coordinates = file.readlines()
x_coordinates = [x.strip() for x in x_coordinates]
x_coordinates = [x.split(' ') for x in x_coordinates]
x_coordinates = [inner for outer in x_coordinates for inner in outer]
x_coordinates = [x for x in x_coordinates if x != ''] # clean list
x_coordinates = [float(x) for x in x_coordinates]
x_coordinates = sorted(x_coordinates)
return x_coordinates
def first_plot(file):
x_coordinates = get_x_coordinates(file)
y_coordinates = [i/100.0 for i in range(1, 101)]
average = sum(x_coordinates)/len(x_coordinates)
S_square = (1.0/99.0)*sum([x*x for x in x_coordinates]) - 100.0/99.0*average**2
z0m = 1.96*sqrt(S_square/100.0)
z0d = 1.96*sqrt(2.0/99.0)*S_square
fig = plt.figure()
ax = fig.gca()
ax.set_xticks(np.arange(x_coordinates[0], x_coordinates[-1], 1))
ax.set_yticks(np.arange(0.0, 1.1, 0.05))
ax.tick_params(axis = 'both', which = 'major', pad = 20)
ax.yaxis.set_ticks_position('left')
axis = fig.add_subplot(1, 1, 1)
axis.spines['left'].set_position('zero')
axis.spines['right'].set_color('none')
axis.spines['top'].set_color('none')
lines = plt.plot(x_coordinates, y_coordinates)
plt.setp(lines, aa = False, linewidth = 0.01, color='k', marker='.', linestyle='steps')
plt.grid()
ax.set_ylabel(r'$\mathit{F^{*}(x)}$', rotation = 0, fontsize = 14)
ax.yaxis.set_label_coords(0.4, 0.95)
ax.set_xlabel(r'$\mathit{X}$', fontsize = 14)
ax.xaxis.set_label_coords(1.020, -0.038)
plt.show()
def second_plot(file):
x_coordinates = get_x_coordinates(file)
hj = round(0.1 * (x_coordinates[-1] - x_coordinates[0]), 4)
print("hj = %f" % (hj))
Aj = []
for i in range(0, 11):
Aj.append(round(x_coordinates[0] + hj * i, 4)) # РРРААААУУНД
print("Aj =", Aj)
#Aj = [round(x_coordinates[0] + hj * i, 4) for i in range(0,11)]
v = list(map(lambda x, y: len(list(
filter(lambda z: x <= z and z <= y, x_coordinates))),
Aj, Aj[1:]))
print("vj =", v)
fzj = [round(0.01 * i / hj, 3) for i in v]
print("равноинтервальная f*j =", fzj)
labels = [str(i) for i in Aj[:-1]]
print("Vj = ", [x/100.0 for x in v])
average = sum(x_coordinates)/len(x_coordinates)
S_square = (1.0/99.0)*sum([x*x for x in x_coordinates]) - 100.0/99.0*average**2
z0m = 1.96*sqrt(S_square/100.0)
z0d = 1.96*sqrt(2.0/99.0)*S_square
a_args = [(x - average)/sqrt(S_square) for x in Aj[1:]]
b_args = [(x + hj - average)/sqrt(S_square) for x in Aj]
f_aj = []
plt.bar(Aj[:-1], fzj, 1.2, align='center', color = 'k')
plt.xticks(Aj[:-1], labels, ha = 'center', rotation = 45)
plt.ylabel(r'$\mathit{f^{*}(x)}$', rotation = 0, fontsize = 14)
plt.xlabel(r'$\mathit{X}$', fontsize = 14)
ax = plt.gca()
ax.xaxis.set_label_coords(1.0, -0.02)
ax.yaxis.set_label_coords(-0.1, 1.02)
plt.grid()
plt.show()
def third_plot(file):
x_coordinates = get_x_coordinates(file)
bj2 = [0.5*(x_coordinates[10*(i+1)] +
x_coordinates[10*(i+1) - 1]) for i in range(9)]
bj2.append(x_coordinates[99])
aj2 = [x_coordinates[0]]
aj2 += bj2[:-1]
hj2 = [x_coordinates[10*i+9] -
x_coordinates[10*i] for i in range(10)]
pairs = list(zip(aj2, hj2))
pairs = list(chain(*pairs))
fzj2 = [round(0.1 / i, 4) for i in hj2]
print('равновероятностная f*j =', fzj2)
print('Aj = ', aj2)
print('Bj = ', bj2)
print('Hj = ', hj2)
plt.bar(aj2, fzj2, hj2, color = 'k')
plt.ylabel(r'$\mathit{f^{*}(x)}$', rotation = 0, fontsize = 14)
plt.xlabel(r'$\mathit{X}$', fontsize = 14)
ax = plt.gca()
ax.xaxis.set_label_coords(1.05, -0.01)
ax.yaxis.set_label_coords(-0.1, 1.02)
plt.grid()
plt.show()
def fourth_plot(file):
try:
file = open(file, "r")
except Exception:
print("Vrong fail neim")
sys.exit(-1)
pairs = file.readlines()
pairs = [x.replace(' ', '') for x in pairs]
pairs = [x.replace('(', '\n').replace(')', '\n') for x in pairs]
result = open('result', 'w')
result.writelines(pairs)
result.close()
x, y = np.loadtxt('result', delimiter = ';', unpack = True)
mx = np.average(x)
my = np.average(y)
alpha_x = np.average(x ** 2)
alpha_y = np.average(y ** 2)
alpha_xy = np.average(x * y)
dx = (50.0 / 49.0) * (alpha_x - mx * mx)
dy = (50.0 / 49.0) * (alpha_y - my * my)
kxy = (50.0 / 49.0) * (alpha_xy - mx * my)
rxy = kxy / sqrt(dx * dy)
a = 0.5 * np.log((1 + rxy) / (1 - rxy)) - 1.96 / sqrt(50.0 - 3)
b = 0.5 * np.log((1 + rxy) / (1 - rxy)) + 1.96 / sqrt(50.0 - 3)
I = [(exp(2 * a) - 1) / (exp(2 * a) + 1), (exp(2 * b) - 1) / (exp(2 * b) + 1)]
z = (abs(rxy) * sqrt(50)) / (1 - rxy * rxy)
print('mx = ', mx)
print('my = ', my)
print('alpha_x = ', alpha_x)
print('alpha_y = ', alpha_y)
print('allha_xy = ', alpha_xy)
print('Dx = ', dx)
print('Dy = ', dy)
print('Kxy = ', kxy)
print('Rxy = ', rxy)
print('a = ', a)
print('b = ', b)
print('I = ', I)
print('Z = ', z)
fig, ax = plt.subplots()
m, b = np.polyfit(x, y, 1)
print('a1 = ', m)
print('a0 = ', b)
ax.plot(x, m * x + b, linewidth = 2)
ax.scatter(x, y)
plt.ylabel(r'$\mathit{Y}$', rotation = 0, fontsize = 14)
plt.xlabel(r'$\mathit{X}$', fontsize = 14)
axis = plt.gca()
axis.xaxis.set_label_coords(1.05, -0.01)
axis.yaxis.set_label_coords(-0.05, 1.01)
plt.show()
def table_bleat(file):
X = get_x_coordinates(file)
ark = 0.01 * sum(X)
s02 = 1.0 / 99 * sum([i*i for i in X]) - 100.0 / 99 * ark * ark
if sys.argv[1] == '5':
def funF0(x):
return (x - X[0]) / (X[-1] - X[0])
elif sys.argv[1] == '6':
def funF0(x):
return 1 - exp(- x / ark)
elif sys.argv[1] == '7':
def funF0(x):
if x == float('-Inf'):
return 0
elif x == float('Inf'):
return 1
t = Symbol('t')
x = (x - ark) / sqrt(s02)
result = 0.5 + float(integrate(exp(- t * t * 0.5), (t, 0, x)) / sqrt(2 * pi))
# print(result)
return result
else:
def funF0(x):
return float('Inf')
hj = 0.1 * (X[-1] - X[0])
Aj = [X[0] + hj * i for i in range(0, 11)]
Bj = Aj[1:]
Aj = Aj[:-1]
if sys.argv[1] == '5':
pass
elif sys.argv[1] == '6':
Aj[0] = 0
Bj[-1] = float('Inf')
elif sys.argv[1] == '7':
Aj[0] = float('-Inf')
Bj[-1] = float('Inf')
print("Aj =", Aj)
print("Bj =", Bj)
vj = list(map(lambda x, y: len(list(
filter(lambda z: x < z and z <= y, X))),
Aj, Bj))
print("p*j =", [0.01 * i for i in vj])
fzj = [0.01 * i / hj for i in vj]
print("равноинтервальная f*j =", fzj)
f0aj = [funF0(i) for i in Aj]
print('f0aj =', f0aj)
f0bj = f0aj[1:] + [funF0(Bj[-1])]
print('f0bj =', f0bj)
pj = [b - a for a, b in zip(f0aj, f0bj)]
print('pj =', pj)
print('summa pj = {0}, 1 - summa = {1}'.format(sum(pj), 1 - sum(pj)))
ppp = []
for p, pz in zip(pj, vj):
ppp.append((0.01 * pz - p)**2 / p)
print('ppp =', ppp)
print('summa =', sum(ppp))
def input_check():
input = int(sys.argv[1])
if input == 1:
first_plot(sys.argv[2])
elif input == 2:
second_plot(sys.argv[2])
elif input == 3:
third_plot(sys.argv[2])
elif input == 4:
fourth_plot(sys.argv[2])
elif 4 < input and input < 8:
table_bleat(sys.argv[2])
else:
print("fuck you, enter coorrect nomer\n")
if len(sys.argv) < 3:
print("kek, vvedi nomer graphika i imya faila\n")
sys.exit(-1)
input_check()
@alex-pat
Copy link

line 52 a_args = [(x - average)/sqrt(S_square) for x in aj] should be deleted

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment