Exemple #1
0
def main():
    # Create Problem
    polynomial = Polynomial(num_terms=5, num_dimensions=2)
    log.info(polynomial)

    # Define Search Range
    search_range = SearchRange()
    search_range.set_feasible_range(10000, 2)

    # Solvers
    # brute_force_solver = BruteForceSolver(search_range)
    genetic_algorithm_solver = GeneticAlgorithmSolver(search_range)

    gui = Gui(polynomial, search_range)
    # benchmark = Benchmark([brute_force_solver, genetic_algorithm_solver])
    benchmark = Benchmark([genetic_algorithm_solver])

    # Benchmark
    benchmark.evaluate(polynomial)

    # Visualize Solvers
    # gui.create_animation(brute_force_solver)
    animation = gui.create_animation(genetic_algorithm_solver)

    # Create Default Visual
    # gui.plot_problem()
    gui.show()
Exemple #2
0
def start_gui():
    board = GuiBoard(9, 9)
    strategy = Strategy()
    p1 = GuiHuman('x', board)
    p2 = Computer('0', board, strategy)
    game = GuiGame(p1, p2, board)
    root = tkinter.Tk()
    my_gui = Gui(root, game)
    root.mainloop()
Exemple #3
0
 def setUp(self):
     from gui.gui import Gui
     self.gui = Gui()
     self.panel = self.gui.create(Panel)
     self.panel.rect = Rect(50, 80, 100, 120)
     self.panel.padding = Rect(2, 3, 5, 11)
     self.panel.margins = Rect(17, 23, 29, 37)
     self.panel.layout_dirty = False
     self.gui.world.layout_dirty = False
Exemple #4
0
    def __init__(self):
        self._detect = GPIODetect(self.gpio_detect)
        self._detect.setup()
        self._detect.detct()
        self._sysInfo.setcommCallback(self.get_system_info)
        # DBG("Welcome to Controller!")
        self._scannerble = ScannerBLE(self.scanner_comm, "hci0")

        self._gui = Gui(self.gui_comm)
        # 注册信号处理函数
        self._thread.signal.connect(self.update_ui)
        self._thread.start()
        self._gui.start_gui()
Exemple #5
0
def main():
    while True:
        gui = Gui()
        game = Game(gui)
        gui.player_bet.destroy()
        for widget in gui.player_info_frame.winfo_children():
            widget.destroy()
        new_round = messagebox.askquestion("New game?")
        if new_round == "no":
            gui.root.destroy()
            break
        else:
            gui.root.destroy()
    return
Exemple #6
0
    def __init__(self):
        # register signal handler
        signal.signal(signal.SIGINT, self._signal_handler)
        signal.signal(signal.SIGTERM, self._signal_handler)

        # flag for activity before quit
        self.is_running = True
        self.is_sig = False

        # user's attributes
        self.nick = None
        self.ip = None
        self.port = None

        # create Hnefatafl
        self.hnef = Hnefatafl()

        # create client network
        self.net = Network(self)

        # create gui
        self.gui = Gui(self)
Exemple #7
0
def main():
    os.environ.setdefault("INFERENCE_SETTINGS_MODULE", "settings")
    arg_list = ["read", "test"]
    parser = argparse.ArgumentParser(prog="manage.py", description="Inference:\
            a tool to infer missing data from its context")
    parser.add_argument("-i", "--data", help="File name of the data file stored in data/",
            type=str, action="store", default=False)
    parser.add_argument("-u", "--upload", help="Add this to upload data through the gui",
            action="store_true")
    parser.add_argument("-t", "--test", help="Runs all tests. For develpment use only", 
            action="store_true")
    args = parser.parse_args()
    if not args.data and args.upload:
        # start gui uploader
        root = tk.Tk()
        root.title("Iference")
        root.geometry('500x500')
        gui = Gui(master=root)
        gui.mainloop()
    if args.data:
        # start some work with the data
        data = Data(args.data)
        data.load_data()
