ivoryos 1.2.5__py3-none-any.whl → 1.4.4__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- docs/source/conf.py +84 -0
- ivoryos/__init__.py +16 -246
- ivoryos/app.py +154 -0
- ivoryos/optimizer/ax_optimizer.py +55 -28
- ivoryos/optimizer/base_optimizer.py +20 -1
- ivoryos/optimizer/baybe_optimizer.py +27 -17
- ivoryos/optimizer/nimo_optimizer.py +173 -0
- ivoryos/optimizer/registry.py +3 -1
- ivoryos/routes/auth/auth.py +35 -8
- ivoryos/routes/auth/templates/change_password.html +32 -0
- ivoryos/routes/control/control.py +58 -28
- ivoryos/routes/control/control_file.py +12 -15
- ivoryos/routes/control/control_new_device.py +21 -11
- ivoryos/routes/control/templates/controllers.html +27 -0
- ivoryos/routes/control/utils.py +2 -0
- ivoryos/routes/data/data.py +110 -44
- ivoryos/routes/data/templates/components/step_card.html +78 -13
- ivoryos/routes/data/templates/workflow_view.html +343 -113
- ivoryos/routes/design/design.py +59 -10
- ivoryos/routes/design/design_file.py +3 -3
- ivoryos/routes/design/design_step.py +43 -17
- ivoryos/routes/design/templates/components/action_form.html +2 -2
- ivoryos/routes/design/templates/components/canvas_main.html +6 -1
- ivoryos/routes/design/templates/components/edit_action_form.html +18 -3
- ivoryos/routes/design/templates/components/info_modal.html +318 -0
- ivoryos/routes/design/templates/components/instruments_panel.html +23 -1
- ivoryos/routes/design/templates/components/python_code_overlay.html +27 -10
- ivoryos/routes/design/templates/experiment_builder.html +3 -0
- ivoryos/routes/execute/execute.py +82 -22
- ivoryos/routes/execute/templates/components/logging_panel.html +50 -25
- ivoryos/routes/execute/templates/components/run_tabs.html +45 -2
- ivoryos/routes/execute/templates/components/tab_bayesian.html +447 -325
- ivoryos/routes/execute/templates/components/tab_configuration.html +303 -18
- ivoryos/routes/execute/templates/components/tab_repeat.html +6 -2
- ivoryos/routes/execute/templates/experiment_run.html +0 -264
- ivoryos/routes/library/library.py +9 -11
- ivoryos/routes/main/main.py +30 -2
- ivoryos/server.py +180 -0
- ivoryos/socket_handlers.py +1 -1
- ivoryos/static/ivoryos_logo.png +0 -0
- ivoryos/static/js/action_handlers.js +259 -88
- ivoryos/static/js/socket_handler.js +40 -5
- ivoryos/static/js/sortable_design.js +29 -11
- ivoryos/templates/base.html +61 -2
- ivoryos/utils/bo_campaign.py +18 -17
- ivoryos/utils/client_proxy.py +267 -36
- ivoryos/utils/db_models.py +286 -60
- ivoryos/utils/decorators.py +34 -0
- ivoryos/utils/form.py +52 -19
- ivoryos/utils/global_config.py +21 -0
- ivoryos/utils/nest_script.py +314 -0
- ivoryos/utils/py_to_json.py +80 -10
- ivoryos/utils/script_runner.py +573 -189
- ivoryos/utils/task_runner.py +69 -22
- ivoryos/utils/utils.py +48 -5
- ivoryos/version.py +1 -1
- {ivoryos-1.2.5.dist-info → ivoryos-1.4.4.dist-info}/METADATA +109 -47
- ivoryos-1.4.4.dist-info/RECORD +119 -0
- ivoryos-1.4.4.dist-info/top_level.txt +3 -0
- tests/__init__.py +0 -0
- tests/conftest.py +133 -0
- tests/integration/__init__.py +0 -0
- tests/integration/test_route_auth.py +80 -0
- tests/integration/test_route_control.py +94 -0
- tests/integration/test_route_database.py +61 -0
- tests/integration/test_route_design.py +36 -0
- tests/integration/test_route_main.py +35 -0
- tests/integration/test_sockets.py +26 -0
- tests/unit/test_type_conversion.py +42 -0
- tests/unit/test_util.py +3 -0
- ivoryos/routes/api/api.py +0 -56
- ivoryos-1.2.5.dist-info/RECORD +0 -100
- ivoryos-1.2.5.dist-info/top_level.txt +0 -1
- {ivoryos-1.2.5.dist-info → ivoryos-1.4.4.dist-info}/WHEEL +0 -0
- {ivoryos-1.2.5.dist-info → ivoryos-1.4.4.dist-info}/licenses/LICENSE +0 -0
docs/source/conf.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
# Configuration file for the Sphinx documentation builder.
|
|
2
|
+
import os
|
|
3
|
+
import sys
|
|
4
|
+
import urllib
|
|
5
|
+
|
|
6
|
+
import requests
|
|
7
|
+
|
|
8
|
+
# -- General configuration
|
|
9
|
+
sys.path.insert(0, os.path.abspath('../../'))
|
|
10
|
+
from ivoryos.version import __version__
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
# appending suite readme.rst to doc
|
|
14
|
+
|
|
15
|
+
external_readme = [
|
|
16
|
+
{
|
|
17
|
+
"name": 'plugin.rst',
|
|
18
|
+
"url": "https://gitlab.com/heingroup/ivoryos-suite/ivoryos-plugin-template/-/raw/main/README.rst"
|
|
19
|
+
},
|
|
20
|
+
{
|
|
21
|
+
"name": 'client.rst',
|
|
22
|
+
"url": "https://gitlab.com/heingroup/ivoryos-suite/ivoryos-client/-/raw/main/README.rst"
|
|
23
|
+
},
|
|
24
|
+
{
|
|
25
|
+
"name": 'mcp.rst',
|
|
26
|
+
"url": "https://gitlab.com/heingroup/ivoryos-suite/ivoryos-mcp/-/raw/main/README.rst"
|
|
27
|
+
}
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
for item in external_readme:
|
|
31
|
+
readme_url = item['url']
|
|
32
|
+
name = item['name']
|
|
33
|
+
output_path = os.path.join(os.path.dirname(__file__), name)
|
|
34
|
+
r = requests.get(readme_url, verify=False)
|
|
35
|
+
if not os.path.exists(output_path):
|
|
36
|
+
with open(output_path, "wb") as f:
|
|
37
|
+
f.write(r.content)
|
|
38
|
+
|
|
39
|
+
# -- Project information
|
|
40
|
+
project = 'ivoryOS'
|
|
41
|
+
copyright = '2024, Ivory Zhang'
|
|
42
|
+
author = 'Ivory Zhang, Lucy Hao'
|
|
43
|
+
version = __version__
|
|
44
|
+
|
|
45
|
+
extensions = [
|
|
46
|
+
'sphinx.ext.duration',
|
|
47
|
+
'sphinx.ext.doctest',
|
|
48
|
+
'sphinx.ext.autosummary',
|
|
49
|
+
'sphinx.ext.intersphinx',
|
|
50
|
+
'sphinxcontrib.httpdomain',
|
|
51
|
+
'sphinxcontrib.autohttp.flask',
|
|
52
|
+
'sphinxcontrib.autohttp.flaskqref'
|
|
53
|
+
]
|
|
54
|
+
|
|
55
|
+
install_requires = [
|
|
56
|
+
'sphinx-autodoc-typehints'
|
|
57
|
+
]
|
|
58
|
+
autodoc_mock_imports = ["flask_sqlalchemy", "another_hard_to_import_lib"]
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
intersphinx_mapping = {
|
|
62
|
+
'python': ('https://docs.python.org/3/', None),
|
|
63
|
+
'sphinx': ('https://www.sphinx-doc.org/en/master/', None),
|
|
64
|
+
}
|
|
65
|
+
intersphinx_disabled_domains = ['std']
|
|
66
|
+
|
|
67
|
+
templates_path = ['_templates']
|
|
68
|
+
|
|
69
|
+
html_static_path = ['_static']
|
|
70
|
+
html_css_files = [
|
|
71
|
+
'custom.css',
|
|
72
|
+
]
|
|
73
|
+
|
|
74
|
+
html_allow_raw_html = True
|
|
75
|
+
|
|
76
|
+
# -- Options for HTML output
|
|
77
|
+
|
|
78
|
+
html_theme = 'sphinx_rtd_theme'
|
|
79
|
+
|
|
80
|
+
# -- Options for EPUB output
|
|
81
|
+
epub_show_urls = 'footnote'
|
|
82
|
+
|
|
83
|
+
# The master toctree document.
|
|
84
|
+
master_doc = 'index'
|
ivoryos/__init__.py
CHANGED
|
@@ -1,248 +1,18 @@
|
|
|
1
|
-
import
|
|
2
|
-
import sys
|
|
3
|
-
import uuid
|
|
4
|
-
from typing import Union
|
|
5
|
-
|
|
6
|
-
from flask import Flask, redirect, url_for, g, Blueprint, session
|
|
7
|
-
from flask_login import AnonymousUserMixin
|
|
8
|
-
|
|
9
|
-
# sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
|
|
10
|
-
|
|
11
|
-
from ivoryos.config import Config, get_config
|
|
12
|
-
from ivoryos.routes.auth.auth import auth, login_manager
|
|
13
|
-
from ivoryos.routes.control.control import control
|
|
14
|
-
from ivoryos.routes.data.data import data
|
|
15
|
-
from ivoryos.routes.library.library import library
|
|
16
|
-
from ivoryos.routes.design.design import design
|
|
17
|
-
from ivoryos.routes.execute.execute import execute
|
|
18
|
-
from ivoryos.routes.api.api import api
|
|
19
|
-
from ivoryos.socket_handlers import socketio
|
|
20
|
-
from ivoryos.routes.main.main import main
|
|
21
|
-
# from ivoryos.routes.monitor.monitor import monitor
|
|
22
|
-
from ivoryos.utils import utils
|
|
23
|
-
from ivoryos.utils.db_models import db, User
|
|
24
|
-
from ivoryos.utils.global_config import GlobalConfig
|
|
1
|
+
from ivoryos.server import run, global_config
|
|
25
2
|
from ivoryos.optimizer.registry import OPTIMIZER_REGISTRY
|
|
26
|
-
from ivoryos.utils.script_runner import ScriptRunner
|
|
27
3
|
from ivoryos.version import __version__ as ivoryos_version
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
url_prefix = os.getenv('URL_PREFIX', "/ivoryos")
|
|
45
|
-
app = Flask(__name__, static_url_path=f'{url_prefix}/static', static_folder='static')
|
|
46
|
-
app.register_blueprint(main, url_prefix=url_prefix)
|
|
47
|
-
app.register_blueprint(auth, url_prefix=f'{url_prefix}/{auth.name}')
|
|
48
|
-
app.register_blueprint(library, url_prefix=f'{url_prefix}/{library.name}')
|
|
49
|
-
app.register_blueprint(control, url_prefix=f'{url_prefix}/instruments')
|
|
50
|
-
app.register_blueprint(design, url_prefix=f'{url_prefix}')
|
|
51
|
-
app.register_blueprint(execute, url_prefix=f'{url_prefix}')
|
|
52
|
-
app.register_blueprint(data, url_prefix=f'{url_prefix}')
|
|
53
|
-
app.register_blueprint(api, url_prefix=f'{url_prefix}/{api.name}')
|
|
54
|
-
|
|
55
|
-
@login_manager.user_loader
|
|
56
|
-
def load_user(user_id):
|
|
57
|
-
"""
|
|
58
|
-
This function is called by Flask-Login on every request to get the
|
|
59
|
-
current user object from the user ID stored in the session.
|
|
60
|
-
"""
|
|
61
|
-
# The correct implementation is to fetch the user from the database.
|
|
62
|
-
return db.session.get(User, user_id)
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
def create_app(config_class=None):
|
|
66
|
-
"""
|
|
67
|
-
create app, init database
|
|
68
|
-
"""
|
|
69
|
-
app.config.from_object(config_class or 'config.get_config()')
|
|
70
|
-
os.makedirs(app.config["OUTPUT_FOLDER"], exist_ok=True)
|
|
71
|
-
# Initialize extensions
|
|
72
|
-
socketio.init_app(app, cors_allowed_origins="*", cookie=None)
|
|
73
|
-
login_manager.init_app(app)
|
|
74
|
-
login_manager.login_view = "auth.login"
|
|
75
|
-
db.init_app(app)
|
|
76
|
-
|
|
77
|
-
# Create database tables
|
|
78
|
-
with app.app_context():
|
|
79
|
-
db.create_all()
|
|
80
|
-
|
|
81
|
-
# Additional setup
|
|
82
|
-
utils.create_gui_dir(app.config['OUTPUT_FOLDER'])
|
|
83
|
-
|
|
84
|
-
# logger_list = app.config["LOGGERS"]
|
|
85
|
-
logger_path = os.path.join(app.config["OUTPUT_FOLDER"], app.config["LOGGERS_PATH"])
|
|
86
|
-
logger = utils.start_logger(socketio, 'gui_logger', logger_path)
|
|
87
|
-
|
|
88
|
-
@app.before_request
|
|
89
|
-
def before_request():
|
|
90
|
-
"""
|
|
91
|
-
Called before
|
|
92
|
-
|
|
93
|
-
"""
|
|
94
|
-
g.logger = logger
|
|
95
|
-
g.socketio = socketio
|
|
96
|
-
session.permanent = False
|
|
97
|
-
# DEMO_MODE: Simulate logged-in user per session
|
|
98
|
-
if app.config.get("DEMO_MODE", False):
|
|
99
|
-
if "demo_user_id" not in session:
|
|
100
|
-
session["demo_user_id"] = f"demo_{str(uuid.uuid4())[:8]}"
|
|
101
|
-
|
|
102
|
-
class SessionDemoUser(AnonymousUserMixin):
|
|
103
|
-
@property
|
|
104
|
-
def is_authenticated(self):
|
|
105
|
-
return True
|
|
106
|
-
|
|
107
|
-
def get_id(self):
|
|
108
|
-
return session.get("demo_user_id")
|
|
109
|
-
|
|
110
|
-
login_manager.anonymous_user = SessionDemoUser
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
@app.route('/')
|
|
115
|
-
def redirect_to_prefix():
|
|
116
|
-
return redirect(url_for('main.index', version=ivoryos_version)) # Assuming 'index' is a route in your blueprint
|
|
117
|
-
|
|
118
|
-
@app.template_filter('format_name')
|
|
119
|
-
def format_name(name):
|
|
120
|
-
name = name.split(".")[-1]
|
|
121
|
-
text = ' '.join(word for word in name.split('_'))
|
|
122
|
-
return text.capitalize()
|
|
123
|
-
|
|
124
|
-
# app.config.setdefault("DEMO_MODE", False)
|
|
125
|
-
return app
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
def run(module=None, host="0.0.0.0", port=None, debug=None, llm_server=None, model=None,
|
|
129
|
-
config: Config = None,
|
|
130
|
-
logger: Union[str, list] = None,
|
|
131
|
-
logger_output_name: str = None,
|
|
132
|
-
enable_design: bool = True,
|
|
133
|
-
blueprint_plugins: Union[list, Blueprint] = [],
|
|
134
|
-
exclude_names: list = [],
|
|
135
|
-
):
|
|
136
|
-
"""
|
|
137
|
-
Start ivoryOS app server.
|
|
138
|
-
|
|
139
|
-
:param module: module name, __name__ for current module
|
|
140
|
-
:param host: host address, defaults to 0.0.0.0
|
|
141
|
-
:param port: port, defaults to None, and will use 8000
|
|
142
|
-
:param debug: debug mode, defaults to None (True)
|
|
143
|
-
:param llm_server: llm server, defaults to None.
|
|
144
|
-
:param model: llm model, defaults to None. If None, app will run without text-to-code feature
|
|
145
|
-
:param config: config class, defaults to None
|
|
146
|
-
:param logger: logger name of list of logger names, defaults to None
|
|
147
|
-
:param logger_output_name: log file save name of logger, defaults to None, and will use "default.log"
|
|
148
|
-
:param enable_design: enable design canvas, database and workflow execution
|
|
149
|
-
:param blueprint_plugins: Union[list[Blueprint], Blueprint] custom Blueprint pages
|
|
150
|
-
:param exclude_names: list[str] module names to exclude from parsing
|
|
151
|
-
"""
|
|
152
|
-
app = create_app(config_class=config or get_config()) # Create app instance using factory function
|
|
153
|
-
|
|
154
|
-
# plugins = load_installed_plugins(app, socketio)
|
|
155
|
-
plugins = []
|
|
156
|
-
if blueprint_plugins:
|
|
157
|
-
config_plugins = load_plugins(blueprint_plugins, app, socketio)
|
|
158
|
-
plugins.extend(config_plugins)
|
|
159
|
-
|
|
160
|
-
def inject_nav_config():
|
|
161
|
-
"""Make NAV_CONFIG available globally to all templates."""
|
|
162
|
-
return dict(
|
|
163
|
-
enable_design=enable_design,
|
|
164
|
-
plugins=plugins,
|
|
165
|
-
)
|
|
166
|
-
|
|
167
|
-
app.context_processor(inject_nav_config)
|
|
168
|
-
port = port or int(os.environ.get("PORT", 8000))
|
|
169
|
-
debug = debug if debug is not None else app.config.get('DEBUG', True)
|
|
170
|
-
|
|
171
|
-
app.config["LOGGERS"] = logger
|
|
172
|
-
app.config["LOGGERS_PATH"] = logger_output_name or app.config["LOGGERS_PATH"] # default.log
|
|
173
|
-
logger_path = os.path.join(app.config["OUTPUT_FOLDER"], app.config["LOGGERS_PATH"])
|
|
174
|
-
dummy_deck_path = os.path.join(app.config["OUTPUT_FOLDER"], app.config["DUMMY_DECK"])
|
|
175
|
-
global_config.optimizers = OPTIMIZER_REGISTRY
|
|
176
|
-
if module:
|
|
177
|
-
app.config["MODULE"] = module
|
|
178
|
-
app.config["OFF_LINE"] = False
|
|
179
|
-
global_config.deck = sys.modules[module]
|
|
180
|
-
global_config.deck_snapshot = utils.create_deck_snapshot(global_config.deck,
|
|
181
|
-
output_path=dummy_deck_path,
|
|
182
|
-
save=True,
|
|
183
|
-
exclude_names=exclude_names
|
|
184
|
-
)
|
|
185
|
-
else:
|
|
186
|
-
app.config["OFF_LINE"] = True
|
|
187
|
-
if model:
|
|
188
|
-
app.config["ENABLE_LLM"] = True
|
|
189
|
-
app.config["LLM_MODEL"] = model
|
|
190
|
-
app.config["LLM_SERVER"] = llm_server
|
|
191
|
-
utils.install_and_import('openai')
|
|
192
|
-
from ivoryos.utils.llm_agent import LlmAgent
|
|
193
|
-
global_config.agent = LlmAgent(host=llm_server, model=model,
|
|
194
|
-
output_path=app.config["OUTPUT_FOLDER"] if module is not None else None)
|
|
195
|
-
else:
|
|
196
|
-
app.config["ENABLE_LLM"] = False
|
|
197
|
-
if logger and type(logger) is str:
|
|
198
|
-
utils.start_logger(socketio, log_filename=logger_path, logger_name=logger)
|
|
199
|
-
elif type(logger) is list:
|
|
200
|
-
for log in logger:
|
|
201
|
-
utils.start_logger(socketio, log_filename=logger_path, logger_name=log)
|
|
202
|
-
|
|
203
|
-
# in case Python 3.12 or higher doesn't log URL
|
|
204
|
-
if sys.version_info >= (3, 12):
|
|
205
|
-
ip = utils.get_local_ip()
|
|
206
|
-
print(f"Server running at http://localhost:{port}")
|
|
207
|
-
if not ip == "127.0.0.1":
|
|
208
|
-
print(f"Server running at http://{ip}:{port}")
|
|
209
|
-
socketio.run(app, host=host, port=port, debug=debug, use_reloader=False, allow_unsafe_werkzeug=True)
|
|
210
|
-
# return app
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
# def load_installed_plugins(app, socketio):
|
|
214
|
-
# """
|
|
215
|
-
# Dynamically load installed plugins and attach Flask-SocketIO.
|
|
216
|
-
# """
|
|
217
|
-
# plugin_names = []
|
|
218
|
-
# for entry_point in entry_points().get("ivoryos.plugins", []):
|
|
219
|
-
# plugin = entry_point.load()
|
|
220
|
-
#
|
|
221
|
-
# # If the plugin has an `init_socketio()` function, pass socketio
|
|
222
|
-
# if hasattr(plugin, 'init_socketio'):
|
|
223
|
-
# plugin.init_socketio(socketio)
|
|
224
|
-
#
|
|
225
|
-
# plugin_names.append(entry_point.name)
|
|
226
|
-
# app.register_blueprint(getattr(plugin, entry_point.name), url_prefix=f"{url_prefix}/{entry_point.name}")
|
|
227
|
-
#
|
|
228
|
-
# return plugin_names
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
def load_plugins(blueprints: Union[list, Blueprint], app, socketio):
|
|
232
|
-
"""
|
|
233
|
-
Dynamically load installed plugins and attach Flask-SocketIO.
|
|
234
|
-
:param blueprints: Union[list, Blueprint] list of Blueprint objects or a single Blueprint object
|
|
235
|
-
:param app: Flask application instance
|
|
236
|
-
:param socketio: Flask-SocketIO instance
|
|
237
|
-
:return: list of plugin names
|
|
238
|
-
"""
|
|
239
|
-
plugin_names = []
|
|
240
|
-
if not isinstance(blueprints, list):
|
|
241
|
-
blueprints = [blueprints]
|
|
242
|
-
for blueprint in blueprints:
|
|
243
|
-
# If the plugin has an `init_socketio()` function, pass socketio
|
|
244
|
-
if hasattr(blueprint, 'init_socketio'):
|
|
245
|
-
blueprint.init_socketio(socketio)
|
|
246
|
-
plugin_names.append(blueprint.name)
|
|
247
|
-
app.register_blueprint(blueprint, url_prefix=f"{url_prefix}/{blueprint.name}")
|
|
248
|
-
return plugin_names
|
|
4
|
+
from ivoryos.utils.decorators import block, BUILDING_BLOCKS
|
|
5
|
+
from ivoryos.app import app, create_app, socketio, db
|
|
6
|
+
|
|
7
|
+
__all__ = [
|
|
8
|
+
"block",
|
|
9
|
+
"BUILDING_BLOCKS",
|
|
10
|
+
"OPTIMIZER_REGISTRY",
|
|
11
|
+
"run",
|
|
12
|
+
"app",
|
|
13
|
+
"ivoryos_version",
|
|
14
|
+
"create_app",
|
|
15
|
+
"socketio",
|
|
16
|
+
"global_config",
|
|
17
|
+
"db"
|
|
18
|
+
]
|
ivoryos/app.py
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import uuid
|
|
3
|
+
|
|
4
|
+
import bcrypt
|
|
5
|
+
from flask import Flask, session, g, redirect, url_for
|
|
6
|
+
from flask_login import AnonymousUserMixin
|
|
7
|
+
|
|
8
|
+
from ivoryos.utils import utils
|
|
9
|
+
from ivoryos.utils.db_models import db, User
|
|
10
|
+
from ivoryos.routes.auth.auth import auth, login_manager
|
|
11
|
+
from ivoryos.routes.control.control import control
|
|
12
|
+
from ivoryos.routes.data.data import data
|
|
13
|
+
from ivoryos.routes.library.library import library
|
|
14
|
+
from ivoryos.routes.design.design import design
|
|
15
|
+
from ivoryos.routes.execute.execute import execute
|
|
16
|
+
from ivoryos.socket_handlers import socketio
|
|
17
|
+
from ivoryos.routes.main.main import main
|
|
18
|
+
from ivoryos.version import __version__ as ivoryos_version
|
|
19
|
+
from sqlalchemy import inspect, text
|
|
20
|
+
|
|
21
|
+
url_prefix = os.getenv('URL_PREFIX', "/ivoryos")
|
|
22
|
+
app = Flask(__name__, static_url_path=f'{url_prefix}/static', static_folder='static')
|
|
23
|
+
app.register_blueprint(main, url_prefix=url_prefix)
|
|
24
|
+
app.register_blueprint(auth, url_prefix=f'{url_prefix}/{auth.name}')
|
|
25
|
+
app.register_blueprint(library, url_prefix=f'{url_prefix}/{library.name}')
|
|
26
|
+
app.register_blueprint(control, url_prefix=f'{url_prefix}/instruments')
|
|
27
|
+
app.register_blueprint(design, url_prefix=f'{url_prefix}')
|
|
28
|
+
app.register_blueprint(execute, url_prefix=f'{url_prefix}')
|
|
29
|
+
app.register_blueprint(data, url_prefix=f'{url_prefix}')
|
|
30
|
+
# app.register_blueprint(api, url_prefix=f'{url_prefix}/{api.name}')
|
|
31
|
+
|
|
32
|
+
def reset_old_schema(engine, db_dir):
|
|
33
|
+
inspector = inspect(engine)
|
|
34
|
+
tables = inspector.get_table_names()
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
# Check if old tables exist (no workflow_phases table)
|
|
38
|
+
has_workflow_phase = 'workflow_phases' in tables
|
|
39
|
+
old_workflow_run = 'workflow_runs' in tables
|
|
40
|
+
old_workflow_step = 'workflow_steps' in tables
|
|
41
|
+
|
|
42
|
+
# v1.3.4 only delete and backup when there is runs but no phases
|
|
43
|
+
if not has_workflow_phase and old_workflow_run:
|
|
44
|
+
print("⚠️ Old workflow database detected! All previous workflows have been reset to support the new schema.")
|
|
45
|
+
# Backup old DB
|
|
46
|
+
db_path = os.path.join(db_dir, "ivoryos.db")
|
|
47
|
+
if os.path.exists(db_path):
|
|
48
|
+
# os.makedirs(backup_dir, exist_ok=True)
|
|
49
|
+
from datetime import datetime
|
|
50
|
+
import shutil
|
|
51
|
+
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
|
|
52
|
+
backup_path = os.path.join(db_dir, f"ivoryos_backup_{ts}.db")
|
|
53
|
+
shutil.copy(db_path, backup_path)
|
|
54
|
+
print(f"Backup created at {backup_path}")
|
|
55
|
+
with engine.begin() as conn:
|
|
56
|
+
# Drop old tables
|
|
57
|
+
if old_workflow_step:
|
|
58
|
+
conn.execute(text("DROP TABLE IF EXISTS workflow_steps"))
|
|
59
|
+
if old_workflow_run:
|
|
60
|
+
conn.execute(text("DROP TABLE IF EXISTS workflow_runs"))
|
|
61
|
+
with engine.begin() as conn:
|
|
62
|
+
try:
|
|
63
|
+
conn.execute(
|
|
64
|
+
text("ALTER TABLE user ADD COLUMN settings TEXT")
|
|
65
|
+
)
|
|
66
|
+
except Exception:
|
|
67
|
+
pass
|
|
68
|
+
|
|
69
|
+
# Recreate new schema
|
|
70
|
+
db.create_all() # creates workflow_runs, workflow_phases, workflow_steps
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def create_admin():
|
|
74
|
+
"""
|
|
75
|
+
Create an admin user with username 'admin' and password 'admin' if it doesn't exist.
|
|
76
|
+
"""
|
|
77
|
+
with app.app_context():
|
|
78
|
+
admin_user = User.query.filter_by(username='admin').first()
|
|
79
|
+
if not admin_user:
|
|
80
|
+
print("Creating default admin user...")
|
|
81
|
+
admin_user = User(
|
|
82
|
+
username='admin',
|
|
83
|
+
password=bcrypt.hashpw("admin".encode('utf-8'), bcrypt.gensalt()),
|
|
84
|
+
)
|
|
85
|
+
db.session.add(admin_user)
|
|
86
|
+
db.session.commit()
|
|
87
|
+
else:
|
|
88
|
+
print("Admin user already exists.")
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def create_app(config_class=None):
|
|
92
|
+
"""
|
|
93
|
+
create app, init database
|
|
94
|
+
"""
|
|
95
|
+
|
|
96
|
+
app.config.from_object(config_class or 'config.get_config()')
|
|
97
|
+
os.makedirs(app.config["OUTPUT_FOLDER"], exist_ok=True)
|
|
98
|
+
# Initialize extensions
|
|
99
|
+
socketio.init_app(app, cors_allowed_origins="*", cookie=None)
|
|
100
|
+
login_manager.init_app(app)
|
|
101
|
+
login_manager.login_view = "auth.login"
|
|
102
|
+
db.init_app(app)
|
|
103
|
+
|
|
104
|
+
# Create database tables
|
|
105
|
+
with app.app_context():
|
|
106
|
+
# db.create_all()
|
|
107
|
+
reset_old_schema(db.engine, app.config['OUTPUT_FOLDER'])
|
|
108
|
+
create_admin()
|
|
109
|
+
|
|
110
|
+
# Additional setup
|
|
111
|
+
utils.create_gui_dir(app.config['OUTPUT_FOLDER'])
|
|
112
|
+
|
|
113
|
+
# logger_list = app.config["LOGGERS"]
|
|
114
|
+
logger_path = os.path.join(app.config["OUTPUT_FOLDER"], app.config["LOGGERS_PATH"])
|
|
115
|
+
logger = utils.start_logger(socketio, 'gui_logger', logger_path)
|
|
116
|
+
|
|
117
|
+
@app.before_request
|
|
118
|
+
def before_request():
|
|
119
|
+
"""
|
|
120
|
+
Called before
|
|
121
|
+
|
|
122
|
+
"""
|
|
123
|
+
g.logger = logger
|
|
124
|
+
g.socketio = socketio
|
|
125
|
+
session.permanent = False
|
|
126
|
+
# DEMO_MODE: Simulate logged-in user per session
|
|
127
|
+
if app.config.get("DEMO_MODE", False):
|
|
128
|
+
if "demo_user_id" not in session:
|
|
129
|
+
session["demo_user_id"] = f"demo_{str(uuid.uuid4())[:8]}"
|
|
130
|
+
|
|
131
|
+
class SessionDemoUser(AnonymousUserMixin):
|
|
132
|
+
@property
|
|
133
|
+
def is_authenticated(self):
|
|
134
|
+
return True
|
|
135
|
+
|
|
136
|
+
def get_id(self):
|
|
137
|
+
return session.get("demo_user_id")
|
|
138
|
+
|
|
139
|
+
login_manager.anonymous_user = SessionDemoUser
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
@app.route('/')
|
|
144
|
+
def redirect_to_prefix():
|
|
145
|
+
return redirect(url_for('main.index', version=ivoryos_version)) # Assuming 'index' is a route in your blueprint
|
|
146
|
+
|
|
147
|
+
@app.template_filter('format_name')
|
|
148
|
+
def format_name(name):
|
|
149
|
+
name = name.split(".")[-1]
|
|
150
|
+
text = ' '.join(word for word in name.split('_'))
|
|
151
|
+
return text.capitalize()
|
|
152
|
+
|
|
153
|
+
# app.config.setdefault("DEMO_MODE", False)
|
|
154
|
+
return app
|
|
@@ -1,25 +1,28 @@
|
|
|
1
1
|
# optimizers/ax_optimizer.py
|
|
2
2
|
from typing import Dict
|
|
3
3
|
|
|
4
|
-
|
|
4
|
+
from pandas import DataFrame
|
|
5
5
|
|
|
6
6
|
from ivoryos.optimizer.base_optimizer import OptimizerBase
|
|
7
7
|
from ivoryos.utils.utils import install_and_import
|
|
8
8
|
|
|
9
9
|
class AxOptimizer(OptimizerBase):
|
|
10
|
-
def __init__(self, experiment_name, parameter_space, objective_config, optimizer_config=None
|
|
10
|
+
def __init__(self, experiment_name, parameter_space, objective_config, optimizer_config=None,
|
|
11
|
+
parameter_constraints:list=None, datapath=None):
|
|
12
|
+
self.trial_index_list = None
|
|
11
13
|
try:
|
|
12
14
|
from ax.api.client import Client
|
|
13
15
|
except ImportError as e:
|
|
14
16
|
install_and_import("ax", "ax-platform")
|
|
15
17
|
raise ImportError("Please install Ax with pip install ax-platform to use AxOptimizer. Attempting to install Ax...")
|
|
16
|
-
super().__init__(experiment_name, parameter_space, objective_config, optimizer_config)
|
|
18
|
+
super().__init__(experiment_name, parameter_space, objective_config, optimizer_config, parameter_constraints, )
|
|
17
19
|
|
|
18
20
|
self.client = Client()
|
|
19
21
|
# 2. Configure where Ax will search.
|
|
20
22
|
self.client.configure_experiment(
|
|
21
23
|
name=experiment_name,
|
|
22
|
-
parameters=self._convert_parameter_to_ax_format(parameter_space)
|
|
24
|
+
parameters=self._convert_parameter_to_ax_format(parameter_space),
|
|
25
|
+
parameter_constraints=parameter_constraints
|
|
23
26
|
)
|
|
24
27
|
# 3. Configure the objective function.
|
|
25
28
|
self.client.configure_optimization(objective=self._convert_objective_to_ax_format(objective_config))
|
|
@@ -30,7 +33,7 @@ class AxOptimizer(OptimizerBase):
|
|
|
30
33
|
@staticmethod
|
|
31
34
|
def _create_generator_mapping():
|
|
32
35
|
"""Create a mapping from string values to Generator enum members."""
|
|
33
|
-
from ax.
|
|
36
|
+
from ax.adapter import Generators
|
|
34
37
|
return {member.value: member for member in Generators}
|
|
35
38
|
|
|
36
39
|
def _convert_parameter_to_ax_format(self, parameter_space):
|
|
@@ -48,12 +51,17 @@ class AxOptimizer(OptimizerBase):
|
|
|
48
51
|
ax_params = []
|
|
49
52
|
for p in parameter_space:
|
|
50
53
|
if p["type"] == "range":
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
54
|
+
# if step is used here, convert to ChoiceParameterConfig
|
|
55
|
+
if len(p["bounds"]) == 3:
|
|
56
|
+
values = self._create_discrete_search_space(range_with_step=p["bounds"],value_type=p["value_type"])
|
|
57
|
+
ax_params.append(ChoiceParameterConfig(name=p["name"], values=values, parameter_type="int", is_ordered=True))
|
|
58
|
+
else:
|
|
59
|
+
ax_params.append(
|
|
60
|
+
RangeParameterConfig(
|
|
61
|
+
name=p["name"],
|
|
62
|
+
bounds=tuple(p["bounds"]),
|
|
63
|
+
parameter_type=p["value_type"]
|
|
64
|
+
))
|
|
57
65
|
elif p["type"] == "choice":
|
|
58
66
|
ax_params.append(
|
|
59
67
|
ChoiceParameterConfig(
|
|
@@ -77,6 +85,11 @@ class AxOptimizer(OptimizerBase):
|
|
|
77
85
|
objectives = []
|
|
78
86
|
for obj in objective_config:
|
|
79
87
|
obj_name = obj.get("name")
|
|
88
|
+
|
|
89
|
+
# # fixing unknown Ax "unsupported operand type(s) for *: 'One' and 'LazyFunction'" in v1.1.2, test is not allowed as objective name
|
|
90
|
+
if obj_name == "test":
|
|
91
|
+
raise ValueError("test is not allowed as objective name")
|
|
92
|
+
|
|
80
93
|
minimize = obj.get("minimize", True)
|
|
81
94
|
weight = obj.get("weight", 1)
|
|
82
95
|
sign = "-" if minimize else ""
|
|
@@ -96,20 +109,30 @@ class AxOptimizer(OptimizerBase):
|
|
|
96
109
|
step_2 = optimizer_config.get("step_2", {})
|
|
97
110
|
step_1_generator = step_1.get("model", "Sobol")
|
|
98
111
|
step_2_generator = step_2.get("model", "BOTorch")
|
|
99
|
-
generator_1 = GenerationStep(
|
|
100
|
-
generator_2 = GenerationStep(
|
|
112
|
+
generator_1 = GenerationStep(generator=generators.get(step_1_generator), num_trials=step_1.get("num_samples", 5))
|
|
113
|
+
generator_2 = GenerationStep(generator=generators.get(step_2_generator), num_trials=step_2.get("num_samples", -1))
|
|
101
114
|
return GenerationStrategy(steps=[generator_1, generator_2])
|
|
102
115
|
|
|
103
116
|
def suggest(self, n=1):
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
117
|
+
trials = self.client.get_next_trials(n)
|
|
118
|
+
trial_index_list = []
|
|
119
|
+
param_list = []
|
|
120
|
+
for trial_index, params in trials.items():
|
|
121
|
+
trial_index_list.append(trial_index)
|
|
122
|
+
param_list.append(params)
|
|
123
|
+
self.trial_index_list = trial_index_list
|
|
124
|
+
return param_list
|
|
107
125
|
|
|
108
126
|
def observe(self, results):
|
|
109
|
-
self.
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
127
|
+
for trial_index, result in zip(self.trial_index_list, results):
|
|
128
|
+
obj_only_result = {k: v for k, v in result.items() if k in [obj["name"] for obj in self.objective_config]}
|
|
129
|
+
self.client.complete_trial(
|
|
130
|
+
trial_index=trial_index,
|
|
131
|
+
raw_data=obj_only_result
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
def get_plots(self, plot_type):
|
|
135
|
+
return None
|
|
113
136
|
|
|
114
137
|
@staticmethod
|
|
115
138
|
def get_schema():
|
|
@@ -117,29 +140,33 @@ class AxOptimizer(OptimizerBase):
|
|
|
117
140
|
"parameter_types": ["range", "choice"],
|
|
118
141
|
"multiple_objectives": True,
|
|
119
142
|
# "objective_weights": True,
|
|
143
|
+
"supports_continuous": True,
|
|
144
|
+
"supports_constraints": True,
|
|
120
145
|
"optimizer_config": {
|
|
121
146
|
"step_1": {"model": ["Sobol", "Uniform", "Factorial", "Thompson"], "num_samples": 5},
|
|
122
147
|
"step_2": {"model": ["BoTorch", "SAASBO", "SAAS_MTGP", "Legacy_GPEI", "EB", "EB_Ashr", "ST_MTGP", "BO_MIXED", "Contextual_SACBO"]}
|
|
123
148
|
},
|
|
149
|
+
|
|
124
150
|
}
|
|
125
151
|
|
|
126
|
-
def append_existing_data(self, existing_data):
|
|
152
|
+
def append_existing_data(self, existing_data:DataFrame):
|
|
127
153
|
"""
|
|
128
154
|
Append existing data to the Ax experiment.
|
|
129
155
|
:param existing_data: A dictionary containing existing data.
|
|
130
156
|
"""
|
|
131
|
-
|
|
132
|
-
if not existing_data:
|
|
133
|
-
return
|
|
157
|
+
|
|
134
158
|
if isinstance(existing_data, DataFrame):
|
|
159
|
+
if existing_data.empty:
|
|
160
|
+
return
|
|
135
161
|
existing_data = existing_data.to_dict(orient="records")
|
|
136
162
|
parameter_names = [i.get("name") for i in self.parameter_space]
|
|
137
163
|
objective_names = [i.get("name") for i in self.objective_config]
|
|
138
|
-
for
|
|
139
|
-
#
|
|
140
|
-
|
|
164
|
+
for entry in existing_data:
|
|
165
|
+
# for name, value in entry.items():
|
|
166
|
+
# First attach the trial and note the trial index
|
|
167
|
+
parameters = {name: value for name, value in entry.items() if name in parameter_names}
|
|
141
168
|
trial_index = self.client.attach_trial(parameters=parameters)
|
|
142
|
-
raw_data = {name: value for name in
|
|
169
|
+
raw_data = {name: value for name, value in entry.items() if name in objective_names}
|
|
143
170
|
# Then complete the trial with the existing data
|
|
144
171
|
self.client.complete_trial(trial_index=trial_index, raw_data=raw_data)
|
|
145
172
|
|