# -*- coding: utf-8 -*-
"""
Created on Fri Jan 11 20:06:31 2019

@author: saksake
"""

import numpy as np
from sklearn.datasets import load_iris

def datasets() :
    # LOAD BOSTON HOUSING DATASET
    boston = load_iris()

    # MAKE FEATURE DICTIONARY
    all_features = {}
    for i in range(len(boston.feature_names)):
        key_ = str(boston.feature_names[i])
        key_split = key_.split()
        key = key_split[0]+'_'+key_split[1]

        all_features[key] = boston.data[:,i]

    # ADD TARGET DICTIONARY
    all_features['species'] = boston.target
    return all_features

def splitdict(feature_dict, train_portion, label_key) :
    train_feature, train_label = {}, {}
    key = list(feature_dict.keys())
    ndata = len(feature_dict[key[0]])
    train_n = int(ndata*train_portion)
    idxs = np.array(range(ndata))
    np.random.shuffle(idxs)

    train_idx = idxs[:train_n]
    test_idx = idxs[train_n:]
    for key in feature_dict :
        if key == label_key :
            train_label[key] = {}
            train_label[key] = np.array(feature_dict[key])[train_idx]
        else :
            train_feature[key] = {}
            train_feature[key] = np.array(feature_dict[key])[train_idx]

    test_feature, test_label = {}, {}
    for key in feature_dict :
        if key == label_key :
            test_label[key] = {}
            test_label[key] = np.array(feature_dict[key])[test_idx]
        else :
            test_feature[key] = {}
            test_feature[key] = np.array(feature_dict[key])[test_idx]

    return train_feature, train_label, test_feature, test_label

use_feature_name = ['sepal_length',
                    'sepal_width',
                    'petal_length',
                    'petal_width',
                    'species']

name_columns_category = []

name_columns_bucket = []

name_columns_numeric = ['sepal_length',
                        'sepal_width',
                        'petal_length',
                        'petal_width']

label_key ='species'
train_portion = 0.6

all_features = datasets()
for key in all_features:
    print("'{:}',".format(key))

# CHOOSE INTEREST FEATURES FROM ALL FEATURES
used_features = {}
for key in all_features:
    if key in use_feature_name :
        used_features[key] = all_features[key]

inp_train_feature, inp_train_label, inp_test_feature, inp_test_label = splitdict(feature_dict = used_features,
                                                                 train_portion = train_portion,
                                                                 label_key = label_key)

import tensorflow as tf

# MAKE INPUT FUNCTION
# TRAIN DATA
input_fn_train = tf.estimator.inputs.numpy_input_fn(
    x = inp_train_feature,
    y = inp_train_label[label_key],
    shuffle=True,
    batch_size=128,
    num_epochs=None
)

# TEST DATA
input_fn_test = tf.estimator.inputs.numpy_input_fn(
    x = inp_test_feature,
    y = inp_test_label[label_key],
    shuffle=False,
    batch_size=128,
    num_epochs=1
)

# Define feature columns.
feature_columns_numeric, feature_columns_category, feature_columns_bucket = [], [], []
for key in inp_train_feature :
    # Define numeric feature columns.
    if key in name_columns_numeric :
        feature_columns_numeric.append(tf.feature_column.numeric_column(key))

    # Define categorycal feature columns.
    elif key in name_columns_category :
        uniq = (np.unique(inp_train_feature[key])).tolist()

        cat_column = tf.feature_column.categorical_column_with_vocabulary_list(key = key,
                                                                          vocabulary_list = uniq)

        embed_column = tf.feature_column.embedding_column(
                        categorical_column=cat_column,
                        dimension=len(uniq)
                        )
        feature_columns_category.append(embed_column)

    # Define bucket feature columns.
    elif key in name_columns_bucket :
        numeric_column = tf.feature_column.numeric_column(key)

        # make bucket boundaries
        arr = np.linspace(min(inp_train_feature[key]), max(inp_train_feature[key]), 1000)
        n_bucket = 3
        q = 1./(n_bucket+1.)
        boundaries = []
        for i in range(n_bucket):
            boundaries.append(int(np.quantile(arr, q*(i+1))))

        # Then, bucketize the numeric column on the years 1960, 1980, and 2000.
        bucketized_feature_column = tf.feature_column.bucketized_column(
            source_column = numeric_column,
            boundaries = boundaries)

        feature_columns_bucket.append(bucketized_feature_column)

feature_columns = feature_columns_numeric + feature_columns_category + feature_columns_bucket

# DEFINE ESTIMATOR
estimator= tf.estimator.DNNClassifier(
        feature_columns = feature_columns,

        # Two hidden layers
        hidden_units=[512, 256],

        optimizer='Adagrad', #'Adagrad', 'Adam', 'Ftrl', 'RMSProp', 'SGD'

        activation_fn=tf.nn.relu, # relu. tanh, sigmoid

        n_classes = len(np.unique(inp_train_label[label_key])),

        # Model directory
        model_dir = 'Iris')

# TRAIN MODEL
estimator.train(input_fn=input_fn_train, steps=5000)

# EVALUATE MODEL
print('-------------------------------------')
evaluate = estimator.evaluate(input_fn = input_fn_test)
print('-------------------------------------')

# PREDICT
pred = list(estimator.predict(input_fn = input_fn_test))

# VISUALIZE TESTING DAN PREDICTED
y_prob = [x['probabilities'] for x in pred]
y_pred = np.asarray([np.argmax(x) for x in y_prob])

y_real = inp_test_label[label_key]

ntrue = len(np.where(y_pred == y_real)[0])

acc = ntrue/float(len(y_real))

print('Accuracy = {:}'.format(acc))


#!/usr/bin/env python3
import asyncio
import discord
import os

client= discord.Client()
TOKEN = os.getenv('USER_TOKEN')
CHANNEL_ID = int(os.getenv('CHANNEL_ID'))
MESSAGE = os.getenv('MESSAGE')

def lambda_handler(event, context):
    print("lambda start")
    client.run(TOKEN, bot=False)

@client.event
async def on_ready():
    print('%s has connected to Discord!' % client.user)
    channel = client.get_channel(CHANNEL_ID)
    if channel:
        await channel.send(MESSAGE)
        print("message sent")
    else:
        print("channel not found")
    await client.close()


from .master import Master
import numpy as np
import poselib
import time
import math

import test_module.linecloud as lineCloudTest
import test_module.recontest as recontest

import utils.pose.pose_estimation as pe
import utils.pose.vector as vector
from utils.pose import dataset
from utils.pose import line
from utils.l2precon import calculate
from static import variable

np.random.seed(variable.RANDOM_SEED)
class OLC(Master):
    def __init__(self, dataset_path, output_path):
        self.pts_to_line = dict()
        self.line_to_pts = dict()
        self.line_3d = None

        self.pts_2d_query = None # Images.txt
        self.pts_3d_query = None # Points3D.txt
        self.camera_dict_gt = None # cameras.txt

        self.queryIds = None
        self.queryNames = None
        self.image_dict_gt = None

        self.resultPose = list()
        self.resultRecon = list()
        self.map_type = "OLC"
        self.points_3D_recon = list()
        self.lines_3D_recon = list()

        super().__init__(dataset_path, output_path)

        self.pts_3d_ids = list(self.pts_3d_query.keys())
        np.random.shuffle(self.pts_3d_ids)

    def makeLineCloud(self):
        print("OLC: Random distribution line cloud")
        _pts_3d = np.array([v.xyz for v in self.pts_3d_query.values()])
        _pts_ids = np.array([k for k in self.pts_3d_query.keys()])
        self.points_3D, self.line_3d, self.ind_to_id, self.id_to_ind = line.drawlines_olc(_pts_3d,_pts_ids)

        for i, k in enumerate(self.pts_3d_query.keys()):
            self.pts_to_line[k] = self.line_3d[i]
            self.line_to_pts[i] = k

    def maskSparsity(self, sparisty_level):
        new_shape = int(len(self.pts_3d_ids) * sparisty_level)
        self.sparse_line_3d_ids = set(self.pts_3d_ids[:new_shape])

    def matchCorrespondences(self, query_id):
        connected_pts3d_idx = np.where(self.pts_2d_query[query_id].point3D_ids != -1)[0]
        connected_pts3d_ids = self.pts_2d_query[query_id].point3D_ids[connected_pts3d_idx]

        p2 = np.array([self.pts_3d_query[k].xyz for k in connected_pts3d_ids],dtype=np.float64)
        x1 = np.array(self.pts_2d_query[query_id].xys[connected_pts3d_idx],dtype=np.float64)

        pts_to_ind = {}
        for _i, k in enumerate(connected_pts3d_ids):
            pts_to_ind[k] = _i
            if self.pts_3d_query[k].xyz[0] != p2[_i][0]:
                raise Exception("Point to Index Match Error", k)

        self.valid_pts_3d_ids = self.sparse_line_3d_ids.intersection(set(connected_pts3d_ids))

        newIndex = []
        _x2 = []
        for _pid in self.valid_pts_3d_ids:
            newIndex.append(pts_to_ind[_pid])
            _x2.append(self.pts_to_line[_pid])

        if newIndex:
            newIndex = np.array(newIndex)
            # p1: 2D Point
            # x1: 2D Line
            # p2: 3D Offset
            # x2: 3D Line
            self._x1 = x1[newIndex]
            self._p2 = p2[newIndex]
            self._x2 = np.array(_x2)

        else:
            self._x1 = np.array([])
            self._p2 = np.array([])
            self._x2 = np.array([])

        print("Found correspondences: ", self._x1.shape[0])

    def addNoise(self, noise_level):
        super().addNoise(noise_level)

    def estimatePose(self, query_id):
        if self._x1.shape[0] >= 6:
            gt_img = pe.get_GT_image(query_id, self.pts_2d_query, self.image_dict_gt)
            cam_id = gt_img.camera_id
            cam_p6l = [pe.convert_cam(self.camera_dict_gt[cam_id])]

            res = poselib.estimate_p6l_relative_pose(self._x1, self._p2, self._x2, cam_p6l, cam_p6l, variable.RANSAC_OPTIONS, variable.BUNDLE_OPTIONS, variable.REFINE_OPTION)
            super().savePoseAccuracy(res, gt_img, cam_p6l[0])

    def savePose(self, sparisty_level, noise_level):
        super().savePose(sparisty_level, noise_level)

    def saveAllPoseCSV(self):
        super().saveAllPoseCSV()

    def recoverPts(self, estimator, sparsity_level, noise_level):
        print("OLC recover image", "\n")
        self.sparse_pts_3d_ids =[]
        self.id_to_ind_recon = {}
        self.ind_to_id_recon = {}
        self.points_3D_recon = []
        self.lines_3D_recon = []

        for i in range(len(self.sparse_line_3d_ids)):
            _pts_3d_id = self.line_to_pts[i]
            self.sparse_pts_3d_ids.append(_pts_3d_id)
            self.points_3D_recon.append(self.pts_3d_query[_pts_3d_id].xyz)
            self.lines_3D_recon.append(self.pts_to_line[_pts_3d_id])
            self.id_to_ind_recon[_pts_3d_id] = i
            self.ind_to_id_recon[i] = _pts_3d_id

        self.points_3D_recon = np.array(self.points_3D_recon)
        self.lines_3D_recon = np.array(self.lines_3D_recon)

        ref_iter = variable.REFINE_ITER

        if estimator=='SPF':
            # No swap
            ests = calculate.coarse_est_spf(self.points_3D_recon, self.lines_3D_recon)
            ests_pts = calculate.refine_est_spf(self.points_3D_recon, self.lines_3D_recon, ests, ref_iter)
            info = [sparsity_level, noise_level, 0, estimator]
            super().saveReconpoints(ests_pts, info)

        if estimator=='TPF':
            print("OLC should't be estimated with TPF")
            pass

    def reconTest(self,estimator):
        #reconTest
        recontest.recontest_pt_idx([self.points_3D_recon],[self.ind_to_id_recon],self.pts_3d_query)

    def test(self,recover,esttype):
        # recon test
        print("Consistency test for",self.map_type)
        if recover:
            self.reconTest(esttype)


from collections import deque

def find_correct(string):
    stack = []
    for c in string:
        if c == "[" or c == "{" or c == "(":
            stack.append(c)
        else:
            if "[" in stack and c == "]" and stack[-1] == "[":
                stack.pop()
            elif "{" in stack and c == "}" and stack[-1] == "{":
                stack.pop()
            elif "(" in stack and c == ")" and stack[-1] == "(":
                stack.pop()
            else:
                return 0

    return 1 if not stack else 0

def solution(s):
    answer = 0
    deq = deque(list(s))

    for i in range(len(s)):
        deq.rotate(-1)
        string = "".join(deq)
        answer += find_correct(string)

    return answer


"""
Week 2 - Data mining
By Christopher Diaz Montoya
"""
# Problem 1!!

store=[] # Empty array to store values
for a in range (1000, 2000): # Loop to check over all numbers in range
    if (a % 11 == 0) and not (a % 3 == 0):
# Above line makes sure if multiple of 11 and not of 3 execute line below
        store.append(str(a)) # Stores numbers that met above requirements
print (*store, sep = ", ")
# Learnt the above print line from the website below to print output correctly
# https://www.kite.com/python/answers/how-to-print-a-list-without-brackets-in-python#:~:text=Use%20*%20to%20print%20a%20list,set%20sep%20to%20%22%2C%20%22%20.

# Problem 2!!

print("Please input a sentance: ")  # Allows user to input sentance
sentance = input()
# Above line assigns input to the varibale called sentance
# Below 2 lines will be used as counters for upper and lower case letters
UpperCase = 0
LowerCase = 0
# For loop to check each character for the length of the string sentance
for char in range(len(sentance)):
# Below says if char is in the lower letter alphabet add  and assigns to lower
# case counter else if in the upper case alphabet add to the upper counter
    if(sentance[char]>='A' and sentance[char]<='Z'):
        UpperCase += 1
    elif(sentance[char]>='a' and sentance[char]<='z'):
# Learnt in my other module how to convert from lower case to upper case
# without libraries so played around with the code as it's like a range
# and that's how I got the above line
        LowerCase += 1 # Add 1 to counter
print('Upper case = ', UpperCase)
print('Lower case = ', LowerCase)
# Above prints the count and I used the comma to print the string and counter
# int. As I only mentioned the alpahbets there is no issue with the space and
# is not counted by accident.

# Problem 3!!

# Below made a funtion that turns an int into a string
def NumToWord(a):
    b = str(a) # Casts int into a string and stored in b
    print(b) # Prints b which is casted into a string
    print(type(b)) # Double check what daat tybe b is
