import pandas as pd
import numpy as np
from training_utils import train_eval_model, store_model

### 1. Load data from data.csv file
data_train = pd.read_csv("data_train.csv", sep=';', header=0, dtype={'Gender': int, 'Age': int, 'Competitionage': int,
                                                                     '50m': np.float64, '100m': np.float64,
                                                                     '200m': np.float64})
X_train = data_train.iloc[:, 0:4]
y_train = data_train.iloc[:, 4:6]

data_val = pd.read_csv("data_val.csv", sep=';', header=0, dtype={'Gender': int, 'Age': int, 'Competitionage': int,
                                                                 '50m': np.float64, '100m': np.float64,
                                                                 '200m': np.float64})
X_test = data_val.iloc[:, 0:4]
y_test = data_val.iloc[:, 4:6]
# Convert pandas dataframes into numpy arrays (it is needed for the fitting)
X_train = X_train.values
X_test = X_test.values
y_train100m = y_train.values[:, 0]
y_train200m = y_train.values[:, 1]
y_test100m = y_test.values[:, 0]
y_test200m = y_test.values[:, 1]

### 2. Define model, train and evaluate
print("Train 100m times")
model100m, _, _ = train_eval_model(X_train, y_train100m, X_test, y_test100m, units=32)

print("Train 200m times")
model200m, _, _ = train_eval_model(X_train, y_train200m, X_test, y_test200m, units=16)

### 3. Store model
store_model(model100m, 'model100m')
store_model(model200m, 'model200m')

### Include this to train 200m model that uses 100m times
print("Train 200m times using 100m training data")
X_train_int = np.c_[X_train, y_train100m]
X_test_int = np.c_[X_test, y_test100m]
model200m_train_100, _, _ = train_eval_model(X_train_int, y_train200m, X_test_int, y_test200m)

print("Train 200m times using 100m prediction data")
pred_100_train = model100m.predict(X_train)
pred_100_test = model100m.predict(X_test)
X_train_int = np.concatenate((X_train, pred_100_train), axis=1)
X_test_int = np.concatenate((X_test, pred_100_test), axis=1)
model200m_itermediate, _, _ = train_eval_model(X_train_int, y_train200m, X_test_int, y_test200m)

store_model(model200m_train_100, 'model200m_using_100m_orig')
store_model(model200m_itermediate, 'model200m_using_100m')


import numpy as np

from ochre.datagen import DataGenerator

def dgen():
    ocr_seqs = ['abc', 'ab', 'ca8']
    gs_seqs = ['abc', 'bb', 'ca']
    p_char = 'P'
    oov_char = '@'
    n = 3
    ci = {'a': 0, 'b': 1, 'c': 2, p_char: 3, oov_char: 4}
    dg = DataGenerator(xData=ocr_seqs, yData=gs_seqs, char_to_int=ci,
                       seq_length=n, padding_char=p_char, oov_char=oov_char,
                       batch_size=1, shuffle=False)

    return dg

def test_dg():
    dg = dgen()

    assert dg.n_vocab == len(dg.char_to_int)
    assert len(dg) == 3

    x, y = dg[0]

    print(x)
    print(y)

    assert np.array_equal(x[0], np.array([0, 1, 2]))
    assert np.array_equal(y[0], np.array([[1, 0, 0, 0, 0],
                                          [0, 1, 0, 0, 0],
                                          [0, 0, 1, 0, 0]]))

def test_convert_sample():
    dg = dgen()

    cases = {
        'aaa': np.array([0, 0, 0]),
        'a': np.array([0, 3, 3]),
        'b8': np.array([1, 4, 3])
    }

    for inp, outp in cases.items():
        assert np.array_equal(dg._convert_sample(inp), outp)


from functools import reduce
from decimal import Decimal

# From stdin:
# num_of_elem=int(input())
# elements=list(map(int,input().split()))

# From a file:
num_of_elem=0
elements=""
with open('input/input03.txt','r') as file_in:
    file_lines=file_in.readlines()
    num_of_elem=int(file_lines[0])
    elements=file_lines[1]
elements=list(map(int,elements.split()))

mean=Decimal(reduce(lambda x, y: x + y,elements)/num_of_elem)
oddNumber=num_of_elem %2 == 0
median=0
if not oddNumber :
    median=elements[int((num_of_elem+1)/2)-1]
else:
    elements.sort()
    middle_left=elements[int(num_of_elem/2)-1]
    middle_right=elements[int(num_of_elem/2)]
    median=Decimal((middle_left+middle_right)/2.0)

elements_set=sorted(set(elements))

mode=None
mode_index_number=None

mode = count = elements.count(elements_set[0])
mode_index_number = elements_set[0]

for i in elements_set[1:len(elements_set)]:
    count = elements.count(i)
    if count > mode:
        mode = count
        mode_index_number = i
    elif count == mode and i < mode_index_number:
        mode_index_number = i

print(round(mean,1))
print(round(median,1))
print(mode_index_number)

10 Days of Statistics/Day 0/Mean Median and Mode/solution.py


from requests import Request, Session
import config
import json

__all__=['SendBookClass', 'SendFindClass']

config_FindClass = config.FindClass()
config_BookClass = config.BookClass()

http_proxy  = "http://localhost:8888"
https_proxy = "https://localhost:8888"
ftp_proxy   = "ftp://10.10.1.10:3128"
#cafile = 'FiddlerRoot.cer'
proxyDict = {
              "http"  : http_proxy,
              "https" : https_proxy,
              "ftp"   : ftp_proxy
            }

#print(config_FindClass.headers)

class CultSend:
    def __init__(self,url=None, headers=None, type=None, payload = None):
        self.url = url
        self.headers = headers
        self.type = type
        self.payload = payload

    def __prepare_session(self):
        s = Session()
        #params_arr = [self.type, self.url, self.headers, self.payload]
        req = self.__utility_params()
        print(req.url)
        prepped = req.prepare()
        #prepped = self.__utility_headers(prepped)
        return s, prepped

    def send_request(self):
        s, prepped = self.__prepare_session()
        print(prepped.headers)
        return s.send(prepped,proxies=proxyDict,verify=False)

    def __utility_headers(self, prepped):
        #print(prepped.headers)
        if self.type == 'GET':
            del prepped.headers['Accept-Encoding']
        return prepped

    def __utility_params(self):
        if self.type == 'GET':
            return Request(self.type, self.url,headers=self.headers)
        else:
            print(self.payload)
            return Request(self.type,self.url,data=json.dumps(self.payload), headers=self.headers)

class SendFindClass(CultSend):
    def __init__(self):
        url = config_FindClass.url
        headers = config_FindClass.headers
        type = config_FindClass.type
        super().__init__(url, headers, type)

class SendBookClass(CultSend):
    def __init__(self, book_id):
        url =config_BookClass.url.format(book_id)
        headers = config_BookClass.headers
        type = config_BookClass.type
        payload = config_BookClass.payload
        super().__init__(url, headers, type, payload)


import argparse
from datetime import datetime
import os

import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.data

from model import Model
from dataset import Dataset
from tqdm import tqdm
from sklearn.metrics import confusion_matrix, roc_curve, auc

import numpy as np
import matplotlib.pyplot as plt
from sklearn import metrics

parser = argparse.ArgumentParser(description='Test a trained multi-resolution gland classification model.')

parser.add_argument('--init_model_file', default='',help='Initial model file (optional)', dest='init_model_file')
parser.add_argument('--image_dir_high', default='../../Images/gland_classification/cropped_patches__complete_and_partial_glands_50_25_512', help='Image directory', dest='image_dir_high')
parser.add_argument('--image_dir_medium', default='../../Images/gland_classification/cropped_patches__complete_and_partial_glands_50_50_512', help='Image directory', dest='image_dir_medium')
parser.add_argument('--image_dir_low', default='../../Images/gland_classification/cropped_patches__complete_and_partial_glands_50_100_512', help='Image directory', dest='image_dir_low')
parser.add_argument('--image_dir_low2', default='../../Images/gland_classification/cropped_patches__complete_and_partial_glands_50_200_512', help='Image directory', dest='image_dir_low2')
parser.add_argument('--slide_list_filename_test', default='../dataset/slide_ids_list_gland_classification_46_slides_test_saved.txt', help='slide list test', dest='slide_list_filename_test')
parser.add_argument('--dataset_type', default='test', help='', dest='dataset_type')
parser.add_argument('--num_classes', default='2', type=int, help='Number of classes', dest='num_classes')
parser.add_argument('--batch_size', default='32', type=int, help='Batch size', dest='batch_size')
parser.add_argument('--metrics_file', default='test_metrics', help='Text file to write test metrics', dest='metrics_file')

FLAGS = parser.parse_args()

model_name = FLAGS.init_model_file.split('/')[-1][15:-4]

out_dir = '{}/{}/{}'.format(FLAGS.metrics_file,model_name,FLAGS.dataset_type)
if not os.path.exists(out_dir):
    os.makedirs(out_dir)

test_metrics_file = '{}/test_scores__{}.txt'.format(out_dir,model_name)
with open(test_metrics_file, 'w') as f:
    f.write('# model_name: {}\n'.format(model_name))
    f.write('# init_model_file: {}\n'.format(FLAGS.init_model_file))
    f.write('# image_dir_high: {}\n'.format(FLAGS.image_dir_high))
    f.write('# image_dir_medium: {}\n'.format(FLAGS.image_dir_medium))
    f.write('# image_dir_low: {}\n'.format(FLAGS.image_dir_low))
    f.write('# image_dir_low2: {}\n'.format(FLAGS.image_dir_low2))
    f.write('# slide_list_filename_test: {}\n'.format(FLAGS.slide_list_filename_test))
    f.write('# num_classes: {}\n'.format(FLAGS.num_classes))
    f.write('# batch_size: {}\n'.format(FLAGS.batch_size))
    f.write('# metrics_file: {}\n'.format(test_metrics_file))
    f.write('# patient_id\tslide_id\timage_id\tlabel\tprediction\tscore_benign\tscore_malignant\n')

