Example #1
0
 def __init__(self, title_txt="File Browser", button_txt="Okay", cls="filedialog", path=None):
     if not path: self.curdir = os.getcwd()
     else: self.curdir = path
     import app
     self.dir_img = basic.Image(app.App.app.theme.get(cls+'.folder', '', 'image'))
     td_style = {'padding_left': 4,
                 'padding_right': 4,
                 'padding_top': 2,
                 'padding_bottom': 2}
     self.title = basic.Label(title_txt, cls=cls+".title.label")
     self.body = table.Table()
     self.list = area.List(width=350, height=150)
     self.input_dir = input.Input(cls=cls+".input")
     self.input_file = input.Input(cls=cls+".input")
     self._list_dir_()
     self.button_ok = button.Button(button_txt)
     self.body.tr()
     self.body.td(basic.Label("Path", cls=cls+".label"), style=td_style, align=-1)
     self.body.td(self.input_dir, style=td_style)
     self.body.tr()
     self.body.td(basic.Label("File", cls=cls+".label"), style=td_style, align=-1)
     self.body.td(self.input_file, style=td_style)
     self.body.td(self.button_ok, style=td_style)
     self.body.tr()
     self.body.td(self.list, colspan=3, style=td_style)
     self.list.connect(CHANGE, self._item_select_changed_, None)
     self.button_ok.connect(CLICK, self._button_okay_clicked_, None)
     self.value = None
     Dialog.__init__(self, self.title, self.body)
Example #2
0
def get_input_instance():
    init()
    input_instance = input.Input(tokens, train_string_input,
                                 train_binary_result, test_string_input,
                                 test_binary_result)

    return input_instance
Example #3
0
 def __init__(self, tx):
     self.version = version.Version(tx)
     self.input_count = input_count.InputCount(tx)
     if self.input_count.value == 0:
         self.segwit = segwit.Segwit(tx)
         self.input_count = input_count.InputCount(tx)
     else:
         self.segwit = None
     self.inputs = []
     for i in range(self.input_count.value):
         self.inputs.append(input.Input(tx))
     self.output_count = output_count.OutputCount(tx)
     self.outputs = []
     for i in range(self.output_count.value):
         self.outputs.append(output.Output(tx))
     if self.segwit is not None:
         for i in range(self.input_count.value):
             self.witness_count = witness_count.WitnessCount(tx)
             self.witnesss = []
             if self.witness_count != 0:
                 for i in range(self.witness_count.value):
                     self.witnesss.append(witness.Witness(tx))
             else:
                 self.witnesss.append(None)
     self.locktime = locktime.Locktime(tx)
Example #4
0
    def parcours(self):
        pos = 0
        pos = self.version.parcours(pos, self)
        pos = self.inputCount.parcours(pos, self)
        for i in range(self.inputCount.decimal):
            self.input = input.Input()
            pos = self.input.txid.parcours(pos, self)
            pos = self.input.vout.parcours(pos, self)
            d = pos
            pos = self.input.scriptSigSize.parcours(pos, self)
            self.input.scriptSig.length = int(self.raw[d:pos], 16)
            pos = self.input.scriptSig.parcours(pos, self)
            pos = self.input.sequence.parcours(pos, self)
            self.inputs.append(self.input)

        if pos != len(self.raw):
            pos = self.outputCount.parcours(pos, self)
            for i in range(self.outputCount.decimal):
                self.output = output.Output()
                pos = self.output.value.parcours(pos, self)
                d = pos
                pos = self.output.scriptPubKeySize.parcours(pos, self)
                self.output.scriptPubKey.length = int(self.raw[d:pos], 16)
                pos = self.output.scriptPubKey.parcours(pos, self)
                self.outputs.append(self.output)

        if pos != len(self.raw):
            pos = self.locktime.parcours(pos, self)