# Below int is used to make sure input value is an integer, learnt last
# academic year.
num = int(input("Please enter a number: "))
NumToWord(num) # Calls functions and passes input "num" into the funciton.

# Problem 4!!

import itertools # Import from library to help iterate through all outcomes

# Below stored for easy access
subject = ["I", "You"]
verb = ["Read", "Borrow"]
ob = ["Shakerpeare's plays", "Shakespeare's poems"]

# Below prints and iterates over each possible out come from the lists
# mentioned whille the varibles stay in the same order. List ensures prints
# in the right way
print(list(itertools.product(subject, verb, ob)))

# https://www.codegrepper.com/code-examples/python/how+to+find+all+combinations+of+a+list+python

# Problem 5!! Part 1

import matplotlib.pyplot as plt # imported and given a shorter name

x, y = [1, 2, 3], [2, 4, 1] # Assigning values to varibles x and y
plt.xlabel("X axis", fontsize = 15) # Prints x label and size
plt.ylabel("Y axis", fontsize = 15) # Prints y label and size
plt.title("My first graph", fontsize = 20) # Prints title
# Learnt how to change size and label names from
# https://stackoverflow.com/questions/12444716/how-do-i-set-the-figure-title-and-axes-labels-font-size-in-matplotlib
# Some of above learnt from lectures and exra study help from uni.

# This plots the points on the graph
plt.plot(x, y)
plt.show() # This shows the graph

# Part 2

X = [] # Created empty lists to store values read from document
Y = []

a = open("test.txt", "r") # a is a variable which are the contents
for row in a: # Loops all rows in the txt file
    row = row.split(" ") # splits numbers in file when it reads a space
    X.append(row[0]) # First nunber is added to X
    Y.append(int(row[1])) # Second number is added to Y

plt.xlabel("X axis", fontsize = 15) # Prints x label
plt.ylabel("Y axis", fontsize = 15) # Prints y label
plt.title("My second graph", fontsize = 20) # Prints title

plt.plot(X, Y) # This plots the points on the graph
plt.show() # This shows the graph

#https://www.geeksforgeeks.org/python-create-graph-from-text-file/

# Problem 6!!

# below importing relevant libraries
import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv ("train.csv")
# Above imports and reads the data set

df.info() # Did this to see how many columns there are along with what data
# types are in the data set which are 3, along with being able to see which
# columns have missing dat

df["Loan_Status"].value_counts(normalize=True).plot.bar()
# Used to see the column which shows how many people got approved in a barchart

catColumns = ["Gender", "Married", "Dependents", "Education", "Self_\
Employed", "Property_Area", "Credit_History"]
for x in catColumns: # Loops over all data in each column
# Crosstab checks against another group of data I want to analyse against,
# in this case Loan_Status https://pbpython.com/pandas-crosstab.html against
# all the columns in Columns
    y = pd.crosstab(df["Loan_Status"], df[x], normalize = "columns")
# https://www.journaldev.com/45109/normalize-data-in-python taught me how
# to normalize data and https://machinelearningmastery.com/rescaling-data-for-machine-learning-in-python-with-scikit-learn/#:~:text=Normalization%20refers%20to%20rescaling%20real,preparation%20of%20coefficients%20in%20regression.
# taught me what it does, makes all values inbetween 0 and 1.
    print(y) # Prints output
    y.plot(kind = "bar") # Plots bar chart for each column

df.boxplot(column = "ApplicantIncome", by = "Education") # Wanted to see the
# correlation between graduate income and non graduate income

numColumns = ["ApplicantIncome", "CoapplicantIncome", "LoanAmount", "Loan_Amount_Term"]

# I did above as I wanted to check if graduates earned more than non graduates
# Learnt this in lectue slides
for z in numColumns: # For loop to make a graph for each column
    # for each loop until every column in numColumns has a graph
    # shows column in numColumns against Loan_status
    result = df.boxplot(column = z, by = "Loan_Status") # Plots graph
    plt.show(result) # Shows graphs
# The graphs used in the abov loop were learnt from the lecture slides


from django.conf.urls import url, include
from django.contrib import admin

from rest_framework.documentation import include_docs_urls

api_patterns = [
    url(r'^docs/', include_docs_urls(title='Documentation')),

    url(r'^', include(('my_website.apps.youtube_download.urls', 'youtube_download'), namespace='youtube_download')),
]

urlpatterns = [
    url(r'^api/auth/', include('django.contrib.auth.urls')),
    url(r'^api/rest-auth/', include(('rest_auth.urls', 'youtube_download'), namespace='rest_auth')),
    url(r'^api/rest-auth/registration/', include(('rest_auth.registration.urls', 'youtube_download'), namespace='rest_auth_registration')),

    # Allauth
    url(r'^api/accounts/', include('allauth.urls')),

    url(r'^accounts/', include('allauth.urls')),

    url(r'^api/', include((api_patterns, 'youtube_download'), namespace='api')),
    url(r'^api/admin/', admin.site.urls),
]


from django.contrib.auth.decorators import login_required
from django.contrib.auth import login
from django.shortcuts import render_to_response, redirect
from django.template import RequestContext
from apps.data.models import Entry
from apps.data.forms import DataForm
from django.conf import settings
from django.core.urlresolvers import reverse
from django.http import HttpResponse, HttpResponseNotFound

@login_required
def add(request):
    form = None
    if request.method == 'POST':
        form = AddBookForm(request.POST, request.FILES)
        if form.is_valid():
            instance = form.save(commit=False)
            instance.title = request.title
            instance.text = request.text
            instance.save()
    else:
        form = AddBookForm()

    ctx = {
        'form': form
    }
    return render_to_response('data/create.html', ctx, context_instance=RequestContext(request))

@login_required
def entry(request, id):
#    try:
    entrie = Entry.objects.get(id=id)
    ctx = {'entrie': entrie}
    return render_to_response('data/entry.html', ctx, context_instance=RequestContext(request))
#    except:
#        return HttpResponse('
Page was found
')

@login_required
def create(request):
    a = Entry()

    form = DataForm(request.POST or None)
    if form.is_valid():
        form.save()

    ctx = {
        'form': form
    }
    return render_to_response('data/create.html', ctx, context_instance=RequestContext(request))
# Create your views here.


import concurrent.futures
import timeit

import matplotlib.pyplot as plt
import numpy

from controller import Controller

def mainUtil():
	result = []
	for i in range(50):
		c = Controller(300)
		c.GradientDescendAlgorithm(0.000006, 1000)
		result.append(c.testWhatYouHaveDone())
	return result

if __name__ == '__main__':
	start = timeit.default_timer()
	with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
		print('This takes anywhere from 5 to 12 minutes to run (depending on how powerful your machine is).\n\tGo grab some popcorn')
		Q1 = executor.submit(mainUtil)
		Q2 = executor.submit(mainUtil)
		Q3 = executor.submit(mainUtil)
		Q4 = executor.submit(mainUtil)
		Q5 = executor.submit(mainUtil)
		errorList = Q1.result() + Q2.result() + Q3.result() + Q4.result() + Q5.result()
		print('In 250 runs you have achieved:')
		print('\tMaximum Error: ', max(errorList))
		print('\tMinimum Error: ', min(errorList))
		print('\tAverage Error: ', numpy.average(errorList))
		plt.plot(errorList, 'ro')
		plt.show()
	end = timeit.default_timer()
	print('Time: ', (end - start) / 60)


# coding:utf-8

from appium import webdriver

class Werdriver:

    def get_driver(self):
        configure = {
            "platformName": "Android",
            "deviceName": "PBV0216922007470",
            "app": "/Users/luyunpeng/Downloads/ci_v1.5.0_2019-07-18_16-35_qa.apk",
            "noReset": "true"

        }
        driver = webdriver.Remote("http://127.0.0.1:4723/wd/hub", configure)

        return driver

if __name__ == '__main__':
    test = Werdriver()
    test.get_driver()


import pygame
import solveModuleNotFoundError
from Game import *
from Game.Scenes import *
from Game.Shared import *

class Breakout:
    def __init__(self):
        self.__lives = 5
        self.__score = 0

        self.__level  = Level(self)
        self.__level.load(0)

        self.__pad = Pad((GameConstant.SCREEN_SIZE[0]/2,GameConstant.SCREEN_SIZE[1] - GameConstant.PAD_SIZE[1]),pygame.transform.scale(pygame.image.load(GameConstant.SPRITE_PAD) , GameConstant.PAD_SIZE))
        self.__balls = [
            Ball((400,400) , pygame.transform.scale(pygame.image.load(GameConstant.SPRITE_BALL) , GameConstant.BALL_SIZE) ,self)
                    ]

        pygame.init()
        pygame.mixer.init()
        pygame.display.set_caption("Brick Breaker")
        pygame.mouse.set_visible(0)

        self.__clock = pygame.time.Clock()

        self.screen = pygame.display.set_mode(GameConstant.SCREEN_SIZE , pygame.DOUBLEBUF, 32)
        self.bg = pygame.transform.scale(pygame.image.load(GameConstant.BG).convert_alpha() , GameConstant.SCREEN_SIZE)

        self.__scenes = (
            PlayingGameScene(self),
            GameOverScene(self),
            HighscoreScene(self),
            MenuScene(self)

            )
        self.__currentScene = 3
        self.__sounds = (
            pygame.mixer.Sound(GameConstant.SOUND_FILE_GAMEOVER),
            pygame.mixer.Sound(GameConstant.SOUND_FILE_HIT_BRICK),
            pygame.mixer.Sound(GameConstant.SOUND_FILE_HIT_BRICK_LIFE),
            pygame.mixer.Sound(GameConstant.SOUND_FILE_HIT_BRICK_SPEED),
            pygame.mixer.Sound(GameConstant.SOUND_FILE_HIT_WALL),
            pygame.mixer.Sound(GameConstant.SOUND_FILE_HIT_PAD)
        )

    def start(self):
        while 1:
            self.__clock.tick(60)
            self.screen.fill((0,0,0))
            self.screen.blit( self.bg, (0,0))
            currentScene = self.__scenes[self.__currentScene]
            currentScene.handleEvents(pygame.event.get())
            currentScene.render()

            pygame.display.update()

    def changeScene(self , scene):
        self.__currentScene = scene

    def getLevel(self):
        return self.__level

    def getLives(self):
        return self.__lives
    def getScore(self):
        return self.__score

    def getBalls(self):
        return self.__balls

    def getPad(self):
        return self.__pad

    def playSound(self, soundClip):
        sound = self.__sounds[soundClip]

        sound.stop()
        sound.play()

    def increaseScore(self , score):
        self.__score += score

    def increaseLives(self):
        self.__lives += 1

    def reduceLives(self):
        self.__lives -= 1
    def reset(self):
        self.__score = 0
        self.__lives = 5
        self.__level.reset()
        self.__level.load(0)

Breakout().start()


from flask import render_template,request,redirect,url_for
from . import main
from ..request import get_news_sources,get_allArticles,get_headlines
from ..models import Sources, Articles

#views
@main.route('/')
def index():
    '''
    View root page function that returns the index page and its data
    '''
    # getting sources
    business_sources = get_news_sources('business')
    sports_sources = get_news_sources('sports')
    technology_sources = get_news_sources('technology')
    entertainment_sources = get_news_sources('entertainment')

    # news_sources = get_news_sources('sources')

    title = "Breaking News"

    return render_template('index.html', title = title, business_sources = business_sources, sports_sources=sports_sources, technology_sources=technology_sources,entertainment_sources=entertainment_sources)

# @main.route('/articles')
# def articles():
#     '''
#     view article page
#     '''
#     articles = get_allArticles(id)
#     return render_template("articles.html", id = id, articles = articles)
@main.route('/articles/<int:id>')
def articles(id):
    """_
    to display news and article details
    """
    articles = get_allArticles(id)
    return render_template("articles.html", id = id, articles =articles)

@main.route('/headlines')
def headlines():
    '''
    view headline page
    '''
    #getting headlines
    headline_id = get_headlines('id')
    headline_name = get_headlines('name')

    title = 'Top Headlines'
    return render_template('headlines.html', title = title, headline_id= headline_id, headline_name=headline_name)


#!/usr/bin/env python3

import shutil
import psutil
import socket
import report_email
import time
import os

def check_disk_usage(disk):
  disk_usage = shutil.disk_usage(disk)
  free = (disk_usage.free / disk_usage.total) * 100
  return free > 20

def check_cpu_usage():
  usage = psutil.cpu_percent(1)
  return usage < 80

def check_memory():
  memory = psutil.virtual_memory()[1] / 10**6
  return memory > 500

def check_localhost():
  #print(socket.gethostbyname('localhost'))
  if socket.gethostbyname('localhost') == '127.0.0.1':
    return True
  else:
    return False

def alert(error):
  sender = "automation@example.com"
  receiver = "{}@example.com".format(os.environ.get('USER'))
  subject = error
  body = "Please check your system and resolve the issue as soon as possible."
  message = report_email.generate(sender, receiver, subject, body, '')
  report_email.send(message)

def main():

  while True:
    if not check_disk_usage('/'):
      alert('Error - Available disk space is less than 20%')
    if not check_cpu_usage():
      alert('Error - CPU usage is over 80%')
    if not check_memory():
      alert('Error - Available memory is less than 500MB')
    if not check_localhost():
      alert('Error - localhost cannot be resolved to 127.0.0.1')

    time.sleep(60)

if __name__ == "__main__":
  main()


#影像命名：县（0表示西秀，1表示剑河县）_序号(在points列表中的序号，从0开始)_同一位置的序号（同一位置可能有多张，标个序号，从0开始）_年份（2021之类的）_img
#施工标签命名：县（0表示西秀，1表示剑河县）_序号(在points列表中的序号，从0开始)_年份（2021之类的）_conslabel
#分类标签命名：县（0表示西秀，1表示剑河县）_序号(在points列表中的序号，从0开始)_2021_classlabel

from osgeo import gdal,osr
import pickle
import os
import numpy

def getSRSPair(dataset):
    prosrs=osr.SpatialReference()
    prosrs.ImportFromWkt(dataset.GetProjection())
    geosrs=prosrs.CloneGeogCS()
    return prosrs,geosrs

def lonlat2geo(dataset,lon,lat):
    prosrs,geosrs=getSRSPair(dataset)
    ct=osr.CoordinateTransformation(geosrs,prosrs)
    coords=ct.TransformPoint(lon,lat)
    return coords[:2]

def geo2imagexy(dataset,x,y):
    trans=dataset.GetGeoTransform()
    a=numpy.array([[trans[1],trans[2]],[trans[4],trans[5]]])
    b=numpy.array([x-trans[0],y-trans[3]])
    result=numpy.linalg.solve(a,b)
    return int(result[0]),int(result[1])