print('model_name: {}'.format(model_name))
print('init_model_file: {}'.format(FLAGS.init_model_file))
print('image_dir_high: {}'.format(FLAGS.image_dir_high))
print('image_dir_medium: {}'.format(FLAGS.image_dir_medium))
print('image_dir_low: {}'.format(FLAGS.image_dir_low))
print('image_dir_low2: {}'.format(FLAGS.image_dir_low2))
print('slide_list_filename_test: {}'.format(FLAGS.slide_list_filename_test))
print('num_classes: {}'.format(FLAGS.num_classes))
print('batch_size: {}'.format(FLAGS.batch_size))
print('metrics_file: {}'.format(test_metrics_file))

test_dataset = Dataset(img_dir_high=FLAGS.image_dir_high, img_dir_medium=FLAGS.image_dir_medium, img_dir_low=FLAGS.image_dir_low, img_dir_low2=FLAGS.image_dir_low2, slide_list_filename=FLAGS.slide_list_filename_test, transforms=False)
num_imgs_test = test_dataset.num_imgs
print("Test Data - num_imgs: {}".format(test_dataset.num_imgs))

# define data loaders
data_loader_test = torch.utils.data.DataLoader(test_dataset, batch_size=FLAGS.batch_size, shuffle=False, num_workers=1)

device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')

# get the model using our helper function
model = Model(pretrained=False, num_classes=FLAGS.num_classes, num_intermediate_features=64)
# move model to the right device
model.to(device)

if FLAGS.init_model_file:
    if os.path.isfile(FLAGS.init_model_file):
        state_dict = torch.load(FLAGS.init_model_file, map_location=lambda storage, loc: storage)
        model.load_state_dict(state_dict['model_state_dict'])
        print("Model weights loaded successfully from file: ", FLAGS.init_model_file)

print('******************** testing ********************')

pbar = tqdm(total=len(data_loader_test))

num_predictions = 0
running_correct_result = 0

label_list = []
predicted_result_list = []
probs_result_list = []

model.eval()
with torch.no_grad():
    for i, (img_paths, img_high, img_medium, img_low, img_low2, label) in enumerate(data_loader_test):

        img_high, img_medium, img_low, img_low2, label = img_high.to(device), img_medium.to(device), img_low.to(device), img_low2.to(device), label.to(device)

        # get logits from the model
        output_high, output_medium, output_low, output_low2, output_result = model(img_high, img_medium, img_low, img_low2)

        # obtain probs
        probs_result = F.softmax(output_result, dim=1)

        # obtain predictions
        _, predicted_result = torch.max(output_result, 1)

        correct_result = (predicted_result == label).sum().item()
        running_correct_result += correct_result

        label_arr = label.cpu().numpy()
        predicted_result_arr = predicted_result.cpu().numpy()
        probs_result_arr = probs_result.cpu().numpy()

        temp_num_predictions = label_arr.shape[0]
        num_predictions += temp_num_predictions
        label_list += list(label_arr)
        predicted_result_list += list(predicted_result_arr)
        probs_result_list += list(probs_result_arr)

        for idx in range(temp_num_predictions):
            with open(test_metrics_file, 'a') as f:
                temp_img_path = img_paths[0][idx]
                patient_id = temp_img_path.split('/')[-3].split('_')[1]
                slide_id = temp_img_path.split('/')[-3].split('_')[3]
                img_id = temp_img_path.split('/')[-1].split('.')[0]
                f.write('{}\t{}\t{}\t{}\t{}\t{:0.4f}\t{:.4f}\n'.format(patient_id, slide_id, img_id, label_arr[idx], predicted_result_arr[idx], probs_result_arr[idx, 0], probs_result_arr[idx, 1]))

        pbar.update(1)

pbar.close()

test_acc_result = running_correct_result / num_predictions
print('test_acc_result:{:.4f}'.format(test_acc_result))

# confusion matrix
cm_test = confusion_matrix(label_list, predicted_result_list, labels=[0,1])
print('cm_test:{}'.format(cm_test))

# per-class accuracy: TPR and TNR
class_acc_test = cm_test.diagonal() / cm_test.sum(1)
print('TNR:{:.4f}, TPR:{:.4f}'.format(class_acc_test[0],class_acc_test[1]))

# Receiver operating chracteristic curve and area under curve value
label_arr = np.array(label_list)
probs_result_arr = np.vstack(probs_result_list)

fpr, tpr, _ = roc_curve(label_arr, probs_result_arr[:,1])
roc_auc = auc(fpr, tpr)

test_metrics_summary_file = '{}/test_metrics_summary__{}.txt'.format(out_dir,model_name)
with open(test_metrics_summary_file, 'w') as f:
    f.write('# model_name: {}\n'.format(model_name))
    f.write('# init_model_file: {}\n'.format(FLAGS.init_model_file))
    f.write('# image_dir_high: {}\n'.format(FLAGS.image_dir_high))
    f.write('# image_dir_medium: {}\n'.format(FLAGS.image_dir_medium))
    f.write('# image_dir_low: {}\n'.format(FLAGS.image_dir_low))
    f.write('# image_dir_low2: {}\n'.format(FLAGS.image_dir_low2))
    f.write('# slide_list_filename_test: {}\n'.format(FLAGS.slide_list_filename_test))
    f.write('# num_classes: {}\n'.format(FLAGS.num_classes))
    f.write('# batch_size: {}\n'.format(FLAGS.batch_size))
    f.write('# test_metrics_summary_file: {}\n'.format(test_metrics_summary_file))
    f.write('# test_acc_result\n')
    f.write('{:.4f}\n'.format(test_acc_result))
    f.write('# cm_test: cm_test[0,0]\tcm_test[0,1]\tcm_test[1,0]\tcm_test[1,1]\n')
    f.write('{:d}\t{:d}\t{:d}\t{:d}\n'.format(cm_test[0,0],cm_test[0,1],cm_test[1,0],cm_test[1,1]))
    f.write('# TNR\tTPR\n')
    f.write('{:.4f}\t{:.4f}\n'.format(class_acc_test[0],class_acc_test[1]))
    f.write('# roc_auc\n')
    f.write('{:.4f}\n'.format(roc_auc))

plt.rcParams.update({'font.size':12,'axes.labelsize':12})

fig,ax = plt.subplots(figsize=(3,3))
lw = 2
ax.plot(fpr, tpr, color='darkorange', lw=lw, label='AUROC = %0.2f' % roc_auc)
ax.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')
ax.set_xlim([-0.05, 1.05])
ax.set_xticks(np.arange(0,1.05,0.2))
ax.set_ylim([-0.05, 1.05])
ax.set_yticks(np.arange(0,1.05,0.2))
ax.set_xlabel('FPR')
ax.set_ylabel('TPR')
ax.set_title('AUROC = %0.4f' % roc_auc)
# ax.legend(loc='lower right')
ax.grid()

fig.tight_layout()
fig_filename = '{}/ROC__{}.png'.format(out_dir,model_name)
fig.savefig(fig_filename, dpi=200)

fig_filename = '{}/ROC__{}.pdf'.format(out_dir,model_name)
fig.savefig(fig_filename, dpi=200)

# plt.show()

plt.close('all')


import sys

def search_next_router(start, end):
    mid_distance = (end - start) // 2
    count = 1
    for idx, a_house in enumerate(houses[1:]):
        if (a_house - houses[idx]) > mid_distance:
            count += 1

    return count

N, C = map(int, input().split())
houses = [int(sys.stdin.readline()) for _ in range(N)].sort()

start, end = houses[0], houses[-1]


# Definition for a binary tree node.
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution:
    def deepestLeavesSum(self, root: TreeNode) -> int:

        queue, result = [root, None], 0
        while len(queue) != 1:
            node = queue.pop(0)
            if node:
                result += node.val
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
            else:
                queue.append(None)
                result = 0
        return result


# -*- coding: utf-8 -*-
# project 1

import pandas as pd
import numpy as np
import matplotlib
import warnings
import matplotlib.pyplot as plt
import os
import seaborn as sns
from scipy import stats as st
from scipy.linalg import svd
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from sklearn.decomposition import PCA
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier

from scipy.stats import norm
warnings.filterwarnings("ignore", category=matplotlib.MatplotlibDeprecationWarning)

### inspect data ###
# finding NaN or no values
# looking for duplicates
def inspect_data(data):
    # check for missing data
    print("Is there missing Data?: ", data.isnull().sum().sum())
    # check for duplicated data
    print("Is there duplicated data?:", data.duplicated().sum())

    # count, mean, std, min, 25, 50(median), 75, max
    #with open(os.path.join(os.getcwd(), "data_measures.txt"), 'w') as f:
    #    f.write(data.describe().round(2).to_string())

    # calculation of simple summary statistics
    stat_df = pd.DataFrame(columns=data.columns, index=(
        "mean", "std","var","min", "25%-percentile", "median",  "75%-percentile", "max", "std (N-1)",  "var (N-1)",
        "mode"))
    for column in data.columns:
        stat_df[column]["mean"] = round(np.mean(data[column]),2)
        stat_df[column]["median"] = round(np.median(data[column]),2)
        stat_df[column]["min"] = round(np.min(data[column]),2)
        stat_df[column]["max"] = round(np.max(data[column]),2)
        stat_df[column]["std"] = round(np.std(data[column]),2)
        stat_df[column]["std (N-1)"] = round(np.std(data[column], ddof=1),2)
        stat_df[column]["var"] = round(np.var(data[column]),2)
        stat_df[column]["var (N-1)"] = round(np.var(data[column], ddof=1),2)
        stat_df[column]["mode"] = st.mode(data[column])
        stat_df[column]["25%-percentile"] = round(np.quantile(data[column], 0.25),2)
        stat_df[column]["75%-percentile"] = round(np.quantile(data[column], 0.75),2)

    # write summary statistics to file
    with open(os.path.join(os.getcwd(), "data_measures.txt"), 'w') as f:
        f.write(stat_df.to_string())

