Ejemplo n.º 1
0
def add_c0_pct_and_outcomes(
    tree_name,
    balanced_h5,
    component_df,
    tiebreak_node,
    weighted_status_flag,
    output_type,
):
    df_transpose = component_df.T
    start_status = datetime.now()
    c0_pct = calc_weighted_status(component_df, df_transpose, tiebreak_node,
                                  weighted_status_flag)
    print_timing_output("CALC_STATUS_TIME: (hh:mm:ss.ms)",
                        datetime.now() - start_status, output_type)
    df_dict_temp = {"% C0": c0_pct}

    mapping = list(balanced_h5["mapping_to_original"])
    df_dict_temp["Vert ID"] = [mapping[i] for i in component_df.index]
    assert len(mapping) == len(component_df.index)
    #print("ATTACHING OUTCOMES?")
    if "tree_bias_score" in balanced_h5.attrs:
        #print("YES")
        outcomes = list(balanced_h5["outcomes"])
        df_dict_temp["outcome"] = outcomes
        assert len(mapping) == len(outcomes)
    df = pd.DataFrame(
        df_dict_temp)  ### creates dataframe with status, node ID, and outcomes
    TimerManager.stopTimerX(0)
    print_timing_output("TOTAL_TIME: (hh:mm:ss.ms)",
                        str(TimerManager.getTimerXElapsed(0)), output_type)
    print("TOTAL_TIME: (hh:mm:ss.ms)", str(TimerManager.getTimerXElapsed(0)))
    return df
Ejemplo n.º 2
0
def process_turn(game: Board, players: list, player_turn: int,
                 timers: TimerManager, underlining):
    valid_move = False
    while not valid_move:
        if game.check_capacity() == 0:
            raise BoardFullError

        print("Current board:")
        game.print_board(underlining=underlining)

        timers.start_timer(players[player_turn])
        try:
            move = input(f"Player {players[player_turn]}, make your move:\n")
            move = move.split()
            if len(move) != 2:
                raise InvalidInputError
            game.set_tile(int(move[0]), int(move[1]), players[player_turn])
            valid_move = True
        except OccupiedSpaceError:
            print("Invalid move. That space is already occupied). Try again.")

        except InvalidInputError:
            print(
                "Invalid input. Please enter two coordinates (row & column) separated by a space."
            )

        else:
            timers.end_timer(players[player_turn])
            player_turn = player_turn + 1 if player_turn + 1 != len(
                players) else 0
            return player_turn
Ejemplo n.º 3
0
def main():
    running = True
    game = Board()
    player_turn = 0
    player_timers = TimerManager()

    while running:
        in_game = True

        # Initialize player list, board, and if the user's output supports underlining
        players = init_players()
        init_board(game)
        underlining = check_underlining()

        while in_game:
            try:
                # Processes the turn AND advances who's turn it is.
                player_turn = process_turn(game, players, player_turn,
                                           player_timers, underlining)
            except BoardFullError:
                print("All spaces have become occupied!")
                in_game = False

            else:
                if game.winner is not None:
                    in_game = False

        game.print_endscreen(player_timers)

        play_again = input(
            "Would you like to start a new game? (Enter 'yes' or 'y' if so)\n")
        if play_again.lower() not in ("yes", 'y'):
            running = False
            print("Terminating program. Thank you for playing!")