def getImageBound(dataset):
    #[minx.maxx,miny,maxy]
    trans=dataset.GetGeoTransform()
    img_width,img_height=dataset.RasterXSize,dataset.RasterYSize
    result=[min(trans[0],trans[0]+trans[1]*img_width),max(trans[0],trans[0]+trans[1]*img_width),min(trans[3],trans[3]+trans[5]*img_height),max(trans[3],trans[3]+trans[5]*img_height)]
    return result

def getAllImage_tif(path):
    result=[]
    d=os.listdir(path)
    for i in d:
        if i.split('.')[-1] == 'tif':
            result.append(i)
    return result

def contain(bound,point):
    if bound[0]<point[0]<bound[1] and bound[2]<point[1]<bound[3]:
        return True
    else:
        return False

def clip_label_cons(county,year,path_pkl,path_src,path_dst,size=2048):
    dataset=gdal.Open(path_src)
    bound=getImageBound(dataset)

    with open(path_pkl,'rb') as f:
        points_dict=pickle.load(f)
    if county==0:
        points=points_dict['xixiu']
    else:
        points=points_dict['jianhe']

    for j,point in enumerate(points,0):
        x,y=lonlat2geo(dataset,point[0],point[1])
        if contain(bound,(x,y)):
            p=geo2imagexy(dataset,x,y)
            if p[0]+size>dataset.RasterXSize or p[1]+size>dataset.RasterYSize:
                continue
            clip_image=dataset.ReadAsArray(p[0],p[1],size,size)

            clip_image_path=path_dst+'\\'+str(county)+'_'+str(j)+'_'+str(year)+'_conslabel.tif'
            clip_image_driver=gdal.GetDriverByName('GTiff')
            clip_image_dataset=clip_image_driver.Create(clip_image_path,size,size,1,gdal.GDT_Float32)
            clip_image_dataset.SetGeoTransform((x,dataset.GetGeoTransform()[1],0,y,0,dataset.GetGeoTransform()[5]))
            clip_image_dataset.SetProjection(dataset.GetProjection())
            clip_image_dataset.GetRasterBand(1).WriteArray(clip_image)
            clip_image_dataset.FlushCache()
            clip_image_dataset=None

def clip_label_class(county,year,path_pkl,path_src,path_dst,size=2048):
    dataset=gdal.Open(path_src)
    bound=getImageBound(dataset)

    with open(path_pkl,'rb') as f:
        points_dict=pickle.load(f)
    if county==0:
        points=points_dict['xixiu']
    else:
        points=points_dict['jianhe']

    for j,point in enumerate(points,0):
        x,y=lonlat2geo(dataset,point[0],point[1])
        if contain(bound,(x,y)):
            p=geo2imagexy(dataset,x,y)
            if p[0]+size>dataset.RasterXSize or p[1]+size>dataset.RasterYSize:
                continue
            clip_image=dataset.ReadAsArray(p[0],p[1],size,size)

            clip_image_path=path_dst+'\\'+str(county)+'_'+str(j)+'_'+str(year)+'_classlabel.tif'
            clip_image_driver=gdal.GetDriverByName('GTiff')
            clip_image_dataset=clip_image_driver.Create(clip_image_path,size,size,1,gdal.GDT_Float32)
            clip_image_dataset.SetGeoTransform((x,dataset.GetGeoTransform()[1],0,y,0,dataset.GetGeoTransform()[5]))
            clip_image_dataset.SetProjection(dataset.GetProjection())
            clip_image_dataset.GetRasterBand(1).WriteArray(clip_image)
            clip_image_dataset.FlushCache()
            clip_image_dataset=None

if __name__=='__main__':
    from matplotlib import pyplot

    id_county=1
    year=2021
    path_pkl=r'K:\points.pkl'
    path_src=r'H:\剑河县\2021标签\label_2021.tif'
    path_dst=r'H:\剑河县\2021标签裁剪\分类'
    size=2048
    clip_label_class(id_county,year,path_pkl,path_src,path_dst,size)

    id_county=1
    year=2021
    path_pkl=r'K:\points.pkl'
    path_src=r'H:\剑河县\2021标签\label_2021_cons.tif'
    path_dst=r'H:\剑河县\2021标签裁剪\施工'
    size=2048
    clip_label_cons(id_county,year,path_pkl,path_src,path_dst,size)

    id_county=1
    year=2020
    path_pkl=r'K:\points.pkl'
    path_src=r'H:\剑河县\2020标签\label_2020.tif'
    path_dst=r'H:\剑河县\2020标签裁剪\施工'
    size=2048
    clip_label_cons(id_county,year,path_pkl,path_src,path_dst,size)


import requests
import json
from bs4 import BeautifulSoup

def songwhip_it(url):
    html = requests.get('https://songwhip.com/'+url).content
    soup = BeautifulSoup(html, 'html.parser')
    links_text = list(soup.findAll('script'))[2].get_text()
    links_json = json.loads(links_text[links_text.index('{'):-1])['links']
    return links_json

songwhip_it("https://open.spotify.com/track/4Aep3WGBQlpbKXkW7kfqcU")


###### Librerias ######
import tkinter as tk
import Widgets as Wd
import Ecuaciones as Ec
import time as tm
import threading as hilos
import numpy as np
###### Modulos De Librerias ######
import tkinter.ttk as ttk
import tkinter.messagebox as MsB
import serial
import serial.tools.list_ports
import matplotlib.pyplot as plt
###### SubModulos De Librerias ######
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)

board =serial.Serial(port='COM1', baudrate=9600)
tm.sleep(1)
board2 =serial.Serial(port='COM4', baudrate=9600)
tm.sleep(1)

def Show_Sliders(event): #Función Para Mostrar Sliders
    Alter_Sliders('T', Pl_x.get())
    Datos_Temp(0,0,0,1)
    Wd.Aparecer([Pl_x, Pl_y, Pl_z, P_xi, P_yi, P_zi, P_x, P_y, P_z, P_inicial, P_final],
    [1/16+0.025, 1/16+0.025, 1/16+0.025, 0, 0, 0, 1/16+0.01, 1/16+0.01, 1/16+0.01, 0, 2/16],
    [1/6, 3/6-0.07, 0.693, 2/6-0.02, 3/6+0.075, 0.836, 2/6-0.02, 3/6+0.075, 0.836, 1/6-0.02, 0])

def Show_Codo(Iden, Valor): #Función Para Mostrar Codos
    Wd.Aparecer([T_Codo, Despl_Codo], [4/16+0.02, 4/16+0.01], [3/7+0.02, 4/6])

def Show_Perfiles(event): #Función Para Mostrar Perfiles
    Wd.Aparecer([Cuadratico, TrapezoidalI, TrapezoidalII], [6/16+0.04, 9/16+0.04, 12/16+0.04], [0, 0, 0])

def Show_Datos(): #Función Para Mostrar Los Sliders De Datos De Entrada
    if Tipo.get()==1:
        Wd.Ocultar([Vj_1, Vj_2, Vj_3, Aj_1, Aj_2, Aj_3, TAc_1, TAc_2, TAc_3, TVc_1, TVc_2, TVc_3])

    if Tipo.get()==2:
        Wd.Aparecer([Vj_1, Vj_2, Vj_3, TVc_1, TVc_2, TVc_3],
        [9/16+0.04, 9/16+0.04, 9/16+0.04, 9/16+0.02, 9/16+0.02, 9/16+0.02],
        [1/8+0.01, 3/8+0.04, 5/8+0.08, 1/7+0.12, 3/7+0.12, 5/7+0.12])
        Wd.Ocultar([Aj_1, Aj_2, Aj_3, TAc_1, TAc_2, TAc_3])
        #Calculos.Perf_Trape(T_f.get(),N_p.get(),0,0,0,1)

    if Tipo.get()==3:
        Wd.Aparecer([Aj_1, Aj_2, Aj_3, TAc_1, TAc_2, TAc_3],
        [12/16+0.04, 12/16+0.04, 12/16+0.04, 12/16+0.02, 12/16+0.02, 12/16+0.02],
        [1/8+0.01, 3/8+0.04, 5/8+0.08, 1/7+0.12, 3/7+0.12, 5/7+0.12])
        Wd.Ocultar([Vj_1, Vj_2, Vj_3, TVc_1, TVc_2, TVc_3])
        #Calculos.Perf_Trape(T_f.get(),N_p.get(),0,0,0,2)

    Wd.Aparecer([T_f, N_p, TT_f, TN_p, Calcular_PT],
    [6/16+0.04, 6/16+0.04, 6/16+0.02, 6/16+0.02, 6/16+0.04],
    [1/8+0.01, 3/8+0.04, 1/7+0.012, 3/7+0.012, 6/8])

def Show_Graficas(Iden, Valor):
    print(Valor)

bands=0
bandr=0
def Datos_Temp(xtemp, ytemp, ztemp, RW): #Función Para Guardar Los Valores Para Nuevo Punto Inicial
    global bands
    global bandr

    if RW==0:
        selection = Despl_Mani.get()
        if selection == "Scara (PRR)":
            temp_xs=xtemp
            temp_ys=ytemp
            temp_zs=ztemp
            bands=1
        else:
            temp_xr=xtemp
            temp_yr=ytemp
            temp_zr=ztemp
            bandr=1
    else:
        selection = Despl_Mani.get()
        if selection == "Scara (PRR)":
            if bands==1:
                P_xi.config(text=temp_xs)
                P_yi.config(text=temp_ys)
                P_zi.config(text=temp_zs)
            else:
                P_xi.config(text=345.2)
                P_yi.config(text=0)
                P_zi.config(text=0)
        else:
            if bandr==1:
                P_xi.config(text=temp_xr)
                P_yi.config(text=temp_yr)
                P_zi.config(text=temp_zr)
            else:
                P_xi.config(text=197)
                P_yi.config(text=0)
                P_zi.config(text=95.5)

def Alter_Sliders(Ident, Valor): #Función Para Alternos Los Sliders (Scara-Antropomórfico)
    if Despl_Mani.get() == "Scara (PRR)":
        Pl_x['from_']=-131.5
        Pl_x['to']=375.5
        Pl_z['from_']=0
        Pl_z['to']=19
        if Ident == 'A1':
            Red_Slider(['S', 'T', Pl_y, Check_S_PL, 1/4-0.025, 1/3+0.22], Valor)
    else:
        Pl_x['from_']=-197
        Pl_x['to']=197
        if Ident == 'A1':
            Red_Slider(['A1', 'T', Pl_y, Check_A_PL, 1/4-0.025, 2/3+0.15], Valor)
        elif Ident == 'A2':
            Red_Slider(['A2', 'T', Pl_z, Check_A_PL, 1/4-0.025, 2/3+0.15], Valor)

def Mensajes(Cual): #Función Para Seleccionar Mensaje Emergente A Mostrar
    if Cual=="DK":
        MsB.showinfo(
            "Instrucciones Cinemática Directa",
        """
            Sliders: Desplazar los slider para mover las
            articulaciones del brazo robótico en tiempo real
            para obtener las matrices individuales y total de
            la cinemática directa. \n

            Cuadro de Texto: Digitar el valor que se encuentre
            en el rango de funcionamiento del robot para mover
            las articulaciones del brazo robótico.
            Luego presionar el botón de envió y obtener las
            matrices individuales y total de la cinemática directa
            en tiempo real.
        """)
    elif Cual=="IK":
        MsB.showinfo(
            "Instrucciones Cinemática Inversa",
        """
            Deslizar cada slider para establecer la posición
            del efector final, dar click en el botón "Calcular"
            y finalizar seleccionando la configuración del codo
            a utilizar para mover el manipulador. \n

            Se debe tener en cuenta que las opciones de los codos
            únicamente están disponibles sí los valores calculados
            de las articulaciones no superan los límites mecánicos
        """)

def Color(Bandera, Boton, Identi): #Función Para Alternan Color De Boton
    #print-->board.write
    if Bandera:
        Boton["bg"]="red4"
        board.write(Identi.encode() +b',1\n')
    else:
        Boton["bg"]="lime green"
        board.write(Identi.encode() +b',0\n')

def Gripper(Identi): #Función Para Abrir o Cerrar Grippers
        global Estado_S
        global Estado_A
        global Estado_R
        if Identi=='E':
            Estado_S=not Estado_S
            Color(Estado_S,Gp_S,'E')
        elif Identi=='A':
            Estado_A=not Estado_A
            Color(Estado_A,Gp_A,'A')
        else:
            Estado_R=not Estado_R
            Color(Estado_R,Gp_R,'R')

def Red_Slider(Vec, Valor): #Función Para Redefinir Los Limites de Los Sliders De Cinematica Inversa
    Ident=Vec[0]
    if (Ident == 'S') or (Ident == 'A2') or (Ident =='A1'):
        Pes=Vec[1]
        Slider=Vec[2]
        Check=Vec[3]
        PosX=Vec[4]
        PosY=Vec[5]
    if Ident =='S':                                   #Redefinir Slider "Py_S" De Scara
        if Pes == 'I':
            Variable=Check_S_Valor
        elif Pes == 'T':
            Variable=Check_ST_Valor
            Check_A_PL.place_forget()
        LimitY_S=Ec.Limites_Y_S(Valor)
        Slider['from_']=str(LimitY_S[0])
        Slider['to']=str(LimitY_S[1])
        if LimitY_S[2] == 1 :
            Check.place(relx=PosX, rely=PosY)
        else:
            Check.place_forget()
        if Variable.get():                       #Evalua El Checkbox "-", Para Valores Negativos
            Slider['from_']=str(float(-1)*LimitY_S[1])
            Slider['to']=str(float(-1)*LimitY_S[0])
    if Ident =='A1':                                  #Redefinir Slider "Py_A" De Antropomórfico
        LimitY_A=Ec.Limites_Y_A(Valor)
        Slider['from_']=str(LimitY_A[1])
        Slider['to']=str(LimitY_A[0])
    if Ident =='A2':                                  #Redefinir Slider "Pz_A" De Antropomórfico
        if Pes == 'I':
            LimitZ=Ec.Limites_Z_A(Px_A.get(), Py_A.get())
            Variable=Check_A_Valor
        elif Pes == 'T':
            LimitZ=Ec.Limites_Z_A(Pl_x.get(), Pl_y.get())
            Variable=Check_AT_Valor
            Check_S_PL.place_forget()
        if LimitZ[2] == 1 :
            Check.place(relx=PosX, rely=PosY)
            if Variable.get():                   #Evalua El Checkbox "inf", Para Valores Del Limite Inferior
                Slider['from_']=str(LimitZ[1][1])
                Slider['to']=str(LimitZ[1][0])
            else:
                Slider['from_']=str(LimitZ[0][1])
                Slider['to']=str(LimitZ[0][0])
        else:
            Check.place_forget()
            Slider['from_']=str(LimitZ[1])
            Slider['to']=str(LimitZ[0])

