Skip to content

Commit

Permalink
Merge pull request #82 from YektaY/config
Browse files Browse the repository at this point in the history
ENH: Creates a config.yaml file to hold badger's settings
  • Loading branch information
roussel-ryan authored Oct 23, 2024
2 parents 615fcca + 7c53408 commit 200ecf8
Show file tree
Hide file tree
Showing 25 changed files with 546 additions and 233 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ __pycache__
/examples/*.yaml
*.pickle
*.db
config.yaml
.vscode
src/badger/_version.py
.coverage*
Empty file added __init__.py
Empty file.
2 changes: 0 additions & 2 deletions src/badger/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from . import _version

try:
from ._version import __version__
except ImportError:
Expand Down
4 changes: 0 additions & 4 deletions src/badger/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

from .log import config_log
config_log() # has to happen here to make sure the config taking effect
from .settings import init_settings
from .actions import show_info
from .actions.doctor import self_check
from .actions.routine import show_routine
Expand All @@ -16,9 +15,6 @@


def main():
# Initialize the Badger settings
init_settings()

# Create the top-level parser
parser = argparse.ArgumentParser(description='Badger the optimizer')
parser.add_argument('-g', '--gui', action='store_true',
Expand Down
11 changes: 6 additions & 5 deletions src/badger/actions/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,13 @@ def show_info(args):
if not check_n_config_paths():
return

from ..settings import read_value
from ..settings import init_settings

BADGER_PLUGIN_ROOT = read_value("BADGER_PLUGIN_ROOT")
BADGER_DB_ROOT = read_value("BADGER_DB_ROOT")
BADGER_LOGBOOK_ROOT = read_value("BADGER_LOGBOOK_ROOT")
BADGER_ARCHIVE_ROOT = read_value("BADGER_ARCHIVE_ROOT")
config_singleton = init_settings()
BADGER_PLUGIN_ROOT = config_singleton.read_value("BADGER_PLUGIN_ROOT")
BADGER_DB_ROOT = config_singleton.read_value("BADGER_DB_ROOT")
BADGER_LOGBOOK_ROOT = config_singleton.read_value("BADGER_LOGBOOK_ROOT")
BADGER_ARCHIVE_ROOT = config_singleton.read_value("BADGER_ARCHIVE_ROOT")

info = {
'name': 'Badger the optimizer',
Expand Down
30 changes: 17 additions & 13 deletions src/badger/actions/config.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
from ..settings import list_settings, read_value, write_value, BADGER_PATH_DICT, BADGER_CORE_DICT
from ..settings import init_settings
import os
import logging
logger = logging.getLogger(__name__)
from ..utils import yprint, convert_str_to_value


def config_settings(args):
config_singleton = init_settings()
key = args.key

if key is None:
yprint(list_settings())
yprint(config_singleton.list_settings())
return

try:
Expand All @@ -29,8 +30,9 @@ def config_settings(args):


def _config_path_var(var_name):
display_name = BADGER_PATH_DICT[var_name]['display name']
desc = BADGER_PATH_DICT[var_name]['description']
config_singleton = init_settings()
display_name = config_singleton[var_name]['display name']
desc = config_singleton[var_name]['description']

print(f'=== Configure {display_name} ===')
print(f'*** {desc} ***\n')
Expand All @@ -41,7 +43,7 @@ def _config_path_var(var_name):
break
if res == 'R':
_res = input(
f'The current value {read_value(var_name)} will be reset, proceed (y/[n])? ')
f'The current value {config_singleton.read_value(var_name)} will be reset, proceed (y/[n])? ')
if _res == 'y':
break
elif (not _res) or (_res == 'n'):
Expand Down Expand Up @@ -74,17 +76,19 @@ def _config_path_var(var_name):
print(f'Invalid choice: {_res}')

if res == 'R':
write_value(var_name, None)
config_singleton.write_value(var_name, None)
print(f'You reset the Badger {display_name} folder setting')
elif res != 'S':
write_value(var_name, res)
config_singleton.write_value(var_name, res)
print(f'You set the Badger {display_name} folder to {res}')


def _config_core_var(var_name):
display_name = BADGER_CORE_DICT[var_name]['display name']
desc = BADGER_CORE_DICT[var_name]['description']
default = BADGER_CORE_DICT[var_name]['default value']
config_singleton = init_settings()

display_name = config_singleton.get_section('core')[var_name]['display name']
desc = config_singleton.get_section('core')[var_name]['description']
default = config_singleton.get_section('core')[var_name]['default value']

print(f'=== Configure {display_name} ===')
print(f'*** {desc} ***\n')
Expand All @@ -95,7 +99,7 @@ def _config_core_var(var_name):
break
if res == 'R':
_res = input(
f'The current value {read_value(var_name)} will be reset to {default}, proceed (y/[n])? ')
f'The current value {config_singleton.read_value(var_name)} will be reset to {default}, proceed (y/[n])? ')
if _res == 'y':
break
elif (not _res) or (_res == 'n'):
Expand All @@ -107,8 +111,8 @@ def _config_core_var(var_name):
break

if res == 'R':
write_value(var_name, default)
config_singleton.write_value(var_name, default)
print(f'You reset the {display_name} setting')
elif res != 'S':
write_value(var_name, convert_str_to_value(res))
config_singleton.write_value(var_name, convert_str_to_value(res))
print(f'You set {display_name} to {res}')
13 changes: 7 additions & 6 deletions src/badger/actions/doctor.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
from ..settings import read_value, BADGER_PATH_DICT, \
reset_settings, mock_settings
from ..settings import init_settings, mock_settings
from .config import _config_path_var


def self_check(args):

config = init_settings()
# Reset Badger
if args.reset:
while True:
Expand All @@ -21,7 +21,7 @@ def self_check(args):
else:
print(f'Invalid choice: {_res}')

reset_settings()
config.reset_settings()
print('Badger has been reset to the factory settings.')
return

Expand All @@ -31,12 +31,13 @@ def self_check(args):


def check_n_config_paths():
good = True
config = init_settings()

good = True
issue_list = []

for pname in BADGER_PATH_DICT.keys():
if not read_value(pname):
for pname in config._config.dict(by_alias=True):
if not config.read_value(pname):
good = False
# dname = BADGER_PATH_DICT[pname]['display name']
# print(f'\n{dname} needs to be configured!')
Expand Down
5 changes: 3 additions & 2 deletions src/badger/actions/install.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from tqdm.auto import tqdm
import shutil
from os.path import exists
from ..settings import read_value
from ..settings import init_settings


def plugin_install(args):
Expand Down Expand Up @@ -44,7 +44,8 @@ def plugin_install(args):
print(f"{args.plugin_type} is an invalid option. Choose one of the following: generator, env, ext, intf, local")
return

plugins_url = read_value('BADGER_PLUGINS_URL')
config = init_settings()
plugins_url = config.read_value('BADGER_PLUGINS_URL')

if args.plugin_specific is None:
if args.plugin_type == 'local':
Expand Down
6 changes: 3 additions & 3 deletions src/badger/actions/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from ..utils import config_list_to_dict, curr_ts
from ..core import run_routine as run
from ..routine import Routine
from ..settings import read_value
from ..settings import init_settings
from ..errors import BadgerRunTerminatedError


Expand Down Expand Up @@ -60,9 +60,9 @@ def after_evaluate(data: DataFrame):
# stas: list
ts = curr_ts()
ts_float = ts.timestamp()

config = init_settings()
# Try dump the run data and interface log to the disk
dump_period = float(read_value('BADGER_DATA_DUMP_PERIOD'))
dump_period = float(config.read_value('BADGER_DATA_DUMP_PERIOD'))
ts_last_dump = storage['ts_last_dump']
if (ts_last_dump is None) or (ts_float - ts_last_dump > dump_period):
storage['ts_last_dump'] = ts_float
Expand Down
5 changes: 3 additions & 2 deletions src/badger/archive.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,14 @@
logger = logging.getLogger(__name__)
from .db import save_run, remove_run_by_filename
from .utils import ts_float_to_str
from .settings import read_value
from .settings import init_settings
from .routine import Routine
from .errors import BadgerConfigError


# Check badger optimization run archive root
BADGER_ARCHIVE_ROOT = read_value('BADGER_ARCHIVE_ROOT')
config_singleton = init_settings()
BADGER_ARCHIVE_ROOT = config_singleton.read_value('BADGER_ARCHIVE_ROOT')
if BADGER_ARCHIVE_ROOT is None:
raise BadgerConfigError('Please set the BADGER_ARCHIVE_ROOT env var!')
elif not os.path.exists(BADGER_ARCHIVE_ROOT):
Expand Down
5 changes: 3 additions & 2 deletions src/badger/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,14 @@
import yaml
import sqlite3
from .routine import Routine
from .settings import read_value
from .settings import init_settings
from .utils import get_yaml_string
from .errors import BadgerConfigError, BadgerDBError


# Check badger database root
BADGER_DB_ROOT = read_value('BADGER_DB_ROOT')
config_singleton = init_settings()
BADGER_DB_ROOT = config_singleton.read_value('BADGER_DB_ROOT')
if BADGER_DB_ROOT is None:
raise BadgerConfigError('Please set the BADGER_DB_ROOT env var!')
elif not os.path.exists(BADGER_DB_ROOT):
Expand Down
5 changes: 3 additions & 2 deletions src/badger/factory.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from .settings import read_value
from .settings import init_settings
from .utils import get_value_or_none
from .errors import (
BadgerConfigError,
Expand Down Expand Up @@ -28,7 +28,8 @@
]

# Check badger plugin root
BADGER_PLUGIN_ROOT = read_value('BADGER_PLUGIN_ROOT')
config_singleton = init_settings()
BADGER_PLUGIN_ROOT = config_singleton.read_value('BADGER_PLUGIN_ROOT')
if BADGER_PLUGIN_ROOT is None:
raise BadgerConfigError('Please set the BADGER_PLUGIN_ROOT env var!')
elif not os.path.exists(BADGER_PLUGIN_ROOT):
Expand Down
6 changes: 3 additions & 3 deletions src/badger/gui/default/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import sys
# import ctypes
from qdarkstyle import load_stylesheet, LightPalette, DarkPalette
from ...settings import read_value
from ...settings import init_settings
from .windows.main_window import BadgerMainWindow

# Fix the scaling issue on multiple monitors w/ different scaling settings
Expand Down Expand Up @@ -50,7 +50,7 @@ def on_timeout():

def launch_gui():
app = QApplication(sys.argv)

config_singleton = init_settings()
# Set app metainfo
app.setApplicationName('Badger')
icon_ref = resources.files(__name__) / 'images/icon.png'
Expand All @@ -63,7 +63,7 @@ def launch_gui():
app.setFont(font)

# Set up stylesheet
theme = read_value('BADGER_THEME')
theme = config_singleton.read_value('BADGER_THEME')
if theme == 'dark':
app.setStyleSheet(load_stylesheet(palette=DarkPalette))
elif theme == 'light':
Expand Down
9 changes: 5 additions & 4 deletions src/badger/gui/default/components/env_cbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
from .var_table import VariableTable
from .obj_table import ObjectiveTable
from .data_table import init_data_table, update_init_data_table
from ....settings import init_settings
from ..utils import MouseWheelWidgetAdjustmentGuard, NoHoverFocusComboBox
from ....settings import read_value, AUTO_REFRESH
from ....utils import strtobool

LABEL_WIDTH = 80
Expand Down Expand Up @@ -40,6 +40,7 @@ def __init__(self, env_dict, parent=None, envs=[]):
self.config_logic()

def init_ui(self):
config_singleton = init_settings()
vbox = QVBoxLayout()

self.content_area.setObjectName('EnvBox')
Expand All @@ -56,7 +57,7 @@ def init_ui(self):
cb.installEventFilter(MouseWheelWidgetAdjustmentGuard(cb))
self.btn_env_play = btn_env_play = QPushButton('Open Playground')
btn_env_play.setFixedSize(128, 24)
if not strtobool(read_value('BADGER_ENABLE_ADVANCED')):
if not strtobool(config_singleton.read_value('BADGER_ENABLE_ADVANCED')):
btn_env_play.hide()
self.btn_docs = btn_docs = QPushButton('Open Docs')
btn_docs.setFixedSize(128, 24)
Expand Down Expand Up @@ -109,7 +110,7 @@ def init_ui(self):
' run. The real values would be regenerated based on'
' the machine state before running the optimization '
'again.')
if not AUTO_REFRESH:
if not config_singleton.read_value("AUTO_REFRESH"):
msg_auto = QLabel('Auto mode is on. To explicitly set the '
'variable ranges and/or initial points, please '
'uncheck the "Automatic" check box.')
Expand Down Expand Up @@ -163,7 +164,7 @@ def init_ui(self):
self.btn_add_var = btn_add_var = QPushButton('Add')
btn_add_var.setFixedSize(96, 24)
btn_add_var.setDisabled(True)
if not strtobool(read_value('BADGER_ENABLE_ADVANCED')):
if not strtobool(config_singleton.read_value('BADGER_ENABLE_ADVANCED')):
btn_add_var.hide()
self.btn_lim_vrange = btn_lim_vrange = QPushButton('Set Variable Range')
btn_lim_vrange.setFixedSize(144, 24)
Expand Down
8 changes: 5 additions & 3 deletions src/badger/gui/default/components/generator_cbox.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
from PyQt5.QtWidgets import QVBoxLayout, QHBoxLayout, QPushButton, QWidget, QPlainTextEdit
from PyQt5.QtWidgets import QComboBox, QCheckBox, QStyledItemDelegate, QLabel
from .collapsible_box import CollapsibleBox
from ....settings import init_settings
from ..utils import MouseWheelWidgetAdjustmentGuard, NoHoverFocusComboBox
from ....settings import read_value
from ....utils import strtobool


Expand All @@ -17,6 +17,8 @@ def __init__(self, parent=None, generators=[], scaling_functions=[]):
self.init_ui()

def init_ui(self):
config_singleton = init_settings()

vbox = QVBoxLayout()

# Algo selector
Expand Down Expand Up @@ -64,7 +66,7 @@ def init_ui(self):
btn_edit_script.hide()
hbox_script.addWidget(check_use_script)
hbox_script.addWidget(btn_edit_script)
if not strtobool(read_value('BADGER_ENABLE_ADVANCED')):
if not strtobool(config_singleton.read_value('BADGER_ENABLE_ADVANCED')):
script_bar.hide()
self.edit = edit = QPlainTextEdit()
# edit.setMaximumHeight(80)
Expand Down Expand Up @@ -113,7 +115,7 @@ def init_ui(self):
vbox_misc.addWidget(params_s)

cbox_misc.setContentLayout(vbox_misc)
if not strtobool(read_value('BADGER_ENABLE_ADVANCED')):
if not strtobool(config_singleton.read_value('BADGER_ENABLE_ADVANCED')):
cbox_misc.hide()

self.setContentLayout(vbox)
Expand Down
Loading

0 comments on commit 200ecf8

Please sign in to comment.