# Data Visualisation
def data_visualisation(data):
    ### plot boxplots/distribution of features ###
    plt.figure(figsize=(10, 8))
    plt.boxplot((data - data.mean()) / data.std(ddof=1) , labels=data.columns)
    plt.title("Boxplots of all Features")
    plt.xlabel("Features")
    plt.ylabel("Data values")
    plt.xticks(rotation=90)
    plt.show()

    #n_bins = 25
    #fig, ax = plt.subplots(2, int(np.ceil(len(data.columns) / 2)))
    #plt.figure().set_figheight(10)
    #plt.figure().set_figwidth(20)
    #fig.tight_layout()
    #for col_id in range(len(data.columns)):
    #    if col_id < int(np.ceil(len(data.columns) / 2)):
    #        ax[0, col_id].hist(data.iloc[:, col_id], bins=n_bins)
    #        ax[0, col_id].set_title(data.columns[col_id])
    #    if col_id >= int(np.ceil(len(data.columns) / 2)):
    #        ax[1, col_id - int(np.ceil(len(data.columns) / 2))].hist(data.iloc[:, col_id], bins=n_bins)
    #        ax[1, col_id - int(np.ceil(len(data.columns) / 2))].set_title(data.columns[col_id])
    #plt.show()

    ### plot histogramms ###
    # Set up the figure size and grid layout
    plt.figure(figsize=(15, 12))
    sns.set_style("whitegrid")

    # Plot histograms for each column
    for i, column in enumerate(data.columns.drop("season"), 1):
        plt.subplot(3, 4, i)
        sns.histplot(data[column], kde=True)
        plt.title(f'Distribution of {column}')
        plt.tight_layout()
    plt.show()

    ### plot correlations ###
    plt.figure(figsize=(10,8))
    sns.heatmap(data.corr(), cmap="RdBu")
    plt.xticks(rotation=90)
    plt.yticks(rotation=0)
    plt.title("Correlation Heat Map")
    plt.tight_layout
    plt.show()
    print(data.corr())

    #calculate empirical covariance and derive empirical correlation
    cov_mat = np.cov(data, rowvar=False, ddof=1)
    print(cov_mat)
    cor_mat = np.zeros((data.shape[1],data.shape[1]))

    for i in range(data.shape[1]):
        for j in range(data.shape[1]):
            cor_mat[i][j] = cov_mat[i][j]/(np.std(data.iloc[:,i],ddof=1)*np.std(data.iloc[:,j],ddof=1))

    fig, ax = plt.subplots(figsize=(10,8))
    sns.heatmap(cor_mat, cmap="RdBu")
    plt.xticks(rotation=90)
    ax.set_xticklabels(data.columns)
    ax.set_yticklabels(data.columns)
    plt.yticks(rotation=0)
    plt.title("Empirical Correlation Heat Map")
    plt.tight_layout
    plt.show()

    #with open(os.path.join(os.getcwd(), "data_measures.txt"), 'w') as f:
    #    f.write(data.corr().to_string())

    ### plot scatter for temperature ###
    # Temp - IBH IBT
    # Season - Temp vis
    fig, ax = plt.subplots(1, 2, figsize=(14, 6))

    ax[0].scatter(data["temp"], data["ibh"], color='blue', label='temp vs ibh')
    ax[0].set_title('Temperature vs IBH')
    ax[0].set_xlabel('Temperature')
    ax[0].set_ylabel('IBH')

    ax[1].scatter(data["temp"], data["ibt"], color='red', label='temp vs ibt')
    ax[1].set_title('Temperature vs IBT')
    ax[1].set_xlabel('Temperature')
    ax[1].set_ylabel('IBT')
    plt.show()

    ### Mapping season to temperature ####
    # Set up the plot
    plt.figure(figsize=(10, 6))
    colors = ['green', "red", "blue", "orange"]
    plt.axhline(y=1, color='grey', linestyle='--', lw=0.5)
    for i, row in data.iterrows():
        plt.scatter(row['temp'], 1, color=colors[data["season"][i]])
    plt.title("Temperature with Season Symbols")
    plt.xlabel("Temperature (°C)")
    plt.yticks([])  # Hide y-ticks as it's a 1D plot
    plt.legend()
    plt.grid(True, which='both', linestyle='--', linewidth=0.5, axis='x')
    plt.tight_layout()
    plt.show()

    ###  Mapping season to temperature and visibility ###
    for c in range(4):
        # select indices belonging to class c:
        class_mask = data["season"] == c
        plt.plot(data["temp"][class_mask], data["vis"][class_mask], 'o', alpha=.3)

    #plt.legend(data["season"])
    plt.legend(["winter", "spring", "summer", "fall"])
    #plt.xlabel(data["temp"])
    #plt.ylabel(data["vis"])
    plt.show()

def pca(data):
    ### transform data ###
    # standardize
    data_pca = data.drop(["doy", "season"], axis=1)

    mean = data_pca.mean()
    std = data_pca.std(ddof=1)
    data_pca_scaled = np.asarray((data_pca - mean) / std)

    ### PCA ###
    U, S, V = svd(data_pca_scaled, full_matrices=False)

    # Compute variance explained by principal components
    rho = (S * S) / (S * S).sum()

    threshold = 0.9

    ### plot explained variance ###
    plt.figure()
    plt.plot(range(1, len(rho) + 1), rho, 'x-', color='red')
    plt.plot(range(1, len(rho) + 1), np.cumsum(rho), 'o-', color='blue')
    plt.plot([1,len(rho)],[threshold, threshold],'k--')
    plt.title('Variance explained by principal components');
    plt.xlabel('Principal component');
    plt.ylabel('Variance explained');
    plt.legend(['Individual', 'Cumulative', 'Threshold'])
    plt.grid()
    plt.show()

    ### transform data onto pca components ###
    V_real = V.T
    Z = data_pca_scaled @ V_real

    ### Plot PCA projection ###
    # pca component indices
    pca_idx = [[0, 1], [1, 4]]
    for idx in pca_idx:
        plt.figure()
        plt.title('Los Angeles Ozone: PCA')
        # Z = array(Z)
        for c in range(len(sorted(set(data["season"])))):
            # select indices belonging to class c:
            class_mask = data["season"] == c
            plt.plot(Z[class_mask, idx[0]], Z[class_mask, idx[1]], 'o', alpha=.5)
        plt.legend(["winter", "spring", "summer", "fall"])
        plt.xlabel('PC{0}'.format(idx[0] + 1))
        plt.ylabel('PC{0}'.format(idx[1] + 1))
        plt.show()

    ### further analysis of most important pca components ###
    # number of pca components to be analysed further
    max_pca = 5

    # plot matrix scatter pca plot for max_pca components
    fig, ax = plt.subplots(max_pca, max_pca, figsize=(20, 10))
    plt.suptitle(f'Los Angeles Ozone: PCA for {max_pca} components')

    for i in range(max_pca):
        for j in range(max_pca):
            for c in range(len(sorted(set(data["season"])))):
                # select indices belonging to class c:
                class_mask = data["season"] == c
                ax[i][j].plot(Z[class_mask, i], Z[class_mask, j], 'o', alpha=.5)

            ax[i][j].set_xlabel('PC{0}'.format(i + 1))
            ax[i][j].set_ylabel('PC{0}'.format(j + 1))
    plt.legend(["winter", "spring", "summer", "fall"])
    plt.tight_layout()
    plt.show()

    ### plot for pca contribution ###
    fig, ax = plt.subplots(figsize=(14, 8))

    for i in range(max_pca):
        ax.plot(data_pca.columns, V_real[:,i], label=f'Component {i + 1}', marker='o')

    for i in range(max_pca):
        print(V_real[:,i])

    ax.set_xticks(data_pca.columns)
    ax.set_xticklabels(data_pca.columns, rotation=45)
    ax.set_ylabel('Loading')
    ax.set_title('PCA Component Loadings for Each Feature')
    ax.grid(True)
    plt.show()

    ### pca heatmap ###
    fig, ax = plt.subplots(figsize=(14, 8))
    im = ax.imshow(V_real[:,0:max_pca], cmap="RdBu")
    ax.legend()
    plt.colorbar(im)
    ax.set_yticks(np.arange(len(data_pca.columns)), labels=data_pca.columns)
    ax.set_xticks(np.arange(max_pca), labels=np.arange(max_pca)+1)
    ax.set_ylabel('Feature')
    ax.set_xlabel('PCA component')
    ax.set_title('PCA Component Loadings for Each Feature')
    plt.show()

