def test_login(self):
        a = Authentication(self.test_db)
        c = Controller(self.test_db)

        a.create_user('employee', 'user1')

        self.assertTrue(c.login('user1', '12345'))
Example #2
0
	def __init__(self, root, state=None):
		self.root = root
		
		ShetClient.__init__(self)
		Controller.__init__(self, state)
		
		self.add_action("set_state", self.set_state)
    def test_get_user_id(self):
        c = Controller(self.test_db)

        cl_id = c.create_client('user1')
        cl_data = c.get_client('id', cl_id)[0]

        self.assertEqual(cl_id, cl_data['id'])
Example #4
0
def main():
    """
    Quick game setup for testing purposes.
    """
    win = pygcurse.PygcurseWindow(80, 30)
    win.font = pygame.font.Font(pygame.font.match_font("consolas"), 18)
    level1 = Dungeon.load_from_file("map/bigmap.txt")
    player = Player(1, 1)
    level1.add_player(player)
    msgbox = MessageBox()

    view = GameView(
        win, {ScrollingView(level1): (0, 0), HUDView(player): (700, 0), MessageBoxView(msgbox, 80, 5): (0, 460)}
    )

    controller = Controller(level1, msgbox, view)
    win.autoupdate = False
    mainClock = pygame.time.Clock()
    running = True

    while running:
        for event in pygame.event.get():
            if event.type == QUIT:
                running = False
            else:
                controller.process_event(event)

        controller.view.draw()
        win.blittowindow()
        mainClock.tick(30)

    pygame.quit()
    sys.exit()
Example #5
0
 def __init__(self, parent):
     Cell.__init__(self, parent)
     Controller.__init__(self, self.parent.canvas, parent)
     self.offset_x = 0
     self.offset_y = 0
     self.update_request = False
     self.old_zoom = False
Example #6
0
def load_controller(botengine):
    """
    Load the Controller object
    :param botengine: Execution environment
    """
    logger = botengine.get_logger()
    try:
        controller = botengine.load_variable("controller")
        logger.info("Loaded the controller")

    except:
        controller = None
        logger.info("Unable to load the controller")

    if controller == None:
        botengine.get_logger().info("Bot : Creating a new Controller object. Hello.")
        controller = Controller()
        botengine.save_variable("controller", controller, required_for_each_execution=True)

        import importlib
        try:
            analytics = importlib.import_module('analytics')
            analytics.get_analytics(botengine).track(botengine, 'reset')

        except ImportError:
            pass


    controller.track_new_and_deleted_devices(botengine)
    controller.initialize(botengine)
    return controller
Example #7
0
def main(_):

    import pprint
    pprint.pprint(FLAGS.__flags)

    config = tf.ConfigProto()
    config.gpu_options.allow_growth = True
    with tf.Session(config=config) as session:
        model = Controller(
            session,
            is_training=FLAGS.is_train,
            save_dir=FLAGS.save_dir,
            dataset_name=FLAGS.dataset,
            checkpoint_dir=FLAGS.checkpoint_dir,
            size_batch=FLAGS.batch_size,
            y_dim=FLAGS.y_dim,
            rb_dim=FLAGS.rb_dim,
            is_simple_q=FLAGS.is_simple_q,
            num_z_channels=FLAGS.z_dim
        )
        if FLAGS.is_train:
            print '\n\tTraining Mode'
            model.train(
                num_epochs=FLAGS.epoch,
            )
        else:
            print '\n\tVisualization Mode'
            model.custom_visualize(testing_samples_dir=FLAGS.test_dir + '/*.jpeg')
Example #8
0
class Simulator:
    def __init__(self):
        self._drone = Drone()
        self._controller = Controller(self._drone)
        self._loop = asyncio.get_event_loop()
        self._drone.set_init([0., 0., 0.], [2., 0., 0.])
        # self._AOO = []
        # self._drone.dt = 5e-4
        # self._drone.noise_z = 1e-10

    def run(self):
        logger.info('starting simulation...')
        self._loop.run_until_complete(self._controller.takeoff())
        self._loop.call_soon_threadsafe(
            self._loop.create_task,
            self._controller.run()
        )
        logger.info('started.')

    @asyncio.coroutine
    def get_data(self):
        pos = self._drone.get_position()
        ori = self._drone.rot
        # oori = ori[:, 2]
        # self._AOO.append(self._drone.acc_sensor[2])
        # self._AOO.append(oori)
        return pos, ori

    @asyncio.coroutine
    def stop(self):
        yield from self._controller.stop()
        yield from self._drone.stop()
Example #9
0
    def mainloop(self):
        self.clock = pygame.time.Clock()
        self.player.rect.center = [self.display.arena[0]/2, self.display.arena[1]/2]
        controller = Controller()
        while self.gameRunning:

            dirty = []
            
            self.clock.tick(FPS)
            self.framerate = self.clock.get_fps()

            self.display.paint_background(dirty)
            self.player.state.set_current_state(self)
            d = self.display.paint_sprite(self.player)
            dirty.insert(len(dirty), d)

            self.steine.update()
            self.ladders.update()
            self.barrels.update()
            self.meanies.update(dirty)

            self.hud.showinfo(self, dirty)
            controller.handle_keyboard_input(self.player)
            self.player.update()
            pygame.display.update(dirty)
Example #10
0
    def _handle(self, sock):
        while True:
            header_length = struct.calcsize(self._header)
            header_buffer = self._recv_n(sock, header_length)
            if header_buffer is None:
                break

            controller_length, = struct.unpack(self._header, header_buffer)
            controller_buffer = self._recv_n(sock, controller_length)
            if controller_buffer is None:
                break

            controller = Controller()
            controller.sock = sock

            try:
                controller.proto.ParseFromString(controller_buffer)
            except DecodeError:
                continue

            if not controller.proto.stub:
                self._handle_response(controller)
            elif controller.proto.notify:
                self._handle_notify(controller)
            else:
                self._handle_request(controller)
Example #11
0
    def __init__(self, event_manager, server_url=None):
        # Setup inital states
        Controller.__init__(self, event_manager)
        self._server_url = server_url
        self.system_state = SystemState.ARMED
        self.user_list = []
        self.input_devices = []
        self.door_timer_delay = DOOR_EVENT_TIMER_DELAY

        # Load the event handlers functions into a dictionary to make calling
        # the appropriate function easier through the enum
        self.event_handling_functions = {
            EventType.DOOR_SENSOR_EVENT: self._handle_door_event,
            EventType.WINDOW_SENSOR_EVENT: self._handle_window_event,
            EventType.FLOOD_SENSOR_EVENT: self._handle_flood_event,
            EventType.TEMP_SENSOR_EVENT: self._handle_temp_event,
            EventType.MOTION_SENSOR_EVENT: self._handle_motion_event,
            EventType.ALARM_EVENT: self._handle_alarm_event,
            EventType.KEYPAD_EVENT: self._handle_keypad_event,
            EventType.NFC_EVENT: self._handle_nfc_event,
        }

        # Subscribe to events
        if self.event_manager is not None:
            for event_type in self.event_handling_functions.keys():
                self.event_manager.subscribe(event_type, self)
Example #12
0
 def run(self, curr_dims=(1600, 875)):
     """
     function that runs the game. like the cpu of the game. kind of.
     """
     rand_outer = [0., pi/2., pi, 3.*pi/2.]
     curr_polypos = [[rand_outer[randint(0, 3)], randint(1, 2), 2, (200, 200, 230)], [rand_outer[randint(0, 3)], randint(3, 4), 2, (200, 200, 230)]]
     screen, buttons, polys = self.init(curr_dims, polypos=curr_polypos)
     control = Controller()
     curr_highScore = 2
     while True:
         pg.event.pump()
         for event in pg.event.get():
             if event.type == QUIT:
                 self.quit()
             elif event.type == VIDEORESIZE:
                 curr_dims = (event.w, event.h)
                 screen, buttons, polys = self.init(curr_dims, polypos=curr_polypos)
             elif event.type == MOUSEBUTTONUP:
                 for i, butt in enumerate(buttons):
                     buttNumb =  butt.liveButton(i)
                     if buttNumb == 0:
                         print "new game"
                         self.run(curr_dims=curr_dims)
                     else:
                         break
             elif event.type == KEYDOWN:
                 if event.key != K_ESCAPE:
                     curr_polypos, curr_highScore = control.keys(event, polys, curr_highScore)
                     if curr_highScore > self.highScore:
                         self.highScore = curr_highScore
                     screen, buttons, polys = self.init(curr_dims, polypos=curr_polypos)
                 else:
                     self.quit()
         pg.display.update()