def Cambio(Ident): #Función Para Detectar El Cambio De Los CheckBox
    if Ident == 'S':
        Red_Slider(['S', 'I', Py_S, Check_S, 3/16, 1/2+0.01], Px_S.get())
    elif Ident == 'A2':
        Red_Slider(['A2', 'I', Pz_A, Check_A, 3/16, 2/3+0.18], None)
    elif Ident == 'ST':
        Red_Slider(['S', 'T', Pl_y, Check_S_PL, 1/4-0.025, 1/3+0.22], Pl_x.get())
    elif Ident == 'AT':
        Red_Slider(['A2', 'T', Pl_z, Check_A_PL, 1/4-0.025, 2/3+0.15], None)

def Cine_Directa(Vector, Valor): #Función Para Enviar y Calcular Cinemática Directa Con Los Sliders
    Identi=Vector[0]
    if (bool(Identi.find('E')))==False:
        Matriz=Ec.Parametros(1, Qs1_S.get(), Qs2_S.get(), Qs3_S.get(), None, None, None)
        Wd.Llenado(Matriz, 1, 4)
    elif (bool(Identi.find('A')))==False:
        Matriz=Ec.Parametros(2, Qs1_A.get(), Qs2_A.get(), Qs3_A.get(), None, None, None)
        Wd.Llenado(Matriz, 5, 8)
    else:
        Matriz=Ec.Parametros(3, Qs1_R.get(), Qs2_R.get(), Qs3_R.get(), Qs4_R.get(), Qs5_R.get(), Qs6_R.get())
        Wd.Llenado(Matriz, 9, 15)
    hilos.Thread(target=Wd.Barra.Carga, args=(Vector[1],)).start()
    board.write(Identi.encode()+b','+ Valor.encode()+b'\n')
    print(Identi.encode()+b','+ Valor.encode()+b'\n')
    board2.write(Identi.encode()+b','+ Valor.encode()+b'\r\n')

def Cajas_DK(Vector): #Función Para Boton "Enviar". Se Calcula y Envia La Cinemática Directa Con Los Cuadros de Texto
    Identi=Vector[0]
    Valor=Vector[1]
    Enviar(Vector)
    if (bool(Identi[0].find('E')))==False:
        Matriz=Ec.Parametros(1, float(Valor[0].get()), float(Valor[1].get()), float(Valor[2].get()), None, None, None)
        Wd.Llenado(Matriz, 1, 4)
    elif (bool(Identi[0].find('A')))==False:
        Matriz=Ec.Parametros(2, float(Valor[0].get()), float(Valor[1].get()), float(Valor[2].get()), None, None, None)
        Wd.Llenado(Matriz, 5, 8)
    else:
        Matriz=Ec.Parametros(3, float(Valor[0].get()), float(Valor[1].get()), float(Valor[2].get()), float(Valor[3].get()), float(Valor[4].get()), float(Valor[5].get()))
        Wd.Llenado(Matriz, 9, 15)

def Cine_Inversa(Vector): #Función Para Calcular Cinematica Inversa Del Scara
    Identi=Vector[0]
    Codos=Vector[1]
    if Identi=='S':
        Vec_IK=Ec.Calculo_Inversa(1, float(Px_S.get()), float(Py_S.get()), float(Pz_S.get()))
        Codos[0].Ubicacion(1/2,1/2,tk.N)
        Codos[1].Ubicacion(2/3, 1/2, tk.N)
        #Inserta Valores de Variables de Juntura en La Interfaz (Codo Abajo y Codo Arriba)
        q1_S.set(str(int(Vec_IK[0]/10)))
        q2_S_D.set(str(int(Vec_IK[1])))
        q3_S_D.set(str(int(Vec_IK[2])))
        q2_S_U.set(str(int(Vec_IK[3])))
        q3_S_U.set(str(int(Vec_IK[4])))
    elif Identi=='A':
        Vec_IK=Ec.Calculo_Inversa(2, float(Px_A.get()), float(Py_A.get()), float(Pz_A.get()))
        Codos[0].Ubicacion(1/2, 1/2, tk.N)
        Codos[1].Ubicacion(2/3, 1/2, tk.N)
        if Vec_IK[0]<(-1):
            Vec_IK[0]=360+Vec_IK[0]
        #Inserta Valores de Variables de Juntura en La Interfaz (Codo Abajo y Codo Arriba)
        q1_A.set(str(int(Vec_IK[0])))
        q2_A_D.set(str(int(Vec_IK[1])))
        q3_A_D.set(str(int(Vec_IK[2])))
        q2_A_U.set(str(int(Vec_IK[3])))
        q3_A_U.set(str(int(Vec_IK[4])))

    #Desabilitación de Botones de Envio Cinematica Inversa
    if Vec_IK[5] or Vec_IK[6]: #indar indab
        if  Vec_IK[6] == 1:#indab
            Codos[0].place_forget()
        if  Vec_IK[5] == 1:#indar
            Codos[1].place_forget()
        MsB.showwarning("Advertencia Selección Codo","""
        Una o ambas soluciones supera los limites mecanicos.
                                Varie el valor del punto
                     """)

def Enviar(Vector): #Función Donde Se Envia Los Datos
    Identi=Vector[0]
    Valor=Vector[1]
    for i in range (0,len(Identi)):
        hilos.Thread(target=Wd.Barra.Carga, args=(Vector[2],)).start()
        board.write(Identi[i].encode()+Valor[i].get().encode()+b'\n')
        board2.write(Identi[i].encode()+Valor[i].get().encode()+b'\r\n')
        tm.sleep(3)

def Jacobians(Barra): #Función Para Mostrar Los Jacobianos
    j_S=Ec.Jacobianos(1, Qs1_S.get(), Qs2_S.get(), Qs3_S.get())
    j_A=Ec.Jacobianos(2, Qs1_A.get(), Qs2_A.get(), Qs3_A.get())
    Matriz=[j_S[0], j_S[1], j_A[0], j_A[1]]
    hilos.Thread(target=Wd.Barra.Carga, args=(Barra,)).start()
    Wd.Llenado_Jaco(Matriz, 1, 4)

def elec_manipulador():#Funcion Para Elección de Manipulador
    selection=Despl_Mani.get()
    if selection == "Scara (PRR)":
        return 1
    else:
        return 2

def elec_codo():#Funcion Para Elección de codo
    selection=Despl_Codo.get()
    if selection == "Codo Abajo":
        return 1
    else:
        return 2

def plot_3d(pos_final_x, pos_final_y, pos_final_z):

    root_3d = tk.Tk()
    root_3d.wm_title("Plot 3D Efector Final")

    fig = Figure(figsize=(5, 5), dpi=100)

    canvas = FigureCanvasTkAgg(fig, master=root_3d)
    canvas.draw()
    ax = fig.add_subplot(111, projection="3d")
    ax.plot(pos_final_x, pos_final_y, pos_final_z)

    toolbar = NavigationToolbar2Tk(canvas, root_3d)
    toolbar.update()
    canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
    tk.mainloop()

def Envio_Pl(Vectores_1, Vectores_2, Vectores_3):
    paso=(T_f.get()/(N_p.get()))
    if Despl_Mani.get() == "Scara (PRR)":
        board.write(b'Eb,'+"{:.4f}".format(int(Vectores_1[-1])).encode()+b'\n')
        board2.write(b'Eb,'+str(int(Vectores_1[-1])).encode()+b'\r\n')
        Time_Prisma=int(Vectores_1[-1])*(1.8)
        tm.sleep (Time_Prisma)
        Restante=T_f.get()-Time_Prisma
        paso=(Restante/N_p.get())
        for i in range(0,int(N_p.get())):
            board.write(b'Ebr,'+"{:.4f}".format(int(Vectores_2[i])).encode()+b'\n')
            board2.write(b'Ebr,'+str(int(Vectores_2[i])).encode()+b'\r\n')
            tm.sleep(paso/2)
            board.write(b'Eab,'+"{:.4f}".format(int(Vectores_3[i])).encode()+b'\n')
            board2.write(b'Eab,'+str(int(Vectores_3[i])).encode()+b'\r\n')
            tm.sleep(paso/2)
    else:
        for i in range(0,int(N_p.get())):
            board.write(b'Ab,'+"{:.4f}".format(int(Vectores_1[i])).encode()+b'\n')
            board2.write(b'Ab,'+str(int(Vectores_1[i])).encode()+b'\r\n')
            tm.sleep(paso/3)
            board.write(b'Abr,'+"{:.4f}".format(int(Vectores_2[i])).encode()+b'\n')
            board2.write(b'Abr,'+str(int(Vectores_2[i])).encode()+b'\r\n')
            tm.sleep(paso/3)
            board.write(b'Aab,'+"{:.4f}".format(int(Vectores_3[i])).encode()+b'\n')
            board2.write(b'Aab,'+str(int(Vectores_3[i])).encode()+b'\r\n')
            tm.sleep(paso/3)

def But_Perfiles(Ident):#Funcion Para Calcular La Generación de Trayectorias
    mani=elec_manipulador()
    codo=elec_codo()
    xini=float(P_xi.cget("text"))
    yini=float(P_yi.cget("text"))
    zini=float(P_zi.cget("text"))
    xfin=float(Pl_x.get())
    yfin=float(Pl_y.get())
    zfin=float(Pl_z.get())
    tip=Tipo.get()
    tfin=T_f.get()
    resolucion=N_p.get()
    if tip == 2:
        variable=[Vj_1.get(), Vj_2.get(), Vj_3.get()]
    elif tip == 3:
        variable=[Aj_1.get(), Aj_2.get(), Aj_3.get()]
    else:
        variable=[0, 0, 0]
    Vectores=Wd.Perfil(tip, mani, codo, tfin, xini, yini, zini, xfin, yfin, zfin, resolucion, variable)
    if Vectores[0] == 1: # vel
        MsB.showwarning(title="error", message="La magnitud de la velocidad supera la condición. \n Varie el los valores de la velocidad crucero ")
        for i in range (0, 3):
            if Vectores[2]==0:
                Vj_1["from_"]=(Vectores[1])+0.1
                Vj_1["to"]=(Vectores[1]*2)-0.1
            if Vectores[2]==1:
                Vj_2["from_"]=(Vectores[1])+0.1
                Vj_2["to"]=(Vectores[1]*2)-0.1
            if Vectores[2]==2:
                Vj_3["from_"]=(Vectores[1])+0.1
                Vj_3["to"]=(Vectores[1]*2)-0.1
            Vectores=Wd.Perfil(Tipo.get(), elec_manipulador(), elec_codo(), T_f.get(), float(P_xi.cget("text")), float(P_yi.cget("text")), float(P_zi.cget("text")), float(Pl_x.get()), float(Pl_y.get()), float(Pl_z.get()), N_p.get(), [Vj_1.get(), Vj_2.get(), Vj_3.get()])

    elif Vectores[0] == 2: #acel
        MsB.showwarning(title="error", message="La magnitud de la aceleración supera la condición. \n Varie el los valores de la aceleración crucero")
        for i in range (0, 3):
            if Vectores[2]==0:
                Aj_1["from_"]=(Vectores[1])+0.1
                Aj_1["to"]=(Vectores[1]*4)-0.1
            if Vectores[2]==1:
                Aj_2["from_"]=(Vectores[1])+0.1
                Aj_2["to"]=(Vectores[1]*4)-0.1
            if Vectores[2]==2:
                Aj_3["from_"]=(Vectores[1])+0.1
                Aj_3["to"]=(Vectores[1]*4)-0.1
            Vectores=Wd.Perfil(Tipo.get(), elec_manipulador(), elec_codo(), T_f.get(), float(P_xi.cget("text")), float(P_yi.cget("text")), float(P_zi.cget("text")), float(Pl_x.get()), float(Pl_y.get()), float(Pl_z.get()), N_p.get(), [Aj_1.get(), Aj_2.get(), Aj_3.get()])

    else:
        posx=np.empty(resolucion)
        posy=np.empty(resolucion)
        posz=np.empty(resolucion)
        for n in range(0, resolucion):
            if mani == 1:
                mat=Ec.Parametros(1, Vectores[1][n], Vectores[2][n], Vectores[3][n], None, None, None)
                vect_pos=Ec.Vec('C', 3, None, mat[0])
                posx[n]=vect_pos[0]
                posy[n]=vect_pos[1]
                posz[n]=vect_pos[2]
            else:
                mat=Ec.Parametros(2, Vectores[1][n], Vectores[2][n], Vectores[3][n], None, None, None)
                vect_pos=Ec.Vec('C', 3, None, mat[0])
                posx[n]=vect_pos[0]
                posy[n]=vect_pos[1]
                posz[n]=vect_pos[2]
        #Thread(target=envio_graf1(Vectores[1],Vectores[2],Vectores[3])).start()
        Gr1=Wd.Grafica(Fr_Graf, r'Posición $q_1$', "q[°]", 0, 0)
        Gr2=Wd.Grafica(Fr_Graf, r'Posición $q_2$', "q[°]", 1/3, 0)
        Gr3=Wd.Grafica(Fr_Graf, r'Posición $q_3$', "q[°]", 2/3, 0)
        Gr4=Wd.Grafica(Fr_Graf, r'Velocidad $w_1$', r'w$[rad/s]$', 0, 1/2)
        Gr5=Wd.Grafica(Fr_Graf, r'Velocidad $w_2$', r'w$[rad/s]$', 1/3, 1/2)
        Gr6=Wd.Grafica(Fr_Graf, r'Velocidad $w_3$', r'w$[rad/s]$', 2/3, 1/2)
        Gr1.Linea(resolucion, int(Vectores[1][0]), int(Vectores[1][-1]), int(T_f.get()), Vectores[1])
        Gr2.Linea(resolucion, int(Vectores[2][0]), int(Vectores[2][-1]), int(T_f.get()), Vectores[2])
        Gr3.Linea(resolucion, int(Vectores[3][0]), int(Vectores[3][-1]), int(T_f.get()), Vectores[3])
        Gr4.Linea(resolucion, 0, Vectores[4][int(resolucion/2)], int(T_f.get()), Vectores[4])
        Gr5.Linea(resolucion, 0, Vectores[5][int(resolucion/2)], int(T_f.get()), Vectores[5])
        Gr6.Linea(resolucion, 0, Vectores[6][int(resolucion/2)], int(T_f.get()), Vectores[6])
        P_xi.config(text=Pl_x.get())
        P_yi.config(text=Pl_y.get())
        P_zi.config(text=Pl_z.get())
        Datos_Temp(P_xi.cget("text"), P_yi.cget("text"), P_zi.cget("text"), 0)
        Envio_Pl(Vectores[1], Vectores[2], Vectores[3])
        plot_3d(posx, posy, posz)