def main():
    ### load data ###
    data_path = os.path.join(os.getcwd(), "LAozone.csv")
    data = pd.read_csv(data_path)

    ### add additional feature ###
    # decoding seasons from doy
    # 0 = winter (december, january, february)
    # 1 = spring (march, april, may)
    # 2 = summer (june, july, august)
    # 3 = autumn (september, october, november)
    data["season"] = 0
    for row in data.index:
        if data["doy"][row] <= 60 or data["doy"][row] > 335:
            data["season"][row] = 0
        if data["doy"][row] > 60 and data["doy"][row] <= 152:
            data["season"][row] = 1
        if data["doy"][row] > 152 and data["doy"][row] <= 244:
            data["season"][row] = 2
        if data["doy"][row] > 244 and data["doy"][row] <= 335:
            data["season"][row] = 3

    inspect_data(data)
    data_visualisation(data)
    pca(data)

    # train the first classifiers

    #data_Y = data["season"].copy()

    #data_X = data.drop(["doy", "season"], axis=1).copy()

    #mean = data_X.mean()
    #std = data_X.std(ddof=1)
    #data_X = np.asarray((data_X - mean) / std)

    #X_train, X_test, y_train, y_test = train_test_split(data_X, data_Y, test_size = 0.2, random_state=5, shuffle=True)

    #KNN = KNeighborsClassifier(n_neighbors = 10)
    #KNN.fit(X_train, y_train)

    #print(KNN.score(X_test,y_test))

    #DT = DecisionTreeClassifier()
    #DT.fit(X_train,y_train)

    #print(DT.score(X_test,y_test))

    #RF = RandomForestClassifier()
    #RF.fit(X_train,y_train)

    #print(RF.score(X_test,y_test))

if __name__ == "__main__":
    main()


"""
Dmytro Mishagli, UCD

04 Dec 2019 -- the script was created.

"""

import numpy as np

def basis(x,n,L):
	'''
	The basis function.
	'''
	return np.sqrt(2/L) * np.sin( x * n * np.pi / L )

def integ(n,m,lower_limit,upper_limit,L):
	"""
	Returns values of the integrals in a Hamiltonian of a square potential well,
	calculated analytically
	"""
	alpha = n*np.pi/L
	beta  = m*np.pi/L

	if n!=m:
		f = lambda x: 0.5 * ( np.sin((alpha-beta)*x)/(alpha-beta) - np.sin((alpha+beta)*x)/(alpha+beta) )
		return 2/L * (f(upper_limit) - f(lower_limit))
	else:
		f = lambda x: 0.5 * ( x - np.sin((alpha+beta)*x)/(alpha+beta) )
		return 2/L * (f(upper_limit) - f(lower_limit))

def potential_piecewise(n,m,Vext,Vint,wells,barriers):
	'''
	Vext - list, left and right (exterior) potential wells' heights
	Vint - list, interatomic wells heights
	wells - list, iterior wells' widths
	barriers - list, distances between the wells
	'''
	# number of wells
	nWells = len(wells)
	# add zero element to the begin of a list of barriers
	barriers = [0] + barriers
	# size of shift from 0
	h = np.sum(wells) + np.sum(barriers)
	# width of an infinite square well
	L = 3*h
	# initialise variables
	s = 0
	lower_limit = h
	upper_limit = h
	# iterate through the square well (sequence of wells)
	for i in range(1,nWells):
		lower_limit += wells[i] + barriers[i-1]
		upper_limit += wells[i] + barriers[i]
		s += Vint[i-1] * integ( n,m, lower_limit, upper_limit, L )
	return Vext[0]*integ(n, m, 0, h, L) + Vext[1]*integ(n, m, L-h, L, L) + s

def get_solution(Vext,Vint,wells,barriers,num_bas_funs):
	# size of shift from 0
	h = np.sum(wells) + np.sum(barriers)
	# width of an infinite square well
	L = 3*h
	# compute a Hamiltonian (n,m) square matrix
	potential_matrix = [[potential_piecewise(n,m,Vext,Vint,wells,barriers) for n in range(1,num_bas_funs+1)] for m in range(1,num_bas_funs+1)]
	# compute a list of eigenvalues for H0
	evalues = [n**2*np.pi**2/(L**2) for n in range(1,num_bas_funs+1)]
	# create a diagonal matrix
	H0 = np.diag(evalues)
	# get solution
	eigvals, eigvecs = np.linalg.eigh(H0+potential_matrix)

	# bound states are below the exterior height
	eigvals = eigvals[eigvals<min(Vext)]
	# transopse the matrix with eigenvectors (we need rows)
	# and left only those who correspond to the bound states
	eigvecs = eigvecs.T[:len(eigvals)]

	return eigvals, eigvecs


import tkinter as tk
from tkinter import ttk
from tkinter import filedialog
import os
import glob
import cv2
import math
import csv
import re
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from tensorflow.keras.applications.imagenet_utils import preprocess_input, decode_predictions
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications.resnet50 import ResNet50
from keras.utils import np_utils
from skimage.transform import resize
from sklearn.model_selection import train_test_split
from tensorflow.keras.layers import Dense, InputLayer, Dropout
from tensorflow.keras.models import Sequential

def load_train_tab(tab_train, root):
    def browse_directory():
        global selected_directory
        filepath = filedialog.askdirectory(title="Select a directory")
        if filepath:
            print("Selected file:", filepath)
            selected_directory = filepath # Save the directory name to the global variable
            directory_entry.delete(0, tk.END)
            directory_entry.insert(0, filepath)

            # Update the video files list
            video_files.config(state="normal")  # Set the state to normal before inserting text
            video_files.delete(1.0, tk.END)
            for file in os.listdir(filepath):
                if file.endswith(".mp4") or file.endswith(".avi") or file.endswith(".mkv"):
                    video_files.insert(tk.END, file + "\n")
            video_files.config(state="disabled")  # Set the state back to disabled after inserting text

    def frame_split():
        # Create a progress bar popup window
        progress_window = tk.Toplevel(root)
        progress_window.title("Splitting Videos")
        progress_label = ttk.Label(progress_window, text="Splitting video into frames...")
        progress_label.pack(padx=10, pady=(10, 0))
        progress = ttk.Progressbar(progress_window, mode="indeterminate", length=300)
        progress.pack(padx=10, pady=(5, 10))
        progress.start(10)
        progress_window.update()

        #check if train/frames path exists, if not, create it
        if os.path.exists(selected_directory + "/train/frames/") == False:
            print("/train/frames folder does not exist. Creating...")
            os.makedirs(selected_directory + "/train/frames/")
        else:
            print("train/frames folder already exists")

        #capture video files in chosen directory
        count = 0
        cap = [cv2.VideoCapture(videoFile) for videoFile in glob.glob(os.path.join(selected_directory, "*.mp4"))] # capturing the video from the given path

        #split the frames from each video then output to train/frames folder
        for i in cap:
            print(str(i))
            frameRate = i.get(5)
            while (i.isOpened()):
                frameID = i.get(1)
                ret, frame = i.read()
                if (ret != True):
                    break
                if (frameID % math.floor(frameRate) == 0):
                    filename = selected_directory + "/train/frames/frame%d.jpg" % (count); count +=1
                    cv2.imwrite(filename, frame)
            i.release()

        #create the excel file from split frames
        print("Creating excel file for classification...")
        header = ['Image_ID', 'Class']
        data = []
        for i in os.listdir(selected_directory + "/train/frames"):
            data.append(str(i))
        data.sort(key=lambda f: int(re.sub('\D', '', f)))
        data2 = []
        for i in data:
            data2.append([i])
        with open(selected_directory + '/train/frames.csv', 'w', encoding='UTF8', newline='') as f:
            writer = csv.writer(f)
            writer.writerow(header)
            writer.writerows(data2)
        print("Done! Please label frames accordingly in 'frames.csv' ")

        # Close the progress bar window
        progress.stop()
        progress_window.destroy()

        # Show a new popup window that says "frame split complete"
        complete_window = tk.Toplevel(root)
        complete_window.title("Complete")
        complete_label = ttk.Label(complete_window, text="Frame splitting complete. \nYour training frames are located in /train/frames/ in your selected directory. \nPlease update your excel file located in the /train/ folder with the necessary labels")
        complete_label.pack(padx=10, pady=(10, 0))
        ok_button = ttk.Button(complete_window, text="OK", command=complete_window.destroy)
        ok_button.pack(padx=10, pady=(5, 10))

        # Update the main window
        root.update()

    def begin_training():
        # Create a progress bar popup window
        progress_window = tk.Toplevel(root)
        progress_window.title("Splitting Videos")
        progress_label = ttk.Label(progress_window, text="Training model...")
        progress_label.pack(padx=10, pady=(10, 0))
        progress = ttk.Progressbar(progress_window, mode="indeterminate", length=300)
        progress.pack(padx=10, pady=(5, 10))
        progress.start(10)
        progress_window.update()

        #load training excel file
        data = pd.read_csv(selected_directory + '/train/frames.csv')

        #count number of areas created in excel file:
        cnt = 0
        visited = []
        for i in range (0, len(data['Class'])):
            if data['Class'][i] not in visited:
                visited.append(data['Class'][i])

                cnt+=1
        X = [ ]     # creating an empty array
        for img_name in data.Image_ID:
            img = plt.imread(selected_directory + '/train/frames/' + img_name)
            X.append(img)  # storing each image in array X
        X = np.array(X)
        y = data.Class
        dummy_y = np_utils.to_categorical(y)
        image = []
        for i in range(0,X.shape[0]):
            a = resize(X[i], preserve_range=True, output_shape=(224,224)).astype(int)      # reshaping to 224*224*3
            image.append(a)
        X = np.array(image)
        X = preprocess_input(X, mode='caffe')
        X_train, X_valid, y_train, y_valid = train_test_split(X, dummy_y, test_size=0.3, random_state=42)
        base_model = ResNet50(weights='imagenet', include_top=False, input_shape=(224, 224, 3))
        X_train = base_model.predict(X_train)
        X_valid = base_model.predict(X_valid)
        X_train.shape, X_valid.shape
        X_train = X_train.reshape(X_train.shape[0], 7*7*2048)      # converting to 1-D
        X_valid = X_valid.reshape(X_valid.shape[0], 7*7*2048)
        train = X_train/X_train.max()      # centering the data
        X_valid = X_valid/X_train.max()
        model = Sequential()
        model.add(InputLayer((7*7*2048,)))    # input layer
        model.add(Dense(units=2048, activation='sigmoid'))   # hidden layer
        model.add(Dropout(0.5))      # adding dropout
        model.add(Dense(units=1024, activation='sigmoid'))    # hidden layer
        model.add(Dropout(0.5))      # adding dropout
        model.add(Dense(units=512, activation='sigmoid'))    # hidden layer
        model.add(Dropout(0.5))      # adding dropout
        model.add(Dense(units=256, activation='sigmoid'))    # hidden layer
        model.add(Dropout(0.5))      # adding dropout
        model.add(Dense(cnt, activation='softmax'))            # output layer
        model.summary()
        model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
        model.fit(train, y_train, epochs=15, validation_data=(X_valid, y_valid))
        model.save(selected_directory + '/train/model')
        # Close the progress bar window
        progress.stop()
        progress_window.destroy()

        # Show a new popup window that says "model training complete"
        complete_window = tk.Toplevel(root)
        complete_window.title("Complete")
        complete_label = ttk.Label(complete_window, text="Model training complete. Model has been saved to /train/model/.\nYou may begin classification of new videos in the classify tab")
        complete_label.pack(padx=10, pady=(10, 0))
        ok_button = ttk.Button(complete_window, text="OK", command=complete_window.destroy)
        ok_button.pack(padx=10, pady=(5, 10))

        # Update the main window
        root.update()

    # Add description text above the browse button
    description_label = ttk.Label(tab_train, text="Select user video folder:")
    description_label.pack(padx=10, pady=(10, 0))

    # Create a frame to hold the directory entry and browse button
    entry_browse_frame = ttk.Frame(tab_train)
    entry_browse_frame.pack(padx=10, pady=(5, 10))

    # Add an empty text box for manual directory input
    directory_entry = ttk.Entry(entry_browse_frame, width=50)
    directory_entry.pack(side="left")

    # Add a browse button to the "Train Model" tab
    browse_button = ttk.Button(entry_browse_frame, text="Browse", command=browse_directory)
    browse_button.pack(side="left", padx=(10, 0))

    # Create a text box to show a list of video files in the chosen directory
    video_files = tk.Text(tab_train, wrap="none", width=50, height=10, state="normal")
    video_files.pack(padx=10, pady=(5, 10))

    # Add split text description above the split button
    split_description_label = ttk.Label(tab_train, text="Split videos into frames and output to a train folder:")
    split_description_label.pack(padx=10, pady=(10, 0))

    # Add a split button to the "Train Model" tab
    split_button = ttk.Button(tab_train, text="Split", command=frame_split)
    split_button.pack(padx=10, pady=(5, 10))

    #Add train text description above train button
    train_description_label = ttk.Label(tab_train, text="Begin training model (please make sure your excel file is properly filled out)")
    train_description_label.pack(padx=10, pady=(10, 0))

    # Add a train button to the "Train Model" tab
    train_button = ttk.Button(tab_train, text="Train", command=begin_training)
    train_button.pack(padx=10, pady=(5, 10))