Ejemplo n.º 4
0
    def __init__(self, ssbot, md, config, MQueue):
        BotInterface.__init__(self, ssbot, md)
        ssbot.registerModuleInfo(
            __name__, "MasterBot", "The Junky",
            "Manages other bots (starts/stops/lists/etc)", "1.0d")
        self.config = config
        self._cmd_handlers = {
            #Cmd_ID,								  cmd_handler_func
            ssbot.registerCommand('!shutdown', None, 7, COMMAND_LIST_ALL, "Master", "", 'Shutdown the master'):
            self.HCShutdown,
            ssbot.registerCommand('!startbot', "!sb", 2, COMMAND_LIST_ALL, "Master", "[type] [arena]", '!startbot type arena'):
            self.HCStartBot,
            ssbot.registerCommand('!killbot', "!kb", 2, COMMAND_LIST_ALL, "Master", "[name]", 'Stop a specific bot'):
            self.HCStopBot,
            ssbot.registerCommand('!listbots', "!lb", 2, COMMAND_LIST_ALL, "Master", "", 'lists all currently running bots'):
            self.HCListBots,
            ssbot.registerCommand(
                '!listbottypes', "!lt", 2, COMMAND_LIST_ALL, "Master", "", '!lists all bot types currently defined in config file'):
            self.HCListBotTypes,
            ssbot.registerCommand('!reloadconf', "!rc", 3, COMMAND_LIST_ALL, "Master", "", 'reload json config file'):
            self.HCLoadConfig,
            ssbot.registerCommand(
                '!unloadmodule', "!um", 7, COMMAND_LIST_ALL, "Master", "[modulename]", 'unload a specific module from systems.module'):
            self.HCUnloadModule,
            ssbot.registerCommand(
                '!log', None, 2, COMMAND_LIST_PP, "Master", "[-clear]", 'default shows last 100 lines from the core logger'):
            self.HCLog
        }
        self._last_instance_id = 0
        self._instances = {}
        #this will copy all log entries to a list, so i can use it for !log
        self.max_recs = 40
        self.listhandler = ListHandler(logging.DEBUG, self.max_recs)
        formatter = logging.Formatter(
            '%(asctime)s:%(name)s:%(levelname)s:%(message)s')
        self.listhandler.setFormatter(formatter)
        self.listhandler.LoadFromFile(os.path.join(os.getcwd(), "Bots.log"))
        self.logger.addHandler(self.listhandler)

        self.logger.info("Master Bot Started")
        if len(config.MasterChats) > 0:
            ssbot.addChat(config.MasterChats)

        self.__queue = MQueue
        self.reactor = None

        self.tm = TimerManager()
Ejemplo n.º 5
0
    def print_endscreen(self, timer_data: TimerManager):
        timers = timer_data.get_timers()

        print()
        print(" --- GAME OVER! ---")
        self.print_board()
        winner = self.winner if self.winner is not None else "Nobody"
        print(f"{winner} won the game!\n"
              "Statistics:\n"
              f"\tMoves made: {self._moves}")
        print("\tHow long players spent making moves:")
        for player, time in timers.items():
            print(f"\t\t{player}: {time:.3f} seconds")
Ejemplo n.º 6
0
def main():
    opening()

    name = 'User'
    prompt = '\n' + name + ': '
    programIsRunning = True

    manager = TimerManager()
    parser = Parser(manager)

    manager.loadData()
    while programIsRunning:
        command = input(prompt)
        parser.parse(command)
        manager.saveData()
Ejemplo n.º 7
0
    execute_jobs_by_config_file(config_obj, True)


def execute_jobs_by_config_file(config_obj, index_run_flag):
    # jobID's: 0 means do it on current machine, None means don't do it (already done or not requested), any other positive integer means do it on LEAP
    if not index_run_flag:
        output_path = get_output_file_path(config_obj)
        set_output_location(config_obj, output_path)
    preprocess_jobID = submit_preprocess_job(config_obj)
    process_jobID = submit_process_job(config_obj, preprocess_jobID)
    postprocess_jobID = submit_postprocess_job(config_obj, process_jobID)


if __name__ == "__main__":

    TimerManager.addTimer("global")
    TimerManager.startTimerX(0)

    if len(sys.argv) == 1:
        config_file_options_list = get_all_config_file_options()
        for index, config_file_option in enumerate(config_file_options_list):
            print(index, " ---> ", config_file_option)
        print()
        print("Legend: (dataset, data_subset_type, matrix_name)")
    else:
        if str(sys.argv[1]).isdigit():
            config_file_option = int(sys.argv[1])
            execute_jobs_by_config_file_index(config_file_option)
        else:
            config_path = str(sys.argv[1])
            config_obj = get_yaml_config_obj_by_path(config_path)