Exemple #8
0
    parser.add_argument("-s",
                        "--speed",
                        type=float,
                        help="simulation speed, default = 1",
                        default=1)
    parser.add_argument("--fps",
                        help="frames per second, default=30",
                        type=int,
                        default=30)
    args = parser.parse_args()
    pygame.init()
    speed = args.speed
    fps = args.fps
    parameters = SimulationParameters()
    world = World(parameters.options["world_pixel_size"],
                  parameters.options["world_nrof_tiles"])
    creature_manager = CreatureManager(parameters.options["nrof_creatures"],
                                       world)
    statistics = Statistics(creature_manager)
    clock = pygame.time.Clock()
    gui = Gui(1000, 600, creature_manager, world, clock, statistics, speed)
    main_loop()
    #cProfile.run("main_loop()")
"""
TODO: Implement Pause function
TODO: Implement Neural Network Viewer
TODO: Partial Screen udpates
TODO: Collect all variables/constants and make them be changeable by parameter or a file
TODO: Creature vision viewer
TODO: Something about the borders
"""
Exemple #9
0
'''
BLACK-AND-WHITE
WinterSalmon
Main
'''

from gui.gui import Gui
from cli.cli import Cli

if __name__ == "__main__":
    # if pygame is not installed run game in commandline mode
    try:
        UI = Gui()
    except ImportError:
        UI = Cli()
    UI.init_screen()
    UI.game_screen()
    UI.credit_screen()
Exemple #10
0
def run_benchmark(root_folder, times, feasible_ranges, polynomial=None):
    if not os.path.exists(root_folder):
        log.info('Creating Folder')
        os.makedirs(root_folder)

    # Create Problem
    if not polynomial:
        polynomial = Polynomial(num_terms=5, num_dimensions=2)

    log.info(polynomial)

    for feasible_range in feasible_ranges:
        search_range = SearchRange()
        search_range.set_feasible_range(feasible_range, 2)
        folder = os.path.join(root_folder,
                              'feasible_range_{}'.format(feasible_range))
        solution_payload = {}

        if not os.path.exists(folder):
            os.mkdir(folder)

        for i in range(times):
            # Create Folder
            run_folder = os.path.join(folder, 'run_{}'.format(i))

            if not os.path.exists(run_folder):
                os.mkdir(run_folder)

                # Solvers
                brute_force_solver = BruteForceSolver(search_range)
                genetic_algorithm_solver = GeneticAlgorithmSolver(search_range)

                solvers = [brute_force_solver, genetic_algorithm_solver]

                # Benchmark
                benchmark = Benchmark(solvers)
                benchmark.evaluate(polynomial)

                # Add to Benchmark
                for solver in solvers:
                    metric = benchmark.get_metrics(solver._id)
                    add_to_benchmark_payload(solution_payload, solver, metric)

                # Save Animations
                gui = Gui(polynomial, search_range)
                genetic_animation = gui.create_animation(
                    genetic_algorithm_solver)
                genetic_animation.save(os.path.join(run_folder, 'genetic.gif'),
                                       writer='imagemagick',
                                       fps=30)

                brute_animation = gui.create_animation(brute_force_solver)
                brute_animation.save(os.path.join(run_folder, 'brute.gif'),
                                     writer='imagemagick',
                                     fps=30)

                # Save Problem
                figure, plot = gui.plot_problem()
                figure.savefig(os.path.join(run_folder, 'problem.png'))

                # Pickle benchmark && solvers && polynomial
                pickle_object(
                    genetic_algorithm_solver,
                    os.path.join(run_folder, 'genetic_solver.pickle'))
                pickle_object(brute_force_solver,
                              os.path.join(run_folder, 'brute_solver.pickle'))
                pickle_object(benchmark,
                              os.path.join(run_folder, 'brute_solver.pickle'))
                pickle_object(gui, os.path.join(run_folder, 'gui.pickle'))

                # Clear Matplotlib figures
                gui.close()

            pickle_object(solution_payload,
                          os.path.join(folder, 'benchmark.pickle'))