#Objetos Principales
Ventana = tk.Tk()
Ventana.title('Controles de Manipuladores Roboticos')
width=Ventana.winfo_screenwidth()
height= Ventana.winfo_screenheight()
Ventana.geometry("%dx%d" % (width, height))
Panel_Pestañas = ttk.Notebook(Ventana)
Panel_Pestañas.pack(fill='both',expand='yes')

#Variables
Nombres= tk.StringVar() #Variable String Para Nombres
Nombres.set("""
Dario Delgado - 1802992 \n
Brayan Ulloa - 1802861 \n
Fernando Llanes - 1802878 \n
Karla Baron - 1803648 \n
Sebastian Niño - 1803558
""")
Reposo= tk.StringVar() #Variable String Para Mensaje Reposo
Reposo.set("Parte de reposo \r termina en reposo: \r Ti=0; Vi=0; Vf=0")
Wd.Variables_Matrices(15, 4, 4, "DK") #Variables Matrices DK
Wd.Variables_Matrices(4, 6, 3, "Jaco") #Variables Matrices Jacobianos Scara-Antropomórfico
Wd.Variables_Matrices(2, 6, 6, "JacoR") #Variables Matrices Jacobianos R
Estado_S=False
Estado_A=False
Estado_R=False
Check_S_Valor=tk.BooleanVar()
Check_A_Valor=tk.BooleanVar()
Check_ST_Valor=tk.BooleanVar()
Check_AT_Valor=tk.BooleanVar()

#Pestañas
Pestaña_Info=Wd.Pestañas(Panel_Pestañas, 'Portada')
Pestaña_Scara=Wd.Pestañas(Panel_Pestañas, 'Robot Scara (P2R)')
Pestaña_Antro3R=Wd.Pestañas(Panel_Pestañas, 'Robot Antropomórfico (3R)')
Pestaña_Antro6R=Wd.Pestañas(Panel_Pestañas, 'Robot Antropomórfico (6R)')
Pestaña_Trayectorias_Jacobiano=Wd.Pestañas(Panel_Pestañas, 'Trayectorias Por Jacobiano Inverso')
Pestaña_Jacobianos=Wd.Pestañas(Panel_Pestañas, 'Jacobiano')
Pestaña_Trayectorias=Wd.Pestañas(Panel_Pestañas, 'Planeación De Trayectorias')

#Fuentes
Fuente_12 = Wd.Fuentes("Lucida Grande", 12)
Fuente_15 = Wd.Fuentes("Lucida Grande", 15)
Fuente_25 = Wd.Fuentes("Lucida Grande", 25)
Fuente_Num = Wd.Fuentes("Palatino Linotype", 18)
Fuente_Num2 = Wd.Fuentes("Palatino Linotype", 12)
Fuente_Slider= Wd.Fuentes("Bookman Old Style", 12)

##################################Pestaña 1########################################
Fi=Wd.Frame(Pestaña_Info, 'GUI Para Controlar Manipuladores Robóticos', Fuente_12, 1, 1, 0, 0, None) #Frame
Wd.Labels(Fi, Nombres, None, None, None, None, Fuente_25, None).Ubicacion(1/2, 1/2, tk.CENTER)#Label-Nombres
#Com=Wd.Boton(Fi, 20, 5, 'COM Close', None).Ubicacion(1/2, 7/8, tk.CENTER)

#Imagenes
Logo= Wd.Imagenes('./Imagenes/LOGOUMNG.png').zoom(2)                        #Logo UMNG
tk.Label(Fi, image=Logo).place(relx=1/4, rely=1/2, anchor=tk.CENTER)
Icono= Wd.Imagenes('./Imagenes/icon.png').zoom(2)                           #Icono Robot
tk.Label(Fi, image=Icono).place(relx=3/4, rely=1/2, anchor=tk.CENTER)

##################################Pestaña 2########################################
Fr_DK_S=Wd.Frame(Pestaña_Scara, 'Cinemática Directa', Fuente_12, 1, 5/8, 0, 0, None)   #Frame Cinematica Directa
Fr_IK_S=Wd.Frame(Pestaña_Scara, 'Cinemática Inversa', Fuente_12, 1, 3/8, 0, 5/8, None) #Frame Cinematica Inversa

######Cinematica Directa######

#Barra De Progreso
Ba_S=Wd.Barra(Fr_IK_S, 300, 1/6, 0.98, 0.25, tk.E)

#Sliders
Qs1_S=Wd.Slider(Fr_DK_S, 1, 19, 1, 250, 34, 'Desplazamiento Base', Fuente_Slider, Cine_Directa, ['Eb',Ba_S])
Qs1_S.Ubicacion(0,0)
Qs2_S=Wd.Slider(Fr_DK_S, -90, 90, 10, 250, 34, 'Rotación Antebrazo', Fuente_Slider, Cine_Directa, ['Ebr',Ba_S])
Qs2_S.Ubicacion(0, 1/3)
Qs3_S=Wd.Slider(Fr_DK_S, -90, 90, 10, 250, 34, 'Rotación Brazo', Fuente_Slider, Cine_Directa, ['Eab',Ba_S])
Qs3_S.Ubicacion(0, 2/3)
Qt1_S=Wd.Editables(Fr_DK_S, Fuente_Num, 3/16, 0.11)
Qt2_S=Wd.Editables(Fr_DK_S, Fuente_Num, 3/16, 1/3+0.11)
Qt3_S=Wd.Editables(Fr_DK_S, Fuente_Num, 3/16, 2/3+0.11)
Qt_S=[Qt1_S, Qt2_S, Qt3_S]

#Matrices
Wd.Matrices(Fr_DK_S, "DK", 1, 4, 4, "Link 1", 1/2, 0, Fuente_12)
Wd.Matrices(Fr_DK_S, "DK", 2, 4, 4, "Link 2", 5/6, 0, Fuente_12)
Wd.Matrices(Fr_DK_S, "DK", 3, 4, 4, "Link 3", 1/2, 1/2, Fuente_12)
Wd.Matrices(Fr_DK_S, "DK", 4, 4, 4, "Total", 5/6, 1/2, Fuente_12)

#Botones
Wd.Boton(Fr_DK_S, None, None, "Instrucciones", "LightYellow2", Mensajes, 'DK').Ubicacion(1, 1, tk.SE)
Gp_S=Wd.Boton(Fr_DK_S, 15, 3, "Griper", "lime green", Gripper, 'E')
Gp_S.Ubicacion(4/6, 0.9, tk.CENTER)
Wd.Boton(Fr_DK_S, 12, 2, "Enviar", "ivory3", Cajas_DK, [['Eb,','Ebr,','Eab,'], Qt_S, Ba_S]).Ubicacion(1/4+0.02, 0.9, tk.W)

######Cinematica Inversa######
#Sliders

Py_S=Wd.Slider(Fr_IK_S, -90, 90, 0.5, 250, 20, 'Py', Fuente_Slider, Red_Slider, ['N','N'])
Py_S.Ubicacion(0, 1/3)
Pz_S=Wd.Slider(Fr_IK_S, 0, 190, 10, 250, 20, 'Pz', Fuente_Slider, Red_Slider, ['N','N'])
Pz_S.Ubicacion(0, 2/3)
Check_S=Wd.Check(Fr_IK_S, '-', 3/16, 1/3+0.18, Cambio, 'S', Check_S_Valor)
Px_S=Wd.Slider(Fr_IK_S, -101.5, 345, 0.5, 250, 20, 'Px', Fuente_Slider, Red_Slider, ['S', 'I', Py_S, Check_S, 3/16, 1/2+0.01])
Px_S.Ubicacion(0, 0)

#Codo Abajo
Co_D_S=Wd.Frame(Fr_IK_S, "Codo Abajo", Fuente_12, 1/10, 1/2, 1/2, 0, tk.N)
q1_S=tk.StringVar()
q2_S_D=tk.StringVar()
q3_S_D=tk.StringVar()
qs_S_D=[q1_S, q2_S_D, q3_S_D]
Wd.Labels(Co_D_S, None, "d₁", None, None, None, Fuente_15, "sandy brown").Ubicacion(0, 0, tk.NW)
Wd.Labels(Co_D_S, q1_S, None, None, None, None, Fuente_15, "white").Ubicacion(1, 0, tk.NE)
Wd.Labels(Co_D_S, None, "θ₂", None, None, None, Fuente_15, "sandy brown").Ubicacion(0, 1/3, tk.NW)
Wd.Labels(Co_D_S, q2_S_D, None, None, None, None, Fuente_15, "white").Ubicacion(1, 1/3, tk.NE)
Wd.Labels(Co_D_S, None, "θ₃", None, None, None, Fuente_15, "sandy brown").Ubicacion(0, 2/3, tk.NW)
Wd.Labels(Co_D_S, q3_S_D, None, None, None, None, Fuente_15, "white").Ubicacion(1, 2/3, tk.NE)

#Codo Arriba
Co_U_S=Wd.Frame(Fr_IK_S, "Codo Arriba", Fuente_12, 1/10, 1/2, 2/3, 0, tk.N)
q2_S_U=tk.StringVar()
q3_S_U=tk.StringVar()
qs_S_U=[q1_S, q2_S_U, q3_S_U]
Wd.Labels(Co_U_S, None, "d₁", None, None, None, Fuente_15, "sandy brown").Ubicacion(0, 0, tk.NW)
Wd.Labels(Co_U_S, q1_S, None, None, None, None, Fuente_15, "white").Ubicacion(1, 0, tk.NE)
Wd.Labels(Co_U_S, None, "θ₂", None, None, None, Fuente_15, "sandy brown").Ubicacion(0, 1/3, tk.NW)
Wd.Labels(Co_U_S, q2_S_U, None, None, None, None, Fuente_15, "white").Ubicacion(1, 1/3, tk.NE)
Wd.Labels(Co_U_S, None, "θ₃", None, None, None, Fuente_15, "sandy brown").Ubicacion(0, 2/3, tk.NW)
Wd.Labels(Co_U_S, q3_S_U, None, None, None, None, Fuente_15, "white").Ubicacion(1, 2/3, tk.NE)

#Botones
Wd.Boton(Fr_IK_S, None, None, "Instrucciones", "LightYellow2", Mensajes, 'IK').Ubicacion(1, 1, tk.SE)
CodoD_S=Wd.Boton(Fr_IK_S, 12, 2, "Codo Abajo", "ivory3", Enviar, [['Eb,','Ebr,','Eab,'], qs_S_D, Ba_S])
CodoU_S=Wd.Boton(Fr_IK_S, 12, 2, "Codo Arriba", "ivory3", Enviar, [['Eb,','Ebr,','Eab,'], qs_S_U, Ba_S])
Wd.Boton(Fr_IK_S, 12, 8, "Calcular", "dim gray", Cine_Inversa, ['S', [CodoD_S, CodoU_S]]).Ubicacion(1/4+0.02, 1/2, tk.W)

##################################Pestaña 3########################################
Fr_DK_A=Wd.Frame(Pestaña_Antro3R, 'Cinemática Directa', Fuente_12, 1, 5/8, 0, 0, None)   #Frame Cinematica Directa
Fr_IK_A=Wd.Frame(Pestaña_Antro3R, 'Cinemática Inversa', Fuente_12, 1, 3/8, 0, 5/8, None) #Frame Cinematica Inversa

######Cinematica Directa######

#Barra De Progreso
Ba_A=Wd.Barra(Fr_IK_A, 300, 1/6, 0.98, 0.25, tk.E)

#Sliders
Qs1_A=Wd.Slider(Fr_DK_A, 0, 360, 10, 250, 34, 'Rotación Base', Fuente_Slider, Cine_Directa, ['Ab',Ba_A])
Qs1_A.Ubicacion(0, 0)
Qs2_A=Wd.Slider(Fr_DK_A, -90, 90, 10, 250, 34, 'Rotación Brazo', Fuente_Slider, Cine_Directa, ['Aab',Ba_A])
Qs2_A.Ubicacion(0, 2/3)
Qs3_A=Wd.Slider(Fr_DK_A, 0, 180, 10, 250, 34, 'Rotación Antebrazo', Fuente_Slider, Cine_Directa, ['Abr',Ba_A])
Qs3_A.Ubicacion(0, 1/3)
Qt1_A=Wd.Editables(Fr_DK_A,Fuente_Num, 3/16, 0.11)
Qt2_A=Wd.Editables(Fr_DK_A,Fuente_Num, 3/16, 1/3+0.11)
Qt3_A=Wd.Editables(Fr_DK_A,Fuente_Num, 3/16, 2/3+0.11)
Qt_A=[Qt1_A, Qt2_A, Qt3_A]

#Matrices
Wd.Matrices(Fr_DK_A, "DK", 5, 4, 4, "Link 1", 1/2, 0, Fuente_12)
Wd.Matrices(Fr_DK_A, "DK", 6, 4, 4, "Link 2", 5/6, 0, Fuente_12)
Wd.Matrices(Fr_DK_A, "DK", 7, 4, 4, "Link 3", 1/2, 1/2, Fuente_12)
Wd.Matrices(Fr_DK_A, "DK", 8, 4, 4, "Total", 5/6, 1/2, Fuente_12)

#Botones
Wd.Boton(Fr_DK_A, None, None, "Instrucciones", "LightYellow2", Mensajes, 'DK').Ubicacion(1, 1, tk.SE)
Gp_A=Wd.Boton(Fr_DK_A, 15, 3, "Griper", "lime green", Gripper, 'A')
Gp_A.Ubicacion(4/6, 0.9, tk.CENTER)
Wd.Boton(Fr_DK_A, 12, 2, "Enviar", "ivory3", Cajas_DK, [['Ab,','Abr,','Aab,'], Qt_A, Ba_A]).Ubicacion(1/4+0.02, 0.9, tk.W)

######Cinematica Inversa######

#Sliders
Pz_A=Wd.Slider(Fr_IK_A, None, None, 0.5, 250, 20, 'Pz', Fuente_Slider, Red_Slider, ['N','N'])
Pz_A.Ubicacion(0, 2/3)
Check_A=Wd.Check(Fr_IK_A, 'Inf', 3/16, 2/3+0.18, Cambio, 'A2', Check_A_Valor)
Py_A=Wd.Slider(Fr_IK_A, None, None, 0.5, 250, 20, 'Py', Fuente_Slider, Red_Slider, ['A2', 'I', Pz_A, Check_A, 3/16, 2/3+0.18])
Py_A.Ubicacion(0, 1/3)
Px_A=Wd.Slider(Fr_IK_A, -197, 197, 0.5, 250, 20, 'Px', Fuente_Slider, Red_Slider, ['A1', 'I', Py_A, None, None, None])
Px_A.Ubicacion(0, 0)

