converted space indentation to tab indentation

This commit is contained in:
ltcptgeneral 2020-05-01 16:15:07 -05:00
parent e3623dec5b
commit 98c48897e0
12 changed files with 2060 additions and 2060 deletions

File diff suppressed because it is too large Load Diff

View File

@ -2,6 +2,6 @@ import numpy as np
def calculate(starting_score, opposing_score, observed, N, K): def calculate(starting_score, opposing_score, observed, N, K):
expected = 1/(1+10**((np.array(opposing_score) - starting_score)/N)) expected = 1/(1+10**((np.array(opposing_score) - starting_score)/N))
return starting_score + K*(np.sum(observed) - np.sum(expected)) return starting_score + K*(np.sum(observed) - np.sum(expected))

View File

@ -1,99 +1,99 @@
import math import math
class Glicko2: class Glicko2:
_tau = 0.5 _tau = 0.5
def getRating(self): def getRating(self):
return (self.__rating * 173.7178) + 1500 return (self.__rating * 173.7178) + 1500
def setRating(self, rating): def setRating(self, rating):
self.__rating = (rating - 1500) / 173.7178 self.__rating = (rating - 1500) / 173.7178
rating = property(getRating, setRating) rating = property(getRating, setRating)
def getRd(self): def getRd(self):
return self.__rd * 173.7178 return self.__rd * 173.7178
def setRd(self, rd): def setRd(self, rd):
self.__rd = rd / 173.7178 self.__rd = rd / 173.7178
rd = property(getRd, setRd) rd = property(getRd, setRd)
def __init__(self, rating = 1500, rd = 350, vol = 0.06): def __init__(self, rating = 1500, rd = 350, vol = 0.06):
self.setRating(rating) self.setRating(rating)
self.setRd(rd) self.setRd(rd)
self.vol = vol self.vol = vol
def _preRatingRD(self): def _preRatingRD(self):
self.__rd = math.sqrt(math.pow(self.__rd, 2) + math.pow(self.vol, 2)) self.__rd = math.sqrt(math.pow(self.__rd, 2) + math.pow(self.vol, 2))
def update_player(self, rating_list, RD_list, outcome_list): def update_player(self, rating_list, RD_list, outcome_list):
rating_list = [(x - 1500) / 173.7178 for x in rating_list] rating_list = [(x - 1500) / 173.7178 for x in rating_list]
RD_list = [x / 173.7178 for x in RD_list] RD_list = [x / 173.7178 for x in RD_list]
v = self._v(rating_list, RD_list) v = self._v(rating_list, RD_list)
self.vol = self._newVol(rating_list, RD_list, outcome_list, v) self.vol = self._newVol(rating_list, RD_list, outcome_list, v)
self._preRatingRD() self._preRatingRD()
self.__rd = 1 / math.sqrt((1 / math.pow(self.__rd, 2)) + (1 / v)) self.__rd = 1 / math.sqrt((1 / math.pow(self.__rd, 2)) + (1 / v))
tempSum = 0 tempSum = 0
for i in range(len(rating_list)): for i in range(len(rating_list)):
tempSum += self._g(RD_list[i]) * \ tempSum += self._g(RD_list[i]) * \
(outcome_list[i] - self._E(rating_list[i], RD_list[i])) (outcome_list[i] - self._E(rating_list[i], RD_list[i]))
self.__rating += math.pow(self.__rd, 2) * tempSum self.__rating += math.pow(self.__rd, 2) * tempSum
def _newVol(self, rating_list, RD_list, outcome_list, v): def _newVol(self, rating_list, RD_list, outcome_list, v):
i = 0 i = 0
delta = self._delta(rating_list, RD_list, outcome_list, v) delta = self._delta(rating_list, RD_list, outcome_list, v)
a = math.log(math.pow(self.vol, 2)) a = math.log(math.pow(self.vol, 2))
tau = self._tau tau = self._tau
x0 = a x0 = a
x1 = 0 x1 = 0
while x0 != x1: while x0 != x1:
# New iteration, so x(i) becomes x(i-1) # New iteration, so x(i) becomes x(i-1)
x0 = x1 x0 = x1
d = math.pow(self.__rating, 2) + v + math.exp(x0) d = math.pow(self.__rating, 2) + v + math.exp(x0)
h1 = -(x0 - a) / math.pow(tau, 2) - 0.5 * math.exp(x0) \ h1 = -(x0 - a) / math.pow(tau, 2) - 0.5 * math.exp(x0) \
/ d + 0.5 * math.exp(x0) * math.pow(delta / d, 2) / d + 0.5 * math.exp(x0) * math.pow(delta / d, 2)
h2 = -1 / math.pow(tau, 2) - 0.5 * math.exp(x0) * \ h2 = -1 / math.pow(tau, 2) - 0.5 * math.exp(x0) * \
(math.pow(self.__rating, 2) + v) \ (math.pow(self.__rating, 2) + v) \
/ math.pow(d, 2) + 0.5 * math.pow(delta, 2) * math.exp(x0) \ / math.pow(d, 2) + 0.5 * math.pow(delta, 2) * math.exp(x0) \
* (math.pow(self.__rating, 2) + v - math.exp(x0)) / math.pow(d, 3) * (math.pow(self.__rating, 2) + v - math.exp(x0)) / math.pow(d, 3)
x1 = x0 - (h1 / h2) x1 = x0 - (h1 / h2)
return math.exp(x1 / 2) return math.exp(x1 / 2)
def _delta(self, rating_list, RD_list, outcome_list, v): def _delta(self, rating_list, RD_list, outcome_list, v):
tempSum = 0 tempSum = 0
for i in range(len(rating_list)): for i in range(len(rating_list)):
tempSum += self._g(RD_list[i]) * (outcome_list[i] - self._E(rating_list[i], RD_list[i])) tempSum += self._g(RD_list[i]) * (outcome_list[i] - self._E(rating_list[i], RD_list[i]))
return v * tempSum return v * tempSum
def _v(self, rating_list, RD_list): def _v(self, rating_list, RD_list):
tempSum = 0 tempSum = 0
for i in range(len(rating_list)): for i in range(len(rating_list)):
tempE = self._E(rating_list[i], RD_list[i]) tempE = self._E(rating_list[i], RD_list[i])
tempSum += math.pow(self._g(RD_list[i]), 2) * tempE * (1 - tempE) tempSum += math.pow(self._g(RD_list[i]), 2) * tempE * (1 - tempE)
return 1 / tempSum return 1 / tempSum
def _E(self, p2rating, p2RD): def _E(self, p2rating, p2RD):
return 1 / (1 + math.exp(-1 * self._g(p2RD) * \ return 1 / (1 + math.exp(-1 * self._g(p2RD) * \
(self.__rating - p2rating))) (self.__rating - p2rating)))
def _g(self, RD): def _g(self, RD):
return 1 / math.sqrt(1 + 3 * math.pow(RD, 2) / math.pow(math.pi, 2)) return 1 / math.sqrt(1 + 3 * math.pow(RD, 2) / math.pow(math.pi, 2))
def did_not_compete(self): def did_not_compete(self):
self._preRatingRD() self._preRatingRD()

File diff suppressed because it is too large Load Diff

View File