Example #13
0
class PachongWin(object):
    def run(self):
        self.root=Tkinter.Tk()
        title='%s爬虫控制窗口'%settings.S_target_website
        self.root.title(title)
        
        #画界面
        self.root.geometry('190x80')
        self.f = Tkinter.Frame(self.root)
        self.b_start=Tkinter.Button(self.f,text='启动',command=self.start)
        self.b_start.config(height=3,width=10)
        self.b_start.pack()
        self.b_stop=Tkinter.Button(self.f,text='退出',state=Tkinter.DISABLED,command=self.stop)
        self.b_stop.config(height=3,width=10)
        self.b_stop.pack()
        self.f.pack()
            
        Tkinter.mainloop()
        
    def start(self):
        self.controller=Controller()
        self.controller.start()
        self.b_start.config(state=Tkinter.DISABLED)
        while not self.controller.engine_is_running:
            pass
        self.b_stop.config(state=Tkinter.ACTIVE)        
        
    def stop(self):
        self.controller.stop()
        self.b_stop.config(state=Tkinter.DISABLED)
        while True:
            t_list=[t for t in self.controller.eng.threads if t.is_running==False]
            if len(t_list)==len(self.controller.eng.threads):
                break;
        self.b_start.config(state=Tkinter.ACTIVE)
Example #14
0
class Watcher(object):
    def __init__(self, logger):
        os.chdir("../")
        self.programPath = os.getcwd()
        os.chdir("app")
        self.__fs = FileSystem(".")
        self.__utils = Utils()
        self.__config = Config(fileSystem=self.__fs)
        self.__db = None
        self.__controller = None
        self.__feeder = None
        self.__webServer = None
        self.__logger = logger
        self.__configWatcher = None
        self.__stompClient = None
        dbName = self.__config.watcher.get("db", "sqlite")
        sys.path.insert(0, "../db/%s" % dbName)
        Database = __import__(dbName).Database
        dbFileName = self.__config.watcher.get("dbFile", "queue.db")

        print "Starting file watcher..."
        #------------------------
        self.__db = Database(dbFileName)
        self.__controller = Controller(self.__db, self.__fs, self.__config, \
                                FileWatcher, WatchDirectory, update=False)
        #self.__controller.configChanged(config)
        #self.__config.addReloadWatcher(self.__controller.configChanged)
        if self.__config.messaging.enabled:
            self.__stompClient = StompClient(self.__config, self.__utils)
            def stompListener(file, eventTime, eventName, isDir):
                if not isDir:
                    try:
                        self.__stompClient.queueUpdate(file, eventName)
                    except Exception, e:
                        msg = "ERROR in stompClient.queueUpdate('%s', '%s) - '%s'"
                        print msg % (file, eventName, str(e))
            self.__controller.addListener(stompListener)
        ## Log events
        def logCallback(file, eventTime, eventName, isDir):
            tStr = time.strftime("%Y%m%dT%H:%M:%S", time.localtime(eventTime))
            print "%s \t%s \t%s \t%s" % (tStr, eventName, isDir, file)
        self.__controller.addListener(logCallback)
        ##
        self.__configWatcher = FileWatcher(self.__config.configFile, self.__fs)
        self.__configWatcher.startWatching()
        def configChanged(file, eventName, **kwargs):
            #file=path, eventTime=eventTime, eventName=eventName, isDir=isDir, walk=False
            if eventName!="del" and file==self.__config.configFile:
                print "configChanged - reloading"
                self.__config.reload()
                self.__controller.configChanged(self.__config)
        self.__configWatcher.addListener(configChanged)

        self.__feeder = Feeder(self.__utils, self.__controller)
        feedservice = self.__config.watcher.get("feedservice", {})
        self.host = feedservice.get("host", "*")
        self.port = feedservice.get("port", 9000)
        s = webServe(self.host, self.port, self.__feeder)
        self.__webServer = s
Example #15
0
class GUI(Tk):
    "represents GUI"
    def __init__(self):
        super().__init__()
   
        self.title("CM Manager " + ".".join(version()))
        self.option_add("*tearOff", FALSE)
        self.resizable(FALSE, FALSE)
        
        '''
        # used when size of the window is changed for placeWindow arguments     
        self.after(250, lambda: print(self.winfo_width()))
        self.after(250, lambda: print(self.winfo_height()))
        '''
        placeWindow(self, 1010, 834)

        # notebook
        self.selectFunction = ttk.Notebook(self)
        self.selectFunction.grid()

        # FileStorage is associated with the Notebook
        self.selectFunction.fileStorage = FileStorage()
        
        self.processor = Processor(self.selectFunction)
        self.explorer = Explorer(self.selectFunction)
        self.controller = Controller(self.selectFunction)

        notepageWidth = 20
        self.selectFunction.add(self.processor, text = "{:^{}}".format("Process", notepageWidth))
        self.selectFunction.add(self.explorer, text = "{:^{}}".format("Explore", notepageWidth))
        self.selectFunction.add(self.controller, text = "{:^{}}".format("Control", notepageWidth))

        self.selectFunction.bind("<<NotebookTabChanged>>", lambda e: self.checkProcessing(e))
            
        # menu
        self["menu"] = MenuCM(self)

        if not optionGet("Developer", False, 'bool'):
            self.protocol("WM_DELETE_WINDOW", self.closeFun)

        self.mainloop()


    def closeFun(self):
        "ask for saving files on exit"
        if doesFileStorageRequiresSave(self):
            answ = messagebox.askyesno(message = "Do you want to save files before leaving?",
                                       icon = "question", title = "Save files?")
            if answ:
                saveFileStorage(self)                
        self.destroy()


    def checkProcessing(self, event):
        """checks whether it is possible for processor and controller to process files and change
        states of buttons accordingly"""
        self.processor.checkProcessing()
        self.controller.checkProcessing()
        self.explorer.checkProcessing()
Example #16
0
    def __init__(self, source, size):
        """Default constructor.

        :param source: Path of the source file the neuron will be created from.
        :param size: Number of neuron to be created through this controller.
        """
        Controller.__init__(self, size, "Creating neurons")
        self.source = source
 def __init__(self, params):
     '''Initialize internal variables'''
     Controller.__init__(self,params)
     
     # This angle shows the direction that the controller
     # tries to follow. It is used by the supervisor
     # to draw and debug this controller
     self.heading_angle = 0
    def test_create_task(self):
        c = Controller(self.test_db)

        task_id = c.create_task(subject='Underwater photos', priority='Medium')
        task_data = c.get_task('id', task_id)[0]

        self.assertEqual('Underwater photos', task_data['subject'])
        self.assertEqual('Medium', task_data['priority'])
Example #19
0
def unittest():
  from controller import Controller
  from fake_robot import FakeRobot
  fake_robot = FakeRobot()
  controller = Controller(fake_robot)
  controller.app = DummyApp()
  syncer = SyncToServer('http://localhost:8080/api/', 5, controller)
  syncer.run()
    def test_create_client(self):
        c = Controller(self.test_db)

        cl_id = c.create_client('cl12345', name='Foo Bar', age='23')
        cl_data = c.get_client('id', cl_id)[0]

        self.assertEqual('Foo Bar', cl_data['name'])
        self.assertEqual('23', cl_data['age'])
