def title(): # Define functions.setup() title = public.fonts['large'].render('Flappe', True, public.YELLOW) hs_text = public.fonts['plain'].render( 'High score: ' + str(public.high_score), True, public.YELLOW) play_btn = sprites.Button( media.MEDIA['play_normal_texture'], media.MEDIA['play_pressed_texture'], public.menu_rects['tt_play'], public.menu_rects['tt_play_pressed'], public.all_sprites) settings_btn = sprites.Button( media.MEDIA['play_normal_texture'], media.MEDIA['play_pressed_texture'], public.menu_rects['tt_settings'], public.menu_rects['tt_settings_pressed'], public.all_sprites) # Loop while True: for event in pygame.event.get(): if event.type == pygame.QUIT: functions.dump_hs() return 1 elif event.type == pygame.MOUSEBUTTONDOWN: if public.menu_rects['tt_play'].collidepoint(event.pos): game() return 1 # Logic functions.update_clouds() functions.update_floors() public.all_sprites.update() sorted_sprites = sorted( public.all_sprites.sprites(), key=lambda x: x.type) # Draw public.screen.fill(public.skycolor) for sprite in sorted_sprites: sprite.draw() public.screen.blit(title, (97, 150)) public.screen.blit(hs_text, ( (public.SWIDTH / 2) - hs_text.get_width() // 2, 290)) pygame.display.flip() public.clock.tick(public.FPS)
def game(): # Define functions.setup() functions.generate_pipes() flappe = sprites.Flappe(public.all_sprites) counter = public.fonts['normal'].render( str(public.score), True, public.txtcolor) # Loop while True: for event in pygame.event.get(): if event.type == pygame.QUIT: return 1 elif event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE and not flappe.toggle: flappe.flap() # Update if flappe.pos.y > public.SHEIGHT: gameover() return 1 functions.update_clouds() functions.update_pipes() functions.update_floors() functions.update_states() public.all_sprites.update() counter = public.fonts['normal'].render( str(public.score), True, public.txtcolor) sorted_sprites = sorted( public.all_sprites.sprites(), key=lambda x: x.type) # Drawing public.screen.fill(public.skycolor) for sprite in sorted_sprites: sprite.draw() public.screen.blit(counter, ( (public.SWIDTH / 2) - counter.get_width() // 2, -7)) pygame.display.flip() public.clock.tick(public.FPS)
def setup(): func.setup() func.root.config(bg=func.generateRandomColor()) welcomeLabel = func.Label(func.root, text="Welcome to Scrabble in Python!") instructionsButton = func.Button(func.root, text="Instructions", command=instructions) playButton = func.Button(func.root, text="Play", command=play) playSavedButton = func.Button(func.root, text="Play Saved Game", command=games.playSavedGame) exitButton = func.Button(func.root, text="Exit", command=exitGame) welcomeLabel.place(x=40, y=0) #instructionsButton.place(x = 90, y = 50) playButton.place(x=110, y=100) #playSavedButton.place(x = 76, y = 150) exitButton.place(x=112, y=200)
def opt_fg(): #Check if queue.txt is usable log, ts, it_n, first_guess, queue_txt = fc.setup(True) #Get data and sample them one_queue, shift_queue = fc.sample_data(queue_txt, log) fc.print_pic_1_2(one_queue, shift_queue, queue_txt, it_n, ts, log) waiter, cooks = fc.allocation_fg(log, first_guess) fc.write_to_file(log, waiter, cooks, True) fc.print_3_fg(ts, log, first_guess) fc.print_3_im_new_all(ts, it_n, log, waiter, cooks) #Check for number of values file fc.finish(it_n, log)
def opt(): #Set objectives obj_5ord = 0.7 obj_8ord = 0.99 obj_5kit = 0.7 obj_8kit = 0.82 #Set timestamp and iterationnumber and if queue.txt is usable log, ts, it_n, exp_txt, queue_txt = fc.setup() #Analyse previous results mean_res, std_res = fc.analyse(exp_txt, log) #Objectives fulfilled? fc.obj_fulfill(mean_res, log) #Utilisation rates fc.ut_rates(mean_res, log) #Get data and sample them one_queue, shift_queue = fc.sample_data(queue_txt, log) # print 1_queue_Iteration and 2_shift_queue_iteration max_dia = fc.print_pic_1_2(one_queue, shift_queue, queue_txt, it_n, ts, log) #Update staff allocation (1. get and allocate, 2. update queues, 3. update obj) waiter, cooks = fc.allocation(log) waiter, cooks, co_ql = fc.upd_ql(log, it_n, waiter, cooks, shift_queue) waiter, cooks, co_obj = fc.upd_obj(log, it_n, waiter, cooks, shift_queue, mean_res) waiter, cooks, co_sm = fc.upd_sm(log, it_n, waiter, cooks, co_ql, co_obj) fc.print_changes(log, waiter, cooks, co_ql, co_obj, co_sm) print(waiter) print(cooks) #Write to files (allocation_staff.xlsx, waiter.txt, cook.txt) fc.write_to_file(log, waiter, cooks) #produce staffing plot fc.print_3_im_new_all(ts, it_n, log, waiter, cooks) #Clean up, update iterationnumber fc.finish(it_n, log)
# -*- coding: utf-8 -*- ''' Created on Mon May 6 18:35:27 2019 ''' from functions import setup, clearscreen from functions import make_appointment, view_appointments from functions import view_schedule #, reschedule_appointment from time import sleep services = {} schedule = {} setup() while True: clearscreen() print('------------------------------------------') print('| Welcome to Madra Dog Grooming Services |') print('------------------------------------------') print('\nFor best results please maximize the size of your window\n') print('Choose from the menu below:\n') print('1. View schedule of appointments (by groomer)') print('2. View appointment details (by client)') print('3. Make new appointment') # print('4. Reschedule appointment') print('5. Quit the system\n') response = input("\nEnter the number for your choice: ") if response == "1": view_schedule() elif response == "2": view_appointments() elif response == "3": make_appointment()
type=str) ap.add_argument('--top_k', default=5, dest="top_k", action="store", type=int) ap.add_argument('--category_names', dest="category_names", action="store", default='cat_to_name.json') ap.add_argument('--gpu', default="gpu", action="store", dest="gpu") pa = ap.parse_args() path_image = pa.input_img number_of_outputs = pa.top_k power = pa.gpu input_img = pa.input_img path = pa.checkpoint model, _, _ = functions.setup() training_loader, testing_loader, validation_loader, train_data = functions.data( ) functions.load_checkpoint(path) with open('cat_to_name.json', 'r') as json_file: cat_to_name = json.load(json_file) probabilities = functions.predict(path_image, model, number_of_outputs, power) labels = [ cat_to_name[str(index + 1)] for index in np.array(probabilities[1][0]) ] probability = np.array(probabilities[0][0])
# By: Theodore Tan #python3 # imports import sys from functions import ac_3, alpha, check_solved, open_file, setup # variables filename = sys.argv[1] # get the filename from the terminal csp = setup(open_file(filename)) # setup the csp using the data check_solved(ac_3(csp), csp) # check if the ac3 algorithm solved the problem
# Simple app that will pull the information from the DFES website via RSS feed, and format it for easy reading. # Currently setup for North Metro, but can be changed extremely easily by simply changing the URL@@ import time import functions as DFESFunctions #This holds all the custom DFESFunctions for the application #===== Start of the Application ===== # First we are going to setup the application DFESFunctions.setup() DFESFunctions.mainMenu()
__author__ = 'Andrew' from hashlib import md5 import urllib2 import sys from urlparse import parse_qs import functions ping = 16 accuracy = 8 server = functions.setup() def speed_test(up, down): get_data = [ 'download=%s' % down, 'ping=%s' % ping, 'upload=%s' % up, 'promo=', 'startmode=%s' % 'pingselect', 'recommendedserverid=%s' % server, 'accuracy=%s' % 8, 'serverid=%s' % server, 'hash=%s' % md5('%s-%s-%s-%s' % (ping, up, down, '297aae72')).hexdigest() ] request = urllib2.Request('http://www.speedtest.net/api/api.php', data='&'.join(get_data)) request.add_header('Referer', 'http://c.speedtest.net/flash/speedtest.swf') connection = urllib2.urlopen(request) response = connection.read() response_code = connection.code connection.close()
import discord import os import music import functions import asyncio from dotenv import load_dotenv from discord.ext import commands load_dotenv() bot = commands.Bot(command_prefix='!') token = os.getenv("DISCORD_BOT_SECRET") music.setup(bot) functions.setup(bot) @bot.event async def on_ready(): print("I'm in") print(bot.user) servers = list(bot.guilds) await bot.change_presence(activity=discord.Game(name='LoL as Zoe')) print('Servers: ') printServers(servers) def printServers(servers): for i in range(len(servers)): print(servers[i].name)
__author__ = 'Andrew' from hashlib import md5 import urllib2 import sys from urlparse import parse_qs import functions ping = 16 accuracy = 8 server = functions.setup() def speed_test(up, down): get_data = [ 'download=%s' % down, 'ping=%s' % ping, 'upload=%s' % up, 'promo=', 'startmode=%s' % 'pingselect', 'recommendedserverid=%s' % server, 'accuracy=%s' % 8, 'serverid=%s' % server, 'hash=%s' % md5('%s-%s-%s-%s' % (ping, up, down, '297aae72') ).hexdigest()] request = urllib2.Request('http://www.speedtest.net/api/api.php', data='&'.join(get_data)) request.add_header('Referer', 'http://c.speedtest.net/flash/speedtest.swf') connection = urllib2.urlopen(request) response = connection.read() response_code = connection.code
import functions import json import os.path from bottle import get, post, delete, request, run # Database Startup functions.setup() # Root Path / # @get('/') def base(): return 'PinterestAPI' ### ### # # # Authentication (Registration, Login) # # # ### ### ### # # Registration - Retrieves user's name, username, and password and stores them in DB # Input - name, username, password # Response - 200, success, user_id # # Registration # To Test Use: # curl -X POST -H "Content-Type: application/json" -d '{"name":"xxxx","username":"******","password":"******"}' http://localhost:8080/v1/reg
else: print("Failed to open the port") print("Press any key to terminate...") getch() quit() # Set port baudrate if portHandler.setBaudRate(BAUDRATE): print("Succeeded to change the baudrate") else: print("Failed to change the baudrate") print("Press any key to terminate...") getch() quit() functions.setup(packetHandler, portHandler, 6) print("hej") functions.setup(packetHandler, portHandler, 7) drive_time = 6 MOVING_SPEED = 420 print("moving back") # Set moving speed dxl_comm_result, dxl_error = packetHandler.write2ByteTxRx( portHandler, 6, ADDR_MX_MOVING_SPEED, MOVING_SPEED + 1024) if dxl_comm_result != COMM_SUCCESS: print("%s" % packetHandler.getTxRxResult(dxl_comm_result)) elif dxl_error != 0: print("%s" % packetHandler.getRxPacketError(dxl_error)) else: print("Dynamixel has been successfully connected")
dest="arch", action="store", default="densenet121", type=str) ap.add_argument('--hidden_units', type=int, dest="hidden_units", action="store", default=120) pa = ap.parse_args() path = pa.save_dir lr = pa.learning_rate structure = pa.arch dropout = pa.dropout hidden_layer1 = pa.hidden_units power = pa.gpu epochs = pa.epochs trainloader, validationloader, testloader, train_data = functions.data() model, optimizer, criterion = functions.setup(structure, dropout, hidden_layer1, lr, power) functions.train_network(model, criterion, optimizer, trainloader, validationloader, epochs, 20, power) functions.save_checkpoint(train_data, epochs, structure, hidden_layer1, dropout, lr, path) print("The Model is trained")
dest="hidden_units", default=256, type=int) parser.add_argument('--dropout', dest="dropout", default=0.2) parser.add_argument('--learning_rate', dest="learning_rate", default=0.001) parser.add_argument('--gpu', dest="gpu", default=True, type=bool) parser.add_argument('--epochs', dest="epochs", default=2, type=int) parser.add_argument('--print_every', dest="print_every", default=10, type=int) parser.add_argument('--save_dir', dest="save_dir", default="./checkpoint.pth", type=str) parsed = parser.parse_args() data_dir = parsed.data_dir arch = parsed.arch hidden_units = parsed.hidden_units dropout = parsed.dropout learning_rate = parsed.learning_rate gpu = parsed.gpu epochs = parsed.epochs print_every = parsed.print_every save_dir = parsed.save_dir trainloader, validloader, class_to_idx = functions.load_data(data_dir) model, criterion, optimizer = functions.setup(arch, hidden_units, dropout, learning_rate, gpu) functions.train_network(model, criterion, optimizer, trainloader, validloader, epochs, print_every, gpu) functions.save_checkpoint(save_dir, arch, hidden_units, dropout, learning_rate, gpu, model, optimizer, class_to_idx)
def program(M0, N0, mode, h0, p0, noise_h, noise_p, controller): M_preys = M0 N_hunters = N0 Ts = 0.0005 # plt.rcParams.update({'font.size': 15}) # h_desired = [3,3,3,-3,-3,-3,-3,3] # p_desired = [0,0] # M_preys = 1 # N_hunters = 4 # D = 5 # """ The main layout of the animation """ # ax = plt.axes(xlim=(-D,D), ylim=(-D,D)) # # """ # Plot preserve # """ # vertsP = [ # (-D, -D), # left, bottom # (-D, D), # left, top # (D, D), # right, top # (D, -D), # right, bottom # (-D, -D), # ignored # ] # vertsPCodes = [ # Path.MOVETO, # Path.LINETO, # Path.LINETO, # Path.LINETO, # Path.CLOSEPOLY, # ] # # vertsPPath = Path(vertsP, vertsPCodes) # vertsPPatch = patches.PathPatch(vertsPPath, facecolor='none', lw=2) # ax.add_patch(vertsPPatch) # for j in range(M_preys): # ax.plot(p_desired[2*j], p_desired[2*j+1], 'o', ms=15, c='g') # for i in range(N_hunters): # ax.plot(h_desired[2*i], h_desired[2*i+1], 'D', ms=15, c='b') # # plt.show() # plt.savefig("G:/Unidades de equipo/EduardoSebastian/TFG/04_Imagenes/Figura3.png") # # plt.close('all') # # h_desired = [2,0,0,2,-2,0,0,-2] # p_desired = [0,0] # M_preys = 1 # N_hunters = 4 # D = 5 # """ The main layout of the animation """ # ax = plt.axes(xlim=(-D,D), ylim=(-D,D)) # # """ # Plot preserve # """ # vertsP = [ # (-D, -D), # left, bottom # (-D, D), # left, top # (D, D), # right, top # (D, -D), # right, bottom # (-D, -D), # ignored # ] # vertsPCodes = [ # Path.MOVETO, # Path.LINETO, # Path.LINETO, # Path.LINETO, # Path.CLOSEPOLY, # ] # # vertsPPath = Path(vertsP, vertsPCodes) # vertsPPatch = patches.PathPatch(vertsPPath, facecolor='none', lw=2) # ax.add_patch(vertsPPatch) # for j in range(M_preys): # ax.plot(p_desired[2*j], p_desired[2*j+1], 'o', ms=15, c='g') # for i in range(N_hunters): # ax.plot(h_desired[2*i], h_desired[2*i+1], 'D', ms=15, c='b') # # plt.show() # plt.savefig("G:/Unidades de equipo/EduardoSebastian/TFG/04_Imagenes/Figura4.png") # # plt.close('all') # # h_desired = h0 # p_desired = p0 # M_preys = 3 # N_hunters = 6 # D = 5 # """ The main layout of the animation """ # ax = plt.axes(xlim=(-D,D), ylim=(-D,D)) # # """ # Plot preserve # """ # vertsP = [ # (-D, -D), # left, bottom # (-D, D), # left, top # (D, D), # right, top # (D, -D), # right, bottom # (-D, -D), # ignored # ] # vertsPCodes = [ # Path.MOVETO, # Path.LINETO, # Path.LINETO, # Path.LINETO, # Path.CLOSEPOLY, # ] # # vertsPPath = Path(vertsP, vertsPCodes) # vertsPPatch = patches.PathPatch(vertsPPath, facecolor='none', lw=2) # ax.add_patch(vertsPPatch) # for j in range(M_preys): # ax.plot(p_desired[2*j], p_desired[2*j+1], 'o', ms=12, c='g') # for i in range(N_hunters): # ax.plot(h_desired[2*i], h_desired[2*i+1], 'D', ms=12, c='b') # # plt.show() # plt.savefig("G:/Unidades de equipo/EduardoSebastian/TFG/04_Imagenes/Figura1.png") # # plt.close('all') if controller == "linear": if mode == 1: h = root(f_1, h0, args=(p0, N0, M0), method='hybr', tol=10e-10) elif mode == 2: h = root(f_2, h0, args=(p0, N0, M0), method='lm', tol=10e-10) elif mode == 3: h = root(f_3, h0, args=(p0, N0, M0), method='hybr', tol=10e-10) elif mode == 4: h = root(f_4, h0, args=(p0, N0, M0), method='lm', tol=10e-10) else: h = root(f_1, h0, args=(p0, N0, M0), method='hybr', tol=10e-10) p = p0 """ REMOVE NEGLIBLE HUNTERS """ hunt = [] N_hunters = N0 for i in range(N_hunters): if ((h.x[2 * i] < 10 and h.x[2 * i] > -10) and (h.x[2 * i + 1] < 10 and h.x[2 * i + 1] > -10)): hunt.append(h.x[2 * i]) hunt.append(h.x[2 * i + 1]) else: N0 -= 1 print("Hunter neglected is: " + str(i)) """ CHECK THE SOLVER """ hi0 = list2mat(hunt) pj0 = list2mat(p) if not h.success: print("not success") XP = -1 YP = -1 XH = -1 YH = -1 error = -1 found = False v_preys = None v_hunters = None converge = False return XP, YP, XH, YH, error, v_preys, v_hunters, found, converge else: """ Now is time to simulate the behavior from the positions calculated previously """ print("success") N_hunters = N0 M_preys = M0 mode = mode h = hunt else: p = p0 h = h0 hi0 = list2mat(h) pj0 = list2mat(p) # h_desired = h.x # p_desired = p0 # M_preys = 3 # N_hunters = 6 # D = 5 # """ The main layout of the animation """ # ax = plt.axes(xlim=(-D,D), ylim=(-D,D)) # # """ # Plot preserve # """ # vertsP = [ # (-D, -D), # left, bottom # (-D, D), # left, top # (D, D), # right, top # (D, -D), # right, bottom # (-D, -D), # ignored # ] # vertsPCodes = [ # Path.MOVETO, # Path.LINETO, # Path.LINETO, # Path.LINETO, # Path.CLOSEPOLY, # ] # # vertsPPath = Path(vertsP, vertsPCodes) # vertsPPatch = patches.PathPatch(vertsPPath, facecolor='none', lw=2) # ax.add_patch(vertsPPatch) # for j in range(M_preys): # ax.plot(p_desired[2*j], p_desired[2*j+1], 'o', ms=12, c='g') # for i in range(N_hunters): # ax.plot(h_desired[2*i], h_desired[2*i+1], 'D', ms=12, c='b') # # plt.show() # plt.savefig("G:/Unidades de equipo/EduardoSebastian/TFG/04_Imagenes/Figura2.png") # # plt.close('all') # time.sleep(2) ############################################################################### ###### LINEAR CONTROLLER ##################################################### ############################################################################### if (controller == "linear"): """ Calculate the state-space system """ A = np.zeros([2 * M_preys, 2 * M_preys]) B = np.zeros([2 * M_preys, 2 * N_hunters]) C = np.eye(2 * M_preys) D = np.zeros([2 * M_preys, 2 * N_hunters]) ############################################################################### ###### MODE 1 CONTROL SYSTEM ################################################# ############################################################################### if mode == 1: for j in range(M_preys): a = np.zeros([2, 2]) b = np.zeros([2, 2]) I = np.matrix([[1, 0], [0, 1]]) for i in range(N_hunters): term = (I * norm(hi0[i] - pj0[j])**3) a += (term + 3 * (norm(hi0[i] - pj0[j]) * np.transpose(hi0[i] - pj0[j]) * (hi0[i] - pj0[j]))) / (norm(hi0[i] - pj0[j])**5) b = (-term + 3 * (norm(hi0[i] - pj0[j]) * np.transpose(hi0[i] - pj0[j]) * (hi0[i] - pj0[j]))) / (norm(hi0[i] - pj0[j])**5) B[2 * j, 2 * i] = b[0, 0] B[2 * j, 2 * i + 1] = b[0, 1] B[2 * j + 1, 2 * i] = b[1, 0] B[2 * j + 1, 2 * i + 1] = b[1, 1] A[2 * j, 2 * j] = a[0, 0] A[2 * j, 2 * j + 1] = a[0, 1] A[2 * j + 1, 2 * j] = a[1, 0] A[2 * j + 1, 2 * j + 1] = a[1, 1] ############################################################################### ###### MODE 2 CONTROL SYSTEM ################################################# ############################################################################### elif mode == 2: var = 1.0 alpha = 100.5 beta = 0.5 radius = 1.0 angry = False for j in range(M_preys): a = np.zeros([2, 2]) b = np.zeros([2, 2]) I = np.matrix([[1, 0], [0, 1]]) for i in range(N_hunters): if norm(pj0[j] - hi0[i]) < radius: angry = True break else: angry = False for i in range(N_hunters): Xi = (pj0[j, 0] - hi0[i, 0])**2 + (pj0[j, 1] - hi0[i, 1])**2 term1 = np.exp(-(1 / (var**2)) * Xi) term2 = np.matrix([[0, 0], [0, 0]]) term2[0, 0] = (pj0[0, 0] - hi0[0, 0]) * (pj0[0, 0] - hi0[0, 0]) term2[0, 1] = (pj0[0, 0] - hi0[0, 0]) * (pj0[0, 1] - hi0[0, 1]) term2[1, 0] = (pj0[0, 0] - hi0[0, 0]) * (pj0[0, 1] - hi0[0, 1]) term2[1, 1] = (pj0[0, 1] - hi0[0, 1]) * (pj0[0, 1] - hi0[0, 1]) if angry: a += I * alpha * term1 - 2 * alpha * ( 1 / (var**2)) * term1 * term2 b = -I * alpha * term1 + 2 * alpha * ( 1 / (var**2)) * term1 * term2 else: a += I * alpha * beta * term1 - 2 * alpha * beta * ( 1 / (var**2)) * term1 * term2 # b = -I * alpha * beta * term1 + 2 * alpha * beta * ( 1 / (var**2)) * term1 * term2 # B[2 * j, 2 * i] = b[0, 0] B[2 * j, 2 * i + 1] = b[0, 1] B[2 * j + 1, 2 * i] = b[1, 0] B[2 * j + 1, 2 * i + 1] = b[1, 1] A[2 * j, 2 * j] = a[0, 0] A[2 * j, 2 * j + 1] = a[0, 1] A[2 * j + 1, 2 * j] = a[1, 0] A[2 * j + 1, 2 * j + 1] = a[1, 1] ############################################################################### ###### MODE 3 CONTROL SYSTEM ################################################# ############################################################################### elif mode == 3: for j in range(M_preys): a = np.zeros([2, 2]) b = np.zeros([2, 2]) I = np.matrix([[1, 0], [0, 1]]) for i in range(N_hunters): term = (I * norm(hi0[i] - pj0[j])**3) a += (term + 3 * (norm(hi0[i] - pj0[j]) * np.transpose(hi0[i] - pj0[j]) * (hi0[i] - pj0[j]))) / (norm(hi0[i] - pj0[j])**5) b = (-term + 3 * (norm(hi0[i] - pj0[j]) * np.transpose(hi0[i] - pj0[j]) * (hi0[i] - pj0[j]))) / (norm(hi0[i] - pj0[j])**5) B[2 * j, 2 * i] = b[0, 0] B[2 * j, 2 * i + 1] = b[0, 1] B[2 * j + 1, 2 * i] = b[1, 0] B[2 * j + 1, 2 * i + 1] = b[1, 1] a += np.matrix([[0.02, -0.002], [-0.007, 0.06]]) A[2 * j, 2 * j] = a[0, 0] A[2 * j, 2 * j + 1] = a[0, 1] A[2 * j + 1, 2 * j] = a[1, 0] A[2 * j + 1, 2 * j + 1] = a[1, 1] ############################################################################### ###### MODE 4 CONTROL SYSTEM ################################################# ############################################################################### elif mode == 4: var = 1.0 alpha = 100.5 beta = 0.5 radius = 1.0 angry = False for j in range(M_preys): a = np.zeros([2, 2]) b = np.zeros([2, 2]) I = np.matrix([[1, 0], [0, 1]]) for i in range(N_hunters): if norm(pj0[j] - hi0[i]) < radius: angry = True break else: angry = False for i in range(N_hunters): Xi = (pj0[j, 0] - hi0[i, 0])**2 + (pj0[j, 1] - hi0[i, 1])**2 term1 = np.exp(-(1 / (var**2)) * Xi) term2 = np.matrix([[0, 0], [0, 0]]) term2[0, 0] = (pj0[0, 0] - hi0[0, 0]) * (pj0[0, 0] - hi0[0, 0]) term2[0, 1] = (pj0[0, 0] - hi0[0, 0]) * (pj0[0, 1] - hi0[0, 1]) term2[1, 0] = (pj0[0, 0] - hi0[0, 0]) * (pj0[0, 1] - hi0[0, 1]) term2[1, 1] = (pj0[0, 1] - hi0[0, 1]) * (pj0[0, 1] - hi0[0, 1]) if angry: a += I * alpha * term1 - 2 * alpha * ( 1 / (var**2)) * term1 * term2 b = -I * alpha * term1 + 2 * alpha * ( 1 / (var**2)) * term1 * term2 else: a += I * alpha * beta * term1 - 2 * alpha * beta * ( 1 / (var**2)) * term1 * term2 # b = -I * alpha * beta * term1 + 2 * alpha * beta * ( 1 / (var**2)) * term1 * term2 # B[2 * j, 2 * i] = b[0, 0] B[2 * j, 2 * i + 1] = b[0, 1] B[2 * j + 1, 2 * i] = b[1, 0] B[2 * j + 1, 2 * i + 1] = b[1, 1] a += np.matrix([[0.02, -0.002], [-0.007, 0.06]]) A[2 * j, 2 * j] = a[0, 0] A[2 * j, 2 * j + 1] = a[0, 1] A[2 * j + 1, 2 * j] = a[1, 0] A[2 * j + 1, 2 * j + 1] = a[1, 1] ############################################################################### ###### DEFAULT MODE CONTROL SYSTEM ########################################### ############################################################################### else: for j in range(M_preys): a = np.zeros([2, 2]) b = np.zeros([2, 2]) I = np.matrix([[1, 0], [0, 1]]) for i in range(N_hunters): term = (I * norm(hi0[i] - pj0[j])**3) a += (term + 3 * (norm(hi0[i] - pj0[j]) * np.transpose(hi0[i] - pj0[j]) * (hi0[i] - pj0[j]))) / (norm(hi0[i] - pj0[j])**5) b = (-term + 3 * (norm(hi0[i] - pj0[j]) * np.transpose(hi0[i] - pj0[j]) * (hi0[i] - pj0[j]))) / (norm(hi0[i] - pj0[j])**5) B[2 * j, 2 * i] = b[0, 0] B[2 * j, 2 * i + 1] = b[0, 1] B[2 * j + 1, 2 * i] = b[1, 0] B[2 * j + 1, 2 * i + 1] = b[1, 1] A[2 * j, 2 * j] = a[0, 0] A[2 * j, 2 * j + 1] = a[0, 1] A[2 * j + 1, 2 * j] = a[1, 0] A[2 * j + 1, 2 * j + 1] = a[1, 1] """ Ensures control functions do not delete rows""" for i in range(2 * M_preys): if sum(A[i]) == 0.0: A[i] = A[i] + 1e-10 if sum(B[i]) == 0.0: B[i] = B[i] + 1e-10 cont_system = control.StateSpace(A, B, C, D) disc_system = control.c2d(cont_system, Ts) """ LQR METHOD """ try: if mode == 1 or mode == 3: [L, S, e] = dlqr(disc_system.A, disc_system.B, 1 * np.eye(2 * M_preys), 2 * np.eye(2 * N_hunters)) else: [L, S, e] = dlqr(disc_system.A, disc_system.B, 1 * np.eye(2 * M_preys), 0.1 * np.eye(2 * N_hunters)) except: print("not success") XP = -1 YP = -1 XH = -1 YH = -1 error = -1 found = False v_preys = None v_hunters = None converge = False return XP, YP, XH, YH, error, v_preys, v_hunters, found, converge """ POLE ASSIGNMENT METHOD """ #poles = np.exp(-1 * np.ones([N_hunters])*Ts) #L = control.place(disc_system.A,disc_system.B,poles) ############################################################################### ###### NON - LINEAR CONTROLLER ############################################### ############################################################################### elif (controller == "non-linear"): Ts = 0.01 L = 0 ############################################################################### ###### NON - LINEAR CONTROLLER WITH ADAPTIVE BEHAVIOR ######################## ############################################################################### elif (controller == "adaptive"): Ts = 0.1 L = np.ones([1, 2 * M_preys]) * 1 ############################################################################### ###### NON - LINEAR CONTROLLER WITH ADAPTIVE BEHAVIOR AND DISTRIBUTED FORM ### ############################################################################### else: return -1 """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """"" """ """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" """""" "" """ Place zero position of hunters and preys """ h_desired = [] h_ini = [] for i in range(len(h)): h_desired.append(h[i]) h_ini.append(h[i] + random.uniform(-noise_h, noise_h)) p_desired = [] p_ini = [] for j in range(len(p)): if (p[j] != 0.0): p_desired.append(p[j]) p_ini.append(p[j] + random.uniform(-noise_p, noise_p)) # p_ini = [1.0,1.0] # p_desired = [0.0,0.0] # h_ini = [-3.0,0.0,0.0,3.0] # p_desired = [0.3,-0.1,-1.0,1.0,-0.8,1.5] # p_ini = [1.0,-0.7,-0.5,1.5,-0.4,2.0] # h_ini = [-0.8,1.2,-1.3,1.5,0.2,0.2,0.3,1.7,3.0,0.0] config = { 'SampleTime': Ts, 'K': 500, 'D': 5.0, 'draw': False, 'anim': False, 'interval': 10, 'H0': h_ini, 'P0': p_ini, 'H_desired': h_desired, 'P_desired': p_desired, 'L': L, 'saveAnim': False, 'controller': controller } XP, YP, XH, YH, error, v_preys, v_hunters, converge = setup( N_hunters, M_preys, mode, config) found = True return XP, YP, XH, YH, error, v_preys, v_hunters, found, converge