Example #1
0
 def show(self,
          parent=None,
          locals={},
          function=None,
          wizard=0,
          docstring=""):
     docstring = util.dedent(docstring)
     self.wizard = wizard
     if function != None:
         self.function = function
     self.setup(parent, locals, docstring, function)
     while 1:
         result = wx.Dialog.ShowModal(self.window)
         try:
             if result == wx.ID_CANCEL:
                 return None
             elif self.function is None:
                 if function is None:
                     return tuple(self.get_args())
                 else:
                     return function + self.get_args_string()
             else:
                 ret = self.function + self.get_args_string()
                 self.window.Destroy()
                 return ret
         except ArgInvalidException, e:
             gui_util.message(str(e))
         #except Exception:
         #   throw
         else:
             break
Example #2
0
 def OnItemSelected(self, e):
     filename = self.GetFilePath()
     if filename == '':
         return
     wx.BeginBusyCursor()
     try:
         filename = filename.encode('utf8')
     except Exception:
         pass
     try:
         try:
             image = core.load_image(filename)
         except Exception, e:
             gui_util.message(
                 "Loading image %s failed. \n\nThe error was:\n%s" %
                 (filename, str(e)))
             return
     finally:
         wx.EndBusyCursor()
     width, height = self.image_display.id.GetSize()
     scale = max(
         float(width) / float(image.width),
         (float(height) / float(image.height)))
     self.image_display.id.set_image(image, weak=0)
     self.image_display.id.scale(scale)
Example #3
0
    def OnChangeFeatures(self, event):
        # ---------------------------------------------------------------------------
        from gamera import plugin
        from gamera.core import ONEBIT
        from gamera.core import ImageBase
        from gamera.args import Args, Check

        if self.classifier == None:
            gui.message("No classifier loaded")
            return

        allFeatures = [x[0] for x in plugin.methods_flat_category("Features", ONEBIT)]
        allFeatures.sort()

        existingFeatures = [x[0] for x in ImageBase.get_feature_functions(self.classifier.features)[0]]

        featureControls = []
        for f in allFeatures:
            featureControls.append(Check("", f, default=(f in existingFeatures)))

        dialog = Args(
            featureControls, name="Feature selection", title="Select the features you want to use for optimization"
        )

        result = dialog.show(self)

        if result == None:
            gui_util.message("No change applied")
            return

        selectedFeatures = [name for check, name in zip(result, allFeatures) if check]
        self.classifier.change_feature_set(selectedFeatures)

        self.UpdatePanels()
Example #4
0
   def __init__(self, parent, x, y, images_, name_=None, shell_=None,
                mode=EXECUTE_MODE, extra_methods={}):
      self.shell = shell_
      self.locals = locals
      self.mode = mode
      self.parent = parent
      if not util.is_sequence(images_):
         self.images = [images_]
      else:
         self.images = images_
      if not util.is_homogeneous_image_list(self.images):
         gui_util.message("All selected images are not of the same type.")
      self.image_name = name_

      self._menu_ids = []
      members = members_for_menu(self.images[0])
      methods = methods_for_menu(self.images[0])
      menu = self.create_menu(
        members, methods,
        self.images[0].data.pixel_type,
        self.images[0].pixel_type_name,
        extra_methods)
      self.did_something = 0
      self.parent.PopupMenu(menu, wx.Point(x, y))
      for i in self._menu_ids:
         self.parent.Disconnect(i)
      menu.Destroy()
Example #5
0
    def OnOpenClassifier(self, event):
    #---------------------------------------------------------------------------
        from gamera.args import Args, Class
        from gamera.gui import gui
        from gamera import knn

        dialog = Args(
            [Class("Classifier", knn._kNNBase)],
             name="Select an existing classifier...")
        results = dialog.show(
            self, gui.main_win.shell.locals,
            docstring="""Choose an already created classifier for optimization.""")

        if results is None:
            return

        self.classifier = results[0]

        if isinstance(self.classifier, knn.kNNInteractive):
            gui_util.message("Given interactive classifier will be converted"\
                " to noninteractive classifier for optimization (internal)")
            self.classifier = self.CopyClassifier(self.classifier)

        self.SetClassifiers()
        self.UpdatePanels()
        self.EnableControls(True)
Example #6
0
    def OnOpenClassifier(self, event):
        # ---------------------------------------------------------------------------
        from gamera.args import Args, Class
        from gamera.gui import gui
        from gamera import knn

        dialog = Args([Class("Classifier", knn._kNNBase)], name="Select an existing classifier...")
        results = dialog.show(
            self, gui.main_win.shell.locals, docstring="""Choose an already created classifier for optimization."""
        )

        if results == None:
            return

        self.classifier = results[0]

        if isinstance(self.classifier, knn.kNNInteractive):
            gui_util.message(
                "Given interactive classifier will be converted"
                " to noninteractive classifier for optimization (internal)"
            )
            self.classifier = self.CopyClassifier(self.classifier)

        self.SetClassifiers()
        self.UpdatePanels()
        self.EnableControls(True)
Example #7
0
 def show(self, parent=None, locals={}, function=None, wizard=0, docstring=""):
    docstring = util.dedent(docstring)
    self.wizard = wizard
    if function != None:
       self.function = function
    self.setup(parent, locals, docstring, function)
    while 1:
       result = wx.Dialog.ShowModal(self.window)
       try:
          if result == wx.ID_CANCEL:
             return None
          elif self.function is None:
             if function is None:
                return tuple(self.get_args())
             else:
                return function + self.get_args_string()
          else:
             ret = self.function + self.get_args_string()
             self.window.Destroy()
             return ret 
       except ArgInvalidException, e:
          gui_util.message(str(e))
       #except Exception:
       #   throw
       else:
          break
Example #8
0
    def OnChangeFeatures(self, event):
    #---------------------------------------------------------------------------
        from gamera import plugin
        from gamera.core import ONEBIT
        from gamera.core import ImageBase
        from gamera.args import Args, Check

        if self.classifier is None:
            gui.message("No classifier loaded")
            return

        allFeatures = [x[0] for x in plugin.methods_flat_category("Features", ONEBIT)]
        allFeatures.sort()

        existingFeatures = [x[0] for x in ImageBase.get_feature_functions(self.classifier.features)[0]]

        featureControls = []
        for f in allFeatures:
            featureControls.append(Check('', f, default=(f in existingFeatures)))

        dialog = Args(featureControls, name = "Feature selection",
            title="Select the features you want to use for optimization")

        result = dialog.show(self)

        if result is None:
            gui_util.message("No change applied")
            return

        selectedFeatures = [name for check, name in zip(result, allFeatures) if check]
        self.classifier.change_feature_set(selectedFeatures)

        self.UpdatePanels()
Example #9
0
   def import_command_line_modules(self):
      sys.argv = config.get_free_args()
      if len(sys.argv):
         file = sys.argv[0]
         try:
            name = os.path.basename(file)[:-3]
            module = imp.load_source(name, file)
            self.shell.locals[name] = module
            self.shell.push(name)
            imported = True
         except Exception as e:
            exc_type, exc_value, exc_traceback = sys.exc_info()
            gui_util.message("Error importing file '%s':\n%s" %
                             (file, "".join(
               traceback.format_exception(exc_type, exc_value, exc_traceback))))

      execfiles = config.get("execfile")
      if execfiles is not None:
         for file in execfiles:
            try:
               self.shell.run("execfile(%s)" % repr(file))
            except Exception as e:
               exc_type, exc_value, exc_traceback = sys.exc_info()
               gui_util.message("Error importing file '%s':\n%s" %
                                (file, "".join(traceback.format_exception(
                  exc_type, exc_value, exc_traceback))))
Example #10
0
 def _OnActivated(self, event):
     from gamera import ruleengine
     item = event.GetItem()
     data = self.GetPyData(item)
     multi_display = self.toplevel.multi_iw.id
     single_display = self.toplevel.single_iw.id
     if isfunction(data):
         engine = ruleengine.RuleEngine([data])
     elif isinstance(data, ruleengine.RuleEngine):
         engine = data
     elif ismodule(data):
         engine = ruleengine.RuleEngine([
             val for val in list(data.__dict__.values())
             if isinstance(val, ruleengine.RuleEngine)
         ])
     added = {}
     removed = {}
     try:
         added, removed = engine.perform_rules(multi_display.GetAllItems())
     except ruleengine.RuleEngineError as e:
         gui_util.message(str(e))
         return
     if len(added) == 0 and len(removed) == 0:
         gui_util.message("No rules matched the data set.")
     multi_display.ClearSelection()
     multi_display.append_and_remove_glyphs(added, removed)
     single_display.highlight_cc(added, 0)
     # single_display.add_highlight_cc(removed, 1)
     self.undo_history.append((added, removed))
     self.added, self.removed = added, removed
Example #11
0
def get(default='untitled', dict={}):
    number = 0
    while 1:
        name = '%s%d' % (default, number)
        while dict.has_key(name):
            number = number + 1
            name = '%s%d' % (default, number)
            if number > 1000:
                number = 0
                break
        dlg = wx.TextEntryDialog(None,
                                 'Please enter a variable name for the result',
                                 'Select a variable name',
                                 name,
                                 style=wx.OK | wx.CANCEL | wx.CENTRE)
        button = dlg.ShowModal()
        if button == wx.ID_OK:
            result = dlg.GetValue()
            dlg.Destroy()
            if not verify_variable_name(result):
                gui_util.message("Invalid variable name: " + result)
                return None
            else:
                return result
        else:
            dlg.Destroy()
            return None
Example #12
0
def get(default='untitled', dict={}):
   number = 0
   while 1:
      name = '%s%d' % (default, number)
      while dict.has_key(name):
         number = number + 1
         name = '%s%d' % (default, number)
         if number > 1000:
            number = 0
            break
      dlg = wx.TextEntryDialog(
          None,
          'Please enter a variable name for the result',
          'Select a variable name', name,
          style=wx.OK|wx.CANCEL|wx.CENTRE)
      button = dlg.ShowModal()
      if button == wx.ID_OK:
         result = dlg.GetValue()
         dlg.Destroy()
         if not verify_variable_name(result):
            gui_util.message("Invalid variable name: " + result)
            return None
         else:
            return result
      else:
         dlg.Destroy()
         return None
Example #13
0
   def __init__(self, parent, x, y, images_, name_=None, shell_=None,
                mode=EXECUTE_MODE, extra_methods={}):
      self.shell = shell_
      self.locals = locals
      self.mode = mode
      self.parent = parent
      if not util.is_sequence(images_):
         self.images = [images_]
      else:
         self.images = images_
      if not util.is_homogeneous_image_list(self.images):
         gui_util.message("All selected images are not of the same type.")
      self.image_name = name_

      self._menu_ids = []
      members = members_for_menu(self.images[0])
      methods = methods_for_menu(self.images[0])
      menu = self.create_menu(
        members, methods,
        self.images[0].data.pixel_type,
        self.images[0].pixel_type_name,
        extra_methods)
      self.did_something = 0
      self.parent.PopupMenu(menu, wx.Point(x, y))
      for i in self._menu_ids:
         self.parent.Disconnect(i)
      menu.Destroy()
Example #14
0
 def print_plot(self, evt):
     printout = backend_wx.PrintoutWx(self.canvas)
     dialog_data = wx.PrintDialogData()
     compat_wx.configure_print_dialog_data(dialog_data)
     printer = wx.Printer(dialog_data)
     if not printer.Print(self, printout, True):
         if printer.GetLastError() == wx.PRINTER_ERROR:
             gui_util.message("A printing error occurred.")
Example #15
0
 def print_plot(self, evt):
    printout = backend_wx.PrintoutWx(self.canvas)
    dialog_data = wx.PrintDialogData()
    compat_wx.configure_print_dialog_data(dialog_data)
    printer = wx.Printer(dialog_data)
    if not printer.Print(self, printout, True):
       if printer.GetLastError() == wx.PRINTER_ERROR:
          gui_util.message("A printing error occurred.")
Example #16
0
 def get_string(self):
     while 1:
         text = self.text.GetValue()
         if not os.path.exists(os.path.abspath(text)):
             gui_util.message("File '%s' does not exist." % text)
             self.OnBrowse(None)
         else:
             break
     return _Filename.get_string(self)
Example #17
0
 def get_string(self):
    while 1:
       text = self.text.GetValue()
       if not os.path.exists(os.path.abspath(text)):
          gui_util.message("File '%s' does not exist." % text)
          self.OnBrowse(None)
       else:
          break
    return _Filename.get_string(self)
Example #18
0
 def OnDoubleClick(self, event):
    if self.currentIcon:
       try:
          source = self.currentIcon.double_click()
       except Exception, e:
          gui_util.message(str(e))
       else:
          if not source is None:
             source = source.split("\n")
             for s in source:
                self.shell.run(s)
Example #19
0
 def double_click(self):
    from gamera.gui import matplotlib_support
    if matplotlib_support.matplotlib_installed:
       name = var_name.get("figure")
       if name != None:
          return "%s = plot(%s)" % (name, self.label)
    else:
       gui_util.message("Plotting is not supported because the optional matplotlib library\n"
                     "could not be found.\n\n"
                     "Download and install matplotlib from matplotlib.sourceforge.net,\n"
                     "then restart Gamera to have plotting support.")
Example #20
0
 def double_click(self):
    from gamera.gui import matplotlib_support
    if matplotlib_support.matplotlib_installed:
       name = var_name.get("figure")
       if name != None:
          return "%s = plot(%s)" % (name, self.label)
    else:
       gui_util.message("Plotting is not supported because the optional matplotlib library\n"
                     "could not be found.\n\n"
                     "Download and install matplotlib from matplotlib.sourceforge.net,\n"
                     "then restart Gamera to have plotting support.")
Example #21
0
 def print_plot(self, evt):
    printout = backend_wx.PrintoutWx(self.canvas)
    dialog_data = wx.PrintDialogData()
    if wx.VERSION < (2, 5):
       dialog_data.EnableHelp(False)
       dialog_data.EnablePageNumbers(False)
       dialog_data.EnableSelection(False)
    printer = wx.Printer(dialog_data)
    if not printer.Print(self, printout, True):
       if printer.GetLastError() == wx.PRINTER_ERROR:
          gui_util.message("A printing error occurred.")
Example #22
0
 def OnDoubleClick(self, event):
     if self.currentIcon:
         try:
             source = self.currentIcon.double_click()
         except Exception, e:
             gui_util.message(str(e))
         else:
             if not source is None:
                 source = source.split("\n")
                 for s in source:
                     self.shell.run(s)
Example #23
0
 def print_plot(self, evt):
     printout = backend_wx.PrintoutWx(self.canvas)
     dialog_data = wx.PrintDialogData()
     if wx.VERSION < (2, 5):
         dialog_data.EnableHelp(False)
         dialog_data.EnablePageNumbers(False)
         dialog_data.EnableSelection(False)
     printer = wx.Printer(dialog_data)
     if not printer.Print(self, printout, True):
         if printer.GetLastError() == wx.PRINTER_ERROR:
             gui_util.message("A printing error occurred.")
Example #24
0
 def OnRightClick(self, event):
    index = event.GetIndex()
    if index < 0 or index >= self.GetItemCount():
       event.Skip()
       return
    for i in range(self.GetItemCount()):
       self.SetItemState(i, 0, wx.LIST_STATE_SELECTED)
    self.SetItemState(index, wx.LIST_STATE_SELECTED, wx.LIST_STATE_SELECTED)
    currentIcon = self.find_icon(index)
    if currentIcon:
       try:
          currentIcon.right_click(self, event, self.shell)
       except Exception, e:
          gui_util.message(str(e))
Example #25
0
 def OnRightClick(self, event):
    index = event.GetIndex()
    if index < 0 or index >= self.GetItemCount():
       event.Skip()
       return
    for i in range(self.GetItemCount()):
       self.SetItemState(i, 0, wx.LIST_STATE_SELECTED)
    self.SetItemState(index, wx.LIST_STATE_SELECTED, wx.LIST_STATE_SELECTED)
    currentIcon = self.find_icon(index)
    if currentIcon:
       try:
          currentIcon.right_click(self, event, self.shell)
       except Exception, e:
          gui_util.message(str(e))
Example #26
0
File: gui.py Project: DDMAL/Gamera
 def import_command_line_modules(self):
    sys.argv = config.get_free_args()
    if len(sys.argv):
       file = sys.argv[0]
       try:
          name = os.path.basename(file)[:-3]
          module = imp.load_source(name, file)
          self.shell.locals[name] = module
          self.shell.push(name)
          imported = True
       except Exception, e:
          exc_type, exc_value, exc_traceback = sys.exc_info()
          gui_util.message("Error importing file '%s':\n%s" %
                           (file, "".join(
             traceback.format_exception(exc_type, exc_value, exc_traceback))))
Example #27
0
 def OnKeyPress(self,event):
    keyID = event.GetKeyCode()
    if self.currentIcon:
       if keyID in (127, 8):
          try:
             source = self.currentIcon.delete_key()
          except Exception, e:
             gui_util.message(str(e))
          else:
             self.currentIcon = None
       elif(keyID==19):
          try:
             source = self.currentIcon.control_s()
          except Exception, e:
             gui_util.message(str(e))
Example #28
0
    def OnSaveXML(self, event):
        #---------------------------------------------------------------------------
        if self.classifier == None:
            gui_util.message("No classifier loaded")
            return

        if self.settingsFilename == None:
            self.OnSaveXMLAs(event)

        # save the current settings into file
        wx.BeginBusyCursor()
        try:
            self.classifier.save_settings(self.settingsFilename)
        finally:
            wx.EndBusyCursor()
Example #29
0
 def OnKeyPress(self, event):
     keyID = event.GetKeyCode()
     if self.currentIcon:
         if keyID in (127, 8):
             try:
                 source = self.currentIcon.delete_key()
             except Exception, e:
                 gui_util.message(str(e))
             else:
                 self.currentIcon = None
         elif (keyID == 19):
             try:
                 source = self.currentIcon.control_s()
             except Exception, e:
                 gui_util.message(str(e))
Example #30
0
    def OnSaveXMLAs(self, event):
    #---------------------------------------------------------------------------
        if self.classifier is None:
            gui_util.message("No classifier loaded")
            return

        filename = gui_util.save_file_dialog(self)
        self.settingsFilename = filename

        # save the current settings into file
        wx.BeginBusyCursor()
        try:
            self.classifier.save_settings(self.settingsFilename)
        finally:
            wx.EndBusyCursor()
Example #31
0
    def OnSaveXMLAs(self, event):
        # ---------------------------------------------------------------------------
        if self.classifier == None:
            gui_util.message("No classifier loaded")
            return

        filename = gui_util.save_file_dialog(self)
        self.settingsFilename = filename

        # save the current settings into file
        wx.BeginBusyCursor()
        try:
            self.classifier.save_settings(self.settingsFilename)
        finally:
            wx.EndBusyCursor()
Example #32
0
    def OnLoadSettings(self, event):
    #---------------------------------------------------------------------------
        from gamera import gamera_xml

        if self.classifier is None:
            gui.message("No classifier loaded")
            return

        filename = gui_util.open_file_dialog(self, gamera_xml.extensions)
        if filename is None:
            gui_util.message("Can't open classifier settings xml file")
            return

        self.classifier.load_settings(filename)

        self.UpdatePanels()
Example #33
0
    def OnIntoGameraGUI(self, event):
    #---------------------------------------------------------------------------
        from gamera import knn
        from gamera.gui import gui
        from gamera.gui import var_name

        name = var_name.get("classifier", gui.main_win.shell.locals)

        if name is None:
            gui_util.message("No valid variable name for classifier entered")
            return

        copiedClassifier = self.CopyClassifier(self.classifier)

        gui.main_win.shell.locals[name] = copiedClassifier
        gui.main_win.shell.run('\n')
Example #34
0
    def OnOpenXML(self, event):
        # ---------------------------------------------------------------------------
        from gamera import gamera_xml
        from gamera import knn

        filename = gui_util.open_file_dialog(self, gamera_xml.extensions)
        if filename == None:
            gui_util.message("Can't open classifier-xml file")
            return

        classifier = knn.kNNNonInteractive(filename)
        self.classifier = classifier
        self.SetClassifiers()

        self.UpdatePanels()
        self.EnableControls(True)
Example #35
0
    def OnIntoGameraGUI(self, event):
        # ---------------------------------------------------------------------------
        from gamera import knn
        from gamera.gui import gui
        from gamera.gui import var_name

        name = var_name.get("classifier", gui.main_win.shell.locals)

        if name == None:
            gui_util.message("No valid variable name for classifier entered")
            return

        copiedClassifier = self.CopyClassifier(self.classifier)

        gui.main_win.shell.locals[name] = copiedClassifier
        gui.main_win.shell.run("\n")
Example #36
0
    def OnLoadSettings(self, event):
        # ---------------------------------------------------------------------------
        from gamera import gamera_xml

        if self.classifier == None:
            gui.message("No classifier loaded")
            return

        filename = gui_util.open_file_dialog(self, gamera_xml.extensions)
        if filename == None:
            gui_util.message("Can't open classifier settings xml file")
            return

        self.classifier.load_settings(filename)

        self.UpdatePanels()
Example #37
0
    def OnOpenXML(self, event):
    #---------------------------------------------------------------------------
        from gamera import gamera_xml
        from gamera import knn

        filename = gui_util.open_file_dialog(self, gamera_xml.extensions)
        if filename is None:
            gui_util.message("Can't open classifier-xml file")
            return

        classifier = knn.kNNNonInteractive(filename)
        self.classifier = classifier
        self.SetClassifiers()

        self.UpdatePanels()
        self.EnableControls(True)
Example #38
0
 def OnItemSelected(self, e):
    filename = self.GetFilePath()
    if filename == '':
       return
    wx.BeginBusyCursor()
    try:
       try:
          image = core.load_image(filename)
       except Exception, e:
          gui_util.message("Loading image %s failed. \n\nThe error was:\n%s"
                           % (filename, str(e)))
          return
    finally:
       wx.EndBusyCursor()
    width, height = self.image_display.id.GetSize()
    scale = max(float(width) / float(image.width),
                (float(height) / float(image.height)))
    self.image_display.id.set_image(image, weak=0)
    self.image_display.id.scale(scale)
Example #39
0
 def _OnActivated(self, event):
    from gamera import ruleengine
    item = event.GetItem()
    data = self.GetPyData(item)
    multi_display = self.toplevel.multi_iw.id
    single_display = self.toplevel.single_iw.id
    if isfunction(data):
       engine = ruleengine.RuleEngine([data])
    elif isinstance(data, ruleengine.RuleEngine):
       engine = data
    elif ismodule(data):
       engine = ruleengine.RuleEngine(
         [val for val in data.__dict__.values()
          if isinstance(val, ruleengine.RuleEngine)])
    added = {}
    removed = {}
    try:
       added, removed = engine.perform_rules(multi_display.GetAllItems())
    except ruleengine.RuleEngineError, e:
       gui_util.message(str(e))
       return
Example #40
0
 def _OnActivated(self, event):
     from gamera import ruleengine
     item = event.GetItem()
     data = self.GetPyData(item)
     multi_display = self.toplevel.multi_iw.id
     single_display = self.toplevel.single_iw.id
     if isfunction(data):
         engine = ruleengine.RuleEngine([data])
     elif isinstance(data, ruleengine.RuleEngine):
         engine = data
     elif ismodule(data):
         engine = ruleengine.RuleEngine([
             val for val in data.__dict__.values()
             if isinstance(val, ruleengine.RuleEngine)
         ])
     added = {}
     removed = {}
     try:
         added, removed = engine.perform_rules(multi_display.GetAllItems())
     except ruleengine.RuleEngineError, e:
         gui_util.message(str(e))
         return
Example #41
0
class RuleEngineRunnerTree(wx.TreeCtrl):
    def __init__(self, toplevel, parent):
        self.toplevel = toplevel
        self.modules = []
        self.undo_history = []
        self.added = []
        self.removed = []
        id = wx.NewId()
        wx.TreeCtrl.__init__(self, parent, id)
        self.root = self.AddRoot("RuleSets")
        self.SetItemHasChildren(self.root, True)
        compat_wx.set_tree_item_data(self, self.root, "")
        compat_wx.handle_event_1(self, wx.EVT_TREE_ITEM_ACTIVATED,
                                 self._OnActivated, id)
        self.Expand(self.root)

    def _OnKey(self, event):
        pass

    def _OnActivated(self, event):
        from gamera import ruleengine
        item = event.GetItem()
        data = self.GetPyData(item)
        multi_display = self.toplevel.multi_iw.id
        single_display = self.toplevel.single_iw.id
        if isfunction(data):
            engine = ruleengine.RuleEngine([data])
        elif isinstance(data, ruleengine.RuleEngine):
            engine = data
        elif ismodule(data):
            engine = ruleengine.RuleEngine([
                val for val in data.__dict__.values()
                if isinstance(val, ruleengine.RuleEngine)
            ])
        added = {}
        removed = {}
        try:
            added, removed = engine.perform_rules(multi_display.GetAllItems())
        except ruleengine.RuleEngineError, e:
            gui_util.message(str(e))
            return
        if len(added) == 0 and len(removed) == 0:
            gui_util.message("No rules matched the data set.")
        multi_display.ClearSelection()
        multi_display.append_and_remove_glyphs(added, removed)
        single_display.highlight_cc(added, 0)
        # single_display.add_highlight_cc(removed, 1)
        self.undo_history.append((added, removed))
        self.added, self.removed = added, removed
Example #42
0
File: gui.py Project: DDMAL/Gamera
 def OnLinkClicked(self, link):
    if not self.message_displayed:
       gui_util.message("Clicking on links is not supported.")
       self.message_displayed = True
Example #43
0
    def startCalculation(self):
    #---------------------------------------------------------------------------

        if self.frame.classifier == None:
            gui_util.message("No classifier loaded")
            return

        # Base GA settings
        base = knnga.GABaseSetting()

        if self.featureSelection.GetValue():
            base.opMode = knnga.GA_SELECTION
        elif self.featureWeighting.GetValue():
            base.opMode = knnga.GA_WEIGHTING

        # Set the normalization state in the used classifier
        if self.classifier.get_normalization_state() != self.normalization.GetValue():
            self.classifier.set_normalization_state(self.normalization.GetValue())

        base.popSize = self.popSize.GetValue()
        base.crossRate = self.crossoverRate.GetValue() / 100.0
        base.mutRate = self.mutationRate.GetValue() / 100.0

        # calculate initial leave one out rate for status display
        self.initLOO = None
        initLOOThread = GAInitialLOOWorker(self.frame.classifier, self.frame)
        initLOOThread.setDaemon(1)
        initLOOThread.start()

        # Selection GA settings
        selection = knnga.GASelection()

        for expertWidget in self.selectionPanel.GetAllSettingWidgets():
            if expertWidget.IsEnabled() and expertWidget.GetValue():
                if expertWidget.GetName() == "rouletteWheel":
                    selection.setRoulettWheel()
                elif expertWidget.GetName() == "rouletteWheelScaled":
                    selection.setRoulettWheelScaled(\
                        self.selectionPanel.roulettWheelPreasure.GetValue())
                elif expertWidget.GetName() == "stochUniSampling":
                    selection.setStochUniSampling()
                elif expertWidget.GetName() == "rankSelection":
                    selection.setRankSelection(\
                        self.selectionPanel.rankSelectionPreasure.GetValue(),\
                        self.selectionPanel.rankSelectionExponent.GetValue())
                elif expertWidget.GetName() == "tournamentSelection":
                    selection.setTournamentSelection(\
                        self.selectionPanel.TournamentSelectionTsize.GetValue())
                elif expertWidget.GetName() == "randomSelection":
                    selection.setRandomSelection()
                else:
                    raise RuntimeError("Unknown selection method choosen")

        # Crossover GA settings
        cross = knnga.GACrossover()

        crossOpSet = False
        for expertWidget in self.crossoverPanel.GetAllSettingWidgets():
            if expertWidget.IsEnabled() and expertWidget.GetValue():
                if expertWidget.GetName() == "nPointCrossover":
                    cross.setNPointCrossover(self.crossoverPanel.nPointCrossoverN.GetValue())
                elif expertWidget.GetName() == "uniformCrossover":
                    cross.setUniformCrossover(self.crossoverPanel.uniformCrossoverPref.GetValue())
                elif expertWidget.GetName() == "SBXcrossover":
                    cross.setSBXcrossover(self.frame.classifier.num_features, 0.0, 1.0, \
                        self.crossoverPanel.sbxCrossoverEta.GetValue())
                elif expertWidget.GetName() == "segmentCrossover":
                    cross.setSegmentCrossover(self.frame.classifier.num_features, 0.0, 1.0, \
                        self.crossoverPanel.segmentCrossoverAlpha.GetValue())
                elif expertWidget.GetName() == "hypercubeCrossover":
                    cross.setHypercubeCrossover(self.frame.classifier.num_features, 0.0, 1.0, \
                        self.crossoverPanel.hypercubeCrossoverAlpha.GetValue())
                else:
                    raise RuntimeError("Unknown crossover method choosen")
                crossOpSet = True
        if not crossOpSet:
            raise RuntimeError("At least one crossover operator must be choosen")

        # Mutation GA settings
        muta = knnga.GAMutation()

        mutOpSet = False
        for expertWidget in self.mutationPanel.GetAllSettingWidgets():
            if expertWidget.IsEnabled() and expertWidget.GetValue():
                if expertWidget.GetName() == "shiftMutation":
                    muta.setShiftMutation()
                elif expertWidget.GetName() == "swapMuation":
                    muta.setSwapMutation()
                elif expertWidget.GetName() == "inversionMutation":
                    muta.setInversionMutation()
                elif expertWidget.GetName() == "binaryMutation":
                    muta.setBinaryMutation(self.mutationPanel.binaryMutationRate.GetValue(), False)
                elif expertWidget.GetName() == "gaussMutation":
                    muta.setGaussMutation(self.frame.classifier.num_features, 0.0, 1.0, \
                        self.mutationPanel.gaussMutationSigma.GetValue(), \
                        self.mutationPanel.gaussMutationPchance.GetValue())
                else:
                    raise RuntimeError("Unknown mutation method choosen")
                mutOpSet = True
        if not mutOpSet:
            raise RuntimeError("At least one mutation operator must be choosen")

        # Replacement GA settings
        replacement = knnga.GAReplacement()

        for expertWidget in self.replacementPanel.GetAllSettingWidgets():
            if expertWidget.IsEnabled() and expertWidget.GetValue():
                if expertWidget.GetName() == "generationalReplacement":
                    replacement.setGenerationalReplacement()
                elif expertWidget.GetName() == "SSGAworse":
                    replacement.setSSGAworse()
                elif expertWidget.GetName() == "SSGAdetTournament":
                    replacement.setSSGAdetTournament(self.replacementPanel.ssgaDetTourTsize.GetValue())
                else:
                    raise RuntimeError("Unknown replacement method choosen")

        # Stop Criteria GA settings
        stop = knnga.GAStopCriteria()

        stopCritSet = False
        for expertWidget in self.stopCriteriaPanel.GetAllSettingWidgets():
            if expertWidget.IsEnabled() and expertWidget.GetValue():
                if expertWidget.GetName() == "bestFitnessStop":
                    stop.setBestFitnessStop(1.0)
                elif expertWidget.GetName() == "maxGenerations":
                    stop.setMaxGenerations(self.stopCriteriaPanel.maxGenerationCount.GetValue())
                elif expertWidget.GetName() == "maxFitnessEvals":
                    stop.setMaxFitnessEvals(self.stopCriteriaPanel.maxFitnessEvalCount.GetValue())
                elif expertWidget.GetName() == "steadyStateStop":
                    stop.setSteadyStateStop(self.stopCriteriaPanel.steadyContinueMin.GetValue(), \
                        self.stopCriteriaPanel.steadyContinueNoChange.GetValue())
                else:
                    raise RuntimeError("Unknown stop criteria choosen")
                stopCritSet = True
        if not stopCritSet:
            raise RuntimeError("At least one stop criteria must be choosen")

        # Parallelization GA settings
        para = knnga.GAParallelization()

        para.mode = self.parallelizationPanel.parallelEnabled.GetValue()
        para.thredNum = self.parallelizationPanel.threadNum.GetValue()

        # encapsulate all settings to the final algorithm
        ga = knnga.GAOptimization(self.frame.classifier, base, selection, cross, \
                                  muta, replacement, stop, para)

        self.workerThread = GAWorker(ga, self.frame)
        self.workerThread.setDaemon(1)

        self.frame.statusPanel.starttime = time.time()
        self.frame.timer.Start(1000)
        self.workerThread.start()

        self.frame.UpdatePanels()
        self.stopButton.Enable()
        self.frame.statusPanel.stopButton.Enable()

        # switch to status panel
        self.frame.notebook.SetSelection(1)
Example #44
0
 def OnLinkClicked(self, link):
     if not self.message_displayed:
         gui_util.message("Clicking on links is not supported.")
         self.message_displayed = True
Example #45
0
class ShellFrame(wx.Frame):
    def __init__(self, parent, id, title):
        global shell
        wx.Frame.__init__(
            self,
            parent,
            id,
            title,
            (100, 100),
            # Win32 change
            [600, 550],
            style=wx.DEFAULT_FRAME_STYLE | wx.CLIP_CHILDREN
            | wx.NO_FULL_REPAINT_ON_RESIZE)
        wx.EVT_CLOSE(self, self._OnCloseWindow)

        self.known_modules = {}
        self.menu = self.make_menu()
        self.SetMenuBar(self.menu)

        if aui:
            self._aui = aui.AuiManager(self)
            nb_style = (aui.AUI_NB_TAB_SPLIT | aui.AUI_NB_TAB_MOVE
                        | aui.AUI_NB_TAB_EXTERNAL_MOVE
                        | aui.AUI_NB_SCROLL_BUTTONS)
            nb = aui.AuiNotebook(self, style=nb_style)
            control_parent = self
        else:
            splitter = wx.SplitterWindow(self,
                                         -1,
                                         style=wx.SP_3DSASH | wx.CLIP_CHILDREN
                                         | wx.NO_FULL_REPAINT_ON_RESIZE
                                         | wx.SP_LIVE_UPDATE)
            control_parent = splitter

        self.icon_display = icon_display.IconDisplay(control_parent, self)
        if aui:
            self.shell = PyShellGameraShell(parent=self)
            rootObject = self.shell.interp.locals
            self.filling = wx.py.filling.Filling(parent=nb,
                                                 rootObject=rootObject,
                                                 rootIsNamespace=True)
            # Add 'filling' to the interpreter's locals.
            self.calltip = Calltip(parent=nb)
            self.sessionlisting = wx.py.crust.SessionListing(parent=nb)
        else:
            crust = PyCrustGameraShell(control_parent, -1)
            self.shell = crust.shell
        self.shell.main_win = self
        self.shell.update = self.Update
        image_menu.set_shell(self.shell)
        image_menu.set_shell_frame(self)
        self.shell.push("from gamera.gui import gui")
        self.shell.push("from gamera.gui.matplotlib_support import *")
        self.shell.push("from gamera.core import *")
        self.shell.push("init_gamera()")

        self.shell.update = self.Update
        self.icon_display.shell = self.shell
        self.icon_display.main = self
        self.Update()
        self.shell.SetFocus()

        if aui:
            self._aui.AddPane(
                self.icon_display,
                aui.AuiPaneInfo().Name("icon_display").CenterPane().MinSize(
                    wx.Size(96, 96)).CloseButton(False).CaptionVisible(
                        True).Caption("Objects").Dockable(True))
            self._aui.AddPane(
                self.shell,
                aui.AuiPaneInfo().Name("shell").CenterPane().MinSize(
                    wx.Size(200, 200)).CloseButton(False).CaptionVisible(
                        True).MaximizeButton(True).Caption(
                            "Interactive Python Shell").Dockable(True))
            nb.AddPage(self.calltip, "Documentation")
            nb.AddPage(self.filling, "Namespace")
            nb.AddPage(self.sessionlisting, "History")
            self._aui.AddPane(
                nb,
                aui.AuiPaneInfo().Name("notebook").CenterPane().MinSize(
                    wx.Size(200, 100)).MaximizeButton(True))

            self._aui.GetPane("notebook").Show().Bottom()
            self._aui.GetPane("icon_display").Show().Left()
            self._aui.Update()
        else:
            splitter.SetMinimumPaneSize(20)
            splitter.SplitVertically(self.icon_display, crust, 120)
            splitter.SetSashPosition(120)

        self.status = StatusBar(self)
        self.SetStatusBar(self.status)
        from gamera.gui import gamera_icons
        icon = wx.IconFromBitmap(gamera_icons.getIconBitmap())
        self.SetIcon(icon)
        self.Move(wx.Point(int(30), int(30)))
        wx.Yield()

    def import_command_line_modules(self):
        sys.argv = config.get_free_args()
        if len(sys.argv):
            file = sys.argv[0]
            try:
                name = os.path.basename(file)[:-3]
                module = imp.load_source(name, file)
                self.shell.locals[name] = module
                self.shell.push(name)
                imported = True
            except Exception, e:
                exc_type, exc_value, exc_traceback = sys.exc_info()
                gui_util.message("Error importing file '%s':\n%s" %
                                 (file, "".join(
                                     traceback.format_exception(
                                         exc_type, exc_value, exc_traceback))))

        execfiles = config.get("execfile")
        if execfiles is not None:
            for file in execfiles:
                try:
                    self.shell.run("execfile(%s)" % repr(file))
                except Exception, e:
                    exc_type, exc_value, exc_traceback = sys.exc_info()
                    gui_util.message(
                        "Error importing file '%s':\n%s" % (file, "".join(
                            traceback.format_exception(exc_type, exc_value,
                                                       exc_traceback))))