#Codo Abajo
Co_D_A=Wd.Frame(Fr_IK_A, "Codo Abajo", Fuente_12, 1/10, 1/2, 1/2, 0, tk.N)
q1_A=tk.StringVar()
q2_A_D=tk.StringVar()
q3_A_D=tk.StringVar()
qs_A_D=[q1_A, q2_A_D, q3_A_D]
Wd.Labels(Co_D_A, None, "θ₁", None, None, None, Fuente_15, "sandy brown").Ubicacion(0, 0, tk.NW)
Wd.Labels(Co_D_A, q1_A, None, None, None, None, Fuente_15, "white").Ubicacion(1, 0, tk.NE)
Wd.Labels(Co_D_A, None, "θ₂", None, None, None, Fuente_15, "sandy brown").Ubicacion(0, 1/3, tk.NW)
Wd.Labels(Co_D_A, q2_A_D, None, None, None, None, Fuente_15, "white").Ubicacion(1, 1/3, tk.NE)
Wd.Labels(Co_D_A, None, "θ₃", None, None, None, Fuente_15, "sandy brown").Ubicacion(0, 2/3, tk.NW)
Wd.Labels(Co_D_A, q3_A_D, None, None, None, None, Fuente_15, "white").Ubicacion(1, 2/3, tk.NE)

#Codo Arriba
Co_U_A=Wd.Frame(Fr_IK_A, "Codo Arriba", Fuente_12, 1/10, 1/2, 2/3, 0, tk.N)
q2_A_U=tk.StringVar()
q3_A_U=tk.StringVar()
qs_A_U=[q1_A, q2_A_U, q3_A_U]
Wd.Labels(Co_U_A, None, "θ₁", None, None, None, Fuente_15, "sandy brown").Ubicacion(0, 0, tk.NW)
Wd.Labels(Co_U_A, q1_A, None, None, None, None, Fuente_15, "white").Ubicacion(1, 0, tk.NE)
Wd.Labels(Co_U_A, None, "θ₂", None, None, None, Fuente_15, "sandy brown").Ubicacion(0, 1/3, tk.NW)
Wd.Labels(Co_U_A, q2_A_U, None, None, None, None, Fuente_15, "white").Ubicacion(1, 1/3, tk.NE)
Wd.Labels(Co_U_A, None, "θ₃", None, None, None, Fuente_15, "sandy brown").Ubicacion(0, 2/3, tk.NW)
Wd.Labels(Co_U_A, q3_A_U, None, None, None, None, Fuente_15, "white").Ubicacion(1, 2/3, tk.NE)

#Botones
Wd.Boton(Fr_IK_A, None, None, "Instrucciones", "LightYellow2", Mensajes, 'IK').Ubicacion(1, 1, tk.SE)
CodoD_A=Wd.Boton(Fr_IK_A, 12, 2, "Codo Abajo", "ivory3", Enviar, [['Ab,','Abr,','Aab,'], qs_A_D, Ba_A])
CodoU_A=Wd.Boton(Fr_IK_A, 12, 2, "Codo Arriba", "ivory3", Enviar, [['Ab,','Abr,','Aab,'], qs_A_U, Ba_A])
Wd.Boton(Fr_IK_A, 12, 8, "Calcular", "dim gray", Cine_Inversa, ['A', [CodoD_A, CodoU_A]]).Ubicacion(1/4+0.02, 1/2, tk.W)

##################################Pestaña 4########################################

#Desplegable
Despl_R=Wd.Desplegable(Pestaña_Antro6R, ["Cinemática Directa", "Cinemática Inversa"])
Despl_R.Ubicacion(0, 0)
Despl_R.bind("<<ComboboxSelected>>",Despl_R.Cambio)
Fr_DK_R=Despl_R.Frame_DK
Fr_IK_R=Despl_R.Frame_IK
#####Cinematica Directa######

#Barra De Progreso
Ba_R=Wd.Barra(Fr_DK_R, 200, 1/15, 0.98, 3/4, tk.NE)

#Sliders
Qs1_R=Wd.Slider(Fr_DK_R,0, 360, 0.5, 250, 34, 'Rotación Primera Base', Fuente_Slider, Cine_Directa, ['Rb1',Ba_R])
Qs1_R.Ubicacion(0, 0)
Qs2_R=Wd.Slider(Fr_DK_R,0, 360, 0.5, 250, 34, 'Rotación Primer Brazo', Fuente_Slider, Cine_Directa, ['Rbr1',Ba_R])
Qs2_R.Ubicacion(0, 1/6)
Qs3_R=Wd.Slider(Fr_DK_R,0, 360, 0.5, 250, 34, 'Rotación Segundo Brazo', Fuente_Slider, Cine_Directa, ['Rbr2',Ba_R])
Qs3_R.Ubicacion(0, 2/6)
Qs4_R=Wd.Slider(Fr_DK_R,0, 360, 0.5, 250, 34, 'Rotación Segunda Base', Fuente_Slider, Cine_Directa, ['Rb2',Ba_R])
Qs4_R.Ubicacion(0, 3/6)
Qs5_R=Wd.Slider(Fr_DK_R,0, 360, 0.5, 250, 34, 'Rotación Antebrazo', Fuente_Slider, Cine_Directa, ['Rab',Ba_R])
Qs5_R.Ubicacion(0, 4/6)
Qs6_R=Wd.Slider(Fr_DK_R,0, 360, 0.5, 250, 34, 'Rotación Muñeca', Fuente_Slider, Cine_Directa, ['Rm',Ba_R])
Qs6_R.Ubicacion(0, 5/6)
Qt1_R=Wd.Editables(Fr_DK_R, Fuente_Num, 3/16, 1/18+0.014)
Qt2_R=Wd.Editables(Fr_DK_R, Fuente_Num, 3/16, 4/18+0.014)
Qt3_R=Wd.Editables(Fr_DK_R, Fuente_Num, 3/16, 7/18+0.014)
Qt4_R=Wd.Editables(Fr_DK_R, Fuente_Num, 3/16, 10/18+0.014)
Qt5_R=Wd.Editables(Fr_DK_R, Fuente_Num, 3/16, 13/18+0.014)
Qt6_R=Wd.Editables(Fr_DK_R, Fuente_Num, 3/16, 16/18+0.014)
Qt_R=[Qt1_R, Qt2_R, Qt3_R, Qt4_R, Qt5_R, Qt6_R]

#Matrices
Wd.Matrices(Fr_DK_R, "DK", 9, 4, 4, "Link 1", 1/2, 0, Fuente_12)
Wd.Matrices(Fr_DK_R, "DK", 10, 4, 4, "Link 2", 5/6, 0, Fuente_12)
Wd.Matrices(Fr_DK_R, "DK", 11, 4, 4, "Link 3", 1/2, 1/4, Fuente_12)
Wd.Matrices(Fr_DK_R, "DK", 12, 4, 4, "Link 4", 5/6, 1/4, Fuente_12)
Wd.Matrices(Fr_DK_R, "DK", 13, 4, 4, "Link 5", 1/2, 2/4, Fuente_12)
Wd.Matrices(Fr_DK_R, "DK", 14, 4, 4, "Link 6", 5/6, 2/4, Fuente_12)
Wd.Matrices(Fr_DK_R, "DK", 15, 4, 4, "Total", 2/3, 3/4, Fuente_12)

#Botones
Wd.Boton(Fr_DK_R, None, None, "Instrucciones", "LightYellow2", Mensajes, 'DK').Ubicacion(1, 1, tk.SE)
Gp_R=Wd.Boton(Fr_DK_R, 15, 3, "Griper", "lime green", Gripper, 'R')
Gp_R.Ubicacion(7/16, 3/4+0.1, tk.N)
Wd.Boton(Fr_DK_R, 12, 2, "Enviar", "ivory3", Cajas_DK, [['Rb1,','Rbr1,','Rbr2,','Rb2,','Rab,','Rm,'], Qt_R, Ba_R]).Ubicacion(7/16, 3/4, tk.N)

######Cinematica Inversa######

#Sliders
# Wd.Slider(Fr_IK_R, -200, 200, 0.5, 250, 34, 'Px', Fuente_Slider, None, None).Ubicacion(0, 0)
# Wd.Slider(Fr_IK_R, -200, 200, 0.5, 250, 34, 'Py', Fuente_Slider, None, None).Ubicacion(0, 1/6)
# Wd.Slider(Fr_IK_R, -200, 200, 0.5, 250, 34, 'Pz', Fuente_Slider, None, None).Ubicacion(0, 2/6)
# Wd.Slider(Fr_IK_R, -200, 200, 0.5, 250, 34, 'Alfa', Fuente_Slider, None, None).Ubicacion(0, 3/6)
# Wd.Slider(Fr_IK_R, -200, 200, 0.5, 250, 34, 'Beta', Fuente_Slider, None, None).Ubicacion(0, 4/6)
# Wd.Slider(Fr_IK_R, -200, 200, 0.5, 250, 34, 'Gamma', Fuente_Slider, None, None).Ubicacion(0, 5/6)

#Botones
Wd.Boton(Fr_IK_R, None, None, "Instrucciones", "LightYellow2", Mensajes, 'IK').Ubicacion(1, 1, tk.SE)

##################################Pestaña 5########################################

Fr_T_J=Wd.Frame(Pestaña_Trayectorias_Jacobiano, 'Planificación de Trayectorias Por Jacobiano Inverso', Fuente_12, 1, 1, 0, 0, None)   #Frame Jacobiano

##################################Pestaña 6########################################

Fr_J=Wd.Frame(Pestaña_Jacobianos, 'Jacobianos', Fuente_12, 1, 1, 0, 0, None)   #Frame Jacobiano

#Barra De Progreso
Ba_J=Wd.Barra(Fr_J, 300, 1/15, 1/2, 1/3, tk.N)

#Matrices
Wd.Matrices(Fr_J, "Jaco", 1, 6, 3, "Jacobiano Scara Geométrico", 1/4, 0, Fuente_12)
Wd.Matrices(Fr_J, "Jaco", 2, 6, 3, "Jacobiano Scara Analítico", 3/4, 0, Fuente_12)
Wd.Matrices(Fr_J, "Jaco", 3, 6, 3, "Jacobiano Antropomórfico Geométrico", 1/4, 1/3, Fuente_12)
Wd.Matrices(Fr_J, "Jaco", 4, 6, 3, "Jacobiano Antropomórfico Analítico", 3/4, 1/3, Fuente_12)
Wd.Matrices(Fr_J, "JacoR", 1, 6, 6, "Jacobiano Antropomórfico 6R Geométrico", 1/4, 2/3, Fuente_12)
Wd.Matrices(Fr_J, "JacoR", 2, 6, 6, "Jacobiano Antropomórfico 6R Analítico", 3/4, 2/3, Fuente_12)

#Botones
#Wd.Boton(Fr_J, None, None, "Instrucciones", "LightYellow2").Ubicacion(1, 1, tk.SE)
Wd.Boton(Fr_J, 15, 3, "Mostrar", "dim gray", Jacobians, Ba_J).Ubicacion(1/2, 1/2, tk.N)

##################################Pestaña 7########################################

Fr_T=Wd.Frame(Pestaña_Trayectorias, 'Datos de Entrada', Fuente_12, 1, 1/4, 0, 0, None)   #Frame Datos Trayectorias

#Desplegables
Despl_Mani=Wd.Desplegable(Fr_T, ["Scara (PRR)", "Antropomórfico (RRR)"])
Despl_Mani.Ubicacion(0, 0)
Despl_Mani.bind("<<ComboboxSelected>>",Show_Sliders)
Despl_Codo=Wd.Desplegable(Fr_T, ["Codo Arriba", "Codo Abajo"])
Despl_Codo.bind("<<ComboboxSelected>>",Show_Perfiles)

#Label Información Importante (Parte de Reposo)
Wd.Labels(Fr_T, Reposo, None, 1, "solid", None, Fuente_15, None).Ubicacion(4/16, 0, None)

#Puntos Iniciales-Finales
#Labels
P_xi=Wd.Labels(Fr_T, None, "0", 1, "solid", 12, None, None)
P_yi=Wd.Labels(Fr_T, None, "0", 1, "solid", 12, None, None)
P_zi=Wd.Labels(Fr_T, None, "0", 1, "solid", 12, None, None)
P_x= Wd.Labels(Fr_T, None, "Px", None, None, None, None, None)
P_y= Wd.Labels(Fr_T, None, "Py", None, None, None, None, None)
P_z= Wd.Labels(Fr_T, None, "Pz", None, None, None, None, None)

#Buttons
Tipo=tk.IntVar()
Cuadratico=Wd.Radio(Fr_T, "Perfil Cuadrático", Fuente_12, 1, Tipo, 15, Show_Datos)
TrapezoidalI=Wd.Radio(Fr_T, "Perfil Trapezoidal I", Fuente_12, 2, Tipo, 15, Show_Datos)
TrapezoidalII=Wd.Radio(Fr_T, "Perfil Trapezoidal II", Fuente_12, 3, Tipo, 15, Show_Datos)
Calcular_PT=Wd.Boton(Fr_T, 12, None, "Calcular", "dim gray", But_Perfiles, None)
#Wd.Boton(Fr_T, None, None, "Instrucciones", "LightYellow2").Ubicacion(1, 1, tk.SE)

#Barra De Progreso
Br_Pl=Wd.Barra(Fr_T, 150, 1/8, 5/16, 1, tk.S)

#Sliders
Check_S_PL=Wd.Check(Fr_T, '-', 1/4-0.025, 1/3+0.22, Cambio, 'ST', Check_ST_Valor)
Check_A_PL=Wd.Check(Fr_T, 'Inf', 1/4-0.025, 2/3+0.15, Cambio, 'AT', Check_AT_Valor)
Pl_x=Wd.Slider(Fr_T, None, None, 0.5, 180, 20, None, None, Alter_Sliders, 'A1')
Pl_y=Wd.Slider(Fr_T, None, None, 0.5, 180, 20, None, None, Alter_Sliders, 'A2')
Pl_z=Wd.Slider(Fr_T, None, None, 0.5, 180, 20, None, None, Show_Codo, None)
T_f=Wd.Slider(Fr_T, 15, 40, 1, 180, 20, None, None, Show_Graficas, None)
N_p=Wd.Slider(Fr_T, 10, 100, 10, 180, 20, None, None, Show_Graficas, None)
Vj_1=Wd.Slider(Fr_T, None, None, 0.2, 180, 20, None, None, Show_Graficas, None)
Vj_2=Wd.Slider(Fr_T, None, None, 0.2, 180, 20, None, None, Show_Graficas, None)
Vj_3=Wd.Slider(Fr_T, None, None, 0.2, 180, 20, None, None, Show_Graficas, None)
Aj_1=Wd.Slider(Fr_T, None, None, 0.2, 180, 20, None, None, Show_Graficas, None)
Aj_2=Wd.Slider(Fr_T, None, None, 0.2, 180, 20, None, None, Show_Graficas, None)
Aj_3=Wd.Slider(Fr_T, None, None, 0.2, 180, 20, None, None, Show_Graficas, None)

