Ejemplo n.º 1
0
 def __init__(self, master=None):
     tk.Frame.__init__(self, master)
     self.master.title("NN - Creator")
     self.grid(sticky=tk.N + tk.S + tk.E + tk.W)
     self.master.title('Sample application')
     self.master.geometry = self.center(HEIGHT, WIDTH)
     self.main_canvas = 0
     self.param_canvas = 0
     self.layers_canvas = 0
     self.network_canvas = 0
     self.score_canvas = 0
     self.alfa_spinner = 0
     self.act_combox = 0
     self.loss_combox = 0
     self.init_combox = 0
     self.opotim_combox = 0
     self.epoch_spinner = 0
     self.batch_spinner = 0
     self.laycnt_spinner = 0
     self.train_btn = 0
     self.draw_btn = 0
     self.load_entry = 0
     self.load_checkbox = 0
     self.save_entry = 0
     self.save_checkbox = 0
     self.lay_btn = 0
     self.plot_tk = None
     self.top_level1 = 0
     self.progress_bar = 0
     self.nr_spin = []
     self.layer_lab = []
     self.network_model = Network_model()
     self.controller = Controller()
     self.createWidgets()
Ejemplo n.º 2
0
 def startGUI(self):
     """
     Starts the BiBler application with the GUI. 
     """
     app = wx.App(False)
     self.control = Controller()
     self.gui = BiBlerGUI(self.control)
     self.control.bindGUI(self.gui)
     self.control.bindApp(self.app)
     self.control.start()
     app.MainLoop()
Ejemplo n.º 3
0
	def human(self, config: Config) -> None:
		assert isinstance(config.white, HumanAgent)

		# agents
		black = self.black
		white = config.white
		# reset agents
		black.reset()
		white.reset()
		print(f'\nHUMAN\n\t{black}\n\t{white}\n')

		for episode in tqdm(range(1, config.num_episodes + 1)):
			# create new game
			game: Game = Game(self.board_size, self.black, config, episode)
			# let black begin
			# get legal actions
			legal_actions: Actions = game.board.get_legal_actions(game.agent.color)
			location, legal_directions = game.agent.next_action(game.board, legal_actions)
			game.board.take_action(location, legal_directions, game.agent.color)
			# create GUI controller
			controller: Controller = Controller(game, self.black)
			# play game
			controller.start()

		# print score
		ties: int = config.num_episodes - black.num_games_won - white.num_games_won
		win_ratio: float = black.num_games_won / config.num_episodes * 100
		print(
			f'({black.num_games_won:>4}|{white.num_games_won:>4}|{ties:>4}) / {config.num_episodes:>4} -> win ratio: {win_ratio:>6.2f} %')
Ejemplo n.º 4
0
 def __init__(self, root, executor, root_directory):
     self.root_directory = root_directory
     self.model = Model(root_directory)
     self.controller = Controller(self.model, root)
     self.view = View(root, self.model, executor, self.controller)
     super(PicCollector, self).__init__()
     self.model.load_model()
     self.model.load_imagedata()
     self.view.setup_view()
Ejemplo n.º 5
0
def edit_directory(astergui, directory):
    """
    Edit Input or Output directory

    Arguments:
        astergui (AsterGui): AsterGui instance.
        directory (Directory): *Directory* object.
    """
    if directory is None:
        return
    try:
        case = directory.case
        dir_type = directory.dir_type
        path = directory.directory
        is_in_dir = dir_type == Directory.InDir
        operation_name = translate("AsterStudy", "Set-up directories")
        ctr = Controller(operation_name, astergui)
        if ctr.controllerStart():
            path = get_directory(astergui.mainWindow(), path, is_in_dir)
            if path:
                if is_in_dir:
                    out_dir = case.out_dir
                    if out_dir is not None and same_path(path, out_dir):
                        message = translate(
                            "DirsPanel", "Input and output "
                            "directories cannot be the same")
                        raise ValueError(message)
                    if is_subpath(path, out_dir) or is_subpath(out_dir, path):
                        message = translate(
                            "DirsPanel", "Input and output "
                            "directories cannot be sub-path "
                            "of each other")
                        raise ValueError(message)
                    if not os.path.exists(path):
                        message = translate(
                            "DirsPanel", "Input directory '{}'"
                            " does not exist").format(path)
                        raise ValueError(message)
                else:
                    in_dir = case.in_dir
                    if in_dir is not None and same_path(path, in_dir):
                        message = translate(
                            "DirsPanel", "Input and output "
                            "directories cannot be the same")
                        raise ValueError(message)
                    if is_subpath(path, in_dir) or is_subpath(in_dir, path):
                        message = translate(
                            "DirsPanel", "Input and output "
                            "directories cannot be sub-path "
                            "of each other")
                        raise ValueError(message)
                directory.directory = path
                ctr.controllerCommit()
                astergui.study().commit(operation_name)
                astergui.update()
            else:
                ctr.controllerAbort()
Ejemplo n.º 6
0
def main():
    event_manager = EventManager()
    game_engine = GameEngine(event_manager)
    view = View(
        event_manager,
        game_engine,
        window_size=(DISPLAY_WIDTH, DISPLAY_HEIGHT),
        window_title="Ultimate Tic Tac Toe",
        fps=30,
    )
    _controller = Controller(event_manager, game_engine, view)
    game_engine.run()
Ejemplo n.º 7
0
def scrape(args):
    if args.subreddits:
        subreddits = args.subreddits
    else:
        subreddits = load_subreddits(args)

    model = DBModel(cdir)
    controller = Controller(model)
    pc = PicConsole(model, controller)
    logger.info(f'Scraping from {subreddits}')
    for subreddit in subreddits:
        pc.scrape_site(subreddit)
Ejemplo n.º 8
0
class BiBler:
    """
    The application launcher.
    """
    def __init__(self):
        """
        (Constructor)
        """
        self.app = BiBlerApp()
        self.control = None
        self.gui = None

    def start(self):
        """
        Starts the BiBler application head-less. 
        """
        self.app.start()

    def startGUI(self):
        """
        Starts the BiBler application with the GUI. 
        """
        app = wx.App(False)
        self.control = Controller()
        self.gui = BiBlerGUI(self.control)
        self.control.bindGUI(self.gui)
        self.control.bindApp(self.app)
        self.control.start()
        app.MainLoop()
Ejemplo n.º 9
0
    def __init__(self):
        super(MainAppWindow, self).__init__()
        self.setWindowIcon(QIcon('icon.ico'))
        self.setWindowTitle(
            'Intel® Integrated Performance Primitives Custom Library Tool')

        project_menu = self.menuBar()

        open_action = project_menu.addAction('Open project')
        save_action = project_menu.addAction('Save project')
        save_as_action = project_menu.addAction('Save project as...')

        self.settings_panel = SettingsPanel()
        self.selection_panel = SelectionPanel(self.settings_panel)
        self.custom_functions_panel = CustomFunctionsPanel(self.settings_panel)

        self.controller = Controller(self, self.settings_panel,
                                     self.selection_panel,
                                     self.custom_functions_panel)

        widget = QWidget()
        self.setCentralWidget(widget)

        layout = QGridLayout()
        layout.addWidget(self.settings_panel, 0, 0, 1, 3)
        layout.addWidget(self.selection_panel, 1, 0)
        layout.addWidget(self.controller, 1, 1, Qt.AlignCenter)
        layout.addWidget(self.custom_functions_panel, 1, 2)
        widget.setLayout(layout)

        open_action.triggered.connect(self.on_open)
        save_action.triggered.connect(self.on_save)
        save_as_action.triggered.connect(self.on_save_as)

        self.project = ''
        self.show()