Example #5
0
    def __init__(self):
        self.WINDOWWIDTH, self.WINDOWHEIGHT = (600, 800)
        input.Input.winSize = [self.WINDOWWIDTH, self.WINDOWHEIGHT]

        self.screen = pygame.display.set_mode(
            (self.WINDOWWIDTH, self.WINDOWHEIGHT))
        self.FPSClock = pygame.time.Clock()
        self.FPS = 60
        self.input = input.Input()
        sound.muted = False

        self.IMAGESCALEUP = 4

        self.screenShakeOffset = [0, 0]

        self.grey = (60, 60, 60)
        self.white = (250, 250, 250)
        self.lightgrey = (170, 170, 170)
        self.yellow = (255, 223, 134)

        self.scoreValues = {
            'shoot bomb': 20,
            'shoot superBomb': 30,
            'destroy bomber': 200
        }
Example #6
0
def main(_):

    config = cf.Config()
    eval_config = cf.Config()
    eval_config.batch_size = 1
    eval_config.num_steps = 1
    train_data, valid_data, test_data, _ = ip.get_raw_data(config.data_path)
    with tf.Graph().as_default():
        initializer = tf.random_uniform_initializer(-config.init_scale, config.init_scale)

        with tf.name_scope("Train"):
            train_input = ip.Input(config=config, data=train_data, name="TrainInput")
            with tf.variable_scope("Model", reuse=None, initializer=initializer):
                m = lm.LMModel(is_training=True, config=config, inputs=train_input)
            tf.summary.scalar("Training Loss", m.cost)
            tf.summary.scalar("Training Rate", m.lr)

        with tf.name_scope("Valid"):
            valid_input = ip.Input(config=config, data=valid_data, name="ValidInput")
            with tf.variable_scope("Model", reuse=True, initializer=initializer):
                mvalid = lm.LMModel(is_training=False, config=config, inputs=valid_input)
            tf.summary.scalar("Validation Loss", mvalid.cost)

        with tf.name_scope("Test"):
            test_input = ip.Input(config=eval_config, data=test_data, name="TestInput")
            with tf.variable_scope("Model", reuse=True, initializer=initializer):
                mtest = lm.LMModel(is_training=False, config=eval_config, inputs=test_input)

        sv = tf.train.Supervisor(logdir=config.save_path)
        config_proto = tf.ConfigProto(allow_soft_placement=False)

        with sv.managed_session(config=config_proto) as session:
            for i in range(config.max_epoch):
                lr_decay = config.lr_decay ** max(i + 1 - config.lr_const_epoch, 0)
                m.update_lr(session, config.learning_rate * lr_decay)

                print("Epoch: %d Learning rate: %.3f" % (i + 1, session.run(m.lr)))
                train_perplexity = run_epoch(session, m, eval_op=m.optim, verbose=True)
                print("Epoch: %d Train Perplexity: %.3f" % (i + 1, train_perplexity))
                valid_perplexity = run_epoch(session, mvalid)
                print("Epoch: %d Valid Perplexity: %.3f" % (i + 1, valid_perplexity))

            test_perplexity = run_epoch(session, mtest)
            print("Test Perplexity: %.3f" % test_perplexity)

            print("Saving model to %s." % config.save_path)
            sv.saver.save(session, config.save_path, global_step=sv.global_step)
Example #7
0
    def __init__(self,
                 title_txt="File Browser",
                 button_txt="Okay",
                 cls="dialog",
                 path=None):
        """FileDialog constructor.

        Keyword arguments:
            title_txt -- title text
            button_txt -- button text
            path -- initial path

        """

        cls1 = 'filedialog'
        if not path: self.curdir = os.getcwd()
        else: self.curdir = path
        self.dir_img = basic.Image(
            pguglobals.app.theme.get(cls1 + '.folder', '', 'image'))
        td_style = {
            'padding_left': 4,
            'padding_right': 4,
            'padding_top': 2,
            'padding_bottom': 2
        }
        self.title = basic.Label(title_txt, cls=cls + ".title.label")
        self.body = table.Table()
        self.list = area.List(width=350, height=150)
        self.input_dir = input.Input()
        self.input_file = input.Input()
        self._list_dir_()
        self.button_ok = button.Button(button_txt)
        self.body.tr()
        self.body.td(basic.Label("Folder"), style=td_style, align=-1)
        self.body.td(self.input_dir, style=td_style)
        self.body.tr()
        self.body.td(self.list, colspan=3, style=td_style)
        self.list.connect(CHANGE, self._item_select_changed_, None)
        self.button_ok.connect(CLICK, self._button_okay_clicked_, None)
        self.body.tr()
        self.body.td(basic.Label("File"), style=td_style, align=-1)
        self.body.td(self.input_file, style=td_style)
        self.body.td(self.button_ok, style=td_style)
        self.value = None
        Dialog.__init__(self, self.title, self.body)