@ -9,38 +9,38 @@ __version__ = "1.0.0.004"
# changelog should be viewed using print(analysis.regression.__changelog__) # changelog should be viewed using print(analysis.regression.__changelog__)
__changelog__ = """ __changelog__ = """
1.0.0.004: 1.0.0.004:
- bug fixes - bug fixes
- fixed changelog - fixed changelog
1.0.0.003: 1.0.0.003:
- bug fixes - bug fixes
1.0.0.002: 1.0.0.002:
-Added more parameters to log, exponential, polynomial -Added more parameters to log, exponential, polynomial
-Added SigmoidalRegKernelArthur, because Arthur apparently needs -Added SigmoidalRegKernelArthur, because Arthur apparently needs
to train the scaling and shifting of sigmoids to train the scaling and shifting of sigmoids
1.0.0.001: 1.0.0.001:
-initial release, with linear, log, exponential, polynomial, and sigmoid kernels -initial release, with linear, log, exponential, polynomial, and sigmoid kernels
-already vectorized (except for polynomial generation) and CUDA-optimized -already vectorized (except for polynomial generation) and CUDA-optimized
""" """
__author__ = ( __author__ = (
"Jacob Levine <jlevine@imsa.edu>", "Jacob Levine <jlevine@imsa.edu>",
"Arthur Lu <learthurgo@gmail.com>" "Arthur Lu <learthurgo@gmail.com>"
) )
__all__ = [ __all__ = [
'factorial', 'factorial',
'take_all_pwrs', 'take_all_pwrs',
'num_poly_terms', 'num_poly_terms',
'set_device', 'set_device',
'LinearRegKernel', 'LinearRegKernel',
'SigmoidalRegKernel', 'SigmoidalRegKernel',
'LogRegKernel', 'LogRegKernel',
'PolyRegKernel', 'PolyRegKernel',
'ExpRegKernel', 'ExpRegKernel',
'SigmoidalRegKernelArthur', 'SigmoidalRegKernelArthur',
'SGDTrain', 'SGDTrain',
'CustomTrain' 'CustomTrain'
] ]
import torch import torch
@ -52,169 +52,169 @@ device = "cuda:0" if torch.torch.cuda.is_available() else "cpu"
#todo: document completely #todo: document completely
def set_device(self, new_device): def set_device(self, new_device):
device=new_device device=new_device
class LinearRegKernel(): class LinearRegKernel():
parameters= [] parameters= []
weights=None weights=None
bias=None bias=None
def __init__(self, num_vars): def __init__(self, num_vars):
self.weights=torch.rand(num_vars, requires_grad=True, device=device) self.weights=torch.rand(num_vars, requires_grad=True, device=device)
self.bias=torch.rand(1, requires_grad=True, device=device) self.bias=torch.rand(1, requires_grad=True, device=device)
self.parameters=[self.weights,self.bias] self.parameters=[self.weights,self.bias]
def forward(self,mtx): def forward(self,mtx):
long_bias=self.bias.repeat([1,mtx.size()[1]]) long_bias=self.bias.repeat([1,mtx.size()[1]])
return torch.matmul(self.weights,mtx)+long_bias return torch.matmul(self.weights,mtx)+long_bias
class SigmoidalRegKernel(): class SigmoidalRegKernel():
parameters= [] parameters= []
weights=None weights=None
bias=None bias=None
sigmoid=torch.nn.Sigmoid() sigmoid=torch.nn.Sigmoid()
def __init__(self, num_vars): def __init__(self, num_vars):
self.weights=torch.rand(num_vars, requires_grad=True, device=device) self.weights=torch.rand(num_vars, requires_grad=True, device=device)
self.bias=torch.rand(1, requires_grad=True, device=device) self.bias=torch.rand(1, requires_grad=True, device=device)
self.parameters=[self.weights,self.bias] self.parameters=[self.weights,self.bias]
def forward(self,mtx): def forward(self,mtx):
long_bias=self.bias.repeat([1,mtx.size()[1]]) long_bias=self.bias.repeat([1,mtx.size()[1]])
return self.sigmoid(torch.matmul(self.weights,mtx)+long_bias) return self.sigmoid(torch.matmul(self.weights,mtx)+long_bias)
class SigmoidalRegKernelArthur(): class SigmoidalRegKernelArthur():
parameters= [] parameters= []
weights=None weights=None
in_bias=None in_bias=None
scal_mult=None scal_mult=None
out_bias=None out_bias=None
sigmoid=torch.nn.Sigmoid() sigmoid=torch.nn.Sigmoid()
def __init__(self, num_vars): def __init__(self, num_vars):
self.weights=torch.rand(num_vars, requires_grad=True, device=device) self.weights=torch.rand(num_vars, requires_grad=True, device=device)
self.in_bias=torch.rand(1, requires_grad=True, device=device) self.in_bias=torch.rand(1, requires_grad=True, device=device)
self.scal_mult=torch.rand(1, requires_grad=True, device=device) self.scal_mult=torch.rand(1, requires_grad=True, device=device)
self.out_bias=torch.rand(1, requires_grad=True, device=device) self.out_bias=torch.rand(1, requires_grad=True, device=device)
self.parameters=[self.weights,self.in_bias, self.scal_mult, self.out_bias] self.parameters=[self.weights,self.in_bias, self.scal_mult, self.out_bias]
def forward(self,mtx): def forward(self,mtx):
long_in_bias=self.in_bias.repeat([1,mtx.size()[1]]) long_in_bias=self.in_bias.repeat([1,mtx.size()[1]])
long_out_bias=self.out_bias.repeat([1,mtx.size()[1]]) long_out_bias=self.out_bias.repeat([1,mtx.size()[1]])
return (self.scal_mult*self.sigmoid(torch.matmul(self.weights,mtx)+long_in_bias))+long_out_bias return (self.scal_mult*self.sigmoid(torch.matmul(self.weights,mtx)+long_in_bias))+long_out_bias
class LogRegKernel(): class LogRegKernel():
parameters= [] parameters= []
weights=None weights=None
in_bias=None in_bias=None
scal_mult=None scal_mult=None
out_bias=None out_bias=None
def __init__(self, num_vars): def __init__(self, num_vars):
self.weights=torch.rand(num_vars, requires_grad=True, device=device) self.weights=torch.rand(num_vars, requires_grad=True, device=device)
self.in_bias=torch.rand(1, requires_grad=True, device=device) self.in_bias=torch.rand(1, requires_grad=True, device=device)
self.scal_mult=torch.rand(1, requires_grad=True, device=device) self.scal_mult=torch.rand(1, requires_grad=True, device=device)
self.out_bias=torch.rand(1, requires_grad=True, device=device) self.out_bias=torch.rand(1, requires_grad=True, device=device)
self.parameters=[self.weights,self.in_bias, self.scal_mult, self.out_bias] self.parameters=[self.weights,self.in_bias, self.scal_mult, self.out_bias]
def forward(self,mtx): def forward(self,mtx):
long_in_bias=self.in_bias.repeat([1,mtx.size()[1]]) long_in_bias=self.in_bias.repeat([1,mtx.size()[1]])
long_out_bias=self.out_bias.repeat([1,mtx.size()[1]]) long_out_bias=self.out_bias.repeat([1,mtx.size()[1]])
return (self.scal_mult*torch.log(torch.matmul(self.weights,mtx)+long_in_bias))+long_out_bias return (self.scal_mult*torch.log(torch.matmul(self.weights,mtx)+long_in_bias))+long_out_bias
class ExpRegKernel(): class ExpRegKernel():
parameters= [] parameters= []
weights=None weights=None
in_bias=None in_bias=None
scal_mult=None scal_mult=None
out_bias=None out_bias=None
def __init__(self, num_vars): def __init__(self, num_vars):
self.weights=torch.rand(num_vars, requires_grad=True, device=device) self.weights=torch.rand(num_vars, requires_grad=True, device=device)
self.in_bias=torch.rand(1, requires_grad=True, device=device) self.in_bias=torch.rand(1, requires_grad=True, device=device)
self.scal_mult=torch.rand(1, requires_grad=True, device=device) self.scal_mult=torch.rand(1, requires_grad=True, device=device)
self.out_bias=torch.rand(1, requires_grad=True, device=device) self.out_bias=torch.rand(1, requires_grad=True, device=device)
self.parameters=[self.weights,self.in_bias, self.scal_mult, self.out_bias] self.parameters=[self.weights,self.in_bias, self.scal_mult, self.out_bias]
def forward(self,mtx): def forward(self,mtx):
long_in_bias=self.in_bias.repeat([1,mtx.size()[1]]) long_in_bias=self.in_bias.repeat([1,mtx.size()[1]])
long_out_bias=self.out_bias.repeat([1,mtx.size()[1]]) long_out_bias=self.out_bias.repeat([1,mtx.size()[1]])
return (self.scal_mult*torch.exp(torch.matmul(self.weights,mtx)+long_in_bias))+long_out_bias return (self.scal_mult*torch.exp(torch.matmul(self.weights,mtx)+long_in_bias))+long_out_bias
class PolyRegKernel(): class PolyRegKernel():
parameters= [] parameters= []
weights=None weights=None
bias=None bias=None
power=None power=None
def __init__(self, num_vars, power): def __init__(self, num_vars, power):
self.power=power self.power=power
num_terms=self.num_poly_terms(num_vars, power) num_terms=self.num_poly_terms(num_vars, power)
self.weights=torch.rand(num_terms, requires_grad=True, device=device) self.weights=torch.rand(num_terms, requires_grad=True, device=device)
self.bias=torch.rand(1, requires_grad=True, device=device) self.bias=torch.rand(1, requires_grad=True, device=device)
self.parameters=[self.weights,self.bias] self.parameters=[self.weights,self.bias]
def num_poly_terms(self,num_vars, power): def num_poly_terms(self,num_vars, power):
if power == 0: if power == 0:
return 0 return 0
return int(self.factorial(num_vars+power-1) / self.factorial(power) / self.factorial(num_vars-1)) + self.num_poly_terms(num_vars, power-1) return int(self.factorial(num_vars+power-1) / self.factorial(power) / self.factorial(num_vars-1)) + self.num_poly_terms(num_vars, power-1)
def factorial(self,n): def factorial(self,n):
if n==0: if n==0:
return 1 return 1
else: else:
return n*self.factorial(n-1) return n*self.factorial(n-1)
def take_all_pwrs(self, vec, pwr): def take_all_pwrs(self, vec, pwr):
#todo: vectorize (kinda) #todo: vectorize (kinda)
combins=torch.combinations(vec, r=pwr, with_replacement=True) combins=torch.combinations(vec, r=pwr, with_replacement=True)
out=torch.ones(combins.size()[0]).to(device).to(torch.float) out=torch.ones(combins.size()[0]).to(device).to(torch.float)
for i in torch.t(combins).to(device).to(torch.float): for i in torch.t(combins).to(device).to(torch.float):
out *= i out *= i
if pwr == 1: if pwr == 1:
return out return out
else: else:
return torch.cat((out,self.take_all_pwrs(vec, pwr-1))) return torch.cat((out,self.take_all_pwrs(vec, pwr-1)))
def forward(self,mtx): def forward(self,mtx):
#TODO: Vectorize the last part #TODO: Vectorize the last part
cols=[] cols=[]
for i in torch.t(mtx): for i in torch.t(mtx):
cols.append(self.take_all_pwrs(i,self.power)) cols.append(self.take_all_pwrs(i,self.power))
new_mtx=torch.t(torch.stack(cols)) new_mtx=torch.t(torch.stack(cols))
long_bias=self.bias.repeat([1,mtx.size()[1]]) long_bias=self.bias.repeat([1,mtx.size()[1]])
return torch.matmul(self.weights,new_mtx)+long_bias return torch.matmul(self.weights,new_mtx)+long_bias
def SGDTrain(self, kernel, data, ground, loss=torch.nn.MSELoss(), iterations=1000, learning_rate=.1, return_losses=False): def SGDTrain(self, kernel, data, ground, loss=torch.nn.MSELoss(), iterations=1000, learning_rate=.1, return_losses=False):
optim=torch.optim.SGD(kernel.parameters, lr=learning_rate) optim=torch.optim.SGD(kernel.parameters, lr=learning_rate)
data_cuda=data.to(device) data_cuda=data.to(device)
ground_cuda=ground.to(device) ground_cuda=ground.to(device)
if (return_losses): if (return_losses):
losses=[] losses=[]
for i in range(iterations): for i in range(iterations):
with torch.set_grad_enabled(True): with torch.set_grad_enabled(True):
optim.zero_grad() optim.zero_grad()
pred=kernel.forward(data_cuda) pred=kernel.forward(data_cuda)
ls=loss(pred,ground_cuda) ls=loss(pred,ground_cuda)
losses.append(ls.item()) losses.append(ls.item())
ls.backward() ls.backward()
optim.step() optim.step()
return [kernel,losses] return [kernel,losses]
else: else:
for i in range(iterations): for i in range(iterations):
with torch.set_grad_enabled(True): with torch.set_grad_enabled(True):
optim.zero_grad() optim.zero_grad()
pred=kernel.forward(data_cuda) pred=kernel.forward(data_cuda)
ls=loss(pred,ground_cuda) ls=loss(pred,ground_cuda)
ls.backward() ls.backward()
optim.step() optim.step()
return kernel return kernel
def CustomTrain(self, kernel, optim, data, ground, loss=torch.nn.MSELoss(), iterations=1000, return_losses=False): def CustomTrain(self, kernel, optim, data, ground, loss=torch.nn.MSELoss(), iterations=1000, return_losses=False):
data_cuda=data.to(device) data_cuda=data.to(device)
ground_cuda=ground.to(device) ground_cuda=ground.to(device)
if (return_losses): if (return_losses):
losses=[] losses=[]
for i in range(iterations): for i in range(iterations):
with torch.set_grad_enabled(True): with torch.set_grad_enabled(True):
optim.zero_grad() optim.zero_grad()
pred=kernel.forward(data) pred=kernel.forward(data)
ls=loss(pred,ground) ls=loss(pred,ground)
losses.append(ls.item()) losses.append(ls.item())
ls.backward() ls.backward()
optim.step() optim.step()
return [kernel,losses] return [kernel,losses]
else: else:
for i in range(iterations): for i in range(iterations):
with torch.set_grad_enabled(True): with torch.set_grad_enabled(True):
optim.zero_grad() optim.zero_grad()
pred=kernel.forward(data_cuda) pred=kernel.forward(data_cuda)
ls=loss(pred,ground_cuda) ls=loss(pred,ground_cuda)
ls.backward() ls.backward()
optim.step() optim.step()
return kernel return kernel