# Practice python, assignment 3
# linked list

# bring codes for the single linked list and stack from the lab and lecture slides.
class LList:
    class Node:
        def __init__(self, val, next=None):
            self.val = val
            self.next = next

    def __init__(self):
        self.head = None
        self.tail = None  # initializing the tail
        self.nVals = 0

    def addFront(self, val):
        new_node = self.Node(val, self.head)

        if self.head is None:  # If the linked list is empty, we should add a node and have both: the head and the tail pointing at it.
            self.tail = new_node

        self.head = new_node
        self.nVals += 1

    def getFront(self):
        if self.head is None:
            return None
        else:
            return self.head.val

    def removeFront(self):
        returned_value = self.head
        if self.head is not None:

            if self.tail == self.head:  # If the tail and the head is pointing to the same node, then the list has only one node. The reference must be removed from both: the tail and the head
                self.head = self.tail = None

            else:
                self.head = self.head.next
            self.nVals -= 1

        return returned_value.val  # return the removed value

    def toList(self):
        result_lst = []
        node = self.head
        while node is not None:
            result_lst.append(node.val)
            node = node.next
        # print(array)
        return result_lst

    # We modified the addBack() from the tutorial slides to make it O(1) instead of O(N)
    def addBack(self, val):
        if self.head is None:
            self.addFront(val)
        else:
            self.tail.next = self.Node(
                val)  # The while loop to reach the tail is not necessary anymore, we can be replace it with the tail node.
            self.tail = self.tail.next  # The tail must be changed to the last node that we just added to the end of the linked list
            self.nVals += 1

    def getBack(self):
        if self.tail is None:
            return None
        else:
            return self.tail.val

    def count(self):
        return self.nVals

##### Part 1: Creating Two Singly Linked List Functions #####

    def printSLL(self):
        node = self.head
        node_lst = []
        if node is None:
            print("Empty Linked List")
        else:
            while node is not None:
                node_lst.append(str(node.val))
                node = node.next
            node_lst_joined = ",".join(node_lst)
            print("[" + node_lst_joined + "]")

    def locate(self, item):
        node = self.head

        if node is None:
            print("Item was not located")
            return
        while node is not None:
            if item != node.val:
                node = node.next
            else:
                print("Item was located")
                return
        print("Item was not located")

# lst = LList()
# lst.addFront(2)
# lst.addFront(5)
# lst.addFront(1)
# lst.printSLL()
#
# lst.locate(2)
#

##### Part 2: Evaluating Postfix Expressions #####

class Stack:
    def __init__(self):
        self.llist = LList()

    def __len__(self):
        return self.llist.nVals

    def push(self, val):
        self.llist.addFront(val)

    def pop(self):
        return self.llist.removeFront()

    def peek(self):
        return self.llist.getFront()

    def getBack(self):
        return self.llist.getBack()

    def __len__(self):
        return self.llist.count()

    def toList(self):
        return list(reversed(self.llist.toList()))

def evalPostfix(e):  # e -> string
    is_error = False
    split_e = e.split()
    # print(split_e)

    # use Stack
    s = Stack()
    operators = ["+", "-", "*", "/"]

    for i in split_e:
        if i not in operators:
            s.push(int(i))
            # print(int(i))
        elif i in operators:
            # error checking
            if len(s) < 2:
                current_stack = s.toList()
                print(f'Error: {current_stack}')
                return
            operand1 = s.pop()
            operand2 = s.pop()

            if i == "+":
                s.push(operand2 + operand1)
            elif i == "-":
                s.push(operand2 - operand1)
            elif i == "*":
                s.push(operand2 * operand1)
            else:
                s.push(operand2 / operand1)

    # error checking
    if len(s) != 1:
        current_stack = s.toList()
        print(f'Error: {current_stack}')
    else:
        # non-error
        try:  # to get integer value if the result is x.0
            if s.peek().is_integer():
                print(int(s.peek()))
            else:
                print(s.peek())
        except:
            print(s.peek())

# evalPostfix("1 2 3 4 * - /")
# evalPostfix("20 5 - 3 / 2 *")
# evalPostfix("+")
# evalPostfix("1")


from celery import shared_task
from celery.utils.log import get_task_logger
from decouple import config

logger = get_task_logger("tasks")
expiration_time = config("EXPIRATION_TIME", default=1800, cast=int)

@shared_task(
    bind=True,
    default_retry_delay=3,
    eta=expiration_time,
    retry_kwargs={"max_retries": 5},
)
def delete_qrcode_task(self, qrcode_id):
    from qrcode_api.apps.api.models import QrCode

    try:
        qrcode = QrCode.objects.get(id=qrcode_id)
        logger.info(f"Deactivating qrcode {qrcode_id}")
        qrcode.active = False
        qrcode.image.delete()
        qrcode.save()
    except Exception as e:
        logger.error(e)
        self.retry(exc=e)


# Module importieren
from machine import Pin
import time

# Pins für die LEDs aktivieren
rot = Pin(14, Pin.OUT)
gelb = Pin(12, Pin.OUT)
gruen = Pin(13, Pin.OUT)

# Funtion für die Ampelschaltung
def ampel(led):
    #for i in range(5):
        led(1)
        time.sleep_ms(3000)
        led(0)
        time.sleep_ms(1)

# Ampelreihenfolge nach Wunsch schalten
for i in range(5):
    ampel(rot)
    ampel(gelb)
    ampel(gruen)
    ampel(gelb)


from tkinter import *

window = Tk()
window.title("Grid Geometry")

lblNumYears = Label(window, text = "Number of Years:")
lblNumYears.grid(row = 0, column = 0, pady = 20) #top left

entNumYears = Entry(window, width =5)
entNumYears.grid(row = 0, column = 1, sticky = S)

btnCalculate = Button(window, text = "Calculate Montly Payment")
btnCalculate.grid(row = 1, column = 0, columnspan = 2, padx = 10, pady = 10)

window.mainloop()


#!/usr/bin/env python
# -*- coding: utf-8 -*-

from PIL import Image
from matplotlib import pyplot as plt

import numpy as np
import pytesseract
import cv2
import tkinter as tk
import logging
import time
import re
import threading