Example #21
0
    def test_run(self):
        event_manager = EventManager([])
        controller = Controller(event_manager)

        controller_thread = threading.Thread(target=controller.run)
        controller_thread.start()

        controller.stop()
        controller_thread.join()
Example #22
0
    def __init__(self, params):
        """init
        @params: 

        """
        Controller.__init__(self,params)

        self.E_k = 0 # integrated error
        self.e_k_1 = 0 # last step error
    def test_create_employee(self):
        c = Controller(self.test_db)

        em_id = c.create_employee('em12345', name='Foo Bar', age='23', pos='3')
        em_data = c.get_employee('id', em_id)[0]

        self.assertEqual('Foo Bar', em_data['name'])
        self.assertEqual('23', em_data['age'])
        self.assertEqual('3', em_data['pos'])
Example #24
0
    def test_stop(self):
        mock_event_manager = mox.MockObject(EventManager)
        mox.Replay(mock_event_manager)

        controller = Controller(mock_event_manager)
        controller.stop()
        controller.run()

        mox.Verify(mock_event_manager)
	def buildValuesBackwards(self, startDate, endDate, location, tracking, storageMWh):
		#reverse the arrays containing price and solar data.
		print "Building Values Backwards"
		tz = SydneyTimezone()
		lat= location[0]
		lon = location[1]
		state= location[2]
		# locationName = location[3]
		startDate = startDate.astimezone(tz)
		endDate = endDate.astimezone(tz)

		controller = Controller(gui=False)
		data = controller.getTimeseriesNemDNICos(state=state, lat = lat, lon = lon, startDate = startDate, endDate = endDate)
		plant = Plant(namePlateMW = 1)
		storage = Storage(storageLevels = self.numStates, effectiveCapacityMWh = storageMWh, batteryType = self.batteryType)
		plant = Plant(1)

		values=np.zeros(shape=(data.shape[0] + 1, storage.getNumStorageLevels()+1))
		destinations = np.zeros(shape=( data.shape[0] + 1, storage.getNumStorageLevels()+1))
		
		totalArrayOutput = 0

		# if self.shaved:
		# 	data = self.shaveNemData(data)

		if tracking:
			COS_INDEX = self.TRACKING_COS_INDEX
		else:
			COS_INDEX = self.FIXED_COS_INDEX

		#iterate backwards through time.
		for timeIndex in np.arange(0, data.shape[0])[::-1]:
			# Get the timeperiod outputs
			cos = data[timeIndex][COS_INDEX]
			price = data[timeIndex][self.PRICE_INDEX]

			if self.capped:
				price = min(price, 300)

			dni = data[timeIndex][self.DNI_INDEX]
			ghi_factor = data[timeIndex][self.GHI_FACTOR_INDEX]
			ghi = np.multiply(ghi_factor, dni)			
			arrayOutput = plant.getPlantOutput(dni=dni, ghi=ghi, timePeriodHrs=0.5, cosine=cos)
			totalArrayOutput = totalArrayOutput + arrayOutput
			date = datetime.datetime(year=int(data[timeIndex][self.YEAR_INDEX]), month = int(data[timeIndex][self.MONTH_INDEX]), day = int(data[timeIndex][self.DAY_INDEX]), hour=int(data[timeIndex][self.HOUR_INDEX]), minute=int(data[timeIndex][self.MINUTE_INDEX]), tzinfo=SydneyTimezone())
			
			# iterate through the storagelevels
			for storageLevel in np.arange(storage.getNumStorageLevels()+1):
				# Find the optimal destination and its corresponding value
				valueAndDestination = self.getValueAndDestination(storage = storage, price=price, solarOutputMWh=arrayOutput, storageLevel=storageLevel,  nextTimePeriodValues = values[timeIndex + 1], date = date)
				values[ timeIndex, storageLevel] = valueAndDestination[0]
				destinations[timeIndex, storageLevel] = valueAndDestination[1]
		
		prices = np.transpose(data)[self.PRICE_INDEX]
		sun = np.transpose(data)[self.DNI_INDEX]
		
		return (values, destinations,prices, sun, totalArrayOutput)
Example #26
0
class Shuffle:
    def __init__(self):
        usage = """shuffle.py [input_folder]"""
        parser = optparse.OptionParser(usage = usage)
        (options, args) = parser.parse_args()

        if len(args) == 0:
            print "A video folder needs to be specified."
            exit()
        else:
            self.folder = args[0]
            if self.folder.endswith("/"):
                self.folder = self.folder[:-1]

            if len(args) == 2:
                self.bpm = int(args[1])
            else:
                self.bpm = 30

        self.engine = Engine()
        self.controller = Controller(self.engine)

        self.tree = []
        self.folder_short = self.folder.split("/")[-1]
        ls = os.listdir(self.folder)

        # Populating database of files in input directory.
        self.browse_folder(ls, self.folder, self.tree)

        self.length = len(self.tree)
        print ""
        print "Found " + str(self.length) + " videos."
        print ""

        self.timeout_id = gobject.timeout_add((60000/self.bpm), self.loop_callback)
        loop = gobject.MainLoop()
        loop.run()

    def loop_callback(self):
            video = random.choice(self.tree)
            self.controller.play(video, 1.0, 0)

            return True

    def browse_folder(self, folder, dir, tree):
        '''Creates a tree of all the files and folder inside the in    put dir.'''

        for files in folder:
            if not files.startswith(".") and (not files == folder):
                files = dir + "/" + files
                tree.append(files)
                if os.path.isdir(files):
                    temp = files[files.find(self.folder_short):]
                    temp = "".join("%s/" % (n) for n in \
                    temp.split("/")[1:])
                    new = os.listdir(files)
                    self.browse_folder(new, files, tree)
Example #27
0
def main():
    args = get_parser().parse_args()

    if args.uri is None:
        args.uri = conf.General["uri"]
    if args.handler == "show_info":
            args.handler = "info"
    ctrl = Controller(args.server, args.server_port)
    ctrl.all(vars(args))
Example #28
0
 def check_for_missing_inmates(self, start_date):
     self._debug('started check_for_missing_inmates')
     inmates = Inmates(Inmate, self._monitor)
     inmates_scraper = InmatesScraper(Http(), inmates, InmateDetails, self._monitor, workers_to_start=70)
     search_commands = SearchCommands(inmates_scraper, self._monitor)
     controller = Controller(self._monitor, search_commands, inmates_scraper, inmates)
     controller.find_missing_inmates(start_date)
     self._debug('waiting for check_for_missing_inmates processing to finish')
     controller.wait_for_finish()
     self._debug('finished check_for_missing_inmates')
Example #29
0
    def test_handle_event(self):
        # This function should be a no-op, nothing should be called on
        # the EventManager
        mock_event_manager = mox.MockObject(EventManager)
        mox.Replay(mock_event_manager)

        controller = Controller(mock_event_manager)
        controller.handle_event('foo')

        mox.Verify(mock_event_manager)
Example #30
0
 def run(self):
     self._debug('started')
     inmates = Inmates(Inmate, self._monitor)
     inmates_scraper = InmatesScraper(Http(), inmates, InmateDetails, self._monitor)
     search_commands = SearchCommands(inmates_scraper, self._monitor)
     controller = Controller(self._monitor, search_commands, inmates_scraper, inmates)
     controller.run()
     self._debug('waiting for processing to finish')
     controller.wait_for_finish()
     self._debug('finished')