Example #46
0
    def startCalculation(self):
    #---------------------------------------------------------------------------

        if self.frame.classifier is None:
            gui_util.message("No classifier loaded")
            return

        # Base GA settings
        base = knnga.GABaseSetting()

        if self.featureSelection.GetValue():
            base.opMode = knnga.GA_SELECTION
        elif self.featureWeighting.GetValue():
            base.opMode = knnga.GA_WEIGHTING

        # Set the normalization state in the used classifier
        if self.classifier.get_normalization_state() != self.normalization.GetValue():
            self.classifier.set_normalization_state(self.normalization.GetValue())

        base.popSize = self.popSize.GetValue()
        base.crossRate = self.crossoverRate.GetValue() / 100.0
        base.mutRate = self.mutationRate.GetValue() / 100.0

        # calculate initial leave one out rate for status display
        self.initLOO = None
        initLOOThread = GAInitialLOOWorker(self.frame.classifier, self.frame)
        initLOOThread.setDaemon(1)
        initLOOThread.start()

        # Selection GA settings
        selection = knnga.GASelection()

        for expertWidget in self.selectionPanel.GetAllSettingWidgets():
            if expertWidget.IsEnabled() and expertWidget.GetValue():
                if expertWidget.GetName() == "rouletteWheel":
                    selection.setRoulettWheel()
                elif expertWidget.GetName() == "rouletteWheelScaled":
                    selection.setRoulettWheelScaled(\
                        self.selectionPanel.roulettWheelPreasure.GetValue())
                elif expertWidget.GetName() == "stochUniSampling":
                    selection.setStochUniSampling()
                elif expertWidget.GetName() == "rankSelection":
                    selection.setRankSelection(\
                        self.selectionPanel.rankSelectionPreasure.GetValue(),\
                        self.selectionPanel.rankSelectionExponent.GetValue())
                elif expertWidget.GetName() == "tournamentSelection":
                    selection.setTournamentSelection(\
                        self.selectionPanel.TournamentSelectionTsize.GetValue())
                elif expertWidget.GetName() == "randomSelection":
                    selection.setRandomSelection()
                else:
                    raise RuntimeError("Unknown selection method chosen")

        # Crossover GA settings
        cross = knnga.GACrossover()

        crossOpSet = False
        for expertWidget in self.crossoverPanel.GetAllSettingWidgets():
            if expertWidget.IsEnabled() and expertWidget.GetValue():
                if expertWidget.GetName() == "nPointCrossover":
                    cross.setNPointCrossover(self.crossoverPanel.nPointCrossoverN.GetValue())
                elif expertWidget.GetName() == "uniformCrossover":
                    cross.setUniformCrossover(self.crossoverPanel.uniformCrossoverPref.GetValue())
                elif expertWidget.GetName() == "SBXcrossover":
                    cross.setSBXcrossover(self.frame.classifier.num_features, 0.0, 1.0, \
                        self.crossoverPanel.sbxCrossoverEta.GetValue())
                elif expertWidget.GetName() == "segmentCrossover":
                    cross.setSegmentCrossover(self.frame.classifier.num_features, 0.0, 1.0, \
                        self.crossoverPanel.segmentCrossoverAlpha.GetValue())
                elif expertWidget.GetName() == "hypercubeCrossover":
                    cross.setHypercubeCrossover(self.frame.classifier.num_features, 0.0, 1.0, \
                        self.crossoverPanel.hypercubeCrossoverAlpha.GetValue())
                else:
                    raise RuntimeError("Unknown crossover method chosen")
                crossOpSet = True
        if not crossOpSet:
            raise RuntimeError("At least one crossover operator must be chosen")

        # Mutation GA settings
        muta = knnga.GAMutation()

        mutOpSet = False
        for expertWidget in self.mutationPanel.GetAllSettingWidgets():
            if expertWidget.IsEnabled() and expertWidget.GetValue():
                if expertWidget.GetName() == "shiftMutation":
                    muta.setShiftMutation()
                elif expertWidget.GetName() == "swapMuation":
                    muta.setSwapMutation()
                elif expertWidget.GetName() == "inversionMutation":
                    muta.setInversionMutation()
                elif expertWidget.GetName() == "binaryMutation":
                    muta.setBinaryMutation(self.mutationPanel.binaryMutationRate.GetValue(), False)
                elif expertWidget.GetName() == "gaussMutation":
                    muta.setGaussMutation(self.frame.classifier.num_features, 0.0, 1.0, \
                        self.mutationPanel.gaussMutationSigma.GetValue(), \
                        self.mutationPanel.gaussMutationPchance.GetValue())
                else:
                    raise RuntimeError("Unknown mutation method chosen")
                mutOpSet = True
        if not mutOpSet:
            raise RuntimeError("At least one mutation operator must be chosen")

        # Replacement GA settings
        replacement = knnga.GAReplacement()

        for expertWidget in self.replacementPanel.GetAllSettingWidgets():
            if expertWidget.IsEnabled() and expertWidget.GetValue():
                if expertWidget.GetName() == "generationalReplacement":
                    replacement.setGenerationalReplacement()
                elif expertWidget.GetName() == "SSGAworse":
                    replacement.setSSGAworse()
                elif expertWidget.GetName() == "SSGAdetTournament":
                    replacement.setSSGAdetTournament(self.replacementPanel.ssgaDetTourTsize.GetValue())
                else:
                    raise RuntimeError("Unknown replacement method chosen")

        # Stop Criteria GA settings
        stop = knnga.GAStopCriteria()

        stopCritSet = False
        for expertWidget in self.stopCriteriaPanel.GetAllSettingWidgets():
            if expertWidget.IsEnabled() and expertWidget.GetValue():
                if expertWidget.GetName() == "bestFitnessStop":
                    stop.setBestFitnessStop(1.0)
                elif expertWidget.GetName() == "maxGenerations":
                    stop.setMaxGenerations(self.stopCriteriaPanel.maxGenerationCount.GetValue())
                elif expertWidget.GetName() == "maxFitnessEvals":
                    stop.setMaxFitnessEvals(self.stopCriteriaPanel.maxFitnessEvalCount.GetValue())
                elif expertWidget.GetName() == "steadyStateStop":
                    stop.setSteadyStateStop(self.stopCriteriaPanel.steadyContinueMin.GetValue(), \
                        self.stopCriteriaPanel.steadyContinueNoChange.GetValue())
                else:
                    raise RuntimeError("Unknown stop criteria chosen")
                stopCritSet = True
        if not stopCritSet:
            raise RuntimeError("At least one stop criteria must be chosen")

        # Parallelization GA settings
        para = knnga.GAParallelization()

        para.mode = self.parallelizationPanel.parallelEnabled.GetValue()
        para.thredNum = self.parallelizationPanel.threadNum.GetValue()

        # encapsulate all settings to the final algorithm
        ga = knnga.GAOptimization(self.frame.classifier, base, selection, cross, \
                                  muta, replacement, stop, para)

        self.workerThread = GAWorker(ga, self.frame)
        self.workerThread.setDaemon(1)

        self.frame.statusPanel.starttime = time.time()
        self.frame.timer.Start(1000)
        self.workerThread.start()

        self.frame.UpdatePanels()
        self.stopButton.Enable()
        self.frame.statusPanel.stopButton.Enable()

        # switch to status panel
        self.frame.notebook.SetSelection(1)
Example #47
0
 def OnLinkClicked(self, link):
     from gamera.gui.gui_util import message
     if not self.message_displayed:
         message("Clicking on links is not supported.")
         self.message_displayed = True
Example #48
0
 def OnLinkClicked(self, link):
    from gamera.gui.gui_util import message
    if not self.message_displayed:
       message("Clicking on links is not supported.")
       self.message_displayed = True