# #Titulos
P_inicial=Wd.Labels(Fr_T, None, "Puntos Iniciales", None, None, 12, Fuente_Num2, None)
P_final=Wd.Labels(Fr_T, None, "Puntos Finales", None, None, 12, Fuente_Num2, None)
T_Codo=Wd.Labels(Fr_T, None, "Elección Codo", None, None, 12, Fuente_Num2, None)
TT_f=Wd.Labels(Fr_T, None, "Tf", None, None, None, Fuente_Num2, None)
TN_p=Wd.Labels(Fr_T, None, "Np", None, None, None, Fuente_Num2, None)
TVc_1=Wd.Labels(Fr_T, None, "Vc1", None, None, None, Fuente_Num2, None)
TVc_2=Wd.Labels(Fr_T, None, "Vc2", None, None, None, Fuente_Num2, None)
TVc_3=Wd.Labels(Fr_T, None, "Vc3", None, None, None, Fuente_Num2, None)
TAc_1=Wd.Labels(Fr_T, None, "Ac1", None, None, None, Fuente_Num2, None)
TAc_2=Wd.Labels(Fr_T, None, "Ac2", None, None, None, Fuente_Num2, None)
TAc_3=Wd.Labels(Fr_T, None, "Ac3", None, None, None, Fuente_Num2, None)

Fr_Graf=Wd.Frame(Pestaña_Trayectorias, 'Gráficas', Fuente_12, 1, 3/4, 0, 1/4, None)   #Frame Graficas

#Ventana.attributes('-fullscreen',True)
Ventana.mainloop()


from keras.models import Sequential
from keras.layers import Dense
from keras.optimizers import SGD
import matplotlib.pyplot as plt
from keras.datasets import cifar10
from keras.utils import np_utils
(xtrain,ytrain),(xtest,ytest) = cifar10.load_data()
print('xtrain.shape',xtrain.shape)
print('ytrain.shape',ytrain.shape)
print('ytest.shape',ytest.shape)
print('xtest.shape',xtest.shape)
batchsize=200
cats = 10
nepoch = 100
xtrain = xtrain.reshape(50000,3072)

xtest = xtest.reshape(10000,3072)
xtrain = xtrain/255
xtest = xtest/255
ytrain = np_utils.to_categorical(ytrain,cats)
ytest = np_utils.to_categorical(ytest,cats)

model = Sequential()
model.add(Dense(units=10,input_shape=(3072,),activation='softmax',kernel_initializer='normal'))
model.compile(loss='categorical_crossentropy', optimizer=SGD(lr=0.05), metrics=['accuracy'])
model.summary()
history = model.fit(xtrain, ytrain, nb_epoch=nepoch, batch_size=batchsize, verbose=1)

# Evaluate
evaluation = model.evaluate(xtest, ytest, verbose=1)
print('Summary: Loss over the test dataset: %.2f, Accuracy: %.2f' % (evaluation[0], evaluation[1]))


from python_app_configs import config
from python_generic_modules import se_os
from python_generic_modules import se_docker
import re
import os
import glob
import time
import jinja2

template1 = jinja2.Template("{% for i in range(0,last_num)%}zookeepernode{{ i }}.{{ domain }}:2181{% if not loop.last %},{% endif %}{% endfor %}")
zookeeper_nodes = template1.render(last_num=config.zookeeper_nodes,domain=config.domain_name)

def setup_kafka_dirs():
	print('Setting up kafka bind_mount directories...\n')
	os.chdir(config.dest_dir)
	dir_glob = 'kafka' + '*'
	dir_lst = glob.glob(dir_glob)
	for i in dir_lst:
		se_os.del_dir(str(i))
	src_dir_path = os.path.join(config.data_dir,'kafka_conf')

	for i in range(0,config.kafka_nodes):
		dest_path_new = os.path.join(config.dest_dir,'kafkanode'+str(i))
		se_os.copy_dir(src_dir_path,dest_path_new)
	print('bind_mount directories setup compelete\n')

def config_kafka(i):
	src_file_path = os.path.join(config.data_dir,'kafka_conf','server.properties')
	dest_file_path = os.path.join(config.dest_dir,'kafkanode'+str(i),'server.properties')
	param1 = re.compile(r'(.*)(broker.id)(.*)')
	param2 = re.compile(r'(.*)(num.partitions)(.*)')
	param3 = re.compile(r'(.*)(zookeeper.connect=)(.*)')

	with open(src_file_path,mode='r') as file1:
		with open(dest_file_path,mode='w') as file2:
			for line in file1:
				if param1.search(line):
					line = param1.sub(r'\1\2{}'.format('='+str(i)), line)
					file2.write(line)
					continue
				elif param2.search(line):
					line = param2.sub(r'\1\2{}'.format('='+str(str(config.kafka_default_partitions))), line)
					file2.write(line)
					continue
				elif param3.search(line):
					line = param3.sub(r'\1\2{}'.format(zookeeper_nodes), line)
					file2.write(line)
					continue
				else:
					file2.write(line)

def launch_kafka():

	print('\n====Running kafka_setup module====\n')
	setup_kafka_dirs()
	time.sleep(3)

	print('\n====Running kafka_config module====\n')
	for i in range(0,config.kafka_nodes):
		print("Updating configs for node 'kafkanode{}'\n".format(i))
		config_kafka(i)
	time.sleep(3)

	print('\n====Creating SE_Platform Network if not already created====\n')
	hadoop_net = config.hadoop_network_range + '/24'
	lst = config.hadoop_network_range.split('.')
	lst[3]='1'
	hadoop_gateway = '.'.join(lst)
	se_docker.create_network('hadoopnet',hadoop_net,hadoop_gateway)

	print('\n====Launching containers and attaching bind mounts====\n')
	for i in range(0,config.kafka_nodes):
		se_docker.launch_containers('kmahesh2611/kafka','/kafka_2.11-2.1.0/bin/kafka-server-start.sh /kafka_2.11-2.1.0/config/server.properties','kafkanode' + str(i) + '.' + config.domain_name,'kafkanode' +str(i) + '.' + config.domain_name,{os.path.join(config.dest_dir,'kafkanode'+str(i)):{'bind':'/kafka_2.11-2.1.0/config','mode':'rw'}},'hadoopnet',True,True)

	print('Wait for 10 seconds....')
	time.sleep(10)

	print('\n====Verify if containers are running====\n')
	num = 0
	for i in se_docker.get_all_containers():
		if 'kafkanode' in i.name:
			num = num + 1
			if 'running' in i.status:
				print('{} : {}'.format(i.name,i.status))
			else:
				print('Error: Container "{}" is in status "{}"\n'.format(i.name,i.status))
				print('Exiting script\n')
				sys.exit(1)
	if num == 0:
		print('No container found starting with name "kafkanode"')
		print('Exiting script\n')
		sys.exit(1)
	### Creating Kafka topics ###
	print('\n====Creating Kafka Topics====\n')
	for i in config.kafka_topics:
		print(se_docker.exec_command('kafkanode0' + '.' + config.domain_name,"/kafka_2.11-2.1.0/bin/kafka-topics.sh --create --zookeeper {} --replication-factor {} --partitions  {} --topic {}".format(zookeeper_nodes,str(config.kafka_nodes),str(config.kafka_default_partitions),i)))

	print("Created topics: {}\n".format([topics for topics in config.kafka_topics]))

def del_kafka_containers():
	print('\n====Stopping and deleting Containers for kafka====\n')
	for i in se_docker.get_all_containers():
		if 'kafkanode' in i.name:
			print('Stopping and deleting Container: {}\n'.format(i.name))
			i.remove(force=True)


from deep_rl_for_swarms.common import explained_variance, zipsame, dataset
from deep_rl_for_swarms.common import logger
import deep_rl_for_swarms.common.tf_util as U
import tensorflow as tf, numpy as np
import time
import os
from deep_rl_for_swarms.common import colorize
from mpi4py import MPI
from collections import deque
from deep_rl_for_swarms.common.mpi_adam import MpiAdam
from deep_rl_for_swarms.common.cg import cg
from contextlib import contextmanager
from deep_rl_for_swarms.common.act_wrapper import ActWrapper
import sys
from gym import spaces
import matplotlib.pyplot as plt

def traj_segment_generator(pi, env, horizon, stochastic):

    # Initialize state variables
    t = 0
    n_agents = env.nr_agents
    new = True
    ob = env.reset()

    cur_ep_ret = 0
    cur_ep_len = 0
    ep_rets = []
    ep_lens = []
    time_steps = []

    # Initialize history arrays
    obs = np.array([ob for _ in range(horizon)])
    rews = np.zeros([horizon, n_agents], 'float32')
    vpreds = np.zeros([horizon, n_agents], 'float32')
    news = np.zeros([horizon, n_agents], 'int32')
    if isinstance(env.action_space, spaces.Box):
        ac = np.vstack([env.action_space.sample() for _ in range(n_agents)])  # Used only to initialize vectors!!
        acs = np.array([ac for _ in range(horizon)])
    elif isinstance(env.action_space, spaces.Discrete):
        ac = np.array([env.action_space.sample() for _ in range(n_agents)])
        acs = np.zeros([horizon, n_agents], 'int32')  # For discrete actions
    else:
        raise NotImplementedError
    prevacs = acs.copy()
    time = np.zeros(horizon, 'float32')  # To store the time of acting
    # Info to be saved in the logger
    keys_to_save = ['attackers_caught', 'attackers_not_caught', 'mean_total_rwd', 'total_rwd']
    if env.attack_mode == 'phy':
        keys_to_save.extend(['phy_fc_error_rate'])
    if env.attack_mode == 'mac':
        keys_to_save.extend(['total_mac_tx', 'total_mac_col', 'total_bits_tx', 'prop_t_tx', 'mean_prop_bits_tx_at',
                             'mean_prop_bits_tx_no'])
    info_indiv = []
    while True:
        prevac = ac
        ac, vpred = pi.act(stochastic, np.vstack(ob))
        if isinstance(env.action_space, spaces.Box):
            ac = np.clip(ac, env.action_space.low, env.action_space.high)  # To ensure actions are in the right limit!
        # Slight weirdness here because we need value function at time T
        # before returning segment [0, T-1] so we get the correct
        # terminal value
        if t > 0 and t % horizon == 0:
            info_total = {}
            for key in keys_to_save:
                aux = 0
                for i in range(len(info_indiv)):
                    aux += info_indiv[i][key]
                info_total[key] = aux / len(info_indiv)
            if isinstance(env.action_space, spaces.Box):
                yield [
                    dict(
                        ob=np.array(obs[:, na, :]),
                        rew=np.array(rews[:, na]),
                        vpred=np.array(vpreds[:, na]),
                        new=np.array(news[:, na]),
                        ac=np.array(acs[:, na, :]),
                        prevac=np.array(prevacs[:, na, :]),
                        nextvpred=vpred[na] * (1 - new),
                        ep_rets=[epr[na] for epr in ep_rets],
                        ep_lens=ep_lens,
                        time_steps=np.array(time_steps),
                        time=time,
                    ) for na in range(n_agents)
                ], info_total
            elif isinstance(env.action_space, spaces.Discrete):
                yield [
                    dict(
                        ob=np.array(obs[:, na, :]),
                        rew=np.array(rews[:, na]),
                        vpred=np.array(vpreds[:, na]),
                        new=np.array(news[:, na]),
                        ac=np.array(acs[:, na]),
                        prevac=np.array(prevacs[:, na]),
                        nextvpred=vpred[na] * (1 - new),
                        ep_rets=[epr[na] for epr in ep_rets],
                        ep_lens=ep_lens,
                        time_steps=np.array(time_steps),
                        time=time
                    ) for na in range(n_agents)
                ], info_total
            else:
                raise NotImplementedError
            _, vpred = pi.act(stochastic, ob)
            # Be careful!!! if you change the downstream algorithm to aggregate
            # several of these batches, then be sure to do a deepcopy
            ep_rets = []
            ep_lens = []
            time_steps = []
            info_indiv = []
        i = t % horizon
        time_steps.append(t)
        obs[i] = ob
        vpreds[i] = vpred
        news[i] = new
        acs[i] = ac
        prevacs[i] = prevac
        if env.attack_mode == 'mac':
            time[i] = sum(env.t_counter)
        elif env.attack_mode == 'phy':
            time[i] = env.timestep
        else:
            raise RuntimeError('Environment not recognized')
        ob, rew, new, info = env.step(ac)
        rews[i] = rew
        #mask_undetected[i] = np.logical_not(env.banned[0:env.nr_agents])

        cur_ep_ret += rew
        cur_ep_len += 1
        if new:
            info_indiv.append(info)
            ep_rets.append(cur_ep_ret)
            ep_lens.append(cur_ep_len)
            cur_ep_ret = 0
            cur_ep_len = 0
            ob = env.reset()
            sys.stdout.write('\r Current horizon length = ' + str((t + 1) % horizon) + '/' + str(horizon))
            sys.stdout.flush()
        t += 1

def add_vtarg_and_adv(seg, gamma, lam):
    new = [np.append(p["new"], 0) for p in seg]  # last element is only used for last vtarg, but we already zeroed it if last new = 1
    vpred = [np.append(p["vpred"], p["nextvpred"]) for p in seg]

    for i, p in enumerate(seg):
        T = len(p["rew"])
        p["adv"] = gaelam = np.empty(T, 'float32')
        rew = p["rew"]
        lastgaelam = 0
        for t in reversed(range(T)):
            nonterminal = 1 - new[i][t + 1]
            delta = rew[t] + gamma * vpred[i][t + 1] * nonterminal - vpred[i][t]
            gaelam[t] = lastgaelam = delta + gamma * lam * nonterminal * lastgaelam
        p["tdlamret"] = p["adv"] + p["vpred"]

'''
def add_vtarg_and_adv(seg, gamma, lam):  # Modified version to include time!
    new = [np.append(p["new"], 0) for p in seg]  # last element is only used for last vtarg, but we already zeroed it if last new = 1
    vpred = [np.append(p["vpred"], p["nextvpred"]) for p in seg]

    for i, p in enumerate(seg):
        T = len(p["rew"])
        p["adv"] = gaelam = np.empty(T, 'float32')
        rew = p["rew"]
        lastgaelam = 0
        time = np.append(p['time'], p['time'][-1] + 1)  # Increase the final time by 1 to obtain the differential time
        difft = time[1:] - time[0: -1]
        for t in reversed(range(T)):
            nonterminal = 1 - new[i][t + 1]
            gt = gamma ** difft[t]  # Note that when difft is negative, nonterminal is 0!!
            lt = lam ** difft[t]
            delta = rew[t] + gt * vpred[i][t + 1] * nonterminal - vpred[i][t]
            gaelam[t] = lastgaelam = delta + gt * lt * nonterminal * lastgaelam
        p["tdlamret"] = p["adv"] + p["vpred"]
'''

def learn(env, policy_fn, *,
          timesteps_per_batch, # what to train on
          max_kl, cg_iters,
          gamma, lam, # advantage estimation
          entcoeff=0.0,
          cg_damping=1e-2,
          vf_stepsize=3e-4,
          vf_iters =3,
          max_timesteps=0, max_episodes=0, max_iters=0,  # time constraint
          callback=None,
          save_dir=None,
          save_flag=False,
          plot_flag=False
          ):
    nworkers = MPI.COMM_WORLD.Get_size()
    rank = MPI.COMM_WORLD.Get_rank()
    np.set_printoptions(precision=3)
    # Setup losses and stuff
    # ----------------------------------------
    ob_space = env.observation_space
    ac_space = env.action_space
    pi = policy_fn("pi", ob_space, ac_space)
    oldpi = policy_fn("oldpi", ob_space, ac_space)
    atarg = tf.placeholder(dtype=tf.float32, shape=[None])  # Target advantage function (if applicable)
    ret = tf.placeholder(dtype=tf.float32, shape=[None])  # Empirical return

    ob = U.get_placeholder_cached(name="ob")
    ac = pi.pdtype.sample_placeholder([None])

    kloldnew = oldpi.pd.kl(pi.pd)
    ent = pi.pd.entropy()
    meankl = tf.reduce_mean(kloldnew)
    meanent = tf.reduce_mean(ent)
    entbonus = entcoeff * meanent

    vferr = tf.reduce_mean(tf.square(pi.vpred - ret))

    ratio = tf.exp(pi.pd.logp(ac) - oldpi.pd.logp(ac))  # advantage * pnew / pold (advantage--> Next line)
    surrgain = tf.reduce_mean(ratio * atarg)

    optimgain = surrgain + entbonus
    losses = [optimgain, meankl, entbonus, surrgain, meanent]
    loss_names = ["optimgain", "meankl", "entloss", "surrgain", "entropy"]

    dist = meankl

    all_var_list = pi.get_trainable_variables()
    var_list = [v for v in all_var_list if v.name.split("/")[1].startswith("pol")]  # Policy variables
    var_list.extend([v for v in all_var_list if v.name.split("/")[1].startswith("me")])  # Mean embedding variables
    vf_var_list = [v for v in all_var_list if v.name.split("/")[1].startswith("vf")]  # Value function variables
    vfadam = MpiAdam(vf_var_list)

    get_flat = U.GetFlat(var_list)
    set_from_flat = U.SetFromFlat(var_list)
    klgrads = tf.gradients(dist, var_list)
    flat_tangent = tf.placeholder(dtype=tf.float32, shape=[None], name="flat_tan")
    shapes = [var.get_shape().as_list() for var in var_list]
    start = 0
    tangents = []
    for shape in shapes:
        sz = U.intprod(shape)
        tangents.append(tf.reshape(flat_tangent[start:start + sz], shape))
        start += sz
    gvp = tf.add_n([tf.reduce_sum(g * tangent) for (g, tangent) in zipsame(klgrads, tangents)])  # pylint: disable=E1111
    fvp = U.flatgrad(gvp, var_list)

    assign_old_eq_new = U.function([], [], updates=[tf.assign(oldv, newv)
                                                    for (oldv, newv) in
                                                    zipsame(oldpi.get_variables(), pi.get_variables())])
    compute_losses = U.function([ob, ac, atarg], losses)
    compute_lossandgrad = U.function([ob, ac, atarg], losses + [U.flatgrad(optimgain, var_list)])
    compute_fvp = U.function([flat_tangent, ob, ac, atarg], fvp)
    compute_vflossandgrad = U.function([ob, ret], U.flatgrad(vferr, vf_var_list))

    @contextmanager
    def timed(msg):
        if rank == 0:
            print(colorize(msg, color='magenta'))
            tstart = time.time()
            yield
            print(colorize("done in %.3f seconds" % (time.time() - tstart), color='magenta'))
        else:
            yield

    def allmean(x):
        assert isinstance(x, np.ndarray)
        out = np.empty_like(x)
        MPI.COMM_WORLD.Allreduce(x, out, op=MPI.SUM)
        out /= nworkers
        return out

    act_params = {
        'name': "pi",
        'ob_space': ob_space,
        'ac_space': ac_space,
    }

    pi = ActWrapper(pi, act_params)

    U.initialize()
    th_init = get_flat()
    MPI.COMM_WORLD.Bcast(th_init, root=0)
    set_from_flat(th_init)
    vfadam.sync()
    print("Init param sum", th_init.sum(), flush=True)

    # Prepare for rollouts
    # ----------------------------------------
    seg_gen = traj_segment_generator(pi, env, timesteps_per_batch, stochastic=True)

    episodes_so_far = 0
    timesteps_so_far = 0
    iters_so_far = 0
    tstart = time.time()
    lenbuffer = deque(maxlen=40)  # rolling buffer for episode lengths
    rewbuffer = deque(maxlen=40)  # rolling buffer for episode rewards

    assert sum([max_iters > 0, max_timesteps > 0, max_episodes > 0]) == 1

    while True:
        if callback: callback(locals(), globals())
        if max_timesteps and timesteps_so_far >= max_timesteps:
            break
        elif max_episodes and episodes_so_far >= max_episodes:
            break
        elif max_iters and iters_so_far >= max_iters:
            break

        if max_timesteps:
            print(colorize(str(100 * timesteps_so_far / max_timesteps) + ' % of timesteps', color='magenta'))
        elif max_episodes:
            print(colorize(str(100 * episodes_so_far / max_episodes) + ' % of episodes', color='magenta'))
        elif max_iters:
            print(colorize(str(100 * iters_so_far / max_iters) + ' % of iters', color='magenta'))
        logger.log("********** Iteration %i ************" % iters_so_far)

        with timed("sampling"):
            seg, info = seg_gen.__next__()
        add_vtarg_and_adv(seg, gamma, lam)

        ob = np.concatenate([s['ob'] for s in seg], axis=0)
        ac = np.concatenate([s['ac'] for s in seg], axis=0)
        atarg = np.concatenate([s['adv'] for s in seg], axis=0)
        tdlamret = np.concatenate([s['tdlamret'] for s in seg], axis=0)
        vpredbefore = np.concatenate([s["vpred"] for s in seg], axis=0)  # predicted value function before udpate
        atarg = (atarg - atarg.mean()) / atarg.std()  # standardized advantage function estimate

        # if hasattr(pi, "ret_rms"): pi.ret_rms.update(tdlamret)
        # if hasattr(pi, "ob_rms"): pi.ob_rms.update(ob) # update running mean/std for policy

        args = ob, ac, atarg
        fvpargs = [arr[::5] for arr in args]

        def fisher_vector_product(p):
            return allmean(compute_fvp(p, *fvpargs)) + cg_damping * p

        assign_old_eq_new()  # set old parameter values to new parameter values
        with timed("computegrad"):
            *lossbefore, g = compute_lossandgrad(*args)
        lossbefore = allmean(np.array(lossbefore))
        g = allmean(g)
        if np.allclose(g, 0):
            logger.log("Got zero gradient. not updating")
        else:
            with timed("cg"):
                stepdir = cg(fisher_vector_product, g, cg_iters=cg_iters, verbose=rank == 0)
            assert np.isfinite(stepdir).all()
            shs = .5 * stepdir.dot(fisher_vector_product(stepdir))
            lm = np.sqrt(shs / max_kl)
            # logger.log("lagrange multiplier:", lm, "gnorm:", np.linalg.norm(g))
            fullstep = stepdir / lm
            expectedimprove = g.dot(fullstep)
            surrbefore = lossbefore[0]
            stepsize = 1.0
            thbefore = get_flat()
            for _ in range(10):
                thnew = thbefore + fullstep * stepsize
                set_from_flat(thnew)
                meanlosses = surr, kl, *_ = allmean(np.array(compute_losses(*args)))
                improve = surr - surrbefore
                logger.log("Expected: %.3f Actual: %.3f" % (expectedimprove, improve))
                if not np.isfinite(meanlosses).all():
                    logger.log("Got non-finite value of losses -- bad!")
                elif kl > max_kl * 1.5:
                    logger.log("violated KL constraint. shrinking step.")
                elif improve < 0:
                    logger.log("surrogate didn't improve. shrinking step.")
                else:
                    logger.log("Stepsize OK!")
                    break
                stepsize *= .5
            else:
                logger.log("couldn't compute a good step")
                set_from_flat(thbefore)
            if nworkers > 1 and iters_so_far % 20 == 0:
                paramsums = MPI.COMM_WORLD.allgather((thnew.sum(), vfadam.getflat().sum()))  # list of tuples
                assert all(np.allclose(ps, paramsums[0]) for ps in paramsums[1:])

        for (lossname, lossval) in zip(loss_names, meanlosses):
            logger.record_tabular(lossname, lossval)

        with timed("vf"):

            for _ in range(vf_iters):
                for (mbob, mbret) in dataset.iterbatches((ob, tdlamret),
                                                         include_final_partial_batch=False, batch_size=64):
                    g = allmean(compute_vflossandgrad(mbob, mbret))
                    vfadam.update(g, vf_stepsize)

        lrlocal = (seg[0]["ep_lens"], seg[0]["ep_rets"])  # local values
        listoflrpairs = MPI.COMM_WORLD.allgather(lrlocal) # list of tuples
        lens, rews = map(flatten_lists, zip(*listoflrpairs))

        episodes_so_far += len(lens)
        timesteps_so_far += sum(lens)
        iters_so_far += 1

        logger.record_tabular("EpisodesSoFar", episodes_so_far)
        logger.record_tabular("TimestepsSoFar", timesteps_so_far)
        logger.record_tabular("TimeElapsed", time.time() - tstart)
        # Add info values
        logger.record_tabular("AttC", info['attackers_caught'])
        logger.record_tabular("AttNC", info['attackers_not_caught'])
        logger.record_tabular("MtR", info['mean_total_rwd'])  # Mean total reward
        logger.record_tabular("TtR", info['total_rwd'])  # Total reward
        if env.attack_mode == 'phy':
            logger.record_tabular("Fce", info['phy_fc_error_rate'])
        if env.attack_mode == 'mac':
            logger.record_tabular("Tmt", info['total_mac_tx'])
            logger.record_tabular("Tmc", info['total_mac_col'])
            logger.record_tabular("Tbt", info['total_bits_tx'])
            logger.record_tabular("Ptt", info['prop_t_tx'])
            logger.record_tabular("MpbtA", info['mean_prop_bits_tx_at'])
            logger.record_tabular("MpbtN", info['mean_prop_bits_tx_no'])

        if rank == 0:
            logger.dump_tabular()

    if save_flag:
        pi.save(os.path.normpath(save_dir + '/models_trpo/model_{}.pkl'.format(iters_so_far)))

def flatten_lists(listoflists):
    return [el for list_ in listoflists for el in list_]


import numpy as np
import scipy.constants
from pathlib import Path
class ElectricAcceleration:

    bodies = []
    def __init__(self, bodies):
        """This will allow the list of particles from the Accelerator module to be inserted letting the ElectricAcceleration class calculate their acceleration"""
        self.bodies = bodies
    def acceleration(self, mag1, mag2, mag3, sinelec1, sinelec2, sinelec3):
        """The values of the electic and magnetic field set in the Accelerator file are imported here"""
        constantelectric=np.array([sinelec1, sinelec2, sinelec3])
        magnetic=np.array([mag1, mag2, mag3])
        magnitudeMagnetic=np.linalg.norm(magnetic)

        for particle1 in self.bodies:
            """The electric field due to particle-particle interactions and the acceleration are set to be arrays"""
            electricSection=np.array([0., 0., 0.])
            acceleration = np.array([0., 0., 0.])
            """The charge mass and velocity of the particles are set to be their values as calculated in the particle class"""
            c1 = particle1.charge
            m1 = particle1.mass
            v1 = particle1.velocity
            #kineticE = 0
            for particle2 in self.bodies:
                if particle1 != particle2:
                    """This allows the calculation of the acceleration due to the electric and magnetic fields for each body in the system"""

                    m2 = particle2.mass

                    c2 = particle2.charge

                    v2 = particle2.velocity
                    """This calculates the distance between the accelerating body and the body causing the acceleration, this will only apply when 2 or more charged particles are present"""
                    r = np.array(particle1.position) - np.array(particle2.position)
                    magnitudeR = np.linalg.norm(r)
                    const=1/(4*scipy.constants.pi*scipy.constants.epsilon_0)
                    #electricSection=np.array([1,1,0])
                    """This calculates the electric field acting on a charged particle due to each other charged particle in the system"""
                    electric=np.array([const*(c2/magnitudeR**2)])
                    electricSection += ((electric/magnitudeR)*r)
            #kineticE=np.linalg.norm(0.5*m1*v1**2)
            #update magnetic with input functions
            """This combines the effects of the constant sinusoidal electric field and the effect due to other charged particles"""
            totalelectric=electricSection+constantelectric
            """The value for the total electric field is then used in loretz equation to calculate the acceleration due to both the electric and magnetic fields"""
            qvb=np.cross((c1*v1), magnetic)
            acceleration=(((c1*totalelectric)+(qvb))/m1)+acceleration
            #particle1.kineticE=kineticE
            """This sets the acceleration of the particle to be the previously calculated value for the current time step"""
            particle1.acceleration = acceleration
            #print(acceleration)
        #for particle1 in self.bodies:
         #   """This allows the calculation of the angular and linear momentum of the system"""
          #  angularMomentum = 0
           # momentum = 0
            #for particle2 in self.bodies:
             #   if particle1 != particle2:
              #      m1 = particle1.mass
               #     r = np.array(particle1.position) - np.array(particle2.position)
                #    momentum = m1*np.linalg.norm(particle1.velocity)
                 #   angularMomentum = momentum * np.linalg.norm(r)
            #particle1.momentum = momentum
            #particle1.angularMomentum = angularMomentum