Ejemplo n.º 10
0
def main():
    app = QtWidgets.QApplication(sys.argv)
    model = Bot()
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)

    ctrl = Controller(app, model, ui)
    ui.getTextBtn.clicked.connect(ctrl.get_text)
    ui.startRaceBtn.clicked.connect(ctrl.start_race)
    ui.closeAll.clicked.connect(ctrl.close_all)
    ui.speedSlider.valueChanged.connect(ctrl.speed_changed_slider)
    ui.speedLine.textChanged.connect(ctrl.speed_changed_editText)

    MainWindow.show()
    MainWindow.move(1280, 0)
    MainWindow.setFixedSize(MainWindow.size())
    sys.exit(app.exec_())
Ejemplo n.º 11
0
    def initUI(self, statusbar):
        self.layout = QGridLayout()
        self.setLayout(self.layout)

        self.layout.setHorizontalSpacing(0)
        self.layout.setContentsMargins(0, 0, 0, 0)

        self.project_file = ''

        self.function_menu = FunctionsMenu()
        self.scripts_menu = ScriptsMenu()
        self.scripts_menu.set_status_output(statusbar)
        self.controller = Controller(self.function_menu, self.scripts_menu)

        self.setMinimumHeight(700)
        self.setMinimumWidth(1000)

        self.open = QPushButton('Open project')
        self.save = QPushButton('Save project')
        self.save_as = QPushButton('Save project as...')

        self.save_as.pressed.connect(self.on_save_as)
        self.save.pressed.connect(self.on_save)
        self.open.pressed.connect(self.on_open)

        self.layout.addWidget(self.open, 0, 0)
        self.layout.addWidget(self.save, 0, 1)
        self.layout.addWidget(self.save_as, 0, 2)

        self.layout.addWidget(self.function_menu, 1, 0, 1, 4)
        self.layout.addWidget(self.controller, 1, 4, Qt.AlignCenter)
        self.layout.addWidget(self.scripts_menu, 1, 5)

        self.layout.setColumnStretch(0, 1)
        self.layout.setColumnStretch(1, 1)
        self.layout.setColumnStretch(2, 1)
        self.layout.setColumnStretch(3, 1)
        self.layout.setColumnStretch(4, 0)
        self.layout.setColumnStretch(5, 4)
Ejemplo n.º 12
0
'''
Created on Jan 13, 2014
@author: Eugene Syriani
@version: 0.2.5

This is the main BiBler module.
Execute this module from the command line to start the application.

@note: It assumes that the L{app} package has a L{statechart.BiBler_Statechart} class
and a L{UserInterface.UserInterface} class that implements L{gui.app_interface.IApplication}.

G{packagetree app, gui, utils}
'''

import wx
from gui.gui import MainWindow 
from gui.controller import Controller
from app.statechart import BiBler_Statechart
from app.UserInterface import UserInterface

if __name__ == '__main__':
    app = wx.App(False)
    controller = Controller()
    controller.bindGUI(MainWindow(controller))
    controller.bindSC(BiBler_Statechart())
    controller.bindApp(UserInterface())
    controller.start()
    app.MainLoop()
Ejemplo n.º 13
0
class MainAppWindow(QMainWindow):
    def __init__(self):
        super(MainAppWindow, self).__init__()
        self.setWindowIcon(QIcon('icon.ico'))
        self.setWindowTitle(
            'Intel® Integrated Performance Primitives Custom Library Tool')

        project_menu = self.menuBar()

        open_action = project_menu.addAction('Open project')
        save_action = project_menu.addAction('Save project')
        save_as_action = project_menu.addAction('Save project as...')

        self.settings_panel = SettingsPanel()
        self.selection_panel = SelectionPanel(self.settings_panel)
        self.custom_functions_panel = CustomFunctionsPanel(self.settings_panel)

        self.controller = Controller(self, self.settings_panel,
                                     self.selection_panel,
                                     self.custom_functions_panel)

        widget = QWidget()
        self.setCentralWidget(widget)

        layout = QGridLayout()
        layout.addWidget(self.settings_panel, 0, 0, 1, 3)
        layout.addWidget(self.selection_panel, 1, 0)
        layout.addWidget(self.controller, 1, 1, Qt.AlignCenter)
        layout.addWidget(self.custom_functions_panel, 1, 2)
        widget.setLayout(layout)

        open_action.triggered.connect(self.on_open)
        save_action.triggered.connect(self.on_save)
        save_as_action.triggered.connect(self.on_save_as)

        self.project = ''
        self.show()

    def on_open(self):
        while True:
            extension = 'CLT project (*' + utils.PROJECT_EXTENSION + ')'
            chosen_path = QFileDialog.getOpenFileName(
                self,
                'Open project',
                '',
                extension,
                options=QFileDialog.DontResolveSymlinks)[0]
            if not chosen_path:
                return
            elif os.path.islink(chosen_path):
                QMessageBox.information(self, 'ERROR!',
                                        'Please, select not a symlink')
                continue
            else:
                self.project = chosen_path
                break

        with open(self.project, 'r') as project_file:
            configs = json.load(project_file)
            self.controller.set_configs(configs)

    def on_save(self):
        return self.on_save_as(self.project)

    def on_save_as(self, project):
        self.controller.get_selected_configs()

        if not project:
            extension = 'CLT project (*' + utils.PROJECT_EXTENSION + ')'
            project = QFileDialog.getSaveFileName(self, 'Save project as...',
                                                  '', extension)[0]
            if not project:
                return
            else:
                self.project = project

        if utils.CONFIGS[utils.PACKAGE]:
            utils.CONFIGS[utils.PACKAGE] = utils.CONFIGS[utils.PACKAGE].root

        with open(project, 'w') as project_file:
            json.dump(utils.CONFIGS, project_file)

    def event(self, e):
        if e.type() == QEvent.Show:
            qt_rectangle = self.frameGeometry()
            center_point = QDesktopWidget().availableGeometry().center()
            qt_rectangle.moveCenter(center_point)
            self.move(qt_rectangle.topLeft())

        return super().event(e)
Ejemplo n.º 14
0
class Main(wx.Frame):
    """The main GUI class."""

    # Hard coded variables.
    min_width = 1000
    min_height = 600

    def __init__(self, parent=None, id=-1, title=""):
        """Initialise the main relax GUI frame."""

        # Store the wxPython info for os/machine/version specific hacks.
        status.wx_info = {}
        status.wx_info["version"] = wx.__version__.split('.')
        status.wx_info["minor"] = "%s.%s" % (status.wx_info["version"][0], status.wx_info["version"][1])
        status.wx_info["os"] = sys.platform
        status.wx_info["build"] = None
        if search('gtk2', wx.version()):
            status.wx_info["build"] = 'gtk'
        elif search('cocoa', wx.version()):
            status.wx_info["build"] = 'cocoa'
        elif search('mac-unicode', wx.version()):
            status.wx_info["build"] = 'carbon'
        status.wx_info["full"] = None
        if status.wx_info["build"]:
            status.wx_info["full"] = "%s-%s" % (status.wx_info["os"], status.wx_info["build"])

        # Some internal variables.
        self.test_suite_flag = False

        # The main window style.
        style = wx.DEFAULT_FRAME_STYLE
        if not status.debug and status.wx_info["os"] != 'darwin':
            style = style | wx.MAXIMIZE

        # Execute the base class __init__ method.
        super(Main, self).__init__(parent=parent, id=id, title=title, style=style)

        # Force the main window to start maximised (needed for MS Windows).
        if not status.debug and status.wx_info["os"] != 'darwin':
            self.Maximize()

        # Set up some standard interface-wide fonts.
        font.setup()

        # Set up the relax icons.
        relax_icons.setup()
        self.SetIcons(relax_icons)

        # Set up the Mac OS X task bar icon.
        #if status.wx_info["os"] == 'darwin' and status.wx_info["build"] != 'gtk':
        #    self.taskbar_icon = Relax_task_bar_icon(self)

        # Initialise some variables for the GUI.
        self.launch_dir = getcwd()

        # Set up the frame.
        self.Layout()
        self.SetSize((self.min_width, self.min_height))
        self.SetMinSize((self.min_width, self.min_height))
        self.Centre()

        # The analysis window object storage.
        self.analysis = Analysis_controller(self)

        # The calculation threads list.
        self.calc_threads = []

        # Initialise the GUI data.
        self.init_data()

        # Build the menu bar.
        self.menu = Menu(self)

        # Build the toolbar.
        self.build_toolbar()

        # Build the controller, but don't show it.
        self.controller = Controller(self)

        # Set the title.
        self.SetTitle("relax " + version)

        # Set up the status bar.
        self.status_bar = self.CreateStatusBar(3, 0)
        self.status_bar.SetStatusWidths([-4, -1, -2])
        self.update_status_bar()

        # Add the start screen.
        self.add_start_screen()

        # Close Box event.
        self.Bind(wx.EVT_CLOSE, self.exit_gui)

        # Initialise the special interpreter thread object.
        self.interpreter = Interpreter()

        # Register functions with the observer objects.
        status.observers.pipe_alteration.register('status bar', self.update_status_bar, method_name='update_status_bar')
        status.observers.result_file.register('gui', self.show_results_viewer_no_warn, method_name='show_results_viewer_no_warn')
        status.observers.exec_lock.register('gui', self.enable, method_name='enab')

        # Assume a script has been run and there is data in the store.
        self.analysis.load_from_store()


    def about_relax(self, event=None):
        """The about message for relax.

        @keyword event: The wx event.
        @type event:    wx event
        """

        # Build the dialog.
        dialog = About_relax(None, -1)

        # The dialog.
        if status.show_gui:
            dialog.Show()


    def action_export_bmrb(self, event=None):
        """Export the contents of the current data pipe for BMRB deposition.

        @keyword event: The wx event.
        @type event:    wx event
        """

        # No current data pipe.
        if not cdp_name():
            gui_raise(RelaxNoPipeError())
            return

        # Open the export window.
        Export_bmrb_window(self)


    def action_state_save(self, event=None):
        """Save the program state.

        @keyword event: The wx event.
        @type event:    wx event
        """

        # Not saved yet, therefore pass execution to state_save_as().
        if not self.save_file:
            self.action_state_save_as(event)
            return

        # Save.
        self.state_save()


    def action_state_save_as(self, event=None):
        """Save the program state with file name selection.

        @keyword event: The wx event.
        @type event:    wx event
        """

        # The dialog.
        dialog = RelaxFileDialog(parent=self, message='Select the relax save state file', defaultFile='state.bz2', wildcard='relax save file (*.bz2)|*.bz2', style=wx.FD_SAVE)

        # Show the dialog and catch if no file has been selected.
        if status.show_gui and dialog.ShowModal() != wx.ID_OK:
            # Don't do anything.
            return

        # The file.
        file_name = dialog.get_file()

        # Set the file name.
        self.save_file = file_name

        # Save.
        self.state_save()


    def add_start_screen(self):
        """Create a start screen for the main window when no analyses exist."""

        # The sizer for the main GUI window.
        sizer = wx.BoxSizer(wx.VERTICAL)
        self.SetSizer(sizer)

        # The relax icon.
        image = wx.StaticBitmap(self, -1, bitmap_setup(IMAGE_PATH+'ulysses_shadowless_400x168.png'))

        # Add the icon to the main spacer with spacing.
        sizer.AddStretchSpacer()
        sizer.Add(image, 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
        sizer.AddStretchSpacer()

        # Re-perform the layout of the GUI elements, and refresh.
        self.Layout()
        self.Refresh()


    def build_toolbar(self):
        """Create the toolbar."""

        # Init.
        self.toolbar = self.CreateToolBar(wx.TB_HORIZONTAL|wx.TB_FLAT)

        # The new analysis button.
        self.TB_FILE_NEW = wx.NewId()
        self.toolbar.AddLabelTool(self.TB_FILE_NEW, "New analysis", wx.Bitmap(fetch_icon('oxygen.actions.document-new', "22x22"), wx.BITMAP_TYPE_ANY), shortHelp="New analysis")
        self.Bind(wx.EVT_TOOL, self.analysis.menu_new, id=self.TB_FILE_NEW)

        # The close analysis button.
        self.TB_FILE_CLOSE = wx.NewId()
        self.toolbar.AddLabelTool(self.TB_FILE_CLOSE, "Close analysis", wx.Bitmap(fetch_icon('oxygen.actions.document-close', "22x22"), wx.BITMAP_TYPE_ANY), shortHelp="Close analysis")
        self.Bind(wx.EVT_TOOL, self.analysis.menu_close, id=self.TB_FILE_CLOSE)

        # The close all analyses button.
        self.TB_FILE_CLOSE_ALL = wx.NewId()
        self.toolbar.AddLabelTool(self.TB_FILE_CLOSE_ALL, "Close all analyses", wx.Bitmap(fetch_icon('oxygen.actions.dialog-close', "22x22"), wx.BITMAP_TYPE_ANY), shortHelp="Close all analyses")
        self.Bind(wx.EVT_TOOL, self.analysis.menu_close_all, id=self.TB_FILE_CLOSE_ALL)

        # A separator.
        self.toolbar.AddSeparator()

        # The open state button.
        self.TB_FILE_OPEN = wx.NewId()
        self.toolbar.AddLabelTool(self.TB_FILE_OPEN, "Open relax state", wx.Bitmap(fetch_icon('oxygen.actions.document-open', "22x22"), wx.BITMAP_TYPE_ANY), shortHelp="Open relax state")
        self.Bind(wx.EVT_TOOL, self.state_load, id=self.TB_FILE_OPEN)

        # The save state button.
        self.TB_FILE_SAVE = wx.NewId()
        self.toolbar.AddLabelTool(self.TB_FILE_SAVE, "Save relax state", wx.Bitmap(fetch_icon('oxygen.actions.document-save', "22x22"), wx.BITMAP_TYPE_ANY), shortHelp="Save relax state")
        self.Bind(wx.EVT_TOOL, self.action_state_save, id=self.TB_FILE_SAVE)

        # The save as button.
        self.TB_FILE_SAVE_AS = wx.NewId()
        self.toolbar.AddLabelTool(self.TB_FILE_SAVE_AS, "Save as", wx.Bitmap(fetch_icon('oxygen.actions.document-save-as', "22x22"), wx.BITMAP_TYPE_ANY), shortHelp="Save as")
        self.Bind(wx.EVT_TOOL, self.action_state_save_as, id=self.TB_FILE_SAVE_AS)

        # A separator.
        self.toolbar.AddSeparator()

        # The relax controller button.
        self.TB_VIEW_CONTROLLER = wx.NewId()
        self.toolbar.AddLabelTool(self.TB_VIEW_CONTROLLER, "Controller", wx.Bitmap(fetch_icon('oxygen.apps.preferences-system-performance', "22x22"), wx.BITMAP_TYPE_ANY), shortHelp="relax controller")
        self.Bind(wx.EVT_TOOL, self.show_controller, id=self.TB_VIEW_CONTROLLER)

        # The spin viewer button.
        self.TB_VIEW_SPIN_VIEW = wx.NewId()
        self.toolbar.AddLabelTool(self.TB_VIEW_SPIN_VIEW, "Spin viewer", wx.Bitmap(fetch_icon('relax.spin', "22x22"), wx.BITMAP_TYPE_ANY), shortHelp="Spin viewer window")
        self.Bind(wx.EVT_TOOL, self.show_tree, id=self.TB_VIEW_SPIN_VIEW)

        # The results viewer button.
        self.TB_VIEW_RESULTS = wx.NewId()
        self.toolbar.AddLabelTool(self.TB_VIEW_RESULTS, "Results viewer", wx.Bitmap(fetch_icon('oxygen.actions.view-statistics', "22x22"), wx.BITMAP_TYPE_ANY), shortHelp="Results viewer window")
        self.Bind(wx.EVT_TOOL, self.show_results_viewer, id=self.TB_VIEW_RESULTS)

        # The data pipe editor button.
        self.TB_VIEW_PIPE_EDIT = wx.NewId()
        self.toolbar.AddLabelTool(self.TB_VIEW_PIPE_EDIT, "Data pipe editor", wx.Bitmap(fetch_icon('relax.pipe', "22x22"), wx.BITMAP_TYPE_ANY), shortHelp="Data pipe editor")
        self.Bind(wx.EVT_TOOL, self.show_pipe_editor, id=self.TB_VIEW_PIPE_EDIT)

        # The relax prompt button.
        self.TB_VIEW_PROMPT = wx.NewId()
        self.toolbar.AddLabelTool(self.TB_VIEW_PROMPT, "relax prompt", wx.Bitmap(fetch_icon('oxygen.mimetypes.application-x-executable-script', "22x22"), wx.BITMAP_TYPE_ANY), shortHelp="The relax prompt GUI window")
        self.Bind(wx.EVT_TOOL, self.show_prompt, id=self.TB_VIEW_PROMPT)

        # Build the toolbar.
        self.toolbar.Realize()


    def close_windows(self):
        """Throw a warning to close all of the non-essential windows when execution is locked.

        This is to speed up the calculations by avoiding window updates.
        """

        # Init the window list.
        win_list = []

        # Is the spin viewer window open?
        if hasattr(self, 'spin_viewer') and self.spin_viewer.IsShown():
            win_list.append('The spin viewer window')

        # Is the pipe editor window open?
        if hasattr(self, 'pipe_editor') and self.pipe_editor.IsShown():
            win_list.append('The data pipe editor window')

        # Is the results viewer window open?
        if hasattr(self, 'results_viewer') and self.results_viewer.IsShown():
            win_list.append('The results viewer window')

        # The windows are not open, so quit.
        if not len(win_list):
            return

        # The text.
        text = "The following windows are currently open:\n\n"
        for win in win_list:
            text = "%s\t%s.\n" % (text, win)
        text = text + "\nClosing these will significantly speed up the calculations."

        # Display the error message dialog.
        dlg = wx.MessageDialog(self, text, caption="Close windows", style=wx.OK|wx.ICON_EXCLAMATION|wx.STAY_ON_TOP)
        if status.show_gui:
            dlg.ShowModal()

        # Otherwise output to stderr.
        else:
            sys.stderr.write(text)


    def contact_relax(self, event=None):
        """Write an email to the relax mailing-list using the standard mailing program.

        @keyword event: The wx event.
        @type event:    wx event
        """

        webbrowser.open_new('mailto:[email protected]')


    def enable(self):
        """Enable and disable certain parts of the main window with the execution lock."""

        # Flag for enabling or disabling the elements.
        enable = False
        if not status.exec_lock.locked():
            enable = True

        # The toolbar.
        wx.CallAfter(self.toolbar.EnableTool, self.TB_FILE_NEW, enable)
        wx.CallAfter(self.toolbar.EnableTool, self.TB_FILE_CLOSE, enable)
        wx.CallAfter(self.toolbar.EnableTool, self.TB_FILE_CLOSE_ALL, enable)
        wx.CallAfter(self.toolbar.EnableTool, self.TB_FILE_OPEN, enable)
        wx.CallAfter(self.toolbar.EnableTool, self.TB_FILE_SAVE, enable)
        wx.CallAfter(self.toolbar.EnableTool, self.TB_FILE_SAVE_AS, enable)


    def exit_gui(self, event=None):
        """Catch the main window closure and perform the exit procedure.

        @keyword event: The wx event.
        @type event:    wx event
        """

        # Ask if the user is sure they would like to exit.
        doexit = wx.ID_YES
        if status.show_gui and not ds.is_empty():
            doexit = Question('Are you sure you would like to quit relax?  All unsaved data will be lost.', title='Exit relax', default=True).ShowModal()

        # Exit.
        if doexit == wx.ID_YES:
            # Restore the IO streams.
            io_streams_restore(verbosity=0)

            # The relax information box.
            info = Info_box()

            # The width of the printout.
            if platform.uname()[0] in ['Windows', 'Microsoft']:
                width = 80
            else:
                width = 100

            # A printout.
            text = "\n\nThank you for citing:\n"
            text += "\n\n%srelaxGUI%s\n\n" % (ansi.relax_prompt, ansi.end)
            for line in wrap(info.bib['Bieri11'].cite_short(), width):
                text += line + '\n'
            text += "\n\n\n%srelax%s\n\n" % (ansi.relax_prompt, ansi.end)
            for line in wrap(info.bib['dAuvergneGooley08a'].cite_short(), width):
                text += line + '\n'
            text += '\n'
            for line in wrap(info.bib['dAuvergneGooley08b'].cite_short(), width):
                text += line + '\n'
            text += '\n'
            text += '\n'
            sys.stdout.write(text)

            # Remove the Mac OS X task bar icon.
            if hasattr(self, 'taskbar_icon'):
                self.taskbar_icon.Destroy()

            # Terminate the interpreter thread to allow for a cleaner exit.
            self.interpreter.exit()

            # End the GUI main loop.
            app = wx.GetApp()
            app.ExitMainLoop()


    def init_data(self):
        """Initialise the data used by the GUI interface."""

        # Temporary data:  the save file.
        self.save_file = None

        # Add the GUI object to the data store, if not present.
        if not hasattr(ds, 'relax_gui'):
            ds.relax_gui = Gui()


    def free_file_format_settings(self, event=None):
        """Open the free file format settings window.

        @keyword event: The wx event.
        @type event:    wx event
        """

        # Build the window.
        win = Free_file_format_window()

        # Show the window.
        if status.show_gui:
            win.Show()


    def references(self, event=None):
        """Display the references relevant for relax.

        @keyword event: The wx event.
        @type event:    wx event
        """

        # Build and show the references window.
        self.references = References(self)
        if status.show_gui:
            self.references.Show()


    def relax_manual(self, event=None):
        """Display the relax manual.

        @keyword event: The wx event.
        @type event:    wx event
        """

        # The PDF manual.
        file = status.install_path + sep+"docs"+sep+"relax.pdf"

        # Test if it exists.
        if not access(file, F_OK):
            error_message("The relax manual '%s' cannot be found.  Please compile using the scons program." % file)
            return

        # Open the relax PDF manual using the native PDF reader.
        open_file(file)


    def reset(self):
        """Reset the GUI."""

        # Close some GUI windows, if open.
        windows = ['pipe_editor', 'relax_prompt', 'results_viewer', 'spin_viewer']
        for window in windows:
            if hasattr(self, window):
                # Get the object.
                win_obj = getattr(self, window)

                # Close the window.
                win_obj.Close()

        # Flush all wx events to make sure the GUI is ready for the next test.
        wx.Yield()

        # Reset the relax controller.
        self.controller.reset()


    def run_test_suite(self, event=None, categories=['system', 'unit', 'gui']):
        """Execute the full test suite.

        @keyword event:         The wx event.
        @type event:            wx event
        @keyword categories:    The list of test categories to run, for example ['system', 'unit', 'gui'] for all tests.
        @type categories:       list of str
        """

        # Ask if this should be done.
        msg = "In running the test suite, relax will be reset and all data lost.  Are you sure you would like to run the test suite?"
        if Question(msg, parent=self, size=(400, 150), default=False).ShowModal() == wx.ID_NO:
            return

        # Set the test suite flag.
        self.test_suite_flag = True

        # Change the cursor to waiting.
        wx.BeginBusyCursor()

        # Set a new style to stay on top, refreshing to update the style (needed for Mac OS X and MS Windows).
        orig_style = self.controller.GetWindowStyle()
        self.controller.SetWindowStyle(orig_style | wx.STAY_ON_TOP)
        self.controller.Refresh()

        # Make the relax controller modal so that all other windows are deactivated (to stop users from clicking on things).
        self.controller.MakeModal(True)

        # Close all open windows.
        if hasattr(self, 'spin_viewer'):
            self.spin_viewer.Close()
        if hasattr(self, 'pipe_editor'):
            self.pipe_editor.Close()
        if hasattr(self, 'results_viewer'):
            self.results_viewer.Close()
        if hasattr(self, 'relax_prompt'):
            self.relax_prompt.Close()

        # Reset relax.
        reset()

        # Show the relax controller.
        self.show_controller(event)

        # Yield
        wx.GetApp().Yield(True)

        # Prevent all new GUI elements from being shown.
        status.show_gui = False

        # Run the tests (with the import here to break a nasty circular import).
        import test_suite.test_suite_runner
        runner = test_suite.test_suite_runner.Test_suite_runner([], from_gui=True, categories=categories)
        runner.run_all_tests()

        # Reactive the GUI.
        status.show_gui = True

        # Turn off the busy cursor.
        if wx.IsBusy():
            wx.EndBusyCursor()

        # Restore the controller.
        self.controller.SetWindowStyle(orig_style)
        self.controller.MakeModal(False)
        self.controller.Refresh()

        # Unset the test suite flag.
        self.test_suite_flag = False

        # Set the controller main gauge to 100%.
        wx.CallAfter(self.controller.main_gauge.SetValue, 100)


    def run_test_suite_gui(self, event=None):
        """Execute the GUI tests.

        @keyword event: The wx event.
        @type event:    wx event
        """

        # Forward the call.
        self.run_test_suite(event, categories=['gui'])


    def run_test_suite_sys(self, event=None):
        """Execute the system tests.

        @keyword event: The wx event.
        @type event:    wx event
        """

        # Forward the call.
        self.run_test_suite(event, categories=['system'])


    def run_test_suite_unit(self, event=None):
        """Execute the unit tests.

        @keyword event: The wx event.
        @type event:    wx event
        """

        # Forward the call.
        self.run_test_suite(event, categories=['unit'])


    def show_controller(self, event=None):
        """Display the relax controller window.

        @keyword event: The wx event.
        @type event:    wx event
        """

        # Bring the window to the front.
        if self.controller.IsShown():
            self.controller.Raise()
            return

        # Open the window.
        if status.show_gui:
            self.controller.Show()


    def show_pipe_editor(self, event=None):
        """Display the data pipe editor window.

        @keyword event: The wx event.
        @type event:    wx event
        """

        # Throw a warning if the execution lock is on.
        if status.exec_lock.locked():
            dlg = wx.MessageDialog(self, "Leaving the pipe editor window open will slow down the calculations.", caption="Warning", style=wx.OK|wx.ICON_EXCLAMATION|wx.STAY_ON_TOP)
            if status.show_gui:
                dlg.ShowModal()

        # Build the pipe editor if needed.
        if not hasattr(self, 'pipe_editor'):
            self.pipe_editor = Pipe_editor(gui=self)

        # Bring the window to the front.
        if self.pipe_editor.IsShown():
            self.pipe_editor.Raise()
            return

        # Open the window.
        if status.show_gui and not self.pipe_editor.IsShown():
            self.pipe_editor.Show()

        # Update the grid.
        self.pipe_editor.update_grid()
        self.pipe_editor.activate()

        # Register the grid for updating when a user function completes or when the GUI analysis tabs change (needed here for the window hiding and associated unregistering).
        self.pipe_editor.observer_setup(register=True)


    def show_prompt(self, event=None):
        """Display the relax prompt window.

        @keyword event: The wx event.
        @type event:    wx event
        """

        # Build the relax prompt if needed.
        if not hasattr(self, 'relax_prompt'):
            self.relax_prompt = Prompt(None, -1, "", parent=self)

        # Bring the window to the front.
        if self.relax_prompt.IsShown():
            self.relax_prompt.Raise()
            return

        # Open the window.
        if status.show_gui:
            self.relax_prompt.Show()


    def show_results_viewer(self, event=None):
        """Display the analysis results.

        @keyword event: The wx event.
        @type event:    wx event
        """

        # Show the results viewer in a thread safe way.
        wx.CallAfter(self.show_results_viewer_safe, warn=True)


    def show_results_viewer_safe(self, warn=False):
        """Display the analysis results in a thread safe wx.CallAfter call.

        @keyword warn:  A flag which if True will cause a message dialog to appear warning about keeping the window open with the execution lock.
        @type warn:     bool
        """

        # Throw a warning if the execution lock is on.
        if warn and status.exec_lock.locked():
            dlg = wx.MessageDialog(self, "Leaving the results viewer window open will slow down the calculations.", caption="Warning", style=wx.OK|wx.ICON_EXCLAMATION|wx.STAY_ON_TOP)
            if status.show_gui:
                wx.CallAfter(dlg.ShowModal)

        # Create the results viewer window if needed.
        if not hasattr(self, 'results_viewer'):
            self.results_viewer = Results_viewer(self)

        # Bring the window to the front.
        if self.results_viewer.IsShown():
            self.results_viewer.Raise()
            return

        # Open the window.
        if status.show_gui and not self.results_viewer.IsShown():
            self.results_viewer.Show()


    def show_results_viewer_no_warn(self):
        """Display the analysis results."""

        # Show the results viewer in a thread safe way with no warning dialog.
        wx.CallAfter(self.show_results_viewer_safe, warn=False)


    def show_tree(self, event=None):
        """Display the molecule, residue, and spin tree window.

        @keyword event: The wx event.
        @type event:    wx event
        """

        # Throw a warning if the execution lock is on.
        if status.exec_lock.locked():
            dlg = wx.MessageDialog(self, "Leaving the spin viewer window open will slow down the calculations.", caption="Warning", style=wx.OK|wx.ICON_EXCLAMATION|wx.STAY_ON_TOP)
            if status.show_gui:
                dlg.ShowModal()

        # Build the spin view window.
        if not hasattr(self, 'spin_viewer'):
            self.spin_viewer = Spin_view_window(None, -1, "", parent=self)

        # Bring the window to the front.
        if self.spin_viewer.IsShown():
            self.spin_viewer.Raise()
            return

        # Open the window (the GUI flag check is inside the Show method).
        if status.show_gui and not self.spin_viewer.IsShown():
            self.spin_viewer.Show()


    def state_load(self, event=None, file_name=None):
        """Load the program state.

        @keyword event:     The wx event.
        @type event:        wx event
        @keyword file_name: The name of the file to load (for dialogless operation).
        @type file_name:    str
        """

        # Execution lock.
        if status.exec_lock.locked():
            return

        # Warning.
        if not self.analysis.init_state or not ds.is_empty():
            # The message.
            msg = "Loading a saved relax state file will cause all unsaved data to be lost.  Are you sure you would to open a save file?"

            # The dialog.
            if status.show_gui and Question(msg, default=True, size=(400, 150)).ShowModal() == wx.ID_NO:
                return

        # Open the dialog.
        if not file_name:
            dialog = RelaxFileDialog(parent=self, message='Select the relax save state file', defaultFile='state.bz2', wildcard='relax save files (*.bz2;*.gz)|*.bz2;*.gz|All files (*)|*', style=wx.FD_OPEN)

            # Show the dialog and catch if no file has been selected.
            if status.show_gui and dialog.ShowModal() != wx.ID_OK:
                # Don't do anything.
                return

            # The file.
            file_name = gui_to_str(dialog.get_file())

        # Yield to allow the cursor to be changed.
        wx.Yield()

        # Change the cursor to waiting, and freeze the GUI.
        wx.BeginBusyCursor()
        self.Freeze()

        # Make sure the GUI returns to normal if a failure occurs.
        try:
            # Delete the current tabs.
            self.analysis.delete_all()

            # Reset the relax data store.
            reset()

            # The new save file name.
            self.save_file = file_name

            # Load the relax state.
            if protected_exec(state.load_state, file_name, verbosity=0):
                # Update the core of the GUI to match the new data store.
                self.sync_ds(upload=False)

            # File loading failure.
            else:
                # Reset relax to clear any partially loaded data.
                reset()

                # Reinitialise the GUI data store structure.
                self.init_data()

        # Reset the cursor, and thaw the GUI.
        finally:
            self.Thaw()

            # Turn off the busy cursor.
            if wx.IsBusy():
                wx.EndBusyCursor()


    def state_save(self):
        """Save the program state."""

        # Update the data store to match the GUI.
        self.sync_ds(upload=True)

        # Save the relax state (with save user feedback).
        try:
            wx.BeginBusyCursor()
            state.save_state(self.save_file, verbosity=0, force=True)

            # Sleep a little so the user sees the busy cursor and knows that a save has occurred!
            sleep(1)

        # Turn off the user feedback.
        finally:
            if wx.IsBusy():
                wx.EndBusyCursor()


    def sync_ds(self, upload=False):
        """Synchronise the GUI and the relax data store, both ways.

        This method allows the GUI information to be uploaded into the relax data store, or for the information in the relax data store to be downloaded by the GUI.

        @keyword upload:    A flag which if True will cause the GUI to send data to the relax data store.  If False, data will be downloaded from the relax data store to update the GUI.
        @type upload:       bool
        """

        # Loop over each analysis.
        for page in self.analysis.analysis_loop():
            # Execute the analysis page specific update methods.
            if hasattr(page, 'sync_ds'):
                page.sync_ds(upload)


    def uf_call(self, event=None):
        """Catch the user function call to properly specify the parent window.

        @keyword event: The wx event.
        @type event:    wx event
        """

        # The user function ID.
        uf_id = event.GetId()

        # Get the user function name.
        name = uf_store.get_uf(uf_id)

        # Call the user function GUI object.
        uf_store[name](event=event, wx_parent=self)


    def update_status_bar(self):
        """Update the status bar info."""

        # Set the current data pipe info.
        pipe = cdp_name()

        # No data pipe.
        if pipe == None:
            pipe = ''

        # Set the status.
        wx.CallAfter(self.status_bar.SetStatusText, "(C) 2001-2013 the relax development team", 0)
        wx.CallAfter(self.status_bar.SetStatusText, "Current data pipe:", 1)
        wx.CallAfter(self.status_bar.SetStatusText, pipe, 2)
Ejemplo n.º 15
0
class Application(tk.Frame):
    def __init__(self, master=None):
        tk.Frame.__init__(self, master)
        self.master.title("NN - Creator")
        self.grid(sticky=tk.N + tk.S + tk.E + tk.W)
        self.master.title('Sample application')
        self.master.geometry = self.center(HEIGHT, WIDTH)
        self.main_canvas = 0
        self.param_canvas = 0
        self.layers_canvas = 0
        self.network_canvas = 0
        self.score_canvas = 0
        self.alfa_spinner = 0
        self.act_combox = 0
        self.loss_combox = 0
        self.init_combox = 0
        self.opotim_combox = 0
        self.epoch_spinner = 0
        self.batch_spinner = 0
        self.laycnt_spinner = 0
        self.train_btn = 0
        self.draw_btn = 0
        self.load_entry = 0
        self.load_checkbox = 0
        self.save_entry = 0
        self.save_checkbox = 0
        self.lay_btn = 0
        self.plot_tk = None
        self.top_level1 = 0
        self.progress_bar = 0
        self.nr_spin = []
        self.layer_lab = []
        self.network_model = Network_model()
        self.controller = Controller()
        self.createWidgets()

    def createWidgets(self):
        top = self.winfo_toplevel()

        top.rowconfigure(0, weight=1)

        top.columnconfigure(0, weight=1)

        self.rowconfigure(0, weight=1)

        self.columnconfigure(0, weight=1)

        self.main_canvas = tk.Canvas(self,
                                     height=HEIGHT,
                                     width=WIDTH,
                                     bg=MAIN_BG)
        self.main_canvas.grid(row=0,
                              column=0,
                              sticky=tk.N + tk.S + tk.E + tk.W)
        self.main_canvas.grid_propagate(0)

        # <--- Parameter canvas --->
        self.param_canvas = tk.Canvas(self.main_canvas,
                                      height=HEIGHT,
                                      width=WIDTH * 0.2,
                                      bg=PARAMS_BG)
        self.param_canvas.grid(row=0, column=0, sticky=tk.W)
        self.param_canvas.grid_propagate(0)
        # <--- Container 1 canvas --->
        container1 = tk.Canvas(self.main_canvas,
                               height=HEIGHT,
                               width=0.6 * WIDTH,
                               bg=PARAMS_BG)
        container1.grid(row=0, column=1, sticky=tk.N + tk.S + tk.E + tk.W)
        # <--- Layers canvas --->
        self.layers_canvas = tk.Canvas(container1,
                                       height=HEIGHT * 0.16,
                                       width=WIDTH * 0.56,
                                       bg=PARAMS_BG)
        self.layers_canvas.grid(row=0, column=1)
        self.layers_canvas.grid_propagate(0)
        # <--- Network canvas --->
        self.network_canvas = tk.Canvas(container1,
                                        height=NET_HEIGHT,
                                        width=NET_WIDTH,
                                        bg=NET_BG)
        self.network_canvas.grid(row=1, column=1)
        self.network_canvas.grid_propagate(0)

        # <--- Alfa Spinner --->
        alfa_label = tk.Label(self.param_canvas,
                              anchor='e',
                              padx=10,
                              pady=10,
                              text="Alfa",
                              bg=PARAMS_BG,
                              font=Font(family='Helvetica',
                                        size=20,
                                        weight='bold'))
        alfa_label.grid(row=0, column=0, padx=10, pady=10)
        self.alfa_spinner = tk.Spinbox(self.param_canvas,
                                       justify=tk.CENTER,
                                       from_=0.001,
                                       increment=0.001,
                                       to=0.999,
                                       width=5,
                                       repeatinterval=25,
                                       font=Font(family='Helvetica', size=20),
                                       textvariable=self.network_model.alfa)
        self.alfa_spinner.grid(row=0, column=1, padx=10, pady=10)
        # <--- Activation ComBox --->
        act_label = tk.Label(self.param_canvas,
                             anchor='e',
                             padx=10,
                             pady=10,
                             text="Activation\n function",
                             bg=PARAMS_BG,
                             font=Font(family='Helvetica',
                                       size=10,
                                       weight='bold'))
        act_label.grid(row=1, column=0, padx=10, pady=10)
        self.act_combox = ttk.Combobox(
            self.param_canvas,
            values=['sigmoid', 'tanh', 'relu', 'leaky_relu'],
            width=10,
            textvariable=self.network_model.act)
        self.act_combox.current(0)
        self.act_combox.grid(row=1, column=1, padx=10, pady=10)
        # <--- Loss Function ComBox --->
        loss_label = tk.Label(self.param_canvas,
                              anchor='e',
                              padx=10,
                              pady=10,
                              text="Loss\n function",
                              bg=PARAMS_BG,
                              font=Font(family='Helvetica',
                                        size=10,
                                        weight='bold'))
        loss_label.grid(row=2, column=0, padx=10, pady=10)
        self.loss_combox = ttk.Combobox(self.param_canvas,
                                        values=['L1', 'L2', 'Cross Entropy'],
                                        width=10,
                                        textvariable=self.network_model.loss)
        self.loss_combox.current(0)
        self.loss_combox.grid(row=2, column=1, padx=10, pady=10)
        # <--- Init weights ComBox --->
        init_label = tk.Label(self.param_canvas,
                              anchor='e',
                              padx=10,
                              pady=10,
                              text="Initializing\n function",
                              bg=PARAMS_BG,
                              font=Font(family='Helvetica',
                                        size=10,
                                        weight='bold'))
        init_label.grid(row=3, column=0, padx=10, pady=10)
        self.init_combox = ttk.Combobox(
            self.param_canvas,
            values=['random', 'Xavier', 'He'],
            width=10,
            textvariable=self.network_model.initializer)
        self.init_combox.current(0)
        self.init_combox.grid(row=3, column=1, padx=10, pady=10)
        # <--- Optimize ComBox --->
        optim_label = tk.Label(self.param_canvas,
                               anchor='e',
                               padx=10,
                               pady=10,
                               text="Optimizing\n function",
                               bg=PARAMS_BG,
                               font=Font(family='Helvetica',
                                         size=10,
                                         weight='bold'))
        optim_label.grid(row=4, column=0, padx=10, pady=10)
        self.optim_combox = ttk.Combobox(
            self.param_canvas,
            values=['sgd', 'sgd_momentum', 'ADAM'],
            width=10,
            textvariable=self.network_model.optim)
        self.optim_combox.current(0)
        self.optim_combox.grid(row=4, column=1, padx=10, pady=10)
        # <--- Epoch Spinner --->
        epoch_label = tk.Label(self.param_canvas,
                               anchor='e',
                               padx=10,
                               pady=10,
                               text="Epochs\n Count",
                               bg=PARAMS_BG,
                               font=Font(family='Helvetica',
                                         size=10,
                                         weight='bold'))
        epoch_label.grid(row=5, column=0, padx=10, pady=10)
        self.epoch_spinner = tk.Spinbox(self.param_canvas,
                                        justify=tk.CENTER,
                                        from_=1,
                                        increment=1,
                                        to=10000,
                                        width=5,
                                        repeatinterval=15,
                                        font=Font(family='Helvetica', size=20),
                                        textvariable=self.network_model.epoch)
        self.epoch_spinner.grid(row=5, column=1, padx=10, pady=10)
        # <--- BatchSize Spinner --->
        batch_label = tk.Label(self.param_canvas,
                               anchor='e',
                               padx=10,
                               pady=10,
                               text="Batch\n size",
                               bg=PARAMS_BG,
                               font=Font(family='Helvetica',
                                         size=10,
                                         weight='bold'))
        batch_label.grid(row=6, column=0, padx=10, pady=10)
        self.batch_spinner = tk.Spinbox(self.param_canvas,
                                        justify=tk.CENTER,
                                        from_=1,
                                        increment=1,
                                        to=100,
                                        width=5,
                                        repeatinterval=25,
                                        font=Font(family='Helvetica', size=20),
                                        textvariable=self.network_model.batch)
        self.batch_spinner.grid(row=6, column=1, padx=10, pady=10)
        # <--- Load network with name of --->
        load_label = tk.Label(self.param_canvas,
                              anchor='e',
                              padx=10,
                              pady=10,
                              text="Load from: ",
                              bg=PARAMS_BG,
                              font=Font(family='Helvetica',
                                        size=10,
                                        weight='bold'))
        load_label.grid(row=7, column=0, padx=10, pady=10)
        self.load_entry = tk.Entry(self.param_canvas,
                                   font=Font(family='Helvetica', size=12),
                                   width=15,
                                   textvariable=self.network_model.load_path)
        self.load_entry.grid(row=7, column=1, pady=10)
        self.load_checkbox = tk.Checkbutton(
            self.param_canvas,
            anchor=tk.E,
            bg=PARAMS_BG,
            variable=self.network_model.load_bool)
        self.load_checkbox.grid(row=7, column=2)
        # <--- Save Network as name --->
        save_label = tk.Label(self.param_canvas,
                              anchor='e',
                              padx=10,
                              pady=10,
                              text="Save as: ",
                              bg=PARAMS_BG,
                              font=Font(family='Helvetica',
                                        size=10,
                                        weight='bold'))
        save_label.grid(row=8, column=0, padx=10, pady=10)
        self.save_entry = tk.Entry(self.param_canvas,
                                   font=Font(family='Helvetica', size=12),
                                   width=15,
                                   textvariable=self.network_model.save_path)
        self.save_entry.grid(row=8, column=1, pady=10)
        self.save_checkbox = tk.Checkbutton(
            self.param_canvas,
            anchor=tk.E,
            activebackground='#001345',
            bg=PARAMS_BG,
            variable=self.network_model.save_bool)
        self.save_checkbox.grid(row=8, column=2)
        # <--- Init Network and draw model on canvas --->
        self.draw_btn = tk.Button(
            self.param_canvas,
            anchor='e',
            padx=5,
            pady=5,
            text="Init model",
            font=Font(family='Helvetica', size=12, weight='bold'),
            bg=BTN_BG,
            command=lambda:
            [self.network_model.init(self),
             self.controller.draw_model(self)])
        self.draw_btn.grid(row=9, column=0, padx=10, pady=10)
        # <--- Start Training --->
        self.train_btn = tk.Button(
            self.param_canvas,
            anchor='e',
            padx=5,
            pady=5,
            text="Train model",
            font=Font(family='Helvetica', size=12, weight='bold'),
            bg=BTN_BG,
            command=lambda: [
                threading.Thread(target=self.controller.start_training,
                                 args=(app, self.network_model)).start()
            ])
        self.train_btn.grid(row=9, column=1, columnspan=1, padx=10, pady=10)

        # <--- Number of layers spinner --->
        laycnt_label = tk.Label(self.layers_canvas,
                                anchor='e',
                                padx=10,
                                pady=10,
                                text="Layers\n Count",
                                bg=PARAMS_BG,
                                font=Font(family='Helvetica',
                                          size=12,
                                          weight='bold'))
        laycnt_label.grid(row=0, column=0, padx=10, pady=10)
        self.laycnt_spinner = tk.Spinbox(
            self.layers_canvas,
            justify=tk.LEFT,
            from_=1,
            increment=1,
            to=MAX_LAY_CNT,
            textvariable=self.network_model.lay_count,
            width=2,
            repeatinterval=200,
            font=Font(family='Helvetica', size=16))
        self.laycnt_spinner.grid(row=0, column=1, padx=10, pady=10)
        '''
        # <--- Button to apply layers change --->
        '''
        self.lay_btn = tk.Button(
            self.layers_canvas,
            bd=4,
            bg=BTN_BG,
            text='Apply',
            font=Font(family='Helvetica', size=12),
            command=lambda:
            [self.network_model.init(self),
             self.controller.show_nrs(self)])
        self.lay_btn.grid(row=1, column=0, columnspan=2, padx=10)
        for i in range(MAX_LAY_CNT):
            neuron_label = tk.Label(self.layers_canvas,
                                    anchor=tk.CENTER,
                                    padx=10,
                                    pady=10,
                                    text="ID",
                                    bg=PARAMS_BG,
                                    font=Font(family='Helvetica',
                                              size=12,
                                              weight='bold'))
            neuron_label.grid(row=0, column=2 + i, padx=10, pady=10)
            neuron_label.grid_remove()
            neuron_spinner = tk.Spinbox(self.layers_canvas,
                                        justify=tk.LEFT,
                                        from_=1,
                                        increment=1,
                                        to=MAX_NEURONS,
                                        width=2,
                                        repeatinterval=20,
                                        font=Font(family='Helvetica', size=16),
                                        textvariable=tk.IntVar())
            neuron_spinner.grid(row=1, column=2 + i, padx=10, pady=10)
            neuron_spinner.grid_remove()
            self.nr_spin.append(neuron_spinner)
            self.layer_lab.append(neuron_label)
        self.nr_spin[0].grid()
        self.layer_lab[0].grid()

        # <--- Atribute names and Labels --->
        self.controller.show_data(self, NET_WIDTH, NET_HEIGHT)

        # <--- Progress Bar --->
        pb = Image.open('../../images/progressbar.png')
        self.progress_bar = ImageTk.PhotoImage(pb)
        self.network_canvas.create_image((0.54 * WIDTH, 0.07 * HEIGHT),
                                         anchor=tk.NW,
                                         image=self.progress_bar,
                                         tag='bar')
        (x1, y1, x2, y2) = self.network_canvas.bbox('bar')
        self.network_canvas.create_text((x1 + 8, y1 + 10),
                                        text='1',
                                        font=Font(family='Helvetica', size=16))
        self.network_canvas.create_text((x1 + 8, y2 - 16),
                                        text='0',
                                        font=Font(family='Helvetica', size=16))

        # <--- Training plot window --->

        self.top_level1 = tk.Toplevel(width=480, height=360, padx=10, pady=10)
        self.top_level1.title("Training plots")
        self.score_canvas = tk.Canvas(self.top_level1, height=360, width=480)
        self.score_canvas.grid(row=0, column=0)
        plot_png = Image.open('../../images/first_plot.png')
        self.plot_tk = ImageTk.PhotoImage(plot_png)
        self.score_canvas.create_image((0, 0),
                                       anchor=tk.NW,
                                       image=self.plot_tk,
                                       tag="img")

    def center(self, game_height, game_width):
        window_height = self.master.winfo_height()
        window_width = self.master.winfo_width()
        screen_width = int(self.master.winfo_screenwidth())
        screen_height = int(self.master.winfo_screenheight())
        print(f"{screen_width}\n{screen_height}")
        x = int((screen_width / 2) - (game_width / 2))
        y = int((screen_height / 2) - (game_height / 2))
        return f"{window_width}x{window_height}+{x}+{y}"
Ejemplo n.º 16
0
                     default='',
                     help='Where to find the Arduino.')
 parser.add_argument('--baudrate',
                     type=int,
                     default=9600,
                     help='Baudrate for the serial connection.')
 # Maze configuration
 parser.add_argument('--rows',
                     type=int,
                     default=2,
                     help='Number of rows in the maze.')
 parser.add_argument('--cols',
                     type=int,
                     default=3,
                     help='Number of cols in the maze.')
 args = parser.parse_args()
 running = True
 try:
     # Setup the serial connection to the Arduino
     with serial.Serial(args.port, args.baudrate) as ser:
         # Setup the GUI controller
         controller = Controller(args.rows, args.cols)
         while running:
             # Note: readline blocks.. If you do not terminate your message
             # with a newline, this will block forever...
             msg = ser.readline()
             print 'Received message: %s' % msg.strip()
             controller.handle_msg(msg)
 except serial.serialutil.SerialException as e:
     print 'Could not connect to the Arduino.'
     print e
Ejemplo n.º 17
0
    gruppeTesting = parser.add_argument_group("Testing")
    gruppeTesting.add_argument("--test", help="Test", action="store_true")

    # Parse CLI-Argumente
    try:
        args = parser.parse_args()
    except:
        print("Fehler bei der Parameteruebergabe... Abbruch")
        quit()

    # Werte CLI-Parameter aus (ohne Serververbindung)
    if len(sys.argv) <= 1:
        # Nichts übergeben -> GUI starten
        del m  # Sauberkeit: loesche das Model, welches hier im CLI-Modus benutzt wird
        Controller()
        quit()
    elif args.gui:
        # GUI
        del m # Sauberkeit: loesche das Model, welches hier im CLI-Modus benutzt wird
        sGuiStyle = args.gui
        if args.gui == "_system_":
            sGuiStyle = None
        Controller(sGuiStyle)
        quit()
    elif args.help:
        # Hilfe
        parser.print_help()
        quit()
    elif args.version:
        # Version
Ejemplo n.º 18
0
    def __init__(self, parent=None, id=-1, title=""):
        """Initialise the main relax GUI frame."""

        # Store the wxPython info for os/machine/version specific hacks.
        status.wx_info = {}
        status.wx_info["version"] = wx.__version__.split('.')
        status.wx_info["minor"] = "%s.%s" % (status.wx_info["version"][0], status.wx_info["version"][1])
        status.wx_info["os"] = sys.platform
        status.wx_info["build"] = None
        if search('gtk2', wx.version()):
            status.wx_info["build"] = 'gtk'
        elif search('cocoa', wx.version()):
            status.wx_info["build"] = 'cocoa'
        elif search('mac-unicode', wx.version()):
            status.wx_info["build"] = 'carbon'
        status.wx_info["full"] = None
        if status.wx_info["build"]:
            status.wx_info["full"] = "%s-%s" % (status.wx_info["os"], status.wx_info["build"])

        # Some internal variables.
        self.test_suite_flag = False

        # The main window style.
        style = wx.DEFAULT_FRAME_STYLE
        if not status.debug and status.wx_info["os"] != 'darwin':
            style = style | wx.MAXIMIZE

        # Execute the base class __init__ method.
        super(Main, self).__init__(parent=parent, id=id, title=title, style=style)

        # Force the main window to start maximised (needed for MS Windows).
        if not status.debug and status.wx_info["os"] != 'darwin':
            self.Maximize()

        # Set up some standard interface-wide fonts.
        font.setup()

        # Set up the relax icons.
        relax_icons.setup()
        self.SetIcons(relax_icons)

        # Set up the Mac OS X task bar icon.
        #if status.wx_info["os"] == 'darwin' and status.wx_info["build"] != 'gtk':
        #    self.taskbar_icon = Relax_task_bar_icon(self)

        # Initialise some variables for the GUI.
        self.launch_dir = getcwd()

        # Set up the frame.
        self.Layout()
        self.SetSize((self.min_width, self.min_height))
        self.SetMinSize((self.min_width, self.min_height))
        self.Centre()

        # The analysis window object storage.
        self.analysis = Analysis_controller(self)

        # The calculation threads list.
        self.calc_threads = []

        # Initialise the GUI data.
        self.init_data()

        # Build the menu bar.
        self.menu = Menu(self)

        # Build the toolbar.
        self.build_toolbar()

        # Build the controller, but don't show it.
        self.controller = Controller(self)

        # Set the title.
        self.SetTitle("relax " + version)

        # Set up the status bar.
        self.status_bar = self.CreateStatusBar(3, 0)
        self.status_bar.SetStatusWidths([-4, -1, -2])
        self.update_status_bar()

        # Add the start screen.
        self.add_start_screen()

        # Close Box event.
        self.Bind(wx.EVT_CLOSE, self.exit_gui)

        # Initialise the special interpreter thread object.
        self.interpreter = Interpreter()

        # Register functions with the observer objects.
        status.observers.pipe_alteration.register('status bar', self.update_status_bar, method_name='update_status_bar')
        status.observers.result_file.register('gui', self.show_results_viewer_no_warn, method_name='show_results_viewer_no_warn')
        status.observers.exec_lock.register('gui', self.enable, method_name='enab')

        # Assume a script has been run and there is data in the store.
        self.analysis.load_from_store()
Ejemplo n.º 19
0
@note: It assumes that the L{app} package has a L{statechart.BiBler_Statechart} class
and a L{UserInterface.UserInterface} class that implements L{gui.app_interface.IApplication}.

G{packagetree app, gui, utils}
'''

import wx
from gui.gui import MainWindow
from gui.controller import Controller
from app.user_interface import UserInterface


def preload(controller):
    import testApplication.oracle as oracle
    for e in oracle.all_entries_all_fields:
        controller.addEntry()
        controller.data.currentEntryBibTeX = e.getBibTeX()
        controller.updateEntry()
    controller.data.entryList = controller.APP.getAllEntries()
    controller.displayEntries()


if __name__ == '__main__':
    app = wx.App(False)
    controller = Controller()
    controller.bindGUI(MainWindow(controller))
    controller.bindApp(UserInterface())
    #preload(controller)
    controller.start()
    app.MainLoop()