View File

@ -11,112 +11,112 @@ __version__ = "2.0.1.001"
#changelog should be viewed using print(analysis.__changelog__) #changelog should be viewed using print(analysis.__changelog__)
__changelog__ = """changelog: __changelog__ = """changelog:
2.0.1.001: 2.0.1.001:
- removed matplotlib import - removed matplotlib import
- removed graphloss() - removed graphloss()
2.0.1.000: 2.0.1.000:
- added net, dataset, dataloader, and stdtrain template definitions - added net, dataset, dataloader, and stdtrain template definitions
- added graphloss function - added graphloss function
2.0.0.001: 2.0.0.001:
- added clear functions - added clear functions
2.0.0.000: 2.0.0.000:
- complete rewrite planned - complete rewrite planned
- depreciated 1.0.0.xxx versions - depreciated 1.0.0.xxx versions
- added simple training loop - added simple training loop
1.0.0.xxx: 1.0.0.xxx:
-added generation of ANNS, basic SGD training -added generation of ANNS, basic SGD training
""" """
__author__ = ( __author__ = (
"Arthur Lu <arthurlu@ttic.edu>," "Arthur Lu <arthurlu@ttic.edu>,"
"Jacob Levine <jlevine@ttic.edu>," "Jacob Levine <jlevine@ttic.edu>,"
) )
__all__ = [ __all__ = [
'clear', 'clear',
'net', 'net',
'dataset', 'dataset',
'dataloader', 'dataloader',
'train', 'train',
'stdtrainer', 'stdtrainer',
] ]
import torch import torch
from os import system, name from os import system, name
import numpy as np import numpy as np
def clear(): def clear():
if name == 'nt': if name == 'nt':
_ = system('cls') _ = system('cls')
else: else:
_ = system('clear') _ = system('clear')
class net(torch.nn.Module): #template for standard neural net class net(torch.nn.Module): #template for standard neural net
def __init__(self): def __init__(self):
super(Net, self).__init__() super(Net, self).__init__()
def forward(self, input): def forward(self, input):
pass pass
class dataset(torch.utils.data.Dataset): #template for standard dataset class dataset(torch.utils.data.Dataset): #template for standard dataset
def __init__(self): def __init__(self):
super(torch.utils.data.Dataset).__init__() super(torch.utils.data.Dataset).__init__()
def __getitem__(self, index): def __getitem__(self, index):
pass pass
def __len__(self): def __len__(self):
pass pass
def dataloader(dataset, batch_size, num_workers, shuffle = True): def dataloader(dataset, batch_size, num_workers, shuffle = True):
return torch.utils.data.DataLoader(dataset, batch_size=batch_size, shuffle=shuffle, num_workers=num_workers) return torch.utils.data.DataLoader(dataset, batch_size=batch_size, shuffle=shuffle, num_workers=num_workers)
def train(device, net, epochs, trainloader, optimizer, criterion): #expects standard dataloader, whch returns (inputs, labels) def train(device, net, epochs, trainloader, optimizer, criterion): #expects standard dataloader, whch returns (inputs, labels)
dataset_len = trainloader.dataset.__len__() dataset_len = trainloader.dataset.__len__()
iter_count = 0 iter_count = 0
running_loss = 0 running_loss = 0
running_loss_list = [] running_loss_list = []
for epoch in range(epochs): # loop over the dataset multiple times for epoch in range(epochs): # loop over the dataset multiple times
for i, data in enumerate(trainloader, 0): for i, data in enumerate(trainloader, 0):
inputs = data[0].to(device) inputs = data[0].to(device)
labels = data[1].to(device) labels = data[1].to(device)
optimizer.zero_grad() optimizer.zero_grad()
outputs = net(inputs) outputs = net(inputs)
loss = criterion(outputs, labels.to(torch.float)) loss = criterion(outputs, labels.to(torch.float))
loss.backward() loss.backward()
optimizer.step() optimizer.step()
# monitoring steps below # monitoring steps below
iter_count += 1 iter_count += 1
running_loss += loss.item() running_loss += loss.item()
running_loss_list.append(running_loss) running_loss_list.append(running_loss)
clear() clear()
print("training on: " + device) print("training on: " + device)
print("iteration: " + str(i) + "/" + str(int(dataset_len / trainloader.batch_size)) + " | " + "epoch: " + str(epoch) + "/" + str(epochs)) print("iteration: " + str(i) + "/" + str(int(dataset_len / trainloader.batch_size)) + " | " + "epoch: " + str(epoch) + "/" + str(epochs))
print("current batch loss: " + str(loss.item)) print("current batch loss: " + str(loss.item))
print("running loss: " + str(running_loss / iter_count)) print("running loss: " + str(running_loss / iter_count))
return net, running_loss_list return net, running_loss_list
print("finished training") print("finished training")
def stdtrainer(net, criterion, optimizer, dataloader, epochs, batch_size): def stdtrainer(net, criterion, optimizer, dataloader, epochs, batch_size):
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
net = net.to(device) net = net.to(device)
criterion = criterion.to(device) criterion = criterion.to(device)
optimizer = optimizer.to(device) optimizer = optimizer.to(device)
trainloader = dataloader trainloader = dataloader
return train(device, net, epochs, trainloader, optimizer, criterion) return train(device, net, epochs, trainloader, optimizer, criterion)