# Dimensioning values
# We are defining global variables based on match data in order to isolate the scoreboard
left_x = 170
upper_y = 50
right_x = 540
lower_y = 80

time_divide = 230
time_width = 60
time_position = 'left'
# If time-position = right : scoreboard is on the left and time on the right
# Else if time position = left : scoreboard is on the right and time on the left

# To deal with time.sleep() and effectively end the threads
#time_value = 0

class ImageHandler(object):

    def __init__(self, export_path, filename_in):
        self.scoreboard_image = None
        self.time_image = None
        self.time_text = None
        self.teams_goals_image = None
        self.teams_goals_text = None

        self.video_source_path = filename_in
        self.export_image_path = export_path + '/football.jpg'
        self.export_path = export_path

        logging.basicConfig(level=logging.WARNING)

    def extract_image_from_video(self):
        """
        Extracts image from video and saves on disk with specified period.

        :param path_to_video: Path to video and video name with file format
        :param export_image_path: Export image path and image name with file format
        :return: -
        """

        vidcap = cv2.VideoCapture(self.video_source_path)
        count = 0
        #success = True
        image_lst = []

        while(True):
            vidcap.set(cv2.CAP_PROP_POS_MSEC, (count * 1000))
            success, image = vidcap.read()
            image_lst.append(image)

            # Stop when last frame is identified
            if count > 1:
                if np.array_equal(image, image_lst[1]):
                    break
                image_lst.pop(0)  # Clean the list
                # save frame as PNG file

            if(ocr.count < ocr.video_length):
                try:
                    cv2.imwrite(self.export_image_path, image)
                    print('{}.sec reading a new frame: {} '.format(count, success))
                    count += 1
                    ocr.count += 1
                    ocr.eImageExported.set()
                    time.sleep(1)
                except Exception as e:
                    pass

    def localize_scoreboard_image(self):
        """
        Finds the scoreboard table in the upper corner, sets scoreboard_image
        and exports the picture as 'scoreboard_table.jpg'

        :return: True when scoreboard is found
                 False when scoreboard is not found
        """

        # Read a snapshot image from the video and convert to gray
        snapshot_image = cv2.imread(self.export_image_path)
        grayscale_image = cv2.cvtColor(snapshot_image, cv2.COLOR_BGR2GRAY)

        self.scoreboard_image = grayscale_image[upper_y:lower_y,
                                                left_x:right_x]
        cv2.imwrite(self.export_path + '/scoreboard_table.jpg',
                    self.scoreboard_image)

    def split_scoreboard_image(self):
        """
        Splits the scoeboard image into two parts, sets 'time_image' and 'teams_goals_image'
        and exports as 'time_table.jpg' and 'teams_goals_table.jpg'
        Left image represents the time.
        Right image represents the teams and goals.

        :return: -
        """

        '''
        self.time_image = self.scoreboard_image[:, 0:175]
        cv2.imwrite('ocr/img/time_table.jpg', self.time_image)

        self.teams_goals_image = self.scoreboard_image[:, 175:]
        cv2.imwrite('ocr/img/teams_goals_table.jpg', self.teams_goals_image)
        '''

        relative_time_divide = time_divide-left_x
        time_end = relative_time_divide + time_width

        if(time_position == 'right'):
            self.time_image = self.scoreboard_image[:,
                                                    relative_time_divide:time_end]
            cv2.imwrite(self.export_path + '/time_table.jpg', self.time_image)

            self.teams_goals_image = self.scoreboard_image[:,
                                                           0:relative_time_divide]
            cv2.imwrite(self.export_path + '/teams_goals_table.jpg',
                        self.teams_goals_image)

        else:
            self.time_image = self.scoreboard_image[:, 0:relative_time_divide]
            cv2.imwrite(self.export_path + '/time_table.jpg', self.time_image)

            self.teams_goals_image = self.scoreboard_image[:,
                                                           relative_time_divide:]
            cv2.imwrite(self.export_path + '/teams_goals_table.jpg',
                        self.teams_goals_image)

    def enlarge_scoreboard_images(self, enlarge_ratio):
        """
        Enlarges 'time_table.jpg' and 'teams_goals_table.jpg'

        :param enlarge_ratio: Defines the enlarging size (e.g 2-3x)
        :return: -
        """
        self.time_image = cv2.resize(
            self.time_image, (0, 0), fx=enlarge_ratio, fy=enlarge_ratio)
        self.teams_goals_image = cv2.resize(
            self.teams_goals_image, (0, 0), fx=enlarge_ratio, fy=enlarge_ratio)

    def _get_time_from_image(self):
        """
        Preprocesses time_image transformations for OCR.
        Exports 'time_ocr_ready.jpg' after the manipulations.
        Reads match time from 'time_ocr_ready.jpg' using Tesseract.
        Applies result to time_text.

        :return: True: string is found
                 False: string is not found
        """

        # Count nonzero to determine contrast type
        ret, threshed_img = cv2.threshold(
            self.time_image, 0, 255, cv2.THRESH_OTSU+cv2.THRESH_BINARY_INV)

        self.time_image = cv2.GaussianBlur(self.time_image, (3, 3), 0)

        kernel = np.ones((3, 3), np.uint8)

        self.time_image = cv2.erode(self.time_image, kernel, iterations=1)
        self.time_image = cv2.dilate(self.time_image, kernel, iterations=1)

        cv2.imwrite(self.export_path + '/time_ocr_ready.jpg', self.time_image)

        self.time_text = pytesseract.image_to_string(
            Image.open(self.export_path + '/time_ocr_ready.jpg'), config="--psm 6")
        logging.info('Time OCR text: {}'.format(self.time_text))

        if self.time_text is not None:
            return True
        return False

    def _get_teams_goals_from_image(self):
        """
        Preprocesses teams_goals_image with transformations for OCR.
        Exports 'teams_goals_ocr_ready.jpg' after the manipulations.
        Reads teams and goals information from 'teams_goals_ocr_ready.jpg' using Tesseract.
        Applies result to teams_goals_text.

        :return: True: string is found
                 False: string is not found

        """
        # Applying Thresholding for Teams goals OCR preprocess
        ret, self.teams_goals_image = cv2.threshold(
            self.teams_goals_image, 0, 255, cv2.THRESH_OTSU+cv2.THRESH_BINARY_INV)

        self.teams_goals_image = cv2.GaussianBlur(
            self.teams_goals_image, (3, 3), 0)

        kernel = np.ones((3, 3), np.uint8)

        #self.teams_goals_image = cv2.erode(self.teams_goals_image, kernel, iterations=1)
        self.teams_goals_image = cv2.dilate(
            self.teams_goals_image, kernel, iterations=1)

        cv2.imwrite(self.export_path + '/teams_goals_ocr_ready.jpg',
                    self.teams_goals_image)

        self.teams_goals_text = pytesseract.image_to_string(
            Image.open(self.export_path + '/teams_goals_ocr_ready.jpg'))
        logging.info('Teams and goals OCR text: {}'.format(
            self.teams_goals_text))

        if self.teams_goals_text is not None:
            return True
        return False

    def get_scoreboard_texts(self):
        """
        Returns an array of strings including OCR read time, teams and goals texts.
        :return: numpy array 'scoreboard_texts'
                 scoreboard_texts[0] : time text value
                 scoreboard_texts[1] : teams and goals text value

        """
        # Read text values using Tesseract OCR
        time_text_exists = self._get_time_from_image()
        teams_goals_text_exists = self._get_teams_goals_from_image()

        scoreboard_texts = []
        # Use values on successful read
        if time_text_exists and teams_goals_text_exists:
            scoreboard_texts.append(self.time_text)
            scoreboard_texts.append(self.teams_goals_text)
            scoreboard_texts = np.array(scoreboard_texts)

        return scoreboard_texts

    def play_match_video(self):

        cap = cv2.VideoCapture(self.video_source_path)
        count = 0

        if(ocr.time_value < ocr.video_length):
            while (cap.isOpened()):
                cap.set(cv2.CAP_PROP_POS_MSEC, (count * 1000))
                ret, frame = cap.read()

                gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

                cv2.imshow('frame', gray)
                time.sleep(1)
                count += 1
                if cv2.waitKey(1) & 0xFF == ord('q'):
                    break

            cap.release()
            cv2.destroyAllWindows()