Example #8
0
 def __init__(self):
     print 'Initializing game.'
     #using pygame
     pygame.init()
     self.clock = pygame.time.Clock()
     self.paddle = o.Paddle()
     self.ball = o.Ball()
     self.block_container = o.BlockContainer()
     self.screen = s.Screen(pygame)
     self.input = i.Input(pygame)
 def __init__(self, data):
     super().__init__()
     self.controller = input.Input()
     self.controllers = []
     self.mode = "controller"
     self.joyInstruct = pygame.image.load(
         os.path.join('assets', 'controller.png'))
     self.keyInstruct = pygame.image.load(
         os.path.join('assets', 'keyboard.png'))
     pygame.joystick.init()
     for i in range(pygame.joystick.get_count()):
         pygame.joystick.Joystick(i).init()
Example #10
0
 def __init__(self, data_path):
     dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
     self.input_device = input.Input()
     self.hid_device = bt_hid.BluetoothHID(data_path)
     self.hid_device.init()
     self.input_device.register_callbacks(self.key_callback,
                                          self.mouse_move_callback,
                                          self.mouse_button_callback,
                                          self.mouse_wheel_callback)
     self.clients = {}
     self.client = None
     self.active_keys = set()
     self.ignore_keys = set()
 def processEvent(self, data, event):
     if event.type == pygame.JOYBUTTONUP:
         if len(
                 self.controllers
         ) < 2 and event.button == 1 and event.joy not in self.controllers:
             self.controllers.append(event.joy)
     elif event.type == pygame.KEYDOWN:
         if event.key == pygame.K_k:
             self.mode = "keyboard"
         elif event.key == pygame.K_j:
             self.mode = "controller"
         elif event.key == pygame.K_RETURN:
             if self.mode == "controller" and len(self.controllers) == 2:
                 data.scene = game.Game(data, [
                     input.Input(joystick=pygame.joystick.Joystick(j))
                     for j in self.controllers
                 ])
             elif self.mode == "keyboard":
                 data.scene = game.Game(data, [
                     input.Input(input.KEYBOARD_P1),
                     input.Input(input.KEYBOARD_P2)
                 ])
Example #12
0
 def __init__(self):
     """Start the program"""
     #sound.startMusic()
     pygame.display.set_caption('Juggleball')
     screen.fill((135, 206, 250))
     pygame.display.update()
     pygame.time.wait(400)
     self.input = input.Input()
     self.mode = 'menu'
     self.menu = MenuScreen('Press SPACE to play Juggleball')
     FPSClock.tick(60)
     self.highScore = 0
     self.isFirstGame = True
     sound.play('whoosh')
Example #13
0
 def __init__(self, data):
     super().__init__()
     self.logo = pygame.image.load(os.path.join('assets', 'logo.png'))
     self.logoRect = self.logo.get_rect()
     self.logoRect.center = (data.width / 2, data.height / 3)
     self.caption = data.font.render("Press Enter to Start !", True,
                                     (255, 255, 255))
     self.captionRect = self.caption.get_rect()
     self.captionRect.center = (data.width / 2, data.height * 2 / 3)
     self.help = data.font.render("Press H for instructions", True,
                                  (255, 255, 255))
     self.helpRect = self.help.get_rect()
     self.helpRect.bottomright = (data.width - 10, data.height - 5)
     self.controller = input.Input()
     self.exitCount = 0
Example #14
0
    def __init__(self):
        pyxel.init(constants.GAME_WIDTH,
                   constants.GAME_HEIGHT,
                   caption=constants.GAME_TITLE,
                   fps=constants.GAME_FPS,
                   scale=constants.GAME_SCALE)

        pyxel.load(constants.RESOURCE_FILE)
        pyxel.image(0).load(0, 0, constants.IMAGE_BANK_0_FILE)

        self.input = input.Input()
        self.game = game.Game()
        pyxel.mouse(False)
        #pyxel.mouse(True)

        pyxel.run(self.update, self.draw)