View File

@ -10,25 +10,25 @@ __version__ = "1.0.0.000"
#changelog should be viewed using print(analysis.__changelog__) #changelog should be viewed using print(analysis.__changelog__)
__changelog__ = """changelog: __changelog__ = """changelog:
1.0.0.000: 1.0.0.000:
- created visualization.py - created visualization.py
- added graphloss() - added graphloss()
- added imports - added imports
""" """
__author__ = ( __author__ = (
"Arthur Lu <arthurlu@ttic.edu>," "Arthur Lu <arthurlu@ttic.edu>,"
"Jacob Levine <jlevine@ttic.edu>," "Jacob Levine <jlevine@ttic.edu>,"
) )
__all__ = [ __all__ = [
'graphloss', 'graphloss',
] ]
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
def graphloss(losses): def graphloss(losses):
x = range(0, len(losses)) x = range(0, len(losses))
plt.plot(x, losses) plt.plot(x, losses)
plt.show() plt.show()

View File

@ -3,24 +3,24 @@ import setuptools
requirements = [] requirements = []
with open("requirements.txt", 'r') as file: with open("requirements.txt", 'r') as file:
for line in file: for line in file:
requirements.append(line) requirements.append(line)
setuptools.setup( setuptools.setup(
name="analysis", name="analysis",
version="1.0.0.012", version="1.0.0.012",
author="The Titan Scouting Team", author="The Titan Scouting Team",
author_email="titanscout2022@gmail.com", author_email="titanscout2022@gmail.com",
description="analysis package developed by Titan Scouting for The Red Alliance", description="analysis package developed by Titan Scouting for The Red Alliance",
long_description="", long_description="",
long_description_content_type="text/markdown", long_description_content_type="text/markdown",
url="https://github.com/titanscout2022/tr2022-strategy", url="https://github.com/titanscout2022/tr2022-strategy",
packages=setuptools.find_packages(), packages=setuptools.find_packages(),
install_requires=requirements, install_requires=requirements,
license = "GNU General Public License v3.0", license = "GNU General Public License v3.0",
classifiers=[ classifiers=[
"Programming Language :: Python :: 3", "Programming Language :: Python :: 3",
"Operating System :: OS Independent", "Operating System :: OS Independent",
], ],
python_requires='>=3.6', python_requires='>=3.6',
) )

View File