class Match(object):

    def __init__(self, export_path, filename_out):
        self.scoreboard_text_values = None

        self.home_score = 0
        self.home_score_temp = 0

        self.home_team = None
        self.home_team_temp = 0
        self.home_team_fullname = None
        self.home_team_identified = False

        self.opponent_score = 0
        self.opponent_score_temp = 0

        self.opponent_team = None
        self.opponent_team_temp = None
        self.opponent_team_fullname = None
        self.opponent_team_identified = False

        self.match_time = None
        self.match_time_temp = None
        self._match_time_prev = []

        self.export_path = export_path
        self.filename_out = filename_out

    def analize_scoreboard(self):
        while (ocr.count < ocr.video_length):
            try:
                ocr.eImageExported.wait()
                ocr.scoreboard.localize_scoreboard_image()
                ocr.scoreboard.split_scoreboard_image()
                ocr.scoreboard.enlarge_scoreboard_images(3)
                OCR_text = ocr.scoreboard.get_scoreboard_texts()
                ocr.football_match.provide_scoreboard_text_values(OCR_text)
                ocr.football_match.update_all_match_info()
                ocr.football_match.print_all_match_info()
                ocr.eImageExported.clear()
            except Exception as e:
                logging.warning(e)

    def provide_scoreboard_text_values(self, scoreboard_text_values):

        self.scoreboard_text_values = scoreboard_text_values

    def cleanse_match_score(self):
        """
        Cleanse home_score_temp and opponent_score_temp values and removes
        noisy starters and enders if present

        :return: -
        """
        score_string = self.scoreboard_text_values[1].split(' ')[1]

        result = []
        for letter in score_string:
            if letter.isdigit():
                result += letter
        self.home_score_temp = result[0]
        self.opponent_score_temp = result[1]

    def cleanse_match_teams(self):
        """
        Cleanse home_team_temp and opponent_team_temp values and removes
        noisy starter or ender if present

        :return: -
        """
        self.home_team_temp = self.scoreboard_text_values[1].split(' ')[0]
        self.opponent_team_temp = self.scoreboard_text_values[1].split(' ')[2]

        # Check and remove noisy starters and enders
        if not self.home_team_temp[0].isalpha():
            self.home_team_temp = self.home_team_temp[1:4]
        elif not self.opponent_team_temp[-1].isalpha():
            self.opponent_team_temp = self.opponent_team_temp[0:3]

    def cleanse_match_time(self):
        """
        Cleanse match_time_temp, and removes noisy starter or ender if present

        :return: -
        """

        self.match_time_temp = self.scoreboard_text_values[0]

        # Check for noisy starters and ender and clean if present
        letter_ptr = 0
        if not self.match_time_temp[letter_ptr].isdigit():
            letter_ptr += 1
        if not self.match_time_temp[letter_ptr].isdigit():
            letter_ptr += 1
            self.match_time_temp = self.match_time_temp[letter_ptr:]
            logging.info("Time text noisy starter removed.")
        elif not self.match_time_temp[-1].isdigit():
            self.match_time_temp = self.match_time_temp[0:-1]
            logging.info("Time text noisy ender removed.")

    def update_match_time(self):
        """
        Validates cleansed match_time_temp with regular expression and sets match_time if valid value exists

        :return: True: time has been updated
                 False: time has not been updated
        """

        # Check if the OCR read value is valid
        time_expr = re.compile('\d\d:\d\d')
        res = time_expr.search(self.match_time_temp)

        if res is None:
            return False

        last_valid_timeval = self.match_time_temp[res.start():res.end()]
        self._match_time_prev.append(last_valid_timeval)

        # Check validity between last time values
        if last_valid_timeval < self._match_time_prev[len(self._match_time_prev)-2]:
            # Minute error occured - minute remain unchanged
            if last_valid_timeval[0:2] < self._match_time_prev[len(self._match_time_prev)-2][0:2]:
                logging.warning(
                    "Minute error occured: minute remain unchanged!")
                fixed_minutes = self._match_time_prev[len(
                    self._match_time_prev)-2][0:2]
                last_valid_timeval = fixed_minutes + last_valid_timeval[2:]

            else:
                # Second error occured - auto increment second
                logging.warning(
                    "Second error occured: auto incremented second!")
                seconds = self._match_time_prev[len(
                    self._match_time_prev)-2][-2:]
                fixed_seconds = str(int(seconds)+1)
                last_valid_timeval = last_valid_timeval[:-2] + fixed_seconds

        # Free unnecessary time values
        if len(self._match_time_prev) > 2:
            self._match_time_prev.pop(0)

        # Write all valid values to a text file for analysis
        self.match_time = last_valid_timeval
        with open(self.export_path + '/' + self.filename_out, 'a') as f:
            f.write("%s,%s\n" % (self.match_time, ocr.count))
        return True

    def update_match_score(self):
        """
        Validates cleansed score with regular expression

        :return: True: score matches the regexp
                 False: score does not match the regexp
        """
        score_expr = re.compile('\d-\d')
        res = score_expr.search(self.scoreboard_text_values[1])

        if res is None:
            return False

        self.home_score = self.home_score_temp
        self.opponent_score = self.opponent_score_temp
        return True

    def update_match_team(self, selected_team):
        """
        Sets cleansed home_team or opponent_team values if not set before

        :return: -
        """
        if selected_team == 'home':
            self.home_team = self.home_team_temp
            self.home_team_identified = True

        elif selected_team == 'opponent':
            self.opponent_team = self.opponent_team_temp
            self.opponent_team_identified = True

    def update_all_match_info(self):
        """
        Attempts to update match infos:
        time, teams, score
        :return: True: update succeed
                 False: update failed
        """
        if len(self.scoreboard_text_values[0]) > 0 and len(self.scoreboard_text_values[1]) > 0:
            try:
                # Clean OCR read time value and update time if valid
                self.cleanse_match_time()
                self.update_match_time()

                # Clean OCR read score value and update score if valid
                self.cleanse_match_score()
                self.update_match_score()

                # Clean OCR read team values and set teams if valid and necessary
                self.cleanse_match_teams()

                if self.home_team_identified is False:
                    self.update_match_team('home')

                if self.opponent_team_identified is False:
                    self.update_match_team('opponent')

            except Exception as e:
                logging.info(e)
                logging.info("Unable to update match info for some reason")
        else:
            logging.info("Unable to update match info: no text received!")

    def print_all_match_info(self):

        home_team_name = self.home_team
        opponent_team_name = self.opponent_team

        if self.home_team_fullname is not None and self.opponent_team_fullname is not None:
            home_team_name = self.home_team_fullname
            opponent_team_name = self.opponent_team_fullname

        print('{} {} {}-{} {}'.format(self.match_time,
                                      home_team_name,
                                      self.home_score,
                                      self.opponent_score,
                                      opponent_team_name))

# MAIN
# Empty times.txt file
def ocr(export_path, filename_in, filename_out, video_length):
    ocr.count = 0
    ocr.video_length = video_length
    open(export_path+'/' + filename_out, 'w').close()

    ocr.eImageExported = threading.Event()

        # Create objects and threads
    ocr.scoreboard = ImageHandler(export_path, filename_in)
    ocr.football_match = Match(export_path, filename_out)

    ocr.tImageExtractor = threading.Thread(
            None, ocr.scoreboard.extract_image_from_video, name="ImageExtractor")
    ocr.tScoreboardAnalyzer = threading.Thread(
            None, ocr.football_match.analize_scoreboard, name="ScoreboardAnalyzer")

    ocr.tImageExtractor.start()
    ocr.tScoreboardAnalyzer.start()

    ocr.tImageExtractor.join()
    ocr.tScoreboardAnalyzer.join()

if __name__ == '__main__' :
    filename_in = 'ocr/tmp/secondmatch.mkv'
    export_path = 'ocr/img'
    filename_out = 'times.txt'
    video_length = 1080
    ocr(export_path, filename_in, filename_out, 1080)


from __future__ import absolute_import, print_function
import os

import numpy as np
import pyopencl as cl

os.environ['PYOPENCL_COMPILER_OUTPUT']='1'
modulepath=os.path.dirname(os.path.abspath(__file__))

class Particles(object):
    def __init__(self,nparticles=1,ndim=10):
        self.nparticles=nparticles
        self.ndim=ndim
        self.data=np.zeros(nparticles*ndim,dtype=np.float64)

class Elements(object):
    value_t = np.dtype({'names'  :['f64','i64','u64'],
                        'formats':['<f8','<i8','<u8'],
                        'offsets':[    0,    0,    0],
                        'itemsize':8})
    DriftId=1
    MultipoleId=2
    def __init__(self,size=40000):
        self.size=size
        self.data=np.zeros(size,dtype=self.value_t)
        self.last=0
        self.elements=[]
    def add_drift(self,length=0.0):
        self.elements.append(self.last)
        self.data['u64'][self.last  ]=self.DriftId
        self.data['f64'][self.last+1]=length
        self.last+=2
    def add_multipole(self,knl=[],ksl=[],length=0.0,hxl=0.0,hyl=0.0):
        self.elements.append(self.last)
        order=max(len(knl),len(ksl))
        self.data['u64'][self.last+0]=self.MultipoleId
        self.data['u64'][self.last+1]=order
        self.data['u64'][self.last+2]=length
        self.data['u64'][self.last+3]=hxl
        self.data['u64'][self.last+4]=hyl
        fact=1
        for nn in range(len(knl)):
           self.data['f64'][self.last+5+nn*2]=knl[nn]/fact
           fact*=nn+1
        fact=1
        for nn in range(len(ksl)):
           self.data['f64'][self.last+5+nn*2+1]=ksl[nn]/fact
           fact*=nn+1
        self.last+=5*2*order

particles=Particles(nparticles=2560,ndim=10)
elements=Elements()

class SixTrackCL(object):
    ro=cl.mem_flags.READ_ONLY | cl.mem_flags.COPY_HOST_PTR
    rw=cl.mem_flags.READ_WRITE | cl.mem_flags.COPY_HOST_PTR
    def __init__(self,particles,elements,device=["0"]):
        self.particles=particles
        self.elements=elements
        srcpath='-I%s'%modulepath
        self.ctx = cl.create_some_context(answers=device)
        self.queue = cl.CommandQueue(self.ctx)
        self.particles_g = cl.Buffer(self.ctx, self.rw, hostbuf=particles.data)
        self.elements_g = cl.Buffer(self.ctx, self.ro, hostbuf=elements.data)
        src=open(os.path.join(modulepath,'sixtracklib_cl.c')).read()
        self.prg=cl.Program(self.ctx,src).build(options=[srcpath])
    def track(self,nturns,elemids):
        elemids=np.array(self.elemids,dtype='uint64')
        elemids_g=cl.Buffer(self.ctx, self.rw, hostbuf=elemids)
        nelems=np.int64(len(elem_ids))
        nturns=np.int64(nturns)
        self.prg.elements_track(queue,[npart],None,
                                self.elements_g, elemids_g, nelems,
                                nturns,
                                self.particles_g)
        cl.enqueue_copy(queue,particles.data,self.particles_g)