Example #15
0
    def __init__(self):
        if not WINDOWEDMODE:
            screenInfo = pygame.display.Info()
            self.WINDOWWIDTH, self.WINDOWHEIGHT = (screenInfo.current_w,
                                                   screenInfo.current_h)
            self.screen = pygame.display.set_mode(
                (self.WINDOWWIDTH, self.WINDOWHEIGHT), FULLSCREEN)
        if WINDOWEDMODE:
            self.WINDOWWIDTH, self.WINDOWHEIGHT = (1450, 1050)
            self.screen = pygame.display.set_mode(
                (self.WINDOWWIDTH, self.WINDOWHEIGHT))
        self.gameSurf = pygame.Surface(self.screen.get_size())
        self.gameSurf.convert()

        self.FPS = 60
        self.FPSClock = pygame.time.Clock()
        self.FPSClock.tick(self.FPS)  # so the first dt value isnt really weird

        self.input = input.Input()
        self.keybinds = {
            'left': [K_LEFT, K_a],
            'right': [K_RIGHT, K_d],
            'jump': [K_SPACE, K_UP, K_w],
            'pull': [K_LSHIFT, K_LCTRL]
        }

        self.currentLevel = 0  # TEMP FOR TESTING should normally be = 0
        self.CELLSIZE = 64

        self.TIMESTEP = 1.0 / self.FPS
        self.PPM = float(self.CELLSIZE)

        self.WHITE = (255, 255, 255)
        self.BLACK = (0, 0, 0)
        self.RED = (220, 20, 20)
        self.SKYBLUE = (135, 206, 250)
        self.DARKBLUE = (0, 35, 102)
        self.YELLOW = (255, 255, 102)
        self.DARKYELLOW = (204, 204, 0)
        self.GREEN = (110, 255, 100)
        self.ORANGE = (255, 165, 0)
        self.DARKGREY = (60, 60, 60)
        self.LIGHTGREY = (180, 180, 180)
        self.CREAM = (255, 255, 204)
Example #16
0
	def __init__ (self, w, h, titulo):
		pygame.init()
		window 			= pygame.display.set_mode((w, h), HWSURFACE|DOUBLEBUF) 
		pygame.mouse.set_visible(False)

		self.nome 		= titulo
		self.dimensoes 	= [w, h]
		self.tela 		= pygame.display.get_surface() 
		self.layers		= [[],[],[],[],[],[]]
		self.loop 		= 1
		self.sprites 	= {}
		self.clock		= 1
		self.input		= input.Input(self)
		self.clock 		= pygame.time.get_ticks()
		self.lastUpdate = self.clock
		self.conteiner	= {}
		self.grupocolisao = []
		self.colisao = colisao.Colisao(self)
		print "-- Engine Carregada"
Example #17
0
def main(stdscr):
    curses.curs_set(0)
    stdscr.noutrefresh()

    main_input = input.Input(stdscr)

    main_map = map.Map(100, 100, rooms=20)

    player = entity.Entity(*main_map.room_list[0].center.point)
    main_map.put_entity(player)

    map_display = display.DisplayMapScroll(main_map,
                                           player,
                                           20, 80,
                                           150, 150)

    hook_display = display.DisplayHook(map_display,
                                       Orientation.bottom,
                                       4, 20)
    hook_to_hook_display = display.DisplayHook(hook_display,
                                               Orientation.right,
                                               4, 10)

    map_display.refresh_map()
    hook_display.refresh()
    hook_to_hook_display.refresh()
    Display.update()

    done = False
    while not done:
        key = main_input.get_move_key()
        main_map.erase_entity(player)
        player.move(key)

        main_map.put_entity(player)
        hook_display.print_screen(str(player.pos.point), 0, 0)

        map_display.refresh_map()
        Display.update()

        if key == entity.Move.done:
            done = True
def get_input_instance(items_kfold_str, with_recipe):
    global items_kfold
    global is_with_recipe

    items_kfold = items_kfold_str
    is_with_recipe = with_recipe

    init()

    # tokens,
    # trainStrInput,
    # trainBinaryResult,
    # testStrInput,
    # testBinaryResult
    input_instance = input.Input(fill_tokens(), fill_string_input('true'),
                                 fill_binary_result('true'),
                                 fill_string_input('false'),
                                 fill_binary_result('false'))

    return input_instance
Example #19
0
 def __init__(self,
              title="",
              default="",
              editable=True,
              special_button=None):
     self.list = area.List(width=350, height=150)
     self.list.connect(CHANGE, self.itemClicked, None)
     self.journalItems = []
     okButton = button.Button("Okay",
                              style={
                                  'width': 80,
                                  'height': 28,
                                  'margin': 8
                              })
     okButton.connect(CLICK, self.okayClicked)
     cancelButton = button.Button("Cancel",
                                  style={
                                      'width': 80,
                                      'height': 28,
                                      'margin': 8
                                  })
     cancelButton.connect(CLICK, self.close)
     self.input_item = input.Input(default)
     self.input_item.connect(CHANGE, self.itemTyped, None)
     self.input_item.disabled = not editable
     body = table.Table()
     body.tr()
     body.td(basic.Label(title), colspan=2)
     body.tr()
     body.td(self.list, colspan=2)
     body.tr()
     if special_button:
         body.td(self.input_item, colspan=1)
         body.td(special_button, colspan=1)
     else:
         body.td(self.input_item, colspan=2)
     body.tr()
     body.td(okButton)
     body.td(cancelButton)
     Dialog.__init__(self, basic.Label(title), body)
Example #20
0
def main():
    '''
    shape
    (2, 6)
    statistics
            District  Latitude  Longitude
    count   2.000000       2.0        2.0
    mean   11.500000       0.0        0.0
    std     9.192388       0.0        0.0
    min     5.000000       0.0        0.0
    25%     8.250000       0.0        0.0
    50%    11.500000       0.0        0.0
    75%    14.750000       0.0        0.0
    max    18.000000       0.0        0.0
    data samples 10 rows
                                        Date     Description  District Primary Type  Latitude  Longitude
    idx
    2017-04-01 11:05:00  04/01/2017 11:05:00 AM   FROM BUILDING        18        THEFT       0.0        0.0
    2017-03-20 21:05:00  03/20/2017 09:05:00 PM  $500 AND UNDER         5        THEFT       0.0        0.0
                                        Date     Description  District Primary Type  Latitude  Longitude
    idx
    2017-04-01 11:05:00  04/01/2017 11:05:00 AM   FROM BUILDING        18        THEFT       0.0        0.0
    2017-03-20 21:05:00  03/20/2017 09:05:00 PM  $500 AND UNDER         5        THEFT       0.0        0.0
    '''
    path = r"src\crime.csv"
    iii = input.Input(path)

    row_num = 10000
    col_name = [
        'Date', 'Description', 'District', 'Primary Type', 'Latitude',
        'Longitude'
    ]
    year = 2017
    nan_not_allowed = 1
    primary_type = 'THEFT'
    time_range = ['2017-03-20', '2017-4-01']
    arrest = 2
    s = iii.data_extract(row_num, col_name, year, nan_not_allowed,
                         primary_type, time_range, arrest)
    print(s)