Exemple #11
0
def main(stdscr):
    from gui.gui import Gui
    log.init()
    Gui(stdscr)
Exemple #12
0
from gui.gui import Gui

if __name__ == '__main__':
    app = Gui()
    app.mainloop()
Exemple #13
0
def main():

    ui = Gui()
    ui.mainloop()
from gui.threadgui import ThreadGui
from camera.camera import Camera
from camera.threadcamera import ThreadCamera
from detector.detector import Detector
from detector.threaddetector import ThreadDetector
import signal

signal.signal(signal.SIGINT, signal.SIG_DFL)

if __name__ == '__main__':

    camera = Camera()
    print(camera)

    app = QtGui.QApplication(sys.argv)
    window = Gui(camera)

    detector = Detector(camera, window)
    print(detector)

    t_cam = ThreadCamera(camera)
    t_cam.start()

    t_detector = ThreadDetector(detector)
    t_detector.start()

    window.setCamera(camera, t_cam)
    window.show()
    window.setDetector(detector, t_detector)
    window.show()
Exemple #15
0
import sys
import argparse

from PyQt5.QtWidgets import QApplication
from gui.gui import Gui

app = QApplication(sys.argv)
app.setOrganizationDomain('rahmedov.com')
app.setObjectName('rahmedov')
app.setApplicationName('rahmedov')
app.setApplicationVersion('0.0.0')

parser = argparse.ArgumentParser(description='Home')
parser.add_argument('-r', '--root', type=str, default='', help='''Root Path''')

args = parser.parse_args()

g = Gui(root=args.root, parent=None)

g.show()
sys.exit(app.exec_())
Exemple #16
0
    await run_tk(root)


if __name__ == "__main__":
    data = Data([150, 41], [540, 386])
    # address = "A6C01837-C772-4ED8-9984-5A006FA27336"
    # address = "0880E3E7-E6A4-4367-A655-9C6E130303A9"
    address = "C0:98:E5:49:00:00"

    parser = argparse.ArgumentParser()
    parser.add_argument('--thread', action='store_true', default=False)
    parser.add_argument('--ble_debug', action='store_true', default=False)
    parser.add_argument('--gui_debug', action='store_true', default=False)
    args = parser.parse_args()

    root = Gui(data, args.gui_debug)
    ble_comm = BleComm(address)

    if not args.thread:
        loop = asyncio.get_event_loop()
        loop.run_until_complete(main_async(root, ble_comm, args.ble_debug))

    else:
        cv_client = CV_Detector(data)
        t1 = Thread(target=cv_client.run_cv)
        t1.setDaemon(True)
        t1.start()

        loop = asyncio.get_event_loop()
        loop.run_until_complete(main_async(root, ble_comm, args.ble_debug))
        t1.join()