@ -4,99 +4,99 @@ import pandas as pd
import time import time
def pull_new_tba_matches(apikey, competition, cutoff): def pull_new_tba_matches(apikey, competition, cutoff):
api_key= apikey api_key= apikey
x=requests.get("https://www.thebluealliance.com/api/v3/event/"+competition+"/matches/simple", headers={"X-TBA-Auth_Key":api_key}) x=requests.get("https://www.thebluealliance.com/api/v3/event/"+competition+"/matches/simple", headers={"X-TBA-Auth_Key":api_key})
out = [] out = []
for i in x.json(): for i in x.json():
if (i["actual_time"] != None and i["actual_time"]-cutoff >= 0 and i["comp_level"] == "qm"): if (i["actual_time"] != None and i["actual_time"]-cutoff >= 0 and i["comp_level"] == "qm"):
out.append({"match" : i['match_number'], "blue" : list(map(lambda x: int(x[3:]), i['alliances']['blue']['team_keys'])), "red" : list(map(lambda x: int(x[3:]), i['alliances']['red']['team_keys'])), "winner": i["winning_alliance"]}) out.append({"match" : i['match_number'], "blue" : list(map(lambda x: int(x[3:]), i['alliances']['blue']['team_keys'])), "red" : list(map(lambda x: int(x[3:]), i['alliances']['red']['team_keys'])), "winner": i["winning_alliance"]})
return out return out
def get_team_match_data(apikey, competition, team_num): def get_team_match_data(apikey, competition, team_num):
client = pymongo.MongoClient(apikey) client = pymongo.MongoClient(apikey)
db = client.data_scouting db = client.data_scouting
mdata = db.matchdata mdata = db.matchdata
out = {} out = {}
for i in mdata.find({"competition" : competition, "team_scouted": team_num}): for i in mdata.find({"competition" : competition, "team_scouted": team_num}):
out[i['match']] = i['data'] out[i['match']] = i['data']
return pd.DataFrame(out) return pd.DataFrame(out)
def get_team_pit_data(apikey, competition, team_num): def get_team_pit_data(apikey, competition, team_num):
client = pymongo.MongoClient(apikey) client = pymongo.MongoClient(apikey)
db = client.data_scouting db = client.data_scouting
mdata = db.pitdata mdata = db.pitdata
out = {} out = {}
return mdata.find_one({"competition" : competition, "team_scouted": team_num})["data"] return mdata.find_one({"competition" : competition, "team_scouted": team_num})["data"]
def get_team_metrics_data(apikey, competition, team_num): def get_team_metrics_data(apikey, competition, team_num):
client = pymongo.MongoClient(apikey) client = pymongo.MongoClient(apikey)
db = client.data_processing db = client.data_processing
mdata = db.team_metrics mdata = db.team_metrics
return mdata.find_one({"competition" : competition, "team": team_num}) return mdata.find_one({"competition" : competition, "team": team_num})
def unkeyify_2l(layered_dict): def unkeyify_2l(layered_dict):
out = {} out = {}
for i in layered_dict.keys(): for i in layered_dict.keys():
add = [] add = []
sortkey = [] sortkey = []
for j in layered_dict[i].keys(): for j in layered_dict[i].keys():
add.append([j,layered_dict[i][j]]) add.append([j,layered_dict[i][j]])
add.sort(key = lambda x: x[0]) add.sort(key = lambda x: x[0])
out[i] = list(map(lambda x: x[1], add)) out[i] = list(map(lambda x: x[1], add))
return out return out
def get_match_data_formatted(apikey, competition): def get_match_data_formatted(apikey, competition):
client = pymongo.MongoClient(apikey) client = pymongo.MongoClient(apikey)
db = client.data_scouting db = client.data_scouting
mdata = db.teamlist mdata = db.teamlist
x=mdata.find_one({"competition":competition}) x=mdata.find_one({"competition":competition})
out = {} out = {}
for i in x: for i in x:
try: try:
out[int(i)] = unkeyify_2l(get_team_match_data(apikey, competition, int(i)).transpose().to_dict()) out[int(i)] = unkeyify_2l(get_team_match_data(apikey, competition, int(i)).transpose().to_dict())
except: except:
pass pass
return out return out
def get_pit_data_formatted(apikey, competition): def get_pit_data_formatted(apikey, competition):
client = pymongo.MongoClient(apikey) client = pymongo.MongoClient(apikey)
db = client.data_scouting db = client.data_scouting
mdata = db.teamlist mdata = db.teamlist
x=mdata.find_one({"competition":competition}) x=mdata.find_one({"competition":competition})
out = {} out = {}
for i in x: for i in x:
try: try:
out[int(i)] = get_team_pit_data(apikey, competition, int(i)) out[int(i)] = get_team_pit_data(apikey, competition, int(i))
except: except:
pass pass
return out return out
def push_team_tests_data(apikey, competition, team_num, data, dbname = "data_processing", colname = "team_tests"): def push_team_tests_data(apikey, competition, team_num, data, dbname = "data_processing", colname = "team_tests"):
client = pymongo.MongoClient(apikey) client = pymongo.MongoClient(apikey)
db = client[dbname] db = client[dbname]
mdata = db[colname] mdata = db[colname]
mdata.replace_one({"competition" : competition, "team": team_num}, {"_id": competition+str(team_num)+"am", "competition" : competition, "team" : team_num, "data" : data}, True) mdata.replace_one({"competition" : competition, "team": team_num}, {"_id": competition+str(team_num)+"am", "competition" : competition, "team" : team_num, "data" : data}, True)
def push_team_metrics_data(apikey, competition, team_num, data, dbname = "data_processing", colname = "team_metrics"): def push_team_metrics_data(apikey, competition, team_num, data, dbname = "data_processing", colname = "team_metrics"):
client = pymongo.MongoClient(apikey) client = pymongo.MongoClient(apikey)
db = client[dbname] db = client[dbname]
mdata = db[colname] mdata = db[colname]
mdata.replace_one({"competition" : competition, "team": team_num}, {"_id": competition+str(team_num)+"am", "competition" : competition, "team" : team_num, "metrics" : data}, True) mdata.replace_one({"competition" : competition, "team": team_num}, {"_id": competition+str(team_num)+"am", "competition" : competition, "team" : team_num, "metrics" : data}, True)
def push_team_pit_data(apikey, competition, variable, data, dbname = "data_processing", colname = "team_pit"): def push_team_pit_data(apikey, competition, variable, data, dbname = "data_processing", colname = "team_pit"):
client = pymongo.MongoClient(apikey) client = pymongo.MongoClient(apikey)
db = client[dbname] db = client[dbname]
mdata = db[colname] mdata = db[colname]
mdata.replace_one({"competition" : competition, "variable": variable}, {"competition" : competition, "variable" : variable, "data" : data}, True) mdata.replace_one({"competition" : competition, "variable": variable}, {"competition" : competition, "variable" : variable, "data" : data}, True)
def get_analysis_flags(apikey, flag): def get_analysis_flags(apikey, flag):
client = pymongo.MongoClient(apikey) client = pymongo.MongoClient(apikey)
db = client.data_processing db = client.data_processing
mdata = db.flags mdata = db.flags
return mdata.find_one({flag:{"$exists":True}}) return mdata.find_one({flag:{"$exists":True}})
def set_analysis_flags(apikey, flag, data): def set_analysis_flags(apikey, flag, data):
client = pymongo.MongoClient(apikey) client = pymongo.MongoClient(apikey)
db = client.data_processing db = client.data_processing
mdata = db.flags mdata = db.flags
return mdata.replace_one({flag:{"$exists":True}}, data, True) return mdata.replace_one({flag:{"$exists":True}}, data, True)

View File

@ -4,56 +4,56 @@ import pymongo
import operator import operator
def load_config(file): def load_config(file):
config_vector = {} config_vector = {}
file = an.load_csv(file) file = an.load_csv(file)
for line in file[1:]: for line in file[1:]:
config_vector[line[0]] = line[1:] config_vector[line[0]] = line[1:]
return (file[0][0], config_vector) return (file[0][0], config_vector)
def get_metrics_processed_formatted(apikey, competition): def get_metrics_processed_formatted(apikey, competition):
client = pymongo.MongoClient(apikey) client = pymongo.MongoClient(apikey)
db = client.data_scouting db = client.data_scouting
mdata = db.teamlist mdata = db.teamlist
x=mdata.find_one({"competition":competition}) x=mdata.find_one({"competition":competition})
out = {} out = {}
for i in x: for i in x:
try: try:
out[int(i)] = d.get_team_metrics_data(apikey, competition, int(i)) out[int(i)] = d.get_team_metrics_data(apikey, competition, int(i))
except: except:
pass pass
return out return out
def main(): def main():
apikey = an.load_csv("keys.txt")[0][0] apikey = an.load_csv("keys.txt")[0][0]
tbakey = an.load_csv("keys.txt")[1][0] tbakey = an.load_csv("keys.txt")[1][0]
competition, config = load_config("config.csv") competition, config = load_config("config.csv")
metrics = get_metrics_processed_formatted(apikey, competition) metrics = get_metrics_processed_formatted(apikey, competition)
elo = {} elo = {}
gl2 = {} gl2 = {}
for team in metrics: for team in metrics:
elo[team] = metrics[team]["metrics"]["elo"]["score"] elo[team] = metrics[team]["metrics"]["elo"]["score"]
gl2[team] = metrics[team]["metrics"]["gl2"]["score"] gl2[team] = metrics[team]["metrics"]["gl2"]["score"]
elo = {k: v for k, v in sorted(elo.items(), key=lambda item: item[1])} elo = {k: v for k, v in sorted(elo.items(), key=lambda item: item[1])}
gl2 = {k: v for k, v in sorted(gl2.items(), key=lambda item: item[1])} gl2 = {k: v for k, v in sorted(gl2.items(), key=lambda item: item[1])}
for team in elo: for team in elo:
print("teams sorted by elo:") print("teams sorted by elo:")
print("" + str(team) + " | " + str(elo[team])) print("" + str(team) + " | " + str(elo[team]))
print("*"*25) print("*"*25)
for team in gl2: for team in gl2:
print("teams sorted by glicko2:") print("teams sorted by glicko2:")
print("" + str(team) + " | " + str(gl2[team])) print("" + str(team) + " | " + str(gl2[team]))
main() main()

View File

@ -7,81 +7,81 @@ __version__ = "0.0.5.002"
# changelog should be viewed using print(analysis.__changelog__) # changelog should be viewed using print(analysis.__changelog__)
__changelog__ = """changelog: __changelog__ = """changelog:
0.0.5.002: 0.0.5.002:
- made changes due to refactoring of analysis - made changes due to refactoring of analysis
0.0.5.001: 0.0.5.001:
- text fixes - text fixes
- removed matplotlib requirement - removed matplotlib requirement
0.0.5.000: 0.0.5.000:
- improved user interface - improved user interface
0.0.4.002: 0.0.4.002:
- removed unessasary code - removed unessasary code
0.0.4.001: 0.0.4.001:
- fixed bug where X range for regression was determined before sanitization - fixed bug where X range for regression was determined before sanitization
- better sanitized data - better sanitized data
0.0.4.000: 0.0.4.000:
- fixed spelling issue in __changelog__ - fixed spelling issue in __changelog__
- addressed nan bug in regression - addressed nan bug in regression
- fixed errors on line 335 with metrics calling incorrect key "glicko2" - fixed errors on line 335 with metrics calling incorrect key "glicko2"
- fixed errors in metrics computing - fixed errors in metrics computing
0.0.3.000: 0.0.3.000:
- added analysis to pit data - added analysis to pit data
0.0.2.001: 0.0.2.001:
- minor stability patches - minor stability patches
- implemented db syncing for timestamps - implemented db syncing for timestamps
- fixed bugs - fixed bugs
0.0.2.000: 0.0.2.000:
- finalized testing and small fixes - finalized testing and small fixes
0.0.1.004: 0.0.1.004:
- finished metrics implement, trueskill is bugged - finished metrics implement, trueskill is bugged
0.0.1.003: 0.0.1.003:
- working - working
0.0.1.002: 0.0.1.002:
- started implement of metrics - started implement of metrics
0.0.1.001: 0.0.1.001:
- cleaned up imports - cleaned up imports
0.0.1.000: 0.0.1.000:
- tested working, can push to database - tested working, can push to database
0.0.0.009: 0.0.0.009:
- tested working - tested working
- prints out stats for the time being, will push to database later - prints out stats for the time being, will push to database later
0.0.0.008: 0.0.0.008:
- added data import - added data import
- removed tba import - removed tba import
- finished main method - finished main method
0.0.0.007: 0.0.0.007:
- added load_config - added load_config
- optimized simpleloop for readibility - optimized simpleloop for readibility
- added __all__ entries - added __all__ entries
- added simplestats engine - added simplestats engine
- pending testing - pending testing
0.0.0.006: 0.0.0.006:
- fixes - fixes
0.0.0.005: 0.0.0.005:
- imported pickle - imported pickle
- created custom database object - created custom database object
0.0.0.004: 0.0.0.004:
- fixed simpleloop to actually return a vector - fixed simpleloop to actually return a vector
0.0.0.003: 0.0.0.003:
- added metricsloop which is unfinished - added metricsloop which is unfinished
0.0.0.002: 0.0.0.002:
- added simpleloop which is untested until data is provided - added simpleloop which is untested until data is provided
0.0.0.001: 0.0.0.001:
- created script - created script
- added analysis, numba, numpy imports - added analysis, numba, numpy imports
""" """
__author__ = ( __author__ = (
"Arthur Lu <learthurgo@gmail.com>", "Arthur Lu <learthurgo@gmail.com>",
"Jacob Levine <jlevine@imsa.edu>", "Jacob Levine <jlevine@imsa.edu>",
) )
__all__ = [ __all__ = [
"main", "main",
"load_config", "load_config",
"simpleloop", "simpleloop",
"simplestats", "simplestats",
"metricsloop" "metricsloop"
] ]
# imports: # imports:
@ -95,273 +95,273 @@ import time
import warnings import warnings
def main(): def main():
warnings.filterwarnings("ignore") warnings.filterwarnings("ignore")
while(True): while(True):
current_time = time.time() current_time = time.time()
print("[OK] time: " + str(current_time)) print("[OK] time: " + str(current_time))
start = time.time() start = time.time()
config = load_config(Path("config/stats.config")) config = load_config(Path("config/stats.config"))
competition = an.load_csv(Path("config/competition.config"))[0][0] competition = an.load_csv(Path("config/competition.config"))[0][0]
print("[OK] configs loaded") print("[OK] configs loaded")
apikey = an.load_csv(Path("config/keys.config"))[0][0] apikey = an.load_csv(Path("config/keys.config"))[0][0]
tbakey = an.load_csv(Path("config/keys.config"))[1][0] tbakey = an.load_csv(Path("config/keys.config"))[1][0]
print("[OK] loaded keys") print("[OK] loaded keys")
previous_time = d.get_analysis_flags(apikey, "latest_update") previous_time = d.get_analysis_flags(apikey, "latest_update")
if(previous_time == None): if(previous_time == None):
d.set_analysis_flags(apikey, "latest_update", 0) d.set_analysis_flags(apikey, "latest_update", 0)
previous_time = 0 previous_time = 0
else: else:
previous_time = previous_time["latest_update"] previous_time = previous_time["latest_update"]
print("[OK] analysis backtimed to: " + str(previous_time)) print("[OK] analysis backtimed to: " + str(previous_time))
print("[OK] loading data") print("[OK] loading data")
start = time.time() start = time.time()
data = d.get_match_data_formatted(apikey, competition) data = d.get_match_data_formatted(apikey, competition)
pit_data = d.pit = d.get_pit_data_formatted(apikey, competition) pit_data = d.pit = d.get_pit_data_formatted(apikey, competition)
print("[OK] loaded data in " + str(time.time() - start) + " seconds") print("[OK] loaded data in " + str(time.time() - start) + " seconds")
print("[OK] running tests") print("[OK] running tests")
start = time.time() start = time.time()
results = simpleloop(data, config) results = simpleloop(data, config)
print("[OK] finished tests in " + str(time.time() - start) + " seconds") print("[OK] finished tests in " + str(time.time() - start) + " seconds")
print("[OK] running metrics") print("[OK] running metrics")
start = time.time() start = time.time()
metricsloop(tbakey, apikey, competition, previous_time) metricsloop(tbakey, apikey, competition, previous_time)
print("[OK] finished metrics in " + str(time.time() - start) + " seconds") print("[OK] finished metrics in " + str(time.time() - start) + " seconds")
print("[OK] running pit analysis") print("[OK] running pit analysis")
start = time.time() start = time.time()
pit = pitloop(pit_data, config) pit = pitloop(pit_data, config)
print("[OK] finished pit analysis in " + str(time.time() - start) + " seconds") print("[OK] finished pit analysis in " + str(time.time() - start) + " seconds")
d.set_analysis_flags(apikey, "latest_update", {"latest_update":current_time}) d.set_analysis_flags(apikey, "latest_update", {"latest_update":current_time})
print("[OK] pushing to database") print("[OK] pushing to database")
start = time.time() start = time.time()
push_to_database(apikey, competition, results, pit) push_to_database(apikey, competition, results, pit)
print("[OK] pushed to database in " + str(time.time() - start) + " seconds") print("[OK] pushed to database in " + str(time.time() - start) + " seconds")
clear() clear()
def clear(): def clear():
# for windows # for windows
if name == 'nt': if name == 'nt':
_ = system('cls') _ = system('cls')
# for mac and linux(here, os.name is 'posix') # for mac and linux(here, os.name is 'posix')
else: else:
_ = system('clear') _ = system('clear')
def load_config(file): def load_config(file):
config_vector = {} config_vector = {}
file = an.load_csv(file) file = an.load_csv(file)
for line in file: for line in file:
config_vector[line[0]] = line[1:] config_vector[line[0]] = line[1:]
return config_vector return config_vector
def simpleloop(data, tests): # expects 3D array with [Team][Variable][Match] def simpleloop(data, tests): # expects 3D array with [Team][Variable][Match]
return_vector = {} return_vector = {}
for team in data: for team in data:
variable_vector = {} variable_vector = {}
for variable in data[team]: for variable in data[team]:
test_vector = {} test_vector = {}
variable_data = data[team][variable] variable_data = data[team][variable]
if(variable in tests): if(variable in tests):
for test in tests[variable]: for test in tests[variable]:
test_vector[test] = simplestats(variable_data, test) test_vector[test] = simplestats(variable_data, test)
else: else:
pass pass
variable_vector[variable] = test_vector variable_vector[variable] = test_vector
return_vector[team] = variable_vector return_vector[team] = variable_vector
return return_vector return return_vector
def simplestats(data, test): def simplestats(data, test):
data = np.array(data) data = np.array(data)
data = data[np.isfinite(data)] data = data[np.isfinite(data)]
ranges = list(range(len(data))) ranges = list(range(len(data)))
if(test == "basic_stats"): if(test == "basic_stats"):
return an.basic_stats(data) return an.basic_stats(data)
if(test == "historical_analysis"): if(test == "historical_analysis"):
return an.histo_analysis([ranges, data]) return an.histo_analysis([ranges, data])
if(test == "regression_linear"): if(test == "regression_linear"):
return an.regression(ranges, data, ['lin']) return an.regression(ranges, data, ['lin'])
if(test == "regression_logarithmic"): if(test == "regression_logarithmic"):
return an.regression(ranges, data, ['log']) return an.regression(ranges, data, ['log'])
if(test == "regression_exponential"): if(test == "regression_exponential"):
return an.regression(ranges, data, ['exp']) return an.regression(ranges, data, ['exp'])
if(test == "regression_polynomial"): if(test == "regression_polynomial"):
return an.regression(ranges, data, ['ply']) return an.regression(ranges, data, ['ply'])
if(test == "regression_sigmoidal"): if(test == "regression_sigmoidal"):
return an.regression(ranges, data, ['sig']) return an.regression(ranges, data, ['sig'])
def push_to_database(apikey, competition, results, pit): def push_to_database(apikey, competition, results, pit):
for team in results: for team in results:
d.push_team_tests_data(apikey, competition, team, results[team]) d.push_team_tests_data(apikey, competition, team, results[team])
for variable in pit: for variable in pit:
d.push_team_pit_data(apikey, competition, variable, pit[variable]) d.push_team_pit_data(apikey, competition, variable, pit[variable])
def metricsloop(tbakey, apikey, competition, timestamp): # listener based metrics update def metricsloop(tbakey, apikey, competition, timestamp): # listener based metrics update
elo_N = 400 elo_N = 400
elo_K = 24 elo_K = 24
matches = d.pull_new_tba_matches(tbakey, competition, timestamp) matches = d.pull_new_tba_matches(tbakey, competition, timestamp)
red = {} red = {}
blu = {} blu = {}
for match in matches: for match in matches:
red = load_metrics(apikey, competition, match, "red") red = load_metrics(apikey, competition, match, "red")
blu = load_metrics(apikey, competition, match, "blue") blu = load_metrics(apikey, competition, match, "blue")
elo_red_total = 0 elo_red_total = 0
elo_blu_total = 0 elo_blu_total = 0
gl2_red_score_total = 0 gl2_red_score_total = 0
gl2_blu_score_total = 0 gl2_blu_score_total = 0
gl2_red_rd_total = 0 gl2_red_rd_total = 0
gl2_blu_rd_total = 0 gl2_blu_rd_total = 0
gl2_red_vol_total = 0 gl2_red_vol_total = 0
gl2_blu_vol_total = 0 gl2_blu_vol_total = 0
for team in red: for team in red:
elo_red_total += red[team]["elo"]["score"] elo_red_total += red[team]["elo"]["score"]
gl2_red_score_total += red[team]["gl2"]["score"] gl2_red_score_total += red[team]["gl2"]["score"]
gl2_red_rd_total += red[team]["gl2"]["rd"] gl2_red_rd_total += red[team]["gl2"]["rd"]
gl2_red_vol_total += red[team]["gl2"]["vol"] gl2_red_vol_total += red[team]["gl2"]["vol"]
for team in blu: for team in blu:
elo_blu_total += blu[team]["elo"]["score"] elo_blu_total += blu[team]["elo"]["score"]
gl2_blu_score_total += blu[team]["gl2"]["score"] gl2_blu_score_total += blu[team]["gl2"]["score"]
gl2_blu_rd_total += blu[team]["gl2"]["rd"] gl2_blu_rd_total += blu[team]["gl2"]["rd"]
gl2_blu_vol_total += blu[team]["gl2"]["vol"] gl2_blu_vol_total += blu[team]["gl2"]["vol"]
red_elo = {"score": elo_red_total / len(red)} red_elo = {"score": elo_red_total / len(red)}
blu_elo = {"score": elo_blu_total / len(blu)} blu_elo = {"score": elo_blu_total / len(blu)}
red_gl2 = {"score": gl2_red_score_total / len(red), "rd": gl2_red_rd_total / len(red), "vol": gl2_red_vol_total / len(red)} red_gl2 = {"score": gl2_red_score_total / len(red), "rd": gl2_red_rd_total / len(red), "vol": gl2_red_vol_total / len(red)}
blu_gl2 = {"score": gl2_blu_score_total / len(blu), "rd": gl2_blu_rd_total / len(blu), "vol": gl2_blu_vol_total / len(blu)} blu_gl2 = {"score": gl2_blu_score_total / len(blu), "rd": gl2_blu_rd_total / len(blu), "vol": gl2_blu_vol_total / len(blu)}
if(match["winner"] == "red"): if(match["winner"] == "red"):
observations = {"red": 1, "blu": 0} observations = {"red": 1, "blu": 0}
elif(match["winner"] == "blue"): elif(match["winner"] == "blue"):
observations = {"red": 0, "blu": 1} observations = {"red": 0, "blu": 1}
else: else:
observations = {"red": 0.5, "blu": 0.5} observations = {"red": 0.5, "blu": 0.5}
red_elo_delta = an.Metrics.elo(red_elo["score"], blu_elo["score"], observations["red"], elo_N, elo_K) - red_elo["score"] red_elo_delta = an.Metrics.elo(red_elo["score"], blu_elo["score"], observations["red"], elo_N, elo_K) - red_elo["score"]
blu_elo_delta = an.Metrics.elo(blu_elo["score"], red_elo["score"], observations["blu"], elo_N, elo_K) - blu_elo["score"] blu_elo_delta = an.Metrics.elo(blu_elo["score"], red_elo["score"], observations["blu"], elo_N, elo_K) - blu_elo["score"]
new_red_gl2_score, new_red_gl2_rd, new_red_gl2_vol = an.Metrics.glicko2(red_gl2["score"], red_gl2["rd"], red_gl2["vol"], [blu_gl2["score"]], [blu_gl2["rd"]], [observations["red"], observations["blu"]]) new_red_gl2_score, new_red_gl2_rd, new_red_gl2_vol = an.Metrics.glicko2(red_gl2["score"], red_gl2["rd"], red_gl2["vol"], [blu_gl2["score"]], [blu_gl2["rd"]], [observations["red"], observations["blu"]])
new_blu_gl2_score, new_blu_gl2_rd, new_blu_gl2_vol = an.Metrics.glicko2(blu_gl2["score"], blu_gl2["rd"], blu_gl2["vol"], [red_gl2["score"]], [red_gl2["rd"]], [observations["blu"], observations["red"]]) new_blu_gl2_score, new_blu_gl2_rd, new_blu_gl2_vol = an.Metrics.glicko2(blu_gl2["score"], blu_gl2["rd"], blu_gl2["vol"], [red_gl2["score"]], [red_gl2["rd"]], [observations["blu"], observations["red"]])
red_gl2_delta = {"score": new_red_gl2_score - red_gl2["score"], "rd": new_red_gl2_rd - red_gl2["rd"], "vol": new_red_gl2_vol - red_gl2["vol"]} red_gl2_delta = {"score": new_red_gl2_score - red_gl2["score"], "rd": new_red_gl2_rd - red_gl2["rd"], "vol": new_red_gl2_vol - red_gl2["vol"]}
blu_gl2_delta = {"score": new_blu_gl2_score - blu_gl2["score"], "rd": new_blu_gl2_rd - blu_gl2["rd"], "vol": new_blu_gl2_vol - blu_gl2["vol"]} blu_gl2_delta = {"score": new_blu_gl2_score - blu_gl2["score"], "rd": new_blu_gl2_rd - blu_gl2["rd"], "vol": new_blu_gl2_vol - blu_gl2["vol"]}
for team in red: for team in red:
red[team]["elo"]["score"] = red[team]["elo"]["score"] + red_elo_delta red[team]["elo"]["score"] = red[team]["elo"]["score"] + red_elo_delta
red[team]["gl2"]["score"] = red[team]["gl2"]["score"] + red_gl2_delta["score"] red[team]["gl2"]["score"] = red[team]["gl2"]["score"] + red_gl2_delta["score"]
red[team]["gl2"]["rd"] = red[team]["gl2"]["rd"] + red_gl2_delta["rd"] red[team]["gl2"]["rd"] = red[team]["gl2"]["rd"] + red_gl2_delta["rd"]
red[team]["gl2"]["vol"] = red[team]["gl2"]["vol"] + red_gl2_delta["vol"] red[team]["gl2"]["vol"] = red[team]["gl2"]["vol"] + red_gl2_delta["vol"]
for team in blu: for team in blu:
blu[team]["elo"]["score"] = blu[team]["elo"]["score"] + blu_elo_delta blu[team]["elo"]["score"] = blu[team]["elo"]["score"] + blu_elo_delta
blu[team]["gl2"]["score"] = blu[team]["gl2"]["score"] + blu_gl2_delta["score"] blu[team]["gl2"]["score"] = blu[team]["gl2"]["score"] + blu_gl2_delta["score"]
blu[team]["gl2"]["rd"] = blu[team]["gl2"]["rd"] + blu_gl2_delta["rd"] blu[team]["gl2"]["rd"] = blu[team]["gl2"]["rd"] + blu_gl2_delta["rd"]
blu[team]["gl2"]["vol"] = blu[team]["gl2"]["vol"] + blu_gl2_delta["vol"] blu[team]["gl2"]["vol"] = blu[team]["gl2"]["vol"] + blu_gl2_delta["vol"]
temp_vector = {} temp_vector = {}
temp_vector.update(red) temp_vector.update(red)
temp_vector.update(blu) temp_vector.update(blu)
for team in temp_vector: for team in temp_vector:
d.push_team_metrics_data(apikey, competition, team, temp_vector[team]) d.push_team_metrics_data(apikey, competition, team, temp_vector[team])
def load_metrics(apikey, competition, match, group_name): def load_metrics(apikey, competition, match, group_name):
group = {} group = {}
for team in match[group_name]: for team in match[group_name]:
db_data = d.get_team_metrics_data(apikey, competition, team) db_data = d.get_team_metrics_data(apikey, competition, team)
if d.get_team_metrics_data(apikey, competition, team) == None: if d.get_team_metrics_data(apikey, competition, team) == None:
elo = {"score": 1500} elo = {"score": 1500}
gl2 = {"score": 1500, "rd": 250, "vol": 0.06} gl2 = {"score": 1500, "rd": 250, "vol": 0.06}
ts = {"mu": 25, "sigma": 25/3} ts = {"mu": 25, "sigma": 25/3}
#d.push_team_metrics_data(apikey, competition, team, {"elo":elo, "gl2":gl2,"trueskill":ts}) #d.push_team_metrics_data(apikey, competition, team, {"elo":elo, "gl2":gl2,"trueskill":ts})
group[team] = {"elo": elo, "gl2": gl2, "ts": ts} group[team] = {"elo": elo, "gl2": gl2, "ts": ts}
else: else:
metrics = db_data["metrics"] metrics = db_data["metrics"]
elo = metrics["elo"] elo = metrics["elo"]
gl2 = metrics["gl2"] gl2 = metrics["gl2"]
ts = metrics["ts"] ts = metrics["ts"]
group[team] = {"elo": elo, "gl2": gl2, "ts": ts} group[team] = {"elo": elo, "gl2": gl2, "ts": ts}
return group return group
def pitloop(pit, tests): def pitloop(pit, tests):
return_vector = {} return_vector = {}
for team in pit: for team in pit:
for variable in pit[team]: for variable in pit[team]:
if(variable in tests): if(variable in tests):
if(not variable in return_vector): if(not variable in return_vector):
return_vector[variable] = [] return_vector[variable] = []
return_vector[variable].append(pit[team][variable]) return_vector[variable].append(pit[team][variable])
return return_vector return return_vector
main() main()

View File

@ -8,20 +8,20 @@ import pymongo
# %% # %%
def get_pit_variable_data(apikey, competition): def get_pit_variable_data(apikey, competition):
client = pymongo.MongoClient(apikey) client = pymongo.MongoClient(apikey)
db = client.data_processing db = client.data_processing
mdata = db.team_pit mdata = db.team_pit
out = {} out = {}
return mdata.find() return mdata.find()
# %% # %%
def get_pit_variable_formatted(apikey, competition): def get_pit_variable_formatted(apikey, competition):
temp = get_pit_variable_data(apikey, competition) temp = get_pit_variable_data(apikey, competition)
out = {} out = {}
for i in temp: for i in temp:
out[i["variable"]] = i["data"] out[i["variable"]] = i["data"]
return out return out
# %% # %%
@ -40,16 +40,16 @@ i = 0
for variable in pit: for variable in pit:
ax[i].hist(pit[variable]) ax[i].hist(pit[variable])
ax[i].invert_xaxis() ax[i].invert_xaxis()
ax[i].set_xlabel('') ax[i].set_xlabel('')
ax[i].set_ylabel('Frequency') ax[i].set_ylabel('Frequency')
ax[i].set_title(variable) ax[i].set_title(variable)
plt.yticks(np.arange(len(pit[variable]))) plt.yticks(np.arange(len(pit[variable])))
i+=1 i+=1
plt.show() plt.show()