# -*- coding: utf-8 -*-
"""
Created on Tue Oct  2 17:51:41 2018

@author: USER
"""
import sys
sys.path.append('..')

import os
import torch
import torch.nn as nn
import numpy as np
import utils.general as utils
import utils.adversarial_ae as ae_utils
from adverse_AE import Adversarial_AE, Discriminator
import torchvision
import torch.optim as optim

if __name__ == '__main__':

    epochs = 50
    batch_size = 100
    latent_dim = 2
    reg = True
    dataloader = utils.get_dataloader(batch_size, pad = False)
    device = utils.get_device()
    step_per_epoch = np.ceil(dataloader.dataset.__len__() / batch_size)
    sample_dir = './samples'
    checkpoint_dir = './checkpoints'

    utils.makedirs(sample_dir, checkpoint_dir)

    AE = Adversarial_AE(latent_dim = latent_dim).to(device)
    D = Discriminator(latent_dim = latent_dim).to(device)

    ae_optim = optim.Adam(AE.parameters())
    d_optim = optim.Adam(D.parameters())

    rec_log = []
    d_log = []

    rec_criterion = nn.MSELoss().to(device)
    discrim_criterion = nn.BCELoss().to(device)

    result = None
    for epoch_i in range(1, epochs + 1):
        for step_i, (img, _) in enumerate(dataloader):
            N = img.shape[0]
            real_label = torch.ones(N).to(device)
            fake_label = torch.zeros(N).to(device)
            soft_label = torch.Tensor(batch_size).uniform_(0.9, 1).to(device)

            img = img.view(N, -1).to(device)
            if result is None:
                result = img

            # Reconstruction phase
            reconstructed = AE(img)

            loss = rec_criterion(reconstructed, img)

            ae_optim.zero_grad()
            loss.backward()
            ae_optim.step()
            rec_log.append(loss.item())

            # Discriminator phase
            z = torch.randn(N, latent_dim).to(device)
            code = AE.encoder(img)
            fake_score = D(code)
            real_score = D(z)

            real_loss = discrim_criterion(real_score, soft_label)
            fake_loss = discrim_criterion(fake_score, fake_label)
            loss = real_loss + fake_loss

            d_optim.zero_grad()
            loss.backward()
            d_optim.step()
            d_log.append(loss.item())

            code = AE.encoder(img)
            fake_score = D(code)
            loss = discrim_criterion(fake_score, real_label)

            ae_optim.zero_grad()
            loss.backward()
            ae_optim.step()

            utils.show_process(epoch_i, step_i + 1, step_per_epoch, rec_log, d_log)

        if epoch_i == 1:
            torchvision.utils.save_image(result.reshape(-1, 1, 28, 28),
                                         os.path.join(sample_dir, 'orig.png'),
                                         nrow = 10)
        reconstructed = AE(result)
        utils.save_image(reconstructed.reshape(-1, 1, 28, 28), 10, epoch_i,
                         step_i + 1, sample_dir)

        utils.save_model(AE, ae_optim, rec_log, checkpoint_dir, 'AE.ckpt')
        utils.save_model(D, d_optim, d_log, checkpoint_dir, 'D.ckpt')

    ae_utils.plot_manifold(AE.encoder, device, dataloader.dataset,
                        dataloader.dataset.__len__(), sample_dir)


with open('input.txt', 'r') as f:
    input = f.readlines()
def findmax():
    max = []
    total = 0
    for x in input:
        if x.strip() != '':
            total += int(x.strip())
        else:
            max.append(total)
            total = 0
    max.sort()
    print(sum(max[-3:]))

findmax()


import math
import itertools

def klauber(x):
    return x*x-x+41

def isPrime(x):
    for i in range(2,1+int(math.sqrt(x))):
        if x%i == 0:
           return False
    return True

def klauberNotPrime(r):
    result = []
    for i in range(1,r):
        if not isPrime(klauber(i)):
            result.append(i)
    return result

class Quadratic:
    def __init__(self, square,linear,constant):
        self.square = square
        self.linear = linear
        self.constant = constant

    def __call__(self, x):
        return self.square*x*x + self.linear*x + self.constant

    def __repr__(self):
        return "Quadratic(%d,%d,%d)" % (self.square,self.linear,self.constant)

# Find best ploynomial which matches all terms in array

def bestPoly(array, cRange, lRange=None, sRange=None):
    if lRange is None: lRange = cRange
    if sRange is None: sRange = lRange
    bestScore = -1
    bestQuadratic = None
    for s in xrange(sRange):
        for l in xrange(lRange):
            if s==0 and l==0:
                continue
            for c in xrange(cRange):
                q = Quadratic(s,l,c)
                score = testPoly(q, array)
                if score>bestScore:
                    bestScore = score
                    bestQuadratic = q
                    print("best Score %d for %s" % (bestScore, bestQuadratic))
    return bestQuadratic

def testPoly(q,array):
    maxArray = array[-1]
    score = 0
    for x in xrange(1,len(array)):
        value = q(x)
        if value>maxArray:
           break
        elif value in array:
           score += 1
        else:
           return -1
    return score

#Calculates a string of the best polynomials in sequence - similar to repRunEx but without replacement/supplementation of the array passed
def bestPolySet(array,cRange,lRange,sRange):
    polySet = []
    while len(array)>0:
        q = bestPoly(array, cRange, lRange, sRange)
        polySet.append(q)
        for x in xrange(1,len(array)):
            v = q(x)
            if v in array:
               array.remove(v)
        print("New Array length %d" % len(array))
    return polySet

#Subtracts a given polynomial from a given array, and returns the result
def subPoly(array, poly):
    currentVal = None
    for i in xrange(0, len(array)):
        currentVal = poly(i)
        if not currentVal > array[len(array)-1]:
            if currentVal in array:
                array.remove(currentVal)
    return array

def kNPsubIP(number, IP):
    array = klauberNotPrime(number)
    for ip in IP:
        array = subPoly(array, ip)
    return array

def repRunEx(number, it):
    tedCruz = [Quadratic(0,0,0)] * it
    for i in xrange(it):
        print(kNPsubIP(number+(i*41), tedCruz))
        tedCruz[i] = bestPoly(kNPsubIP(number+(i*41), tedCruz), 2000, 200, 20)
    print(tedCruz)

#The following two arrays are for use by the BestList
bestQuadList = [Quadratic(0,0,0)] * 5

bestScoreList = [0] * 5

#Quadratics for testing functions
a = Quadratic(1,1,1)
b = Quadratic(2,2,2)
c = Quadratic(3,3,3)
d = Quadratic(4,4,4)
e = Quadratic(5,5,5)

def bestList(quadratic, score):
    lowestScore = 100000
    lowestIndex = 100000
    for i in xrange(len(bestScoreList)):
        if lowestScore > bestScoreList[i]:
            lowestScore = bestScoreList[i]
            lowestIndex = i
    if score > lowestScore:
        bestScoreList[lowestIndex] = score
        bestQuadList[lowestIndex] = quadratic
        return (bestQuadList)
    return (bestQuadList)

def bestPolyLoop(kArray, cRange, lRange=None, sRange=None):
    global bestQuadList
    global bestScoreList
    bestQuadList = [Quadratic(0,0,0)] * 5
    bestScoreList = [0] * 5
    bestListReceived = []
    if lRange == None: lRange = cRange
    if sRange == None: sRange = lRange
    for s in xrange(sRange):
        for l in xrange(lRange):
            if s==0 and l==0:
                continue
            for c in xrange(cRange):
                q = Quadratic(s,l,c)
                score = testPoly(q, kArray)
                bestListReceived = bestList(q, score)
    return bestListReceived

#def pseudoGenetics(layers, krange, kInc, cRange, lRange, sRange, currentlyExcludedQuads):
 #   tL = []
  #  for i in xRange(layers):
   #     tL += bestPolyLoop(krange, cRange, lRange, sRange)

def layerScore(path, krange, cRange, lRange, sRange):
    arrayToTrim = klauberNotPrime(krange)
    importantPolyList = []
    for i in xrange(len(path)):
        regularPolyList = bestPolyLoop(arrayToTrim, cRange, lRange, sRange)
        #print(regularPolyList)
        #print(path)
        #print(i)
        importantPoly = regularPolyList[path[i]]
        #print(path[i])
        print(importantPoly)
        #print("The array length before subtraction is: " + str(len(arrayToTrim)))
        arrayToTrim = subPoly(arrayToTrim, importantPoly)
        #print("The array length after subtraction is: " + str(len(arrayToTrim)))
        #print(arrayToTrim)
        importantPolyList.append(importantPoly)
    return len(arrayToTrim)

def fixedPseudoGenetics(krange, cRange, lRange, sRange, recWidth):
    lowestScore = 1000000000
    bestTriple = [9999] * 5
    for a in xrange(recWidth):
        for b in xrange(recWidth):
            for c in xrange(recWidth):
                for d in xrange(recWidth):
                    for e in xrange(recWidth):
                        path = [a,b,c,d,e]
                        print(path)
                        tScore = layerScore(path, krange, cRange, lRange, sRange)
                        if lowestScore > tScore:
                            print(lowestScore)
                            print(tScore)
                            lowestScore = tScore
                            for i in xrange(len(path)):
                                bestTriple[i] = path[i]
    return bestTriple

#Make an array of the klauberNotPrimes up to the krange
#Find the top polynomials with bestPolyLoop
#Call self with first element of array as currentlyExcludedQuads, and with layers = layers - 1
#If layers = 0 print the string of