Exemple #17
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--p0-agent",
        type=str,
        choices=['static', 'rule', 'random', 'alphasheep', 'user'],
        required=True)
    parser.add_argument(
        "--alphasheep-checkpoint",
        help="Checkpoint for AlphaSheep, if --p0-agent=alphasheep.",
        required=False)
    parser.add_argument(
        "--agent-config",
        help="YAML file, containing agent specifications for AlphaSheep.",
        required=False)
    args = parser.parse_args()
    agent_choice = args.p0_agent
    as_checkpoint_path = args.alphasheep_checkpoint
    as_config_path = args.agent_config
    if agent_choice == "alphasheep" and (not as_checkpoint_path
                                         or not as_config_path):
        raise ValueError(
            "Need to specify --alphasheep-checkpoint and --agent-config if --p0_agent=alphasheep."
        )

    # Init logging and adjust log levels for some classes.
    init_logging()
    logger = get_named_logger("{}.main".format(
        os.path.splitext(os.path.basename(__file__))[0]))
    get_class_logger(GameController).setLevel(
        logging.DEBUG)  # Log every single card.
    get_class_logger(Gui).setLevel(logging.DEBUG)  # Log mouse clicks.
    get_class_logger(RuleBasedAgent).setLevel(
        logging.DEBUG)  # Log decisions by the rule-based players.

    # Create the agent for Player 0.
    if agent_choice == "alphasheep":

        # Load config. We ignore the "training" and "experiment" sections, but we need "agent_config".
        logger.info(f'Loading config from "{as_config_path}"...')
        config = load_config(as_config_path)
        get_class_logger(DQNAgent).setLevel(logging.DEBUG)  # Log Q-values.
        alphasheep_agent = DQNAgent(0, config=config, training=False)
        alphasheep_agent.load_weights(as_checkpoint_path)
        p0 = Player("0-AlphaSheep", agent=alphasheep_agent)
    elif agent_choice == "user":
        p0 = Player("0-User", agent=GUIAgent(0))
    elif agent_choice == "rule":
        p0 = Player("0-Hans", agent=RuleBasedAgent(0))
    elif agent_choice == "static":
        p0 = Player("0-Static", agent=StaticPolicyAgent(0))
    else:
        p0 = Player("0-RandomGuy", agent=RandomCardAgent(0))

    # Players 1-3 are RuleBasedAgents.
    players = [
        p0,
        Player("1-Zenzi", agent=RuleBasedAgent(1)),
        Player("2-Franz", agent=RuleBasedAgent(2)),
        Player("3-Andal", agent=RuleBasedAgent(3))
    ]

    # Rig the game so Player 0 has the cards to play a Herz-Solo.
    # Also, force them to play it.
    game_mode = GameMode(GameContract.suit_solo,
                         trump_suit=Suit.herz,
                         declaring_player_id=0)
    controller = GameController(players,
                                dealing_behavior=DealWinnableHand(game_mode),
                                forced_game_mode=game_mode)

    # The GUI initializes PyGame and registers on events provided by the controller. Everything single-threaded.
    #
    # The controller runs the game as usual. Whenever the GUI receives an event, it can block execution, so the controller must wait
    # for the GUI to return control. Until then, it can draw stuff and wait for user input (mouse clicks, card choices, ...).
    logger.info("Starting GUI.")
    with Gui(controller.game_state) as gui:
        # Run an endless loop of single games.
        logger.info("Starting game loop...")
        try:
            while True:
                controller.run_game()
        except UserQuitGameException:  # Closing the window or pressing [Esc]
            logger.info("User quit game.")

    logger.info("Shutdown.")
Exemple #18
0
import sys
from PyQt4 import QtGui
from gui.gui import Gui
from gui.threadgui import ThreadGui
from camera.camera import Camera
from camera.threadcamera import ThreadCamera
import signal

signal.signal(signal.SIGINT, signal.SIG_DFL)

if __name__ == '__main__':

    camera = Camera()
    print(camera)
    app = QtGui.QApplication(sys.argv)
    window = Gui()
    window.setCamera(camera)
    window.show()

    t1 = ThreadCamera(camera)
    t1.start()

    t2 = ThreadGui(window)
    t2.start()

    sys.exit(app.exec_())
Exemple #19
0
import PySimpleGUI as sg
import traceback
import sys

from common.handleconfig import HandleConfig
from gui.gui import Gui

Version = '4.6'

if len(sys.argv) <= 1:
    # normal start, run with a gui
    # cmd:python D:\Projects\ExcelToDatabase\main.py
    # exe:ExcelToDatabase.exe
    sg.ChangeLookAndFeel('dark')
    HandleConfig = HandleConfig()
    Gui = Gui()

    def exception_format():
        # format exception output
        return "".join(
            traceback.format_exception(sys.exc_info()[0],
                                       sys.exc_info()[1],
                                       sys.exc_info()[2],
                                       limit=-1))

    default_values = HandleConfig.get_defaults()
    window = sg.Window('ExcelToDatabase {0}'.format(Version),
                       Gui.generate_layout(),
                       location=(700, 50))

    while True: