Ejemplo n.º 1
0
 def test_create_instance(self):
     """ Create instance of Config. """
     cfg = core.Config()
     self.assertEqual(cfg.sections, {})
     self.assertEqual(cfg.selected_cfgfile, None)
     self.assertEqual(cfg.fns[0], 'tyme.cfg')
     self.assertTrue(cfg.fns[1].endswith('.tyme.cfg'))
Ejemplo n.º 2
0
 def test_importDefaultsAddsNewSection(self):
     c = core.Config()
     self.assertTrue(not c.has_section("Test"),
                     "Config should not have test section until imported")
     c.importDefaults("Test", {"a": "b"})
     self.assertEquals(c.get("Test", "a"), "b",
                       "Config should import default and create section")
Ejemplo n.º 3
0
    def read_config(self):
        """ Read configuration. """
        # Read configuration and get section names
        cfg = core.Config()
        cfg.read()
        log.info("selected config file : %s" % cfg.selected_cfgfile)

        # Load submodule
        modules = {
            modname: importer.find_module(modname).load_module(modname)
            for importer, modname, ispkg in pkgutil.iter_modules(notif.__path__)
            if modname in cfg.sections.keys()
        }
        log.info("load submodule : %s" % list(modules.keys()))

        # Create notification instance for each activated submodule
        self.notifs = dict()
        for modname, m in modules.items():
            t = [e for e in dir(m) if e.startswith('Notification')]

            if not len(t):
                raise SystemError(("The '{modname}' module must contain a "
                                   "'Notification...' class").format(**locals()))

            if len(t) > 1:
                raise SystemError(("The '{modname}' module must contain only one "
                                   "'Notification...' class").format(**locals()))

            cls = m.__dict__[t[0]]  # class
            kw = cfg.sections[modname]  # dict from configuration
            self.notifs[modname] = cls(**kw)  # new instance
Ejemplo n.º 4
0
    def populate_table(self):
        self.table.clearContents()
        self.table.setRowCount(len(self.runs) + 1)
        cls_sum = 0
        dist_sum = []
        dist_cnt = []
        runs_by_name = sorted(self.runs, key=lambda run: run['name'])
        for row, run in enumerate(runs_by_name):

            colormap = run['colormaps'][-1]
            l_counts = [colormap.count(x) for x in set(colormap)]
            l_counts.sort(reverse=True)

            for index, val in enumerate(l_counts):
                if index >= len(dist_sum):
                    dist_sum.append(val)
                    dist_cnt.append(1)
                else:
                    dist_sum[index] += val
                    dist_cnt[index] += 1
            cls_sum += len(l_counts)

            params = self.get_params(run)
            conf = core.Config(params)

            for col in range(6):
                item = QTableWidgetItem('')

                if col == 0:
                    item = QTableWidgetItem(run['name'][14:])
                elif col == 1:
                    item = QTableWidgetItem(str(len(l_counts)))
                elif col == 2:
                    item = QTableWidgetItem(str(l_counts))
                elif col == 3:
                    item = QTableWidgetItem(
                        '%.4f' % (1 / conf.dataset.getOptimalFitness(conf)))
                elif col == 4:
                    item = QTableWidgetItem('%.4f' %
                                            (1 / run['measures'][-1][5]))
                elif col == 5:
                    btn = QPushButton(self.table)
                    btn.setText('Show')
                    btn.clicked.connect(partial(self.show_details, row - 1))
                    self.table.setCellWidget(row + 1, col, btn)

                if col != 5:
                    self.table.setItem(row + 1, col, item)

        avg_clsnum = '%.3f' % (cls_sum / len(self.runs))
        avg_dist = []
        for index, val in enumerate(dist_sum):
            avg_dist.append(dist_sum[index] / dist_cnt[index])
        avg_dist_str = ["%.1f" % t for t in avg_dist]

        for index, val in enumerate(
            ['Average', avg_clsnum, '[' + ", ".join(avg_dist_str) + ']']):
            item = QTableWidgetItem(val)
            self.table.setItem(0, index, item)
Ejemplo n.º 5
0
 def test_importDefaultsDoesNotOverride(self):
     c = core.Config()
     c.add_section("Test")
     c.set("Test", "a", "testvalue")
     c.importDefaults("Test", {"a": "b"})
     self.assertEquals(
         c.get("Test", "a"), "testvalue",
         "Config should not import default when there is already a value")
Ejemplo n.º 6
0
 def test_config_no_file(self):
     """ Test of Config with no configuration file. """
     with tempfile.TemporaryDirectory() as tmpdir:
         os.chdir(tmpdir)
         cfg = core.Config()
         cfg.fns = []  # remove any reference to config path
         cfg.read()
     self.assertTrue('stderr' in cfg.sections.keys())
     self.assertEqual(len(cfg.sections['stderr']), 0)
Ejemplo n.º 7
0
 def test_config_empty_file(self):
     """ Test of Config with empty configuration file. """
     with tempfile.TemporaryDirectory() as tmpdir:
         os.chdir(tmpdir)
         with open('tyme.cfg', 'w') as f:
             f.write("\n\n")
         cfg = core.Config()
         cfg.read()
     self.assertEqual(len(cfg.sections.keys()), 0)
Ejemplo n.º 8
0
 def test_config_1section(self):
     """ Test of Config with one section. """
     with tempfile.TemporaryDirectory() as tmpdir:
         os.chdir(tmpdir)
         with open('tyme.cfg', 'w') as f:
             f.write("[spam]\negg = aZeRtY\nbacon = PoIuY\n\n")
         cfg = core.Config()
         cfg.read()
     self.assertEqual(list(cfg.sections.keys()), ['spam'])
     self.assertTrue('egg' in cfg.sections['spam'].keys())
     self.assertTrue('bacon' in cfg.sections['spam'].keys())
     self.assertEqual(cfg.sections['spam']['egg'], 'aZeRtY')
     self.assertEqual(cfg.sections['spam']['bacon'], 'PoIuY')
Ejemplo n.º 9
0
 def test_config_2sections(self):
     """ Test of Config with two sections. """
     with tempfile.TemporaryDirectory() as tmpdir:
         os.chdir(tmpdir)
         with open('tyme.cfg', 'w') as f:
             f.write("[foo]\nspam = 55\negg = 12\n\n[bar]\npy = 3\n\n")
         cfg = core.Config()
         cfg.read()
     self.assertTrue('foo' in cfg.sections.keys())
     self.assertTrue('bar' in cfg.sections.keys())
     self.assertTrue('spam' in cfg.sections['foo'].keys())
     self.assertTrue('egg' in cfg.sections['foo'].keys())
     self.assertTrue('py' in cfg.sections['bar'].keys())
     self.assertEqual(cfg.sections['foo']['spam'], '55')
     self.assertEqual(cfg.sections['foo']['egg'], '12')
     self.assertEqual(cfg.sections['bar']['py'], '3')
Ejemplo n.º 10
0
    def run_group_changed(self, rg_index):
        run_paths = []
        self.runs = []

        if rg_index != 0:
            basepath = os.path.join(self.resfolder,
                                    self.run_groups[rg_index - 1])
            for dirname, dirnames, filenames in os.walk(basepath):
                for f in filenames:
                    run_paths.append(os.path.join(basepath, f))
        else:
            self.table.clearContents()
            self.clearLabels()
            return

        log = logger.Log()
        for path in run_paths:
            run = {}
            log.load(path)
            run['params'] = log.head_as_array
            run['colormaps'] = log.colormaps
            run['measures'] = log.measures
            dirs, filename = os.path.split(path)
            run['dataset'] = filename.split('_')[2]
            run['name'] = filename
            self.runs.append(run)

        params = self.get_params(self.runs[0])
        params['Feature significance'] = False if params[
            'Distance measure'] is not 'Minkowski2' else params[
                'Feature significance']
        self.window.label_dataset.setText(params['Dataset'])
        opt_config = core.Config(params)
        self.window.label_classes.setText(
            str(opt_config.dataset.params['Classes']))

        distribution = []
        for k, v in opt_config.dataset.params['Clusters'].iteritems():
            distribution.append(v)

        self.window.label_distribution.setText(str(distribution))

        self.populate_table()
Ejemplo n.º 11
0
 def test_setDoesNotChangeCass(self):
     c = core.Config()
     c.add_section("TesT")
     c.set("TesT", "AbC", "TestValuE")
     self.assertEquals(c.get("TesT", "AbC"), "TestValuE",
                       "Config should not change case of imported values")