Example #31
0
class UI:
    def __init__(self, n):
        self.__problem = Problem(n)
        self.__controller = Controller(self.__problem)
        self.__eaAverage = []
        self.__psoAverage = []

    def particleSwarmOptimization(self):
        startClock = time()
        noIteratii = int(input("Enter the number of iterations = "))
        dimPopulation = int(input("Enter the dimension of the population = "))

        # numbers for permutations will be in interval [1, n]
        vmin = 1
        vmax = n
        # maximum fitness possible
        maximumFitness = 4 * vmax

        # specific parameters for PSO
        w = 1.0
        c1 = 1.
        c2 = 2.5
        sizeOfNeighborhood = 20

        optimIndividual, fitnessOptim = self.__controller.ParticleSwarmOptimization(noIteratii, dimPopulation, vmin, vmax, w, c1, c2, sizeOfNeighborhood)
        print ('Result: The detected matrix after ', noIteratii, ' iterations is: ')
        print(optimIndividual)
        print (' with fitness optim = ', fitnessOptim, '/', maximumFitness)
        print('execution time = ', time() - startClock, " seconds")

    def animate_EA(self, x_vals, y_vals, index, r):
        population = 40
        P = ChromozomePopulation(population, 1, n) #population = 40
        pop = P.getPopulation()
         
        r = random.randrange(1, 40)
        x_vals.append(next(index))
        y_vals.append(P.fitness(pop[r], n))
        self.__eaAverage.append(P.fitness(pop[r], n))
        
        plt.cla()
        plt.plot(x_vals, y_vals)
        plt.show()
        
    def animate_PSO(self, x_vals, y_vals, index, r):
        population = 40
        P = ParticlePopulation(population, 1, n) #population = 40
        pop = P.getPopulation()
         
        r = random.randrange(1, 40)
        particle = pop[r]
        x_vals.append(next(index))
        y_vals.append(particle.fitness(particle))
        self.__psoAverage.append(particle.fitness(particle))
        
        plt.cla()
        plt.plot(x_vals, y_vals)
        plt.show()
            
    def statisticsEvolutionaryAlgorithm(self, n):
        plt.style.use('fivethirtyeight')
        
        x_vals = []
        y_vals = []
        
        index = count()
        
        for run in range(30): #run = 30
            r = random.randrange(1, 40)
            #evaluation = 1000 (interval)
            FuncAnimation(plt.gcf(), self.animate_EA(x_vals, y_vals, index, r), interval = 1000)
        
        plt.tight_layout()
        
        #average display for best solution
        sum_num = 0
        for t in self.__eaAverage:
            sum_num = sum_num + t           

        avg = sum_num / len(self.__eaAverage)
        print ("Average of fitness score is: ", avg)
        
        #standard deviation display for best solution
        deviation = statistics.stdev(self.__eaAverage)
        print ("Standard deviation of fitness score is: ", deviation)
        
    def statisticsParticleSwarmOptimization(self, n):
        plt.style.use('fivethirtyeight')
        
        x_vals = []
        y_vals = []
        
        index = count()
        
        for run in range(30): #run = 30
            r = random.randrange(1, 40)
            #evaluation = 1000 (interval)
            FuncAnimation(plt.gcf(), self.animate_PSO(x_vals, y_vals, index, r), interval = 1000)
        
        plt.tight_layout()
        
        #average display for best solution
        sum_num = 0
        for t in self.__psoAverage:
            sum_num = sum_num + t           

        avg = sum_num / len(self.__psoAverage)
        print ("Average of fitness score is: ", avg)
        
        #standard deviation display for best solution
        deviation = statistics.stdev(self.__psoAverage)
        print ("Standard deviation of fitness score is: ", deviation)
        
    def evolutionaryAlgorithm(self):
        startClock = time()
        noIteratii = int(input("Enter the number of iterations = "))
        dimPopulation = int(input("Enter the dimension of the population = "))

        # numbers for permutations will be in interval [1, n]
        vmin = 1
        vmax = n

        # the mutation probability
        pM = float(input("Enter the mutation probability = "))
        # maximum fitness possible
        maximumFitness = 4 * vmax

        optimIndividual, fitnessOptim = self.__controller.EvolutionaryAlgorithm(noIteratii, dimPopulation, vmin, vmax, pM)
        print ('Result: The detected matrix after ', noIteratii, ' iterations is: ')
        print(optimIndividual)
        print (' with fitness optim = ', fitnessOptim, '/', maximumFitness)
        print('execution time = ', time() - startClock, " seconds")

    def hillClimbing(self):
        startClock = time()
        # maximum fitness possible
        maximumFitness = 4 * n

        optimIndividual, fitnessOptim = self.__controller.HillClimbing(n)
        print ('Result: The detected matrix is: ')
        print(optimIndividual)
        print (' with fitness optim = ', fitnessOptim, '/', maximumFitness)
        print('execution time = ', time() - startClock, " seconds")

    def run(self):
        runM = True
        printMainMenu()
        while runM:
            command = int(input(">>"))
            if command == 0:
                runM = False
            elif command == 1:
                self.statisticsEvolutionaryAlgorithm(n)
                #self.evolutionaryAlgorithm()
            elif command == 2:
                self.hillClimbing()
            elif command == 3:
                self.statisticsParticleSwarmOptimization(n)
                #self.particleSwarmOptimization()
            else:
                print ("Invalid command")
Example #32
0
import matplotlib.pyplot as plt
import numpy as np
import sys
sys.path.append('..')  # add parent directory
import vtolParam as P
from controller import Controller
from signalGenerator import signalGenerator
from vtolAnimation import vtolAnimation
from plotData import plotData
from vtolDynamics import vtolDynamics

# instantiate reference input classes
vtol = vtolDynamics()
ctrl = Controller()
z_reference = signalGenerator(amplitude=2, frequency=0.08)
h_reference = signalGenerator(amplitude=1, frequency=0.05)

# set disturbance input
disturbance = 0.1

# instantiate the simulation plots and animation
dataPlot = plotData()
animation = vtolAnimation()

t = P.t_start  # time starts at t_start
while t < P.t_end:  # main simulation loop
    # set variables
    z_r = z_reference.square(t)
    h_r = h_reference.square(t)

    # Propagate dynamics in between plot samples
Example #33
0
policy_model = MLPNormalPolicy([state_dim, 20, action_dim],
                               sigma=2,
                               learning_rate=1e-3,
                               act_bound=2,
                               activation=F.relu,
                               init_value=0.4)
value_model = MLPValue([state_dim, 20, 1],
                       learning_rate=5e-4,
                       epsilon=0.1,
                       activation=F.relu)

model = Controller(
    name,
    policy_model,
    value_model,
    reset_prob=0.02,
    history_depth=2,
    verbose=True,
)
model.set_seeds(41)
model.train(iterations=30,
            exp_episodes=50,
            exp_timesteps=100,
            val_epochs=200,
            pol_epochs=200,
            batch_size=64,
            pickle_name='v0.1')

policy_model.save('../run/' + name + '.pth')
Example #34
0
 def Get_PhysicalPersonForName(name):
     pp = PhysicalPerson()
     pp.Name = name
     ctr = Controller(pp)
     result = ctr.Get_PhysicalPersonForName()
     return result
Example #35
0
else:
    print(
        "Usage: $rushour.py [-v] [-i] [file_path] \n\t-v: Verbose mode \n\t-i: Interactive mode (overrides file usage)	\n\tfile_path: Parse a text file containing a game board"
    )
    sys.exit()

if verbose:
    print("\nBoard acquired: ")
    for x in range(0, rows):
        print(board[x])
    print("\nFinding any solution...")

board = ''.join(board)
model = Model(rows, cols, board)
controller = Controller(model, verbose)

if (controller.play()):
    if len(model.solution) > 0:  #Paranoia
        depth = len(model.solution)
        if interactive or verbose:
            for x in range(1, depth):
                print("\nStep {} - {}".format(x, model.solution[x]))
                for z in range(0, rows):
                    print(model.solution_frames[x][z])
            print("\nWon in {} steps!".format(depth - 1))
            print("\nTime: {0:.3} seconds".format(time.time() - start_time))
        else:
            f = open(file_path + '.solved', 'w')
            f.write("Step 0 - Origin board")
            for x in range(0, rows):