Ejemplo n.º 8
0
class Bot(BotInterface):
    def __init__(self, ssbot, md, config, MQueue):
        BotInterface.__init__(self, ssbot, md)
        ssbot.registerModuleInfo(
            __name__, "MasterBot", "The Junky",
            "Manages other bots (starts/stops/lists/etc)", "1.0d")
        self.config = config
        self._cmd_handlers = {
            #Cmd_ID,								  cmd_handler_func
            ssbot.registerCommand('!shutdown', None, 7, COMMAND_LIST_ALL, "Master", "", 'Shutdown the master'):
            self.HCShutdown,
            ssbot.registerCommand('!startbot', "!sb", 2, COMMAND_LIST_ALL, "Master", "[type] [arena]", '!startbot type arena'):
            self.HCStartBot,
            ssbot.registerCommand('!killbot', "!kb", 2, COMMAND_LIST_ALL, "Master", "[name]", 'Stop a specific bot'):
            self.HCStopBot,
            ssbot.registerCommand('!listbots', "!lb", 2, COMMAND_LIST_ALL, "Master", "", 'lists all currently running bots'):
            self.HCListBots,
            ssbot.registerCommand(
                '!listbottypes', "!lt", 2, COMMAND_LIST_ALL, "Master", "", '!lists all bot types currently defined in config file'):
            self.HCListBotTypes,
            ssbot.registerCommand('!reloadconf', "!rc", 3, COMMAND_LIST_ALL, "Master", "", 'reload json config file'):
            self.HCLoadConfig,
            ssbot.registerCommand(
                '!unloadmodule', "!um", 7, COMMAND_LIST_ALL, "Master", "[modulename]", 'unload a specific module from systems.module'):
            self.HCUnloadModule,
            ssbot.registerCommand(
                '!log', None, 2, COMMAND_LIST_PP, "Master", "[-clear]", 'default shows last 100 lines from the core logger'):
            self.HCLog
        }
        self._last_instance_id = 0
        self._instances = {}
        #this will copy all log entries to a list, so i can use it for !log
        self.max_recs = 40
        self.listhandler = ListHandler(logging.DEBUG, self.max_recs)
        formatter = logging.Formatter(
            '%(asctime)s:%(name)s:%(levelname)s:%(message)s')
        self.listhandler.setFormatter(formatter)
        self.listhandler.LoadFromFile(os.path.join(os.getcwd(), "Bots.log"))
        self.logger.addHandler(self.listhandler)

        self.logger.info("Master Bot Started")
        if len(config.MasterChats) > 0:
            ssbot.addChat(config.MasterChats)

        self.__queue = MQueue
        self.reactor = None

        self.tm = TimerManager()

    def setReactor(self, reactor):
        self.reactor = reactor

    def GetBotConfig(self, btype):
        for b in self.config.Bots.values():
            if b.Type.lower() == btype.lower():
                return b
        else:
            return None

    def GenerateValidNames(self, btype):
        bconfig = self.GetBotConfig(btype)
        maxbots = bconfig.MaxBots
        validnames = []
        name = bconfig.Name
        if (maxbots > 1):
            for i in range(1, maxbots):
                validnames.append(name + str(i))
        else:
            validnames.append(name)
        return validnames

    def StopAllBots(self):
        for k, v in self._instances.iteritems():
            if v.is_alive() == 1:
                v.RequestStop()
                self.logger.critical("Requested Stop for " + v.bname)

    def DeleteInactiveBots(self):
        keys2del = []
        for k, v in self._instances.iteritems():
            if v.is_alive() == 1:
                pass
            else:
                keys2del.append(k)
        for k in keys2del:
            del self._instances[k]

    def HCShutdown(self, ssbot, event):
        self.StopAllBots()
        ssbot.sendReply(event, "ok")
        self.logger.critical("Master is being Shutdown command issued by: " +
                             event.pname)
        self.tm.set(10, (3, None))

    def StartBot(self, ssbot, pname, btype, arena, args):
        bconfig = self.GetBotConfig(btype)
        if bconfig != None:
            validname = None
            for n in self.GenerateValidNames(btype):
                if (n.lower() in self._instances):
                    continue
                else:
                    validname = n
                    break
            if (validname != None):
                self._last_instance_id += 1
                newbot = BotInstance(self._last_instance_id, bconfig.Type,
                                     bconfig.Description, pname, validname,
                                     bconfig.Password,
                                     bconfig.ConfigurationFile,
                                     self.config.Host, self.config.Port, arena,
                                     bconfig.Modules, self.__queue, args,
                                     logging.getLogger("ML." + bconfig.Type))
                self._instances[newbot.bname.lower()] = newbot
                newbot.AddToReactor(self.reactor)
                self.logger.info("%s started to %s by %s" %
                                 (bconfig.Type, arena, pname))
                return 1  #success
            else:
                return -2  #all bots of type used
        else:
            return -1  #type not found

    def HCStartBot(self, ssbot, event):
        self.DeleteInactiveBots()
        if len(event.arguments) >= 2:
            btype = event.arguments[0]
            arena = event.arguments[1]
            args = event.arguments_after[2] if len(event.arguments) > 2 else ""
            r = self.StartBot(ssbot, event.pname, btype, arena, args)
            if r == 1:
                ssbot.sendReply(event, "ok")
            elif r == -1:
                ssbot.sendReply(event, "Error:type(%s) not found" % (type))
            elif r == -2:
                ssbot.sendReply(event, "all %s in use" % (type))
        else:
            ssbot.sendReply(event, "Usage: !startbot type arena")

    def HCStopBot(self, ssbot, event):
        if (len(event.arguments) == 1
                and event.arguments[0].lower() in self._instances):
            b = self._instances[event.arguments[0].lower()]
            b.RequestStop()
            ssbot.sendReply(event, "Stop Requested")
            self.logger.info("%s killed %s (Stop Requested)", event.pname,
                             event.arguments[0])
        else:
            ssbot.sendReply(event, "Bot Not Found")

    def HCListBots(self, ssbot, event):
        c = 0
        for v in self._instances.values():
            ssbot.sendReply(
                event, "ID:%3i Type:%6s Name:%20s Arena:%10s alive:%i" %
                (v.id, v.type, v.bname, v.arena, v.is_alive()))
            c += 1
        if c == 0:
            ssbot.sendReply(event, "No Active Bots")

    def HCListBotTypes(self, ssbot, event):
        if len(event.arguments) == 1:
            b = self.config.Bots.get(event.arguments[0].lower(), None)
            if b:
                ssbot.sendReply(event, "Type: " + b.Type)
                ssbot.sendReply(event, "Description: " + b.Description)
                ssbot.sendReply(event, "BotBaseName: " + b.Name)
                ssbot.sendReply(event, "TotalBots: " + str(b.MaxBots))
                ssbot.sendReply(event, "ConfigFile: " + b.ConfigurationFile)
                txt = ""
                c = 0
                ssbot.sendReply(event, "-" * 10 + "Modules" + "-" * 10)
                for b in b.Modules:
                    if c != 0 and c % 2 == 0:
                        ssbot.sendReply(event, "Modules:" + txt[1:])
                        txt = ""
                    txt += "," + b[0]
                    c += 1

                if len(txt) > 0:
                    ssbot.sendReply(event, "Modules:" + txt[1:])
            else:
                ssbot.sendReply(
                    event, "Error:type(%s) not found" % (event.arguments[0]))
        else:
            c = 0
            txt = ""
            for b in self.config.Bots.values():
                c += 1
                if (c % 5 == 0):
                    ssbot.sendReply(event, "Types:" + txt[1:])
                    txt = ""
                txt += "," + b.Type

            if len(txt) > 0:
                ssbot.sendReply(event, "Types:" + txt[1:])
            if c == 0:
                ssbot.sendReply(event, "No Bot Types Defined")

    def HCUnloadModule(self, ssbot, event):
        if len(event.arguments) > 0:
            name = event.arguments[0]
            if name in sys.modules:
                del sys.modules[name]
                ssbot.sendReply(event, "module unloaded")
            else:
                ssbot.sendReply(event, "module not found")
        else:
            ssbot.sendReply(event, "invalid syntax")

    def HCLog(self, ssbot, event):
        if len(event.arguments) > 0 and event.arguments[0].lower() == "-clear":
            self.listhandler.Clear()
            ssbot.sendReply(event, "on screen log cleared")
        else:
            for r in self.listhandler.GetEntries():
                ssbot.sendReply(event, r)

    def HCLoadConfig(self, ssbot, event):
        try:
            oc = copy.deepcopy(self.config)
            self.config.Load()
            ssbot.sendReply(event, "Config Reloaded")
            self.logger.info("config file reloaded by %s" % (event.pname, ))
        except:
            self.config = oc
            ssbot.sendReply(event, "failure, still using old configuration")

    def HandleEvents(self, ssbot, event):
        if event.type == EVENT_COMMAND and event.command.id in self._cmd_handlers:
            self._cmd_handlers[event.command.id](ssbot, event)
        elif event.type == EVENT_LOGIN:
            self.tm.set(
                10, (2, None)
            )  # for periodic deleting of inactive bots and removing of old list entries from log
            c = 60  #wait for bot to login
            for b in self.config.AutoLoad:  #stagger the bots to load by 180 sec each
                c += 180
                self.tm.set(c, (1, b))
                self.logger.info("Queued:[Sb] %s -> %s" % b)
        elif event.type == EVENT_TICK:
            self.SendBroadcastsToAttachedBots(ssbot)
            #self.logger.info("tick")
            timer_expired = self.tm.getExpired()  # a timer expired
            if timer_expired:
                #self.logger.info("timer expired")

                if timer_expired.data[0] == 1:  #start a bot
                    t = timer_expired.data[1]
                    #ssbot.sendPublicMessage("!sb %s %s" % t)
                    r = self.StartBot(ssbot, ssbot.name, t[0], t[1], "")
                    if r == 1:
                        ssbot.sendPublicMessage(
                            "autospawn:successfull spawned %s to %s" % t)
                    elif r == -1:
                        ssbot.sendPublicMessage(
                            "autospawn:Error:type(%s) not found" % (t[0]))
                    elif r == -2:
                        ssbot.sendPublicMessage("autospawn:all %s in use" %
                                                (t[0]))
                elif timer_expired.data[0] == 2:  #do maintenance
                    self.DeleteInactiveBots()
                    self.listhandler.RemoveOld()
                    self.tm.set(10, (2, None))
                elif timer_expired.data[0] == 3:  #shutdown
                    self.logger.info("calling disconnect")
                    ssbot.disconnectFromServer()
                    #ssbot.stopReactor()

    def SendBroadcastsToAttachedBots(self, ssbot):
        if self.__queue.size() > 0:  # broadcasts waiting
            b = self.__queue.dequeue()
            while b:  #broadcasts waiting
                for bot in self._instances.values():
                    if bot.is_alive():
                        bot.queueBroadcast(b)  #all attached bots
                ssbot.queueBroadcast(b)  #modules attached to master
                b = self.__queue.dequeue()  #will return None if there are none

    def Cleanup(self):
        pass