Example #21
0
def main_loop():
    global silence_time
    button = io.Input()
    #debug_point = 1397 # debug

    while True:
        #shift_data = closest_checkpoint(debug_point)
        shift_data = closest_checkpoint()
        print('#### MAIN LOOP ####')
        print(shift_data)

        while shift_data['check_time']:
            time_now = get_int_time_now()
            #time_now = 1398
            if shift_data['stop'] > time_now:
                beep(B_WARN)
            elif shift_data['stop'] == time_now:
                beep(B_FAIL)
                print('SYSTEM IN PAUSE FOR 60 SECONDS DUE TO SHIFT FAIL')
                time.sleep(60)
                break

            if button.watch_file() == HIGH:
                beep(B_OK)
                delay_time = ((shift_data['stop'] - time_now) + 1) * 60
                print('SYSTEM IN PAUSE FOR {} SECONDS'.format(delay_time))
                # force pause until check_time is false, avoiding this loop
                #time.sleep(10)
                time.sleep(delay_time)
                debug_point = 1402  # debug
                break

        time.sleep(.4)

        # 1 - if it's checkpoint time, set flag with start and keep warning period
        # 2 - keep checking for input HIGH or LOW, while beep(B_WARN)
        # 3 - keep checking for end warning period
        """ new_input = button.watch_file()   
Example #22
0
def run():
	my.input = input.Input()
	menu = MainMenu()
	my.transition = -1 # fade between menus/game states
	if my.gameRunning: # debug mode is enabled
		handler = logic.Handler()
	else:
		pygame.time.wait(600) # pause for effect

	while True: # main game loop
	
		deltaTime = my.FPSCLOCK.tick(my.FPS)
		if my.gameRunning:
			handler.update(deltaTime / 1000.0) # update the game
	
		else: # display menu
			nextMenu = menu.update()

			if nextMenu == 'main':
				menu = MainMenu()
			elif nextMenu == 'embark':
				menu = EmbarkMenu()
			elif nextMenu == 'credits':
				menu = CreditsMenu()
			elif nextMenu == 'quit':
				my.input.terminate()
			elif nextMenu == 'play':
				handler = logic.Handler() # start a new game

		if my.transition == 'begin': 
			my.transition = 255
		if my.transition > 0:
			my.transition -= 3 * deltaTime / 17
			my.lastSurf.set_alpha(my.transition)
			my.screen.blit(my.lastSurf, (0, 0))

		pygame.display.update()
		pygame.display.set_caption('Aedificus: Fathers of Rome' + ' ' * 10 + 'FPS: ' + str(int(my.FPSCLOCK.get_fps())))
Example #23
0
 def __init__(self):
     self.game_state = self.State.INITIALIZING
     os.environ["SDL_VIDEO_CENTERED"] = "1"
     pygame.init()
     self.frame_timer = pygame.time.Clock()
     self.input_handler = input.Input()
     self.input_handler.add_listener(self)
     self.main_menu = menu.Menu()
     self.main_menu.add_listener(self)
     self.file_handler = filehandler.FileHandler()
     self.settings = {"GridWidth": 10, "GridHeight": 10, "MineCount": 20}
     proposed_grid_width = self.file_handler.get_setting("GridWidth", 5, 35)
     if proposed_grid_width != None:
         self.settings["GridWidth"] = proposed_grid_width
     proposed_grid_height = self.file_handler.get_setting(
         "GridHeight", 5, 30)
     if proposed_grid_height != None:
         self.settings["GridHeight"] = proposed_grid_height
     proposed_mine_count = self.file_handler.get_setting(
         "MineCount", 1,
         self.settings["GridWidth"] * self.settings["GridHeight"] - 1)
     if proposed_mine_count != None:
         self.settings["MineCount"] = proposed_mine_count
Example #24
0
 def make_input(self,name,value,zero_after=None):
     self.add(input.Input(name,value,zero_after=zero_after))
Example #25
0
def run_training():
    """Train MNIST for a number of steps."""
    # Tell TensorFlow that the model will be built into the default Graph.
    with tf.Graph().as_default():
        # Generate placeholders for the images and labels.
        state_placeholder, action_placeholder = placeholder_inputs()
        game = input.Input(3, 2)

        def multilayer_perceptron(_X, _weights, _biases):
            layer_1 = tf.nn.relu(
                tf.add(tf.matmul(_X, _weights['h1']), _biases['b1']))
            layer_2 = tf.nn.relu(
                tf.add(tf.matmul(layer_1, _weights['h2']), _biases['b2']))
            return tf.matmul(layer_2, _weights['out']) + _biases['out']

        # Store layers weight & bias
        weights = {
            'h1': tf.Variable(tf.random_normal([75, 75])),
            'h2': tf.Variable(tf.random_normal([75, 40])),
            'out': tf.Variable(tf.random_normal([40, 3]))
        }
        biases = {
            'b1': tf.Variable(tf.random_normal([75])),
            'b2': tf.Variable(tf.random_normal([40])),
            'out': tf.Variable(tf.random_normal([3]))
        }

        # Construct model
        pred = multilayer_perceptron(state_placeholder, weights, biases)

        # Add to the Graph the Ops for loss calculation.
        loss = arch.loss(pred, action_placeholder)

        # Add to the Graph the Ops that calculate and apply gradients.
        train_op = arch.training(loss, FLAGS.learning_rate)

        # Build the summary operation based on the TF collection of Summaries.
        r = []
        l = []
        x = []
        t = []
        summary_op = tf.merge_all_summaries()

        # Add the variable initializer Op.
        init = tf.initialize_all_variables()

        # Create a saver for writing training checkpoints.
        saver = tf.train.Saver(tf.all_variables())

        # Create a session for running Ops on the Graph.
        sess = tf.Session()

        # Instantiate a SummaryWriter to output summaries and the Graph.
        summary_writer = tf.train.SummaryWriter(FLAGS.train_dir, sess.graph)

        # And then after everything is built:

        # Run the Op to initialize the variables.
        sess.run(init)

        #ckpt = tf.train.get_checkpoint_state(FLAGS.train_dir)
        #if ckpt and ckpt.model_checkpoint_path:
        #  print('Loading ' + ckpt.model_checkpoint_path)
        #  # Restores from checkpoint
        #saver.restore(sess, "data/model_1.ckpt")
        model_num = 0  #int(ckpt.model_checkpoint_path.split("_")[1].split(".")[0]) + 1
        print(model_num)
        epsilon = 1
        wins = 0
        game_length = np.zeros(100)
        avg_score = np.zeros(100)
        xs = 0
        steps = 0
        avg_loss = np.zeros(100)
        avg_loss.fill(100)
        avg_score.fill(-100)
        print('Start Training...')
        # Start the training loop.
        for step in xrange(EPOCHS):
            #start_time = time.time()
            game.restart()
            status = 1
            turns = 0
            print("Game #: " + str(step), end="")
            while status == 1:
                #We are in state S
                #Let's run our Q function on S to get Q values for all possible actions
                state = game.grid()
                qval = sess.run(
                    pred, feed_dict={state_placeholder: state.reshape(1, 75)})

                if (random.random() < epsilon):  #choose random action
                    action = np.random.randint(0, 3)
                else:  #choose best action from Q(s,a) values
                    action = (np.argmax(qval))
                #Take action, observe new state S'
                game.move(action)
                new_state = game.grid()
                #Observe reward
                reward = game.reward()

                #Get max_Q(S',a)
                newQ = sess.run(
                    pred,
                    feed_dict={state_placeholder: new_state.reshape(1, 75)})
                maxQ = np.max(newQ)
                y = np.zeros((1, 3))
                y[:] = qval[:]

                if reward < -1:  #non-terminal state
                    update = (reward + (GAMMA * maxQ))
                else:  #terminal state
                    update = reward
                y[0][action] = update  #target output

                feeddict = fill_feed_dict(state.reshape(1, 75), y,
                                          state_placeholder,
                                          action_placeholder)
                _, loss_value = sess.run([train_op, loss], feed_dict=feeddict)
                avg_loss[turns % 100] = loss_value * 100
                turns += 1
                if game.total_out(-1) + game.pits != 3:
                    game.display()
                    print('pits')
                    print(turns)
                if game.total_out(1) + game.goals != 2:
                    game.display()
                    print('goals')
                    print(turns)
                if reward < -1 or turns >= TURN_BOUNDRY:
                    status = 0

            print(" - Turns: %d" % (turns), end="")
            print(" - EC: %.2f" % (game.total_score))
            if len(game_length) >= 100:
                game_length[steps % 100] = turns
                avg_score[steps % 100] = game.total_score
            else:
                game_length.append(turns)
                avg_score.append(game.total_score)
            if turns >= 1000:
                wins += 1
            if epsilon > 0.001:
                epsilon -= (1 / EPOCHS)

            #duration = time.time() - start_time

            if step == 0 or (step + 1) % 100 == 0:
                # Print status to stdout.
                print(
                    'Step %d: loss = %.2f, avg game len = %.2f, avg score = %.2f, wins = %d'
                    % (step, np.mean(avg_loss), np.mean(game_length),
                       np.mean(avg_score), wins))
                # Update the events file.
                #summary_str = sess.run(summary_op, feed_dict=feeddict)
                #summary_writer.add_summary(summary_str, step)

            if step == 0 or (step + 1) % 10 == 0:
                r.append(np.mean(avg_score))
                l.append(np.mean(avg_loss))
                t.append(np.mean(game_length))
                xs += 1
                x.append(xs * 10)

            if (step + 1) % (1000) == 0:
                save_path = saver.save(
                    sess, "data/model_" + str(model_num) + ".ckpt")
                print("Model saved in file: %s" % save_path)
                model_num += 1
                turns = 0
                game.restart()
                status = 1
                while status == 1:
                    game.display()
                    #We are in state S
                    #Let's run our Q function on S to get Q values for all possible actions
                    state = game.grid()
                    qval = sess.run(
                        pred,
                        feed_dict={state_placeholder: state.reshape(1, 75)})

                    if (random.random() < epsilon):  #choose random action
                        action = np.random.randint(0, 3)
                        print('r')
                    else:  #choose best action from Q(s,a) values
                        action = (np.argmax(qval))
                        print('c')
                    #Take action, observe new state S'
                    game.move(action)
                    new_state = game.grid()
                    #Observe reward
                    reward = game.reward()
                    turns += 1
                    if reward < -1 or turns >= 100:
                        status = 0
                game.display
                print(turns, game.total_score)

            steps += 1
            if wins > 0:
                r.append(np.mean(avg_score))
                l.append(np.mean(avg_loss))
                t.append(np.mean(game_length))
                xs += 1
                x.append(xs * 10)
                break

    print(r, l, t, x)
    plt.plot(x, l, 'b')
    plt.plot(x, r, 'r')
    plt.plot(x, t, 'g')
    plt.axis([0, 1000, -100, 2000])
    plt.show()
Example #26
0
 def __init__(self):
     super().__init__()
     self.help = pygame.image.load(os.path.join('assets', 'help.jpg'))
     self.y = 0
     self.controller = input.Input()
Example #27
0
def load(inputPath, configPath):
    '''
    Populates input parameters via YAML input; converts and validates parameters.

    Input(s): inputPath (str), configPath (str) \n
    Output(s): <none>
    '''

    # YAML parse
    configDict = util_yaml.load(configPath)
    inputDict = util_yaml.load(inputPath)
    inputDict = util_yaml.process(inputDict)

    # Instantiate input object
    inp = input.Input()

    # Param config: min, max, quantity

    for group in configDict.keys():
        for param in configDict[group].keys():
            for field in configDict[group][param].keys():

                value = configDict[group][param][field]
                setattr(getattr(getattr(inp, group), param), field, value)

    # Param assignment: value, unit, dist

    for group in inputDict.keys():
        for param in inputDict[group].keys():

            # Multiple fields specified by user
            if (isinstance(inputDict[group][param], dict)):

                for field in inputDict[group][param].keys():

                    value = inputDict[group][param][field]
                    setattr(getattr(getattr(inp, group), param), field, value)

            # Only "value" is specified by user
            else:

                value = inputDict[group][param]
                getattr(getattr(inp, group), param).value = value

    # Param conversion & validation
    util_unit.config()

    for group in inputDict.keys():
        for param in inputDict[group].keys():

            obj = getattr(getattr(inp, group), param)

            if (isinstance(obj, input.Param)):

                obj.value = util_unit.convert(obj.value, obj.quantity,
                                              obj.unit)

                print("value: ", obj.value)

                cond = obj.check_value()

            elif (isinstance(obj, input.Name)):
                cond = obj.check_path()

            print(param + ": ", cond)
 def readFile(self):
     # Reading the graph from the input file
     self.graphInput = input.Input()
     self.graphInput.readFile('input.json')
 def __init__(self):
     self.WINDOWWIDTH, self.WINDOWHEIGHT = (1200, 800)
     self.screen = pygame.display.set_mode(
         (self.WINDOWWIDTH, self.WINDOWHEIGHT))
     self.FPSClock = pygame.time.Clock()
     self.input = input.Input()
Example #30
0
 def __init__(self, data, game):
     self.game = game
     self.controller = input.Input()
     self.overlay = pygame.Surface((data.width, data.height))
     self.overlay.set_alpha(150)