Example #36
0
 def test_load_word_file(self):
     controller = Controller()
     actual = controller.load_file("test2.docx")
     expected = [['class ToyBox {\n', '    name : String\n', '}\n'],
                 ['class Toy {\n', '}\n']]
     self.assertEqual(expected, actual)
Example #37
0
from loop import Loop
from controller import Controller
from paddle import Paddle
from ball import Ball
from scoreboard import Scoreboard
from line import Line

print('running')
pygame.init()

win_w = 500
win_h = 500
win = pygame.display.set_mode((win_w, win_h))
pygame.display.set_caption("Wernk-Pong")

controller = Controller()
paddle_1 = Paddle(win_w, win_h, 10, "assets/wernkepaddle3.png", 10,
                  controller.up, controller.down)
paddle_2 = Paddle(win_w, win_h, win_w - 30, "assets/beckpaddle3.png", 10,
                  controller.up, controller.down)
scoreboard = Scoreboard(win_w, win_h)
ball = Ball(paddle_1, paddle_2, scoreboard, win_w, win_h, 30,
            "assets/wernkeball2.png",
            "assets/beckball.png")  # 15 seems to fast for the player
line = Line(win_w, win_h)

sprites = pygame.sprite.Group([paddle_1, paddle_2, scoreboard, ball, line])

run = True

while run:
Example #38
0
ground_shape = igeBullet.shape(igeBullet.STATIC_PLANE_PROXYTYPE,
                               normal=(0, 1, 0),
                               constant=0)
ground_body = igeBullet.rigidBody(ground_shape, 0, (0, 0, 0), (0, 0, 0, 1))
world.add(ground_body)

efig = utl.GetFigure()
efig.clearMesh()
shape = igeBullet.shape(igeBullet.SPHERE_SHAPE_PROXYTYPE, radius=1)
body2 = igeBullet.rigidBody(shape, 5, (0, 10, 0), (0, 0, 0, 1))
world.add(body2)
utl.AddShapeMesh(shape)

char = Character(world)
cam = TargetCamera()
controller = Controller()

# sphere = core.figure('sphere')
# sphere.position = (0,10,0)
# poss = sphere.getVertexElements(0,core.ATTRIBUTE_ID_POSITION, space=core.WorldSpace)
# tris = sphere.getTriangles(0)
# soft = igeBullet.softBody(world, poss, tris)
# sphere.position = (0,0,0)

showcase2D = core.showcase('2dcase')
showcase3D = core.showcase("3dcase")

showcase3D.add(ground)
showcase3D.add(char.figure)
showcase3D.add(efig)
Example #39
0
# FULLSCREEN = 5
# SCREENSHOT = 6

# Old Controls:
# - K_SPACE: 'nab'
# - K_TAB: toggle feat display
# - K_UP: 'leap' combo; increase an amount in menu
# - K_LEFT
# - K_RIGHT
# - K_DOWN: decrease an amount in menu

# DOCUMENTATION: Ensure that the instructions in the "CONTROLS" section
# of the readme match this file.

# capitalized ones are not related to controlling the character:
controller1 = Controller()
controller1.addKeyAsAxisValue(K_LEFT, 'x', -1)
controller1.addKeyAsAxisValue(K_RIGHT, 'x', 1)
controller1.addKeyAsAxisValue(K_UP, 'y', -1)
controller1.addKeyAsAxisValue(K_DOWN, 'y', 1)  # for menus  & "easy mode"
controller1.addKeyAsAxisValue(K_a, 'x', -1)
controller1.addKeyAsAxisValue(K_d, 'x', 1)
controller1.addKeyAsAxisValue(K_w, 'y', -1)
controller1.addKeyAsAxisValue(K_s, 'y', 1)
controller1.addKey(K_RETURN, 'nab')  # formerly K_SPACE
controller1.addKey(K_TAB, 'feat')
controller1.addKey(K_SPACE, 'jump')  # formerly K_UP; combo is 'leap'
controller1.addKey(K_BACKSPACE, 'BACK')
controller1.addKey(K_ESCAPE, 'EXIT')
controller1.addKey(K_f, 'FULLSCREEN')
controller1.addKey(K_F12, 'SCREENSHOT')
Example #40
0
class ConsoleUI:
    def __init__(self, platform):
        self.platform = platform
        self.is_running = False
        self.controller = Controller()
        self.menu = {
            '1': (self.add_numbers, "Adunati 2 numere"),
            '2': (self.subtract_numbers, "Scadeti 2 numere"),
            '3': (self.multiply_numbers, "Inmultiti 2 numere"),
            '4': (self.divide_numbers, "Impartiti 2 numere"),
            '5': (self.convert_general,
                  "Convertiti dintr-o baza in alta prin detectare automata"),
            '6':
            (self.convert_intermediary,
             "Convertiti dintr-o baza in alta folosind o baza intermediara"),
            '7': (self.convert_substitution,
                  "Convertiti dintr-o baza in alta prin substitutie"),
            '8': (self.convert_division,
                  "Convertiti dintr-o baza in alta prin impartiri succesive"),
            '9': (self.convert_fast,
                  "Convertiti dintr-o baza in alta prin conversie rapida"),
            '10': (self.print_start_message, "Afisati mesajul initial"),
            'x': (self.close, "Inchide aplicatia")
        }

    def close(self):
        self.is_running = False

    def add_numbers(self):
        """
            Adds 2 numbers read from the console in a given base and outputs the result

            Raises:
                ValueError: if either the number or the base is wrong
        """
        A = input("Introduceti numarul A: ")
        A = parse_to_bignumber(A)
        validate_number(A)

        B = input("Introduceti numarul B: ")
        B = parse_to_bignumber(B)
        validate_number(B)

        try:
            base = int(input("Introduceti baza pentru a efectua A + B: "))
        except ValueError:
            raise ValueError(
                "Baza trebuie sa fie din multimea {2, 3, 4, 5, 6, 7, 8, 9, 10, 16}"
            )
        validate_base(base)

        self.print_delimiter()

        A = self.controller.convert_general(A, base)
        B = self.controller.convert_general(B, base)

        print(A, "+", B, "=", A + B)

    def subtract_numbers(self):
        """
            Subtracts 2 numbers read from the console in a given base and outputs the result

            Raises:
                ValueError: if either the number or the base is wrong
        """
        A = input("Introduceti numarul A: ")
        A = parse_to_bignumber(A)
        validate_number(A)

        B = input("Introduceti numarul B: ")
        B = parse_to_bignumber(B)
        validate_number(B)

        try:
            base = int(input("Introduceti baza pentru a efectua A - B: "))
        except ValueError:
            raise ValueError(
                "Baza trebuie sa fie din multimea {2, 3, 4, 5, 6, 7, 8, 9, 10, 16}"
            )
        validate_base(base)

        self.print_delimiter()

        A = self.controller.convert_general(A, base)
        B = self.controller.convert_general(B, base)

        print(A, "-", B, "=", A - B)

    def multiply_numbers(self):
        """
            Multiplies 2 numbers read from the console in a given base and outputs the result

            Raises:
                ValueError: if either the number or the base is wrong
        """
        A = input("Introduceti numarul A: ")
        A = parse_to_bignumber(A)
        validate_number(A)

        B = input("Introduceti cifra B: ")
        B = parse_to_bignumber(B)
        validate_number(B)

        try:
            base = int(input("Introduceti baza pentru a efectua A * B: "))
        except ValueError:
            raise ValueError(
                "Baza trebuie sa fie din multimea {2, 3, 4, 5, 6, 7, 8, 9, 10, 16}"
            )
        validate_base(base)

        self.print_delimiter()

        A = self.controller.convert_general(A, base)
        B = self.controller.convert_general(B, base)

        print(A, "*", B, "=", A * B)

    def divide_numbers(self):
        """
            Divides 2 numbers read from the console in a given base and outputs the result and the remainder

            Raises:
                ValueError: if either the number or the base is wrong
        """
        A = input("Introduceti numarul A: ")
        A = parse_to_bignumber(A)
        validate_number(A)

        B = input("Introduceti cifra B: ")
        B = parse_to_bignumber(B)
        validate_number(B)

        try:
            base = int(input("Introduceti baza pentru a efectua A / B: "))
        except ValueError:
            raise ValueError(
                "Baza trebuie sa fie din multimea {2, 3, 4, 5, 6, 7, 8, 9, 10, 16}"
            )
        validate_base(base)

        self.print_delimiter()

        A = self.controller.convert_general(A, base)
        B = self.controller.convert_general(B, base)

        result, remainder = A // B
        print(A, "/", B, "=", str(result) + ", rest =", remainder)

    def convert_general(self):
        """
            Converts a number to a given base in the most optimal approach

            Raises:
                ValueError: if either the number or the base is wrong
        """
        A = input("Introduceti numarul A: ")
        A = parse_to_bignumber(A)
        validate_number(A)

        try:
            base = int(input("Introduceti baza destinatie: "))
        except ValueError:
            raise ValueError(
                "Baza trebuie sa fie din multimea {2, 3, 4, 5, 6, 7, 8, 9, 10, 16}"
            )
        validate_base(base)

        self.print_delimiter()

        self.controller.convert_general(A, base)

    def convert_intermediary(self):
        """
            Converts a number to a given base using an intermediary base

            Raises:
                ValueError: if either the number or the base is wrong
        """
        A = input("Introduceti numarul A: ")
        A = parse_to_bignumber(A)
        validate_number(A)

        try:
            intermediary_base = int(input("Introduceti baza intermediara: "))
        except ValueError:
            raise ValueError(
                "Baza trebuie sa fie din multimea {2, 3, 4, 5, 6, 7, 8, 9, 10, 16}"
            )
        validate_base(intermediary_base)

        try:
            base = int(input("Introduceti baza destinatie: "))
        except ValueError:
            raise ValueError(
                "Baza trebuie sa fie din multimea {2, 3, 4, 5, 6, 7, 8, 9, 10, 16}"
            )
        validate_base(base)

        self.print_delimiter()

        self.controller.convert_intermediary(A, base, intermediary_base)

    def convert_substitution(self):
        """
            Converts a number to a given base using the substitution method

            Raises:
                ValueError: if either the number or the base is wrong
                            if the number base is bigger than the given base
        """
        A = input("Introduceti numarul A: ")
        A = parse_to_bignumber(A)
        validate_number(A)

        try:
            base = int(input("Introduceti baza destinatie: "))
        except ValueError:
            raise ValueError(
                "Baza trebuie sa fie din multimea {2, 3, 4, 5, 6, 7, 8, 9, 10, 16}"
            )
        validate_base(base)

        self.print_delimiter()

        self.controller.convert_substitution(A, base)

    def convert_division(self):
        """
            Converts a number to a given base using the division method

            Raises:
                ValueError: if either the number or the base is wrong
                            if the number base is smaller than the given base
        """
        A = input("Introduceti numarul A: ")
        A = parse_to_bignumber(A)
        validate_number(A)

        try:
            base = int(input("Introduceti baza destinatie: "))
        except ValueError:
            raise ValueError(
                "Baza trebuie sa fie din multimea {2, 3, 4, 5, 6, 7, 8, 9, 10, 16}"
            )
        validate_base(base)

        self.print_delimiter()

        self.controller.convert_division(A, base)

    def convert_fast(self):
        """
            Converts a number to a given base using the fast conversion method

            Raises:
                ValueError: if either the number or the base is wrong
                            if the number base or the destination base are not powers of 2
        """
        A = input("Introduceti numarul A: ")
        A = parse_to_bignumber(A)
        validate_number(A)

        try:
            base = int(input("Introduceti baza destinatie: "))
        except ValueError:
            raise ValueError(
                "Baza trebuie sa fie din multimea {2, 3, 4, 5, 6, 7, 8, 9, 10, 16}"
            )
        validate_base(base)

        self.print_delimiter()

        self.controller.convert_fast(A, base)

    def print_menu(self):
        for id, task in self.menu.items():
            print(str(id) + '.' + task[1])

    def print_delimiter(self):
        print("-" * 30)

    def print_start_message(self):
        self.print_delimiter()
        print("Aplicatie realizata de Cazaciuc Valentin, grupa 211")
        print("Indicatii de utilizare:")
        print(
            "    -la fiecare iteratie va aparea un meniu; introduceti cifra sau litera respectiva si apasati Enter"
        )
        print(
            "    -cand aveti de introdus un numar, el trebuie sa fie de forma [numar(baza)]; de exemplu pentru a introduce pe 13 in baza 10 si 16 se va scrie 13(10), respectiv 13(16)"
        )
        print(
            "    -cand aveti de introdus o baza, ea trebuie sa fie de forma [baza]; de exemplu pentru baza 10 introduceti 10 si apasati Enter"
        )
        print(
            "    -daca se fac greseli(cum ar fi o baza diferita de cele posibile, un numar cu cifrele mai mari sau egale decat baza, caractere indisponibile sau format gresit) ele vor fi semnalate, iar programul va continua"
        )
        self.print_delimiter()

    def run(self):
        """
            Runs the console application

            Steps:
                -print menu
                -take input
                -call functions based on input
                -clear screen
        """
        self.print_start_message()
        self.is_running = True
        while self.is_running:
            self.print_menu()
            self.print_delimiter()
            cmd = input("Introduceti comanda: ").strip()
            try:
                self.menu[cmd][0]()
            except KeyError:
                print("Introduceti o comanda valida")
            except ValueError as error:
                print(error)
            cmd = input("Apasati tasta Enter pentru a continua...")
            #print("\n" * 20)
            if self.platform == "Windows":
                os.system("cls")
            else:
                os.system("clear")
class ControllerNode():
    def __init__(self):
        """Initialize a new controller instance."""
        self.freq = 100  # in Hz
        # self.s = 3  # battery configuration 3s/4s
        # self.v_c = 4.7  # voltage per lipo cell
        # self.v_s = self.s * self.v_c  # supply voltage
        # self.k_v = 580  # RPM/Volt e.g. MN3508 580/ MN3110 700Kv
        # self.idle_rpm = self.k_v * self.v_s  # idle RPM

        # An old regression model
        # self.prop_size = 13  # in inch
        # self.zero_rpm = 5974.71 - 350.00 * self.prop_size
        # half throttle RPM 4000
        # self.hover_rpm = 5974.71 - 350.00 * self.prop_size + 5340 * 0.5
        # full throttle RPM 6600
        # self.full_rpm = 5974.71 - 350.00 * self.prop_size + 5340 * 1

        self.zero_rpm = 2500
        self.hover_rpm = 2600
        self.full_rpm = 2800

        print("Controlling rpm between", self.zero_rpm, " and ", self.full_rpm)

        self.sub = rospy.Subscriber('/phoenix/imu', Imu, self.imu_callback)
        self.pub = rospy.Publisher('/phoenix/cmd_motor', MotorMessage)
        r = rospy.Rate(self.freq)

        self.drone = Drone()
        self.controller = Controller(self.drone)

        self.xdot_desired = np.zeros((3, 1))
        self.thetadot_desired = np.zeros((3, 1))

        self.last = rospy.get_time()

        while not rospy.is_shutdown():
            r.sleep()

    def imu_callback(self, imu_msg):
        """React on new imu measurements."""
        now = rospy.get_time()
        dt = now - self.last
        self.last = now

        # Update the drones internal state
        self.drone.thetadot[0] = imu_msg.angular_velocity.x
        self.drone.thetadot[1] = imu_msg.angular_velocity.y
        self.drone.thetadot[2] = imu_msg.angular_velocity.z

        self.drone.xdoubledot[0] = imu_msg.linear_acceleration.x
        self.drone.xdoubledot[1] = imu_msg.linear_acceleration.y
        self.drone.xdoubledot[2] = imu_msg.linear_acceleration.z

        self.drone.xdot = self.drone.xdot  # +self.drone.xdoubledot*dt

        # calculate motor commands
        cmds = self.controller.calculate_control_command(self.xdot_desired,
                                                         self.thetadot_desired.item(2))
        print("cmds", cmds)
        cmds = np.clip(cmds, 0, 3)
        print("clipped cmds", cmds)

        cmds = self.zero_rpm + cmds * (self.full_rpm - self.hover_rpm)
        cmds = np.clip(cmds, 2500, 2800)

        # publish MotorMessage to uart bridge
        motor_msg = MotorMessage()
        motor_msg.motor0 = cmds[0]  # Front left
        motor_msg.motor1 = cmds[1]  # Front right
        motor_msg.motor2 = cmds[2]  # Back left
        motor_msg.motor3 = cmds[3]  # Back right
        self.pub.publish(motor_msg)
Example #42
0
"""

"""
from maze import Maze
from nezha import Nezha
from controller import Controller

maze_list = [
    [1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1],
    [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
    [1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1],
    [1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1],
    [1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1],
    [1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1],
    [1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1],
    [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1],
    [1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1],
    [1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1],
    [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1],
    [1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1],
    [1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1],
]
Maze(maze_list)
nezha = Nezha(maze_list, 0, 5, 12, 7)
Controller(nezha.go_up, nezha.go_down, nezha.go_left, nezha.go_right)
Example #43
0
class Main:
    controller = Controller()
    controller.run()
    def __init__(
            self,
            experiment_name='test',
            multiplemode="no",  # yes or no
            enemies=[1],  # array with 1 to 8 items, values from 1 to 8
            loadplayer="yes",  # yes or no
            loadenemy="yes",  # yes or no
            level=2,  # integer
            playermode="ai",  # ai or human
            enemymode="static",  # ai or static
            speed="fastest",  # normal or fastest
            inputscoded="no",  # yes or no
            randomini="no",  # yes or no
            sound="on",  # on or off
            contacthurt="player",  # player or enemy
            logs="on",  # on or off
            savelogs="yes",  # yes or no
            clockprec="low",
            timeexpire=3000,  # integer
            overturetime=100,  # integer
            solutions=None,  # any
            player_controller=None,  # controller object
            enemy_controller=None):  # controller object

        # initializes parameters

        self.experiment_name = experiment_name
        self.multiplemode = multiplemode
        self.enemies = enemies
        self.enemyn = enemies[0]  # initial current enemy
        self.loadplayer = loadplayer
        self.loadenemy = loadenemy
        self.level = level
        self.playermode = playermode
        self.enemymode = enemymode
        self.speed = speed
        self.inputscoded = inputscoded
        self.randomini = randomini
        self.sound = sound
        self.contacthurt = contacthurt
        self.logs = logs
        self.savelogs = savelogs
        self.clockprec = clockprec
        self.timeexpire = timeexpire
        self.overturetime = overturetime
        self.solutions = solutions

        # initializes default random controllers

        if self.playermode == "ai" and player_controller == None:
            self.player_controller = Controller()
        else:
            self.player_controller = player_controller

        if self.enemymode == "ai" and enemy_controller == None:
            self.enemy_controller = Controller()
        else:
            self.enemy_controller = enemy_controller

        # initializes log file
        if self.logs == "on" and self.savelogs == "yes":
            file_aux = open(self.experiment_name + '/evoman_logs.txt', 'w')
            file_aux.close()

        # initializes pygame library
        pygame.init()
        self.print_logs("MESSAGE: Pygame initialized for simulation.")

        # initializes sound library for playing mode
        if self.sound == "on" and self.playermode == "human":
            pygame.mixer.init()
            self.print_logs("MESSAGE: sound has been turned on.")

        # initializes joystick library
        if self.playermode == "human":
            pygame.joystick.init()
            self.joy = pygame.joystick.get_count()

        self.clock = pygame.time.Clock()  # initializes game clock resource

        # generates screen
        if self.playermode == 'human':  # playing mode in fullscreen
            flags = DOUBLEBUF | FULLSCREEN
        else:
            flags = DOUBLEBUF

        self.screen = pygame.display.set_mode((736, 512), flags)

        self.screen.set_alpha(None)  # disables uneeded alpha
        pygame.event.set_allowed([QUIT, KEYDOWN,
                                  KEYUP])  # enables only needed events

        self.load_sprites()
Example #45
0
 def setUp(self):
     '''Method run before every test. Use this to prepare the test fixture.'''
     self.controller = Controller()
     self.w = self.controller.right_widget.automatic_mode.window
     Controller.allWidgets_setCheckable(self.controller.app)
from controller import Controller

controller = Controller()

count = 0

while count < 3:
    name = str(input("Digite o nome da música: "))
    author = str(input("Digite o nome do autor: "))
    genre = str(input("Digite o nome da (gênero): "))
    count = count+1
    controller.save(name, author, genre)
    pass
© 2020 GitHub, Inc.
Example #47
0
 def test_load_incorrect_file_format(self):
     controller = Controller()
     actual = controller.load_file("test.pdf")
     self.assertRaises(NameError, actual)
Example #48
0
 def test_load_file_not_found_exception(self):
     controller = Controller()
     actual = controller.load_file("C:\\Users\\Luna\\ICT\\test2.txt")
     self.assertRaises(FileNotFoundError, actual)
Example #49
0
 def users_by_tags(self):
     tags = Controller.get_value("Enter tags: ", str)
     res = self.__server.users_by_tags(tags)
     View.print_list("Users: ", res)
Example #50
0
 def Get_PhysicalPersonForID(id):
     pp = PhysicalPerson()
     pp.Id = id
     ctr = Controller(pp)
     result = ctr.Get_PhysicalPersonForID()
     return result
Example #51
0
 def test_load_txt_file3(self):
     controller = Controller()
     actual = controller.load_file("test3.txt")
     expected = [['class ToyBox {\n', '    name : String\n', '}\n'],
                 ['class Toy {\n', '    number: int\n', '}\n']]
     self.assertEqual(expected, actual)
Example #52
0
 def shortest_path(self):
     username1 = Controller.get_value("Enter first user: "******"Enter second user: ", str)
     res = self.__server.shortest_path(username1, username2)
     View.show_way(res)
Example #53
0
 def test_load_incorrect_file_exception(self):
     controller = Controller()
     actual = controller.load_file("test2.csv")
     self.assertRaises(NameError, actual)
Example #54
0
    BatchConverter(780, 200, 6, [1, 1, 1, 0, 0, 0, 0, 0], [link_2], "C", 70))
pipes.append(Pipe(800, 100, 20, 100, batchReactors[len(batchReactors) - 1]))
sources.append(ChemicalSource(800, 80, 0, [pipes[len(pipes) - 1]], 20, "C1"))
pipes.append(Pipe(500, 220, 280, 20, batchReactors[len(batchReactors) - 1]))
sources.append(ChemicalSource(480, 220, 1, [pipes[len(pipes) - 1]], 40, "C2"))
pipes.append(Pipe(940, 220, -100, 20, batchReactors[len(batchReactors) - 1]))
sources.append(ChemicalSource(940, 220, 2, [pipes[len(pipes) - 1]], 20, "C3"))

batchReactors.append(
    BatchConverter(620, 20, 7, [1, 1, 0, 0, 0, 0, 0, 0], [link_3], "D", 70))
pipes.append(Pipe(420, 40, 200, 20, batchReactors[len(batchReactors) - 1]))
sources.append(ChemicalSource(400, 40, 0, [pipes[len(pipes) - 1]], 20, "D1"))
pipes.append(Pipe(880, 40, -200, 20, batchReactors[len(batchReactors) - 1]))
sources.append(ChemicalSource(880, 40, 1, [pipes[len(pipes) - 1]], 40, "D2"))

controller = Controller(batchReactors, sources, pipes)
if enableLog:
    logger = Logger(logName, controller)

controller.updateControls([
    #							[BaR, Chm, Fuz, Src, Val],
    [4, 0, 1, 0, 0.5],
    [4, 0, 2, 0, 0.75],
    [4, 0, 1, 1, 0.5],
    [4, 0, 2, 1, 0.75],
    [4, 0, 1, 2, 0.5],
    [4, 0, 2, 2, 1],
    [4, 0, 1, 3, 0.5],
    [4, 0, 2, 3, 1],
    [4, 0, 1, 4, 0.5],
    [4, 0, 2, 4, 1],
Example #55
0
    def __init__(self):
        self.map = Map()
        self.map.random_map()

        self.controller = Controller(Drone(PARAM_BATTERY), self.map)
Example #56
0
def main():
    lqr.init()
    clock = pygame.time.Clock()

    pos = np.asmatrix([0., 1., 0.]).T
    vel = np.asmatrix([3., 0., 3.]).T

    visualizer = vis.Visualizer()

    fps = 60
    dt = 1.0 / fps
    t = 0.0
    i = 0

    maxon_motor = motor.Motor(
        resistance=1.03,
        torque_constant=0.0335,
        speed_constant=0.0335,
        rotor_inertia=135*1e-3*(1e-2**2))
    gearbox = motor.Gearbox(gear_ratio=20.0 / 60.0, gear_inertia=0)
    gear_motor = motor.GearMotor(maxon_motor, gearbox)
    our_robot = robot.Robot(
        robot_mass=6.5,
        robot_radius=0.085,
        gear_motor=gear_motor,
        robot_inertia=6.5*0.085*0.085*0.5,
        wheel_radius=0.029,
        wheel_inertia=2.4e-5,
        wheel_angles = np.deg2rad([45, 135, -135, -45]))
        # wheel_angles=np.deg2rad([60, 129, -129, -60]))

    controller = Controller(dt, our_robot)

    while not visualizer.close:
        visualizer.update_events()

        v = 3

        rx = np.asmatrix([np.sin(v * t), np.cos(v * t / 3), v * np.sin(t)]).T
        rv = v * np.asmatrix([np.cos(v * t), -np.sin(v * t / 3) / 3, np.cos(t)]).T
        ra = v ** 2 * np.asmatrix([-np.sin(v * t), -np.cos(v * t / 3) / 9, -np.sin(t) / v]).T

        vel_b = np.linalg.inv(rotation_matrix(pos[2,0])) * vel
        rv_b = np.linalg.inv(rotation_matrix(pos[2,0])) * rv

        rx_b = np.linalg.inv(rotation_matrix(pos[2,0])) * rx
        pos_b = np.linalg.inv(rotation_matrix(pos[2,0])) * pos

        # u = controller.feedforward_control(pos, vel, rx, rv, ra)
        state_vector = np.vstack((rx_b-pos_b,rv_b-vel_b))
        u = lqr.controlLQR(state_vector) # +=
        u = u[2:,0]
        # u = controller.control(pos, vel, rx, rv, ra)

        vdot_b = our_robot.forward_dynamics_body(vel_b, u)
        vdot = our_robot.forward_dynamics_world(pos, vel, u)

        # print(u - our_robot.inverse_dynamics_body(vel_b, vdot_b))

        robot.sysID(u[0,0], u[1,0], u[2,0], u[3,0], vel_b[0,0], vel_b[1,0], vel_b[2,0], vdot_b[0,0], vdot_b[1,0], vdot_b[2,0])
        
        visualizer.draw(pos, rx)
        pos += dt * vel + 0.5 * vdot * dt ** 2
        vel += dt * vdot
        # robot_data_line = [vdot_b[0,0], vdot_b[1,0], vdot_b[2,0], vel_b[0,0], vel_b[1,0], vel_b[2,0], u[0,0], u[1,0], u[2,0], u[3,0]]
        # robot_data.append(robot_data_line)

        clock.tick(60)
        t += dt
        i += 1
        if t > 20:
            print("t = 20")
            t = 0.0
            i = 0
            pos = np.asmatrix([0, 1, 0.]).T
            vel = np.asmatrix([3, 0, 3.]).T
            controller.reset()
    robot.main()
Example #57
0
    def __init__(self,
                 address,
                 port,
                 queue,
                 scope_on=False,
                 n_frames=100,
                 n_fft=1e3,
                 n_avg=10,
                 save_raw=False,
                 save_psd=True,
                 convert=None):
        """
        constructs the DAQ class, starts the logger

            args:
                address - (string) : string containing the IPv4 address of the controller, eg. '192.168.1.28'
                port - (int) : port number the controller is on, eg. 10000
                queue - (Queue) : queue object to write the data to in a thread safe way
                n_frames - (int) : number of frames to acquire each time the circular buffer is read out
                n_fft - (int) : number of frames in each PSD and CSV file
                scope_on - (bool) : boolean flag to specify if the scope is being used, if so puts the decoded frames in the queue
                save_raw - (bool) : boolean flag to specify if the raw traces (converted if conversions provided) are saved to a CSV file
                save_psd - (bool) : boolean flag to specify if the psd (converted if conversions provided) are saved to a CSV file
                convert - (None or dict) : optional parameter to pass that gives a conversion for variables if the key matches the controller
            returns:
                nothing
        """

        self.logger = logging.getLogger('vib_daq.daq.DAQ')
        self.ctrl = Controller(address, port)
        self.udbf = UDBF()

        #queue for storing the data
        self.queue = queue

        #boolean options which dictate behaviour of DAQ
        self.take_data = True
        self.paused = False
        self.scope_on = scope_on
        self.save_raw = save_raw
        self.save_psd = save_psd

        #optional conversion argument, either None or a dict
        self.convert = convert

        #parameters regarding the number of frames acquired and psd/file size
        self.n_frames = n_frames
        self.n_fft = n_fft
        self.n_avg = n_avg

        self.logger.info('Created DAQ successfully')

        #get the binary header from the controller
        bin_head = self.ctrl.acquire_head()

        #decode the binary header
        self.udbf.decode_header(bin_head)
        self.logger.info('Succesfully decoded binary header')

        #get sampling frequency
        self.fs = self.udbf.SampleRate
Example #58
0
 def __init__(self, n):
     self.__problem = Problem(n)
     self.__controller = Controller(self.__problem)
     self.__eaAverage = []
     self.__psoAverage = []
Example #59
0
x_test = x_test.astype('float32') / 255.
y_train = to_categorical(y_train, 10)
y_test = to_categorical(y_test, 10)

dataset = [x_train, y_train, x_test,
           y_test]  # pack the dataset for the NetworkManager

previous_acc = 0.0
total_reward = 0.0

with policy_sess.as_default():
    # create the Controller and build the internal policy network
    controller = Controller(policy_sess,
                            NUM_LAYERS,
                            state_space,
                            reg_param=REGULARIZATION,
                            exploration=EXPLORATION,
                            controller_cells=CONTROLLER_CELLS,
                            embedding_dim=EMBEDDING_DIM,
                            restore_controller=RESTORE_CONTROLLER)

# create the Network Manager
manager = NetworkManager(dataset,
                         epochs=MAX_EPOCHS,
                         child_batchsize=CHILD_BATCHSIZE,
                         clip_rewards=CLIP_REWARDS,
                         acc_beta=ACCURACY_BETA)

# get an initial random state space if controller needs to predict an
# action from the initial state
state = state_space.get_random_state_space(NUM_LAYERS)
print("Initial Random State : ", state_space.parse_state_space_list(state))
Example #60
0
from controller import Controller
from model import Model

if __name__ == "__main__":
    ''' Model creation. '''
    model = Model("source")
    ''' Controller creation. Use model as agruement. '''
    controller = Controller(model)
    ''' The start of console application. '''
    controller.start()
    ''' The save of the model. '''
    model.save()