Merge pull request #922 from c-bata/followup-jupyterlab-optuna

Add `jupyterlab-optuna`
This commit is contained in:
c-bata
2024-08-08 11:20:29 +09:00
committed by GitHub
46 changed files with 10152 additions and 59 deletions
+3 -1
View File
@@ -2,4 +2,6 @@ venv
.venv
standalone_app
vscode
tslib
tslib
jupyterlab
pkg
+6 -1
View File
@@ -37,6 +37,11 @@ serve-browser-app: tslib $(RUSTLIB_OUT)
vscode-extension: vscode/assets/bundle.js
cd vscode && npm install && npm run vscode:prepublish && vsce package
.PHONY: jupyterlab-extension
jupyterlab-extension: tslib
cd optuna_dashboard && npm install && npm run build:pkg
cd jupyterlab && python -m build --sdist
.PHONY: sdist
sdist: pyproject.toml $(DASHBOARD_TS_OUT)
python -m build --sdist
@@ -52,7 +57,7 @@ docs: docs/conf.py $(RST_FILES)
.PHONY: fmt
fmt:
npm run fmt
black ./optuna_dashboard/ ./python_tests/ ./e2e_tests/
black ./optuna_dashboard/ ./python_tests/ ./e2e_tests/ ./jupyterlab/
isort .
.PHONY: clean
+3 -1
View File
@@ -10,7 +10,9 @@
"vscode/src/**/*.tsx",
"tslib/**/*.ts",
"tslib/**/*.tsx",
"tslib/**/*.mjs"
"tslib/**/*.mjs",
"jupyterlab/src/**/*.ts",
"jupyterlab/src/**/*.tsx"
],
"ignore": [
"optuna_dashboard/ts/components/PlotlyColorTemplates.ts",
+9
View File
@@ -0,0 +1,9 @@
.yarn/
jupyterlab_optuna/labextension
jupyterlab_optuna/_version.py
lib/
tsconfig.tsbuildinfo
.yarnrc.yml
.pnp.cjs
.pnp.loader.mjs
+95
View File
@@ -0,0 +1,95 @@
# jupyterlab-optuna
A JupyterLab extension for Optuna
## Requirements
- JupyterLab >= 4.0.0
## Install
To install the extension, execute:
```bash
pip install jupyterlab-optuna
```
## Uninstall
To remove the extension, execute:
```bash
pip uninstall jupyterlab-optuna
```
## Troubleshoot
If you are seeing the frontend extension, but it is not working, check
that the server extension is enabled:
```bash
jupyter server extension list
```
If the server extension is installed and enabled, but you are not seeing
the frontend extension, check the frontend extension is installed:
```bash
jupyter labextension list
```
## Contributing
### Development install
Note: You will need NodeJS to build the extension package.
The `jlpm` command is JupyterLab's pinned version of
[yarn](https://yarnpkg.com/) that is installed with JupyterLab. You may use
`yarn` or `npm` in lieu of `jlpm` below.
```bash
# Clone the repo to your local environment
# Change directory to the jupyterlab_optuna directory
# Install package in development mode
pip install -e ".[dev]"
# Link your development version of the extension with JupyterLab
jupyter labextension develop . --overwrite
# Server extension must be manually installed in develop mode
jupyter server extension enable jupyterlab_optuna
# Rebuild extension Typescript source after making changes
jlpm build
```
You can watch the source directory and run JupyterLab at the same time in different terminals to watch for changes in the extension's source and automatically rebuild the extension.
```bash
# Watch the source directory in one terminal, automatically rebuilding when needed
jlpm watch
# Run JupyterLab in another terminal
jupyter lab
```
With the watch command running, every saved change will immediately be built locally and available in your running JupyterLab. Refresh JupyterLab to load the change in your browser (you may need to wait several seconds for the extension to be rebuilt).
By default, the `jlpm build` command generates the source maps for this extension to make it easier to debug using the browser dev tools. To also generate source maps for the JupyterLab core extensions, you can run the following command:
```bash
jupyter lab build --minimize=False
```
### Development uninstall
```bash
# Server extension must be manually disabled in develop mode
jupyter server extension disable jupyterlab_optuna
pip uninstall jupyterlab_optuna
```
In development mode, you will also need to remove the symlink created by `jupyter labextension develop`
command. To find its location, you can run `jupyter labextension list` to figure out where the `labextensions`
folder is located. Then you can remove the symlink named `jupyterlab-optuna` within that folder.
### Packaging the extension
See [RELEASE](RELEASE.md)
+111
View File
@@ -0,0 +1,111 @@
# Making a new release of jupyterlab_optuna
The extension can be published to `PyPI` and `npm` manually or using the [Jupyter Releaser](https://github.com/jupyter-server/jupyter_releaser).
## Manual release
### Python package
This extension can be distributed as Python packages. All of the Python
packaging instructions are in the `pyproject.toml` file to wrap your extension in a
Python package. Before generating a package, you first need to install some tools:
```bash
pip install build twine hatch
```
Bump the version using `hatch`. By default this will create a tag.
See the docs on [hatch-nodejs-version](https://github.com/agoose77/hatch-nodejs-version#semver) for details.
```bash
hatch version <new-version>
```
Make sure to clean up all the development files before building the package:
```bash
jlpm clean:all
```
You could also clean up the local git repository:
```bash
git clean -dfX
```
To create a Python source package (`.tar.gz`) and the binary package (`.whl`) in the `dist/` directory, do:
```bash
python -m build
```
> `python setup.py sdist bdist_wheel` is deprecated and will not work for this package.
Then to upload the package to PyPI, do:
```bash
twine upload dist/*
```
### NPM package
To publish the frontend part of the extension as a NPM package, do:
```bash
npm login
npm publish --access public
```
## Automated releases with the Jupyter Releaser
The extension repository should already be compatible with the Jupyter Releaser.
Check out the [workflow documentation](https://jupyter-releaser.readthedocs.io/en/latest/get_started/making_release_from_repo.html) for more information.
Here is a summary of the steps to cut a new release:
- Add tokens to the [Github Secrets](https://docs.github.com/en/actions/security-guides/encrypted-secrets) in the repository:
- `ADMIN_GITHUB_TOKEN` (with "public_repo" and "repo:status" permissions); see the [documentation](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token)
- `NPM_TOKEN` (with "automation" permission); see the [documentation](https://docs.npmjs.com/creating-and-viewing-access-tokens)
- Set up PyPI
<details><summary>Using PyPI trusted publisher (modern way)</summary>
- Set up your PyPI project by [adding a trusted publisher](https://docs.pypi.org/trusted-publishers/adding-a-publisher/)
- The _workflow name_ is `publish-release.yml` and the _environment_ should be left blank.
- Ensure the publish release job as `permissions`: `id-token : write` (see the [documentation](https://docs.pypi.org/trusted-publishers/using-a-publisher/))
</details>
<details><summary>Using PyPI token (legacy way)</summary>
- If the repo generates PyPI release(s), create a scoped PyPI [token](https://packaging.python.org/guides/publishing-package-distribution-releases-using-github-actions-ci-cd-workflows/#saving-credentials-on-github). We recommend using a scoped token for security reasons.
- You can store the token as `PYPI_TOKEN` in your fork's `Secrets`.
- Advanced usage: if you are releasing multiple repos, you can create a secret named `PYPI_TOKEN_MAP` instead of `PYPI_TOKEN` that is formatted as follows:
```text
owner1/repo1,token1
owner2/repo2,token2
```
If you have multiple Python packages in the same repository, you can point to them as follows:
```text
owner1/repo1/path/to/package1,token1
owner1/repo1/path/to/package2,token2
```
</details>
- Go to the Actions panel
- Run the "Step 1: Prep Release" workflow
- Check the draft changelog
- Run the "Step 2: Publish Release" workflow
## Publishing to `conda-forge`
If the package is not on conda forge yet, check the documentation to learn how to add it: https://conda-forge.org/docs/maintainer/adding_pkgs.html
Otherwise a bot should pick up the new version publish to PyPI, and open a new PR on the feedstock repository automatically.
+6
View File
@@ -0,0 +1,6 @@
<svg class="optuna-animation" xmlns="http://www.w3.org/2000/svg" width="294.7" height="280" viewBox="0 0 221 210">
<path fill="rgb(6, 71, 135)" d="M104.5.6c-31.2 4.6-55 16.5-74.5 37A107.3 107.3 0 0 0 3.2 84.9a78.4 78.4 0 0 0-2.6 24.6c0 12.5.3 16.4 2.2 23.5a114.2 114.2 0 0 0 19.5 38 114 114 0 0 0 103.3 37.5 111.6 111.6 0 0 0 83.1-63.1 100.3 100.3 0 0 0 11-44.9c.4-11.5.1-15.7-1.5-23.5a85.3 85.3 0 0 0-25.1-47.1 98 98 0 0 0-49.4-27c-8-2-31.9-3.4-39.2-2.3zm35.3 16.8A90 90 0 0 1 206.7 80a112 112 0 0 1 0 40.8 103.3 103.3 0 0 1-73.7 72 76.6 76.6 0 0 1-25 2.5 77 77 0 0 1-23.2-2.1 99.6 99.6 0 0 1-68.4-66.7 64 64 0 0 1-2.8-22.5c-.1-11.3.3-14.8 2.2-21.4C25.5 49.2 53.6 25 92.5 16.9a156 156 0 0 1 47.3.5z"/>
<path fill="rgb(12, 97, 152)" d="M94.6 29.5A88.3 88.3 0 0 0 68 39.1c-17 8.8-30.5 22-38.1 37.4a56.4 56.4 0 0 0-6.7 32c.9 18.9 7.2 32.1 22.7 47.5 13 12.8 25.8 20 44.9 25.2 11 3 31.5 2.9 42.7-.1a85.5 85.5 0 0 0 61.1-60.1c2.3-8.8 2.4-26.3.1-35a78.6 78.6 0 0 0-55.2-54.6 74.9 74.9 0 0 0-23.5-3c-9.9-.2-16.7.1-21.4 1.1zm37.2 11.1a61 61 0 0 1 29.7 17.9 55 55 0 0 1 18.6 43.6c.3 39.1-30.4 68.9-71.1 69.1-16.9 0-30-4.1-42.5-13.4A59.7 59.7 0 0 1 47.1 83c15.6-33 51.5-51 84.7-42.4z"/>
<path fill="rgb(39, 126, 170)" d="M96 57.6a58.6 58.6 0 0 0-40 35 43 43 0 0 0 1.6 30.4 62.8 62.8 0 0 0 20.2 22.6 70.7 70.7 0 0 0 28.8 10c34.6 3.2 64.7-28.1 58-60.4a50 50 0 0 0-37.3-37.7c-7.2-1.9-24-1.8-31.3.1zm31.9 16.1A32 32 0 0 1 148 93.4c.7 2.4 1.1 6.8.8 11.5a28 28 0 0 1-3.8 13.9 43.4 43.4 0 0 1-18.8 17.9c-5.2 2.5-6.7 2.8-16.7 2.8-9.8 0-11.6-.3-16.7-2.7-17.2-8-24.7-25.5-17.6-41a43.9 43.9 0 0 1 52.7-22.1z"/>
<path fill="rgb(77, 154, 184)" d="M109.5 86.9c-12.1 3-20.9 13.7-19.1 23.4 2.6 14.1 25 17.3 37.4 5.4 4.5-4.3 6.4-8.1 6.4-13.1.2-11.4-11.6-18.8-24.7-15.7zm7.7 11.8c4.5 4 .5 13.3-5.7 13.3-4.3 0-6.5-2.2-6.5-6.6 0-6.6 7.6-10.9 12.2-6.7z"/>
</svg>

After

Width:  |  Height:  |  Size: 1.8 KiB

+5
View File
@@ -0,0 +1,5 @@
{
"packageManager": "python",
"packageName": "jupyterlab_optuna",
"uninstallInstructions": "Use your Python package manager (pip, conda, etc.) to uninstall the package jupyterlab_optuna"
}
@@ -0,0 +1,7 @@
{
"ServerApp": {
"jpserver_extensions": {
"jupyterlab_optuna": true
}
}
}
+33
View File
@@ -0,0 +1,33 @@
try:
from ._version import __version__
except ImportError:
# Fallback when using the package in dev mode without installing
# in editable mode with pip. It is highly recommended to install
# the package from a stable release or in editable mode:
# https://pip.pypa.io/en/stable/topics/local-project-installs/#editable-installs
import warnings
warnings.warn("Importing 'jupyterlab_optuna' outside a proper installation.")
__version__ = "dev"
from .handlers import setup_handlers
def _jupyter_labextension_paths():
return [{"src": "labextension", "dest": "jupyterlab-optuna"}]
def _jupyter_server_extension_points():
return [{"module": "jupyterlab_optuna"}]
def _load_jupyter_server_extension(server_app):
"""Registers the API handler to receive HTTP requests from the frontend extension.
Parameters
----------
server_app: jupyterlab.labapp.LabApp
JupyterLab application instance
"""
setup_handlers(server_app.web_app)
name = "jupyterlab_optuna"
server_app.log.info(f"Registered {name} server extension")
+95
View File
@@ -0,0 +1,95 @@
from __future__ import annotations
import json
import threading
from typing import TYPE_CHECKING
from jupyter_server.base.handlers import APIHandler
from jupyter_server.utils import url_path_join
from optuna_dashboard.artifact._backend_to_store import to_artifact_store
import tornado
try:
from optuna.artifacts import FileSystemArtifactStore
except ImportError:
from optuna_dashboard.artifact.file_system import FileSystemBackend as FileSystemArtifactStore
from optuna_dashboard import wsgi
from tornado.web import FallbackHandler
from tornado.wsgi import WSGIContainer
if TYPE_CHECKING:
from _typeshed.wsgi import WSGIApplication
API_NAMESPACE = "jupyterlab-optuna"
_dashboard_app: WSGIApplication | None = None
_is_initialized = False
threading_lock = threading.Lock()
class RouteHandler(APIHandler):
@tornado.web.authenticated
def post(self):
global _dashboard_app, _is_initialized
input_data = self.get_json_body()
storage_url = input_data.get("storage_url")
artifact_path = input_data.get("artifact_path")
if storage_url is None:
self.set_status(400)
self.finish(json.dumps({"reason": "storage_url is required"}))
return
if artifact_path:
artifact_store = to_artifact_store(FileSystemArtifactStore(artifact_path))
else:
artifact_store = None
with threading_lock:
_dashboard_app = wsgi(storage=storage_url, artifact_store=artifact_store)
_is_initialized = True
self.finish(json.dumps({"is_initialized": True}))
class InitializedStateHandler(APIHandler):
@tornado.web.authenticated
def get(self):
self.finish(json.dumps({"is_initialized": _is_initialized}))
def dashboard_app(env, start_response):
# Set Content-Type
if "/api/" in env["PATH_INFO"]:
env["CONTENT_TYPE"] = "application/json"
env["PATH_INFO"] = env["PATH_INFO"].replace(f"/{API_NAMESPACE}", "")
if _dashboard_app is None:
start_response("400 Bad Request", [{"Content-Type": "application/json"}])
return [b'{"reason": "app is not initialized"}']
return _dashboard_app(env, start_response)
def setup_handlers(web_app):
host_pattern = ".*$"
base_url = web_app.settings["base_url"]
# Prepend the base_url so that it works in a JupyterHub setting
initialize_route_pattern = url_path_join(base_url, API_NAMESPACE, "api/is_initialized")
handlers = [(initialize_route_pattern, InitializedStateHandler)]
web_app.add_handlers(host_pattern, handlers)
resister_route_pattern = url_path_join(base_url, API_NAMESPACE, "api/register_dashboard_app")
handlers = [(resister_route_pattern, RouteHandler)]
web_app.add_handlers(host_pattern, handlers)
route_pattern = url_path_join(base_url, API_NAMESPACE, r"(.*)")
handlers = [
(route_pattern, FallbackHandler, dict(fallback=WSGIContainer(dashboard_app))),
]
web_app.add_handlers(host_pattern, handlers)
+132
View File
@@ -0,0 +1,132 @@
{
"name": "jupyterlab-optuna",
"version": "0.1.0",
"description": "A JupyterLab extension for Optuna",
"keywords": [
"jupyter",
"jupyterlab",
"jupyterlab-extension",
"optuna"
],
"homepage": "https://github.com/optuna/optuna-dashboard",
"bugs": {
"url": "https://github.com/optuna/optuna-dashboard/issues"
},
"license": "MIT",
"author": "Optuna Development Team",
"files": [
"lib/**/*.{d.ts,eot,gif,html,jpg,js,js.map,json,png,svg,woff2,ttf}",
"style/**/*.{css,js,eot,gif,html,jpg,json,png,svg,woff2,ttf}"
],
"main": "lib/index.js",
"types": "lib/index.d.ts",
"style": "style/index.css",
"repository": {
"type": "git",
"url": "https://github.com/optuna/optuna-dashboard.git"
},
"scripts": {
"build": "jlpm build:lib && jlpm build:labextension:dev",
"build:prod": "jlpm clean && jlpm build:lib:prod && jlpm build:labextension",
"build:labextension": "jupyter labextension build .",
"build:labextension:dev": "jupyter labextension build --development True .",
"build:lib": "tsc --sourceMap",
"build:lib:prod": "tsc",
"clean": "jlpm clean:lib",
"clean:lib": "rimraf lib tsconfig.tsbuildinfo",
"clean:labextension": "rimraf jupyterlab_optuna/labextension jupyterlab_optuna/_version.py",
"clean:all": "jlpm clean:lib && jlpm clean:labextension",
"install:extension": "jlpm build",
"lint": "jlpm prettier",
"lint:check": "jlpm prettier:check",
"prettier": "jlpm prettier:base --write --list-different",
"prettier:base": "prettier \"**/*{.ts,.tsx,.js,.jsx,.css,.json,.md}\"",
"prettier:check": "jlpm prettier:base --check",
"watch": "run-p watch:src watch:labextension",
"watch:src": "tsc -w --sourceMap",
"watch:labextension": "jupyter labextension watch ."
},
"dependencies": {
"@emotion/react": "^11.10.8",
"@emotion/styled": "^11.10.8",
"@jupyterlab/application": "^4.0.0",
"@jupyterlab/apputils": "^4.0.0",
"@jupyterlab/coreutils": "^6.0.0",
"@jupyterlab/launcher": "^4.0.0",
"@jupyterlab/services": "^7.0.0",
"@mui/icons-material": "^5.11.6",
"@mui/lab": "^5.0.0-alpha.128",
"@mui/material": "^5.12.1",
"@optuna/optuna-dashboard": "link:../optuna_dashboard",
"@types/chroma-js": "^2.4.1",
"@types/signals": "^1.0.2",
"elkjs": "^0.8.2",
"ngl": "^2.1.1",
"notistack": "^3.0.1",
"plotly.js-dist-min": "^2.22.0",
"react": "link:../tslib/react/node_modules/react",
"react-dom": "^18.2.0",
"react-markdown": "^8.0.4",
"react-router-dom": "6.11.0",
"react-syntax-highlighter": "^15.5.0",
"reactflow": "^11.8.3",
"recoil": "^0.7.7",
"rehype-mathjax": "^4.0.2",
"remark-gfm": "^3.0.1",
"remark-math": "^5.1.1"
},
"devDependencies": {
"@jupyterlab/builder": "^4.0.0",
"@optuna/types": "link:../tslib/types",
"@types/json-schema": "^7.0.11",
"@types/plotly.js": "^2.12.11",
"@types/react": "link:../tslib/react/node_modules/@types/react",
"@types/react-dom": "^18.0.10",
"@types/react-syntax-highlighter": "^15.5.5",
"css-loader": "^6.8.1",
"mkdirp": "^1.0.3",
"npm-run-all": "^4.1.5",
"prettier": "^2.8.7",
"rimraf": "^4.4.1",
"source-map-loader": "^1.0.2",
"style-loader": "^3.3.3",
"typescript": "~5.0.2",
"yjs": "^13.5.0"
},
"sideEffects": [
"style/*.css",
"style/index.js"
],
"styleModule": "style/index.js",
"publishConfig": {
"access": "public"
},
"jupyterlab": {
"discovery": {
"server": {
"managers": [
"pip"
],
"base": {
"name": "jupyterlab_optuna"
}
}
},
"extension": true,
"outputDir": "jupyterlab_optuna/labextension"
},
"prettier": {
"singleQuote": true,
"trailingComma": "none",
"arrowParens": "avoid",
"endOfLine": "auto",
"overrides": [
{
"files": "package.json",
"options": {
"tabWidth": 4
}
}
]
}
}
+80
View File
@@ -0,0 +1,80 @@
[build-system]
requires = ["hatchling>=1.5.0", "jupyterlab>=4.0.0,<5", "hatch-nodejs-version>=0.3.2"]
build-backend = "hatchling.build"
[project]
name = "jupyterlab-optuna"
readme = "README.md"
requires-python = ">=3.8"
classifiers = [
"Framework :: Jupyter",
"Framework :: Jupyter :: JupyterLab",
"Framework :: Jupyter :: JupyterLab :: 4",
"Framework :: Jupyter :: JupyterLab :: Extensions",
"Framework :: Jupyter :: JupyterLab :: Extensions :: Prebuilt",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
]
dependencies = [
"jupyter_server>=2.0.1,<3", "optuna-dashboard>=0.12.0"
]
dynamic = ["version", "description", "authors", "urls", "keywords"]
[project.optional-dependencies]
dev = ["jupyter"]
[tool.hatch.version]
source = "nodejs"
[tool.hatch.metadata.hooks.nodejs]
fields = ["description", "authors", "urls"]
[tool.hatch.build.targets.sdist]
artifacts = ["jupyterlab_optuna/labextension"]
exclude = [".github", "binder"]
[tool.hatch.build.targets.wheel.shared-data]
"jupyterlab_optuna/labextension" = "share/jupyter/labextensions/jupyterlab-optuna"
"install.json" = "share/jupyter/labextensions/jupyterlab-optuna/install.json"
"jupyter-config/server-config" = "etc/jupyter/jupyter_server_config.d"
[tool.hatch.build.hooks.version]
path = "jupyterlab_optuna/_version.py"
[tool.hatch.build.hooks.jupyter-builder]
dependencies = ["hatch-jupyter-builder>=0.5"]
build-function = "hatch_jupyter_builder.npm_builder"
ensured-targets = [
"jupyterlab_optuna/labextension/static/style.js",
"jupyterlab_optuna/labextension/package.json",
]
skip-if-exists = ["jupyterlab_optuna/labextension/static/style.js"]
[tool.hatch.build.hooks.jupyter-builder.build-kwargs]
build_cmd = "build:prod"
npm = ["jlpm"]
[tool.hatch.build.hooks.jupyter-builder.editable-build-kwargs]
build_cmd = "install:extension"
npm = ["jlpm"]
source_dir = "src"
build_dir = "jupyterlab_optuna/labextension"
[tool.jupyter-releaser.options]
version_cmd = "hatch version"
[tool.jupyter-releaser.hooks]
before-build-npm = [
"python -m pip install 'jupyterlab>=4.0.0,<5'",
"jlpm",
"jlpm build:prod"
]
before-build-python = ["jlpm clean:all"]
[tool.check-wheel-contents]
ignore = ["W002"]
+1
View File
@@ -0,0 +1 @@
__import__("setuptools").setup()
+303
View File
@@ -0,0 +1,303 @@
import {
APIClient,
APIMeta,
CompareStudiesPlotType,
CreateNewStudyResponse,
FeedbackComponentType,
ParamImportancesResponse,
PlotResponse,
PlotType,
RenameStudyResponse,
StudyDetail,
StudyDetailResponse,
StudySummariesResponse,
StudySummary,
Trial,
UploadArtifactAPIResponse,
} from "@optuna/optuna-dashboard"
import * as Optuna from "@optuna/types"
import { requestAPI } from "./handler"
export class JupyterlabAPIClient extends APIClient {
// biome-ignore lint/complexity/noUselessConstructor: <explanation>
constructor() {
super()
}
getMetaInfo = () =>
requestAPI<APIMeta>("/api/meta").then<APIMeta>((res) => res)
getStudyDetail = (
studyId: number,
nLocalTrials: number
): Promise<StudyDetail> =>
requestAPI<StudyDetailResponse>(
`/api/studies/${studyId}/?after=${nLocalTrials}`,
{
method: "GET",
}
).then((res) => {
const trials = res.trials.map((trial): Trial => {
return this.convertTrialResponse(trial)
})
const best_trials = res.best_trials.map((trial): Trial => {
return this.convertTrialResponse(trial)
})
return {
id: studyId,
name: res.name,
datetime_start: new Date(res.datetime_start),
directions: res.directions,
user_attrs: res.user_attrs,
trials: trials,
best_trials: best_trials,
union_search_space: res.union_search_space,
intersection_search_space: res.intersection_search_space,
union_user_attrs: res.union_user_attrs,
has_intermediate_values: res.has_intermediate_values,
note: res.note,
objective_names: res.objective_names,
form_widgets: res.form_widgets,
is_preferential: res.is_preferential,
feedback_component_type: res.feedback_component_type,
preferences: res.preferences,
preference_history: res.preference_history?.map(
this.convertPreferenceHistory
),
plotly_graph_objects: res.plotly_graph_objects,
artifacts: res.artifacts,
skipped_trial_numbers: res.skipped_trial_numbers ?? [],
}
})
getStudySummaries = (): Promise<StudySummary[]> =>
requestAPI<StudySummariesResponse>("/api/studies").then((res) => {
return res.study_summaries.map((study): StudySummary => {
return {
study_id: study.study_id,
study_name: study.study_name,
directions: study.directions,
user_attrs: study.user_attrs,
is_preferential: study.is_preferential,
datetime_start: study.datetime_start
? new Date(study.datetime_start)
: undefined,
}
})
})
createNewStudy = (
studyName: string,
directions: Optuna.StudyDirection[]
): Promise<StudySummary> =>
requestAPI<CreateNewStudyResponse>("/api/studies", {
body: JSON.stringify({
study_name: studyName,
directions,
}),
method: "POST",
}).then((res) => {
const study_summary = res.study_summary
return {
study_id: study_summary.study_id,
study_name: study_summary.study_name,
directions: study_summary.directions,
// best_trial: undefined,
user_attrs: study_summary.user_attrs,
is_preferential: study_summary.is_preferential,
datetime_start: study_summary.datetime_start
? new Date(study_summary.datetime_start)
: undefined,
}
})
deleteStudy = (
studyId: number,
removeAssociatedArtifacts: boolean
): Promise<void> =>
requestAPI<void>(`/api/studies/${studyId}`, {
method: "DELETE",
body: JSON.stringify({
remove_associated_artifacts: removeAssociatedArtifacts,
}),
}).then(() => {
return
})
renameStudy = (studyId: number, studyName: string): Promise<StudySummary> =>
requestAPI<RenameStudyResponse>(`/api/studies/${studyId}/rename`, {
body: JSON.stringify({ study_name: studyName }),
method: "POST",
}).then((res) => {
return {
study_id: res.study_id,
study_name: res.study_name,
directions: res.directions,
user_attrs: res.user_attrs,
is_preferential: res.is_prefential,
datetime_start: res.datetime_start
? new Date(res.datetime_start)
: undefined,
}
})
saveStudyNote = (
studyId: number,
note: { version: number; body: string }
): Promise<void> =>
requestAPI<void>(`/api/studies/${studyId}/note`, {
body: JSON.stringify(note),
method: "PUT",
}).then(() => {
return
})
saveTrialNote = (
studyId: number,
trialId: number,
note: { version: number; body: string }
): Promise<void> =>
requestAPI<void>(`/api/studies/${studyId}/${trialId}/note`, {
body: JSON.stringify(note),
method: "PUT",
}).then(() => {
return
})
uploadTrialArtifact = (
studyId: number,
trialId: number,
fileName: string,
dataUrl: string
): Promise<UploadArtifactAPIResponse> =>
requestAPI<UploadArtifactAPIResponse>(
`/api/artifacts/${studyId}/${trialId}`,
{
body: JSON.stringify({
file: dataUrl,
filename: fileName,
}),
method: "POST",
}
).then((res) => {
return res
})
uploadStudyArtifact = (
studyId: number,
fileName: string,
dataUrl: string
): Promise<UploadArtifactAPIResponse> =>
requestAPI<UploadArtifactAPIResponse>(`/api/artifacts/${studyId}`, {
body: JSON.stringify({
file: dataUrl,
filename: fileName,
}),
method: "POST",
}).then((res) => {
return res
})
deleteTrialArtifact = (
studyId: number,
trialId: number,
artifactId: string
): Promise<void> =>
requestAPI<void>(`/api/artifacts/${studyId}/${trialId}/${artifactId}`, {
method: "DELETE",
}).then(() => {
return
})
deleteStudyArtifact = (studyId: number, artifactId: string): Promise<void> =>
requestAPI<void>(`/api/artifacts/${studyId}/${artifactId}`, {
method: "DELETE",
}).then(() => {
return
})
tellTrial = async (
trialId: number,
state: Optuna.TrialStateFinished,
values?: number[]
): Promise<void> => {
const req: { state: Optuna.TrialState; values?: number[] } = {
state: state,
values: values,
}
await requestAPI<void>(`/api/trials/${trialId}/tell`, {
body: JSON.stringify(req),
method: "POST",
})
}
saveTrialUserAttrs = async (
trialId: number,
user_attrs: { [key: string]: number | string }
): Promise<void> => {
const req = { user_attrs: user_attrs }
await requestAPI<void>(`/api/trials/${trialId}/user-attrs`, {
body: JSON.stringify(req),
method: "POST",
})
return
}
getParamImportances = (
studyId: number
): Promise<Optuna.ParamImportance[][]> =>
requestAPI<ParamImportancesResponse>(
`/api/studies/${studyId}/param_importances`
).then((res) => {
return res.param_importances
})
reportPreference = (
studyId: number,
candidates: number[],
clicked: number
): Promise<void> =>
requestAPI<void>(`/api/studies/${studyId}/preference`, {
body: JSON.stringify({
candidates: candidates,
clicked: clicked,
mode: "ChooseWorst",
}),
method: "POST",
}).then(() => {
return
})
skipPreferentialTrial = (studyId: number, trialId: number): Promise<void> =>
requestAPI<void>(`/api/studies/${studyId}/${trialId}/skip`, {
method: "POST",
}).then(() => {
return
})
removePreferentialHistory = (
studyId: number,
historyUuid: string
): Promise<void> =>
requestAPI<void>(`/api/studies/${studyId}/preference/${historyUuid}`, {
method: "DELETE",
}).then(() => {
return
})
restorePreferentialHistory = (
studyId: number,
historyUuid: string
): Promise<void> =>
requestAPI<void>(`/api/studies/${studyId}/preference/${historyUuid}`, {
method: "POST",
}).then(() => {
return
})
reportFeedbackComponent = (
studyId: number,
component_type: FeedbackComponentType
): Promise<void> =>
requestAPI<void>(`/api/studies/${studyId}/preference_feedback_component`, {
body: JSON.stringify({ component_type: component_type }),
method: "POST",
}).then(() => {
return
})
getPlot = (studyId: number, plotType: PlotType): Promise<PlotResponse> =>
requestAPI<PlotResponse>(
`/api/studies/${studyId}/plot/${plotType}`
).then<PlotResponse>((res) => res)
getCompareStudiesPlot = (
studyIds: number[],
plotType: CompareStudiesPlotType
): Promise<PlotResponse> => {
return requestAPI<PlotResponse>(`/api/compare-studies/plot/${plotType}`, {
body: JSON.stringify({ study_ids: studyIds }),
}).then<PlotResponse>((res) => res)
}
}
+31
View File
@@ -0,0 +1,31 @@
import { TextField, TextFieldProps } from "@mui/material"
import React, { FC, useEffect } from "react"
export const DebouncedInputTextField: FC<{
onChange: (s: string, valid: boolean) => void
delay: number
textFieldProps: TextFieldProps
}> = ({ onChange, delay, textFieldProps }) => {
const [text, setText] = React.useState<string>("")
const [valid, setValidity] = React.useState<boolean>(true)
// biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
useEffect(() => {
const timer = setTimeout(() => {
onChange(text, valid)
}, delay)
return () => {
clearTimeout(timer)
}
}, [text, delay])
return (
<TextField
onChange={(e) => {
setText(e.target.value)
setValidity(e.target.validity.valid)
}}
{...textFieldProps}
/>
)
}
@@ -0,0 +1,256 @@
import RestartAltIcon from "@mui/icons-material/RestartAlt"
import StartIcon from "@mui/icons-material/Start"
import {
Box,
Button,
CssBaseline,
FormControl,
Typography,
} from "@mui/material"
import CircularProgress from "@mui/material/CircularProgress"
import {
APIClientProvider,
App,
ConstantsContext,
} from "@optuna/optuna-dashboard"
import { SnackbarProvider, enqueueSnackbar } from "notistack"
import React, { Dispatch, FC, SetStateAction, useEffect, useState } from "react"
import { JupyterlabAPIClient } from "../apiClient"
import { requestAPI } from "../handler"
import { DebouncedInputTextField } from "./Debounce"
const jupyterlabAPIClient = new JupyterlabAPIClient()
export const JupyterLabEntrypoint: FC = () => {
const [ready, setReady] = useState(false)
const [pathName, setPathName] = useState("")
useEffect(() => {
setPathName(window.location.pathname)
}, [])
if (!ready) {
return (
<>
<CssBaseline />
<SnackbarProvider maxSnack={3}>
<Box
sx={{
minHeight: "100vh",
display: "flex",
flexDirection: "column",
justifyContent: "center",
alignItems: "center",
}}
>
<JupyterLabStartWidget
showOptunaDashboard={() => {
setReady(true)
}}
/>
</Box>
</SnackbarProvider>
</>
)
}
return (
<ConstantsContext.Provider
value={{
environment: "jupyterlab",
url_prefix: pathName,
}}
>
<APIClientProvider apiClient={jupyterlabAPIClient}>
<App />
</APIClientProvider>
</ConstantsContext.Provider>
)
}
const JupyterLabStartWidget: FC<{
showOptunaDashboard: () => void
}> = ({ showOptunaDashboard }) => {
const [loading, setLoading] = useState(true)
const [isInitialized, setIsInitialized] = useState(false)
useEffect(() => {
setLoading(true)
requestAPI<{ is_initialized: boolean }>("/api/is_initialized", {
method: "GET",
})
.then((res) => {
setIsInitialized(res.is_initialized)
setLoading(false)
})
.catch((err) => {
setLoading(false)
enqueueSnackbar("Failed to check the initialized state", {
variant: "error",
})
console.error(err)
})
}, [])
if (loading) {
return (
<Box
sx={{
height: "100vh",
display: "flex",
flexDirection: "column",
justifyContent: "center",
alignItems: "center",
}}
>
<CircularProgress />
</Box>
)
}
if (isInitialized) {
return (
<Box
sx={{
display: "flex",
flexDirection: "column",
width: "600px",
borderRadius: "8px",
boxShadow: "rgba(0, 0, 0, 0.08) 0 8px 24px",
padding: "64px",
}}
>
<Typography variant="h4">Continue or Reset?</Typography>
<Typography sx={{ margin: "8px 0" }}>
Continue with the existing storage URL and artifact path settings, or
you can reset them.
</Typography>
<Button
variant="contained"
onClick={showOptunaDashboard}
color="primary"
startIcon={<StartIcon />}
sx={{ margin: "8px 0", minWidth: "120px" }}
>
Continue
</Button>
<Button
variant="outlined"
onClick={() => {
setIsInitialized(false)
}}
color="primary"
startIcon={<RestartAltIcon />}
sx={{ margin: "8px 0", minWidth: "120px" }}
>
Reset
</Button>
</Box>
)
}
return (
<StartDashboardForm
showOptunaDashboard={showOptunaDashboard}
setLoading={setLoading}
/>
)
}
const StartDashboardForm: FC<{
showOptunaDashboard: () => void
setLoading: Dispatch<SetStateAction<boolean>>
}> = ({ showOptunaDashboard, setLoading }) => {
const [storageURL, setStorageURL] = useState("")
const [artifactPath, setArtifactPath] = useState("")
const [isValidURL, setIsValidURL] = useState(false)
// biome-ignore lint/complexity/useRegexLiterals: <explanation>
const rfc1738Pattern = new RegExp(
"[\\w\\+]+://([^:/]*(.*)?@)?((\\[[^/]+\\]|[^/:]+)?([^/]*)?)?(/.*)?"
)
const handleValidateURL = (url: string): void => {
url.startsWith("redis") || url.match(rfc1738Pattern)
? setIsValidURL(true)
: setIsValidURL(false)
}
const handleCreateNewDashboard = () => {
setLoading(true)
requestAPI<{ is_initialized: boolean }>("/api/register_dashboard_app", {
method: "POST",
body: JSON.stringify({
storage_url: storageURL,
artifact_path: artifactPath,
}),
})
.then((_res) => {
setLoading(false)
showOptunaDashboard()
})
.catch((err) => {
setLoading(false)
enqueueSnackbar("Failed to initialize Optuna Dashboard", {
variant: "error",
})
console.error(err)
})
}
return (
<Box
sx={{
display: "flex",
flexDirection: "column",
width: "600px",
borderRadius: "8px",
boxShadow: "rgba(0, 0, 0, 0.08) 0 8px 24px",
padding: "64px",
}}
>
<Typography variant="h4">Initialize Dashboard</Typography>
<Typography sx={{ margin: "8px 0" }}>
Please enter a storage URL and an artifact path.
</Typography>
<FormControl>
<DebouncedInputTextField
onChange={(s) => {
handleValidateURL(s)
setStorageURL(s)
}}
delay={500}
textFieldProps={{
autoFocus: true,
fullWidth: true,
label: "Storage URL",
type: "text",
sx: { margin: "8px 0" },
}}
/>
</FormControl>
<FormControl>
<DebouncedInputTextField
onChange={(s) => {
setArtifactPath(s)
}}
delay={500}
textFieldProps={{
fullWidth: true,
label: "Artifact path (Optional)",
type: "text",
sx: { margin: "8px 0" },
}}
/>
</FormControl>
<Button
variant="contained"
onClick={handleCreateNewDashboard}
color="primary"
disabled={!isValidURL}
sx={{ margin: "8px 0" }}
>
Create
</Button>
</Box>
)
}
+48
View File
@@ -0,0 +1,48 @@
import { URLExt } from "@jupyterlab/coreutils"
import { ServerConnection } from "@jupyterlab/services"
/**
* Call the API extension
*
* @param endPoint API REST end point for the extension
* @param init Initial values for the request
* @returns The response body interpreted as JSON
*/
export async function requestAPI<T>(
endPoint = "",
init: RequestInit = {}
): Promise<T> {
// Make request to Jupyter API
const settings = ServerConnection.makeSettings()
const requestUrl = URLExt.join(
settings.baseUrl,
"jupyterlab-optuna", // API Namespace
endPoint
)
let response: Response
try {
response = await ServerConnection.makeRequest(requestUrl, init, settings)
} catch (error) {
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
throw new ServerConnection.NetworkError(error as any)
}
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
let data: any = await response.text()
if (data.length > 0) {
try {
data = JSON.parse(data)
} catch (error) {
console.log("Not a JSON response body.", response)
}
}
if (!response.ok) {
throw new ServerConnection.ResponseError(response, data.message || data)
}
return data
}
+66
View File
@@ -0,0 +1,66 @@
import { JupyterFrontEnd, JupyterFrontEndPlugin } from "@jupyterlab/application"
import { ICommandPalette } from "@jupyterlab/apputils"
import optunaLogo from "../img/optuna_logo.svg"
import { ILauncher } from "@jupyterlab/launcher"
import { LabIcon } from "@jupyterlab/ui-components"
import { MainAreaWidget } from "@jupyterlab/apputils"
import { OptunaDashboardWidget } from "./widget"
/**
* The command IDs used by the server extension plugin.
*/
namespace CommandIDs {
export const get = "server:get-file"
export const ui = "server:dashboard-ui"
}
/**
* Initialization data for the jupyterlab-optuna extension.
*/
const plugin: JupyterFrontEndPlugin<void> = {
id: "@jupyterlab-examples/server-extension:plugin",
description:
"A minimal JupyterLab extension with backend and frontend parts.",
autoStart: true,
optional: [ILauncher],
requires: [ICommandPalette],
activate: (
app: JupyterFrontEnd,
palette: ICommandPalette,
launcher: ILauncher | null
) => {
console.log(
"JupyterLab extension @jupyterlab-examples/server-extension is activated!"
)
console.log("ICommandPalette:", palette)
const { commands, shell } = app
const optunaIcon = new LabIcon({
name: "ui-components:optuna",
svgstr: optunaLogo,
})
commands.addCommand(CommandIDs.ui, {
caption: "Launch Optuna Dashboard",
label: "Optuna Dashboard",
icon: (args) => (args.isPalette ? undefined : optunaIcon),
execute: () => {
const content = new OptunaDashboardWidget()
const widget = new MainAreaWidget<OptunaDashboardWidget>({ content })
widget.title.label = "Optuna Dashboard Widget"
widget.title.icon = optunaIcon
shell.add(widget, "main")
},
})
if (launcher) {
launcher.add({
command: CommandIDs.ui,
})
}
},
}
export default plugin
+4
View File
@@ -0,0 +1,4 @@
declare module "*.css"
declare module "*.png"
declare module "*.jpg"
declare module "*.svg"
+14
View File
@@ -0,0 +1,14 @@
import { ReactWidget } from "@jupyterlab/ui-components"
import React from "react"
import { JupyterLabEntrypoint } from "./components/JupyterLabEntrypoint"
export class OptunaDashboardWidget extends ReactWidget {
constructor() {
super()
this.addClass("jp-react-widget")
}
render(): JSX.Element {
return <JupyterLabEntrypoint />
}
}
+5
View File
@@ -0,0 +1,5 @@
/*
See the JupyterLab Developer Guide for useful CSS Patterns:
https://jupyterlab.readthedocs.io/en/stable/developer/css.html
*/
+1
View File
@@ -0,0 +1 @@
@import url('base.css');
+1
View File
@@ -0,0 +1 @@
import './base.css';
+27
View File
@@ -0,0 +1,27 @@
{
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"baseUrl": ".",
"composite": true,
"declaration": true,
"esModuleInterop": true,
"incremental": true,
"jsx": "react",
"module": "esnext",
"moduleResolution": "node",
"noEmitOnError": true,
"noImplicitAny": true,
"noUnusedLocals": true,
"preserveWatchOutput": true,
"resolveJsonModule": true,
"outDir": "lib",
"paths": {
"plotly.js-dist-min": ["node_modules/@types/plotly.js"]
},
"rootDir": "src",
"strict": true,
"strictNullChecks": true,
"target": "ES2018"
},
"include": ["src/**/*", "src/types/**/*"]
}
+8597
View File
File diff suppressed because it is too large Load Diff
+10
View File
@@ -54,6 +54,7 @@
"compression-webpack-plugin": "^11.0.0",
"css-loader": "^6.9.1",
"esbuild-loader": "^4.0.3",
"process": "^0.11.10",
"style-loader": "^3.3.4",
"ts-loader": "^9.5.1",
"typescript": "^5.3.3",
@@ -17776,6 +17777,15 @@
"node": ">=6"
}
},
"node_modules/process": {
"version": "0.11.10",
"resolved": "https://registry.npmjs.org/process/-/process-0.11.10.tgz",
"integrity": "sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A==",
"dev": true,
"engines": {
"node": ">= 0.6.0"
}
},
"node_modules/promise-worker-transferable": {
"version": "1.0.4",
"license": "Apache-2.0",
+3 -2
View File
@@ -3,8 +3,8 @@
"private": true,
"version": "0.0.1",
"description": "Dashboard for Optuna",
"main": "pkg/pkg_index.js",
"types": "types/pkg_index.d.ts",
"module": "pkg/pkg_index.js",
"types": "pkg/pkg_index.d.ts",
"scripts": {
"watch": "NODE_ENV=development TYPESCRIPT_LOADER=esbuild-loader webpack --watch",
"build": "webpack",
@@ -61,6 +61,7 @@
"compression-webpack-plugin": "^11.0.0",
"css-loader": "^6.9.1",
"esbuild-loader": "^4.0.3",
"process": "^0.11.10",
"style-loader": "^3.3.4",
"ts-loader": "^9.5.1",
"typescript": "^5.3.3",
+3 -3
View File
@@ -20,7 +20,7 @@ export type APIMeta = {
plotlypy_is_available: boolean
}
interface TrialResponse {
export interface TrialResponse {
trial_id: number
study_id: number
number: number
@@ -40,7 +40,7 @@ interface TrialResponse {
constraints: number[]
}
interface PreferenceHistoryResponse {
export interface PreferenceHistoryResponse {
history: {
id: string
candidates: number[]
@@ -102,7 +102,7 @@ export type RenameStudyResponse = {
study_name: string
directions: Optuna.StudyDirection[]
user_attrs: Optuna.Attribute[]
is_prefential: boolean
is_prefential: boolean // TODO(porink0424): Fix typo
datetime_start?: string
}
+1 -1
View File
@@ -23,7 +23,7 @@ import {
export class AxiosClient extends APIClient {
private axiosInstance: AxiosInstance
constructor() {
constructor(API_ENDPOINT: string | undefined) {
super()
this.axiosInstance = axios.create({ baseURL: API_ENDPOINT })
}
+13 -10
View File
@@ -8,11 +8,12 @@ import {
import blue from "@mui/material/colors/blue"
import pink from "@mui/material/colors/pink"
import { SnackbarProvider } from "notistack"
import React, { FC, useMemo, useState, useEffect } from "react"
import React, { useMemo, useState, useEffect, FC } from "react"
import { BrowserRouter as Router, Route, Routes } from "react-router-dom"
import { RecoilRoot } from "recoil"
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
import { useConstants } from "../constantsProvider"
import { CompareStudies } from "./CompareStudies"
import { StudyDetail } from "./StudyDetail"
import { StudyList } from "./StudyList"
@@ -49,6 +50,8 @@ export const App: FC = () => {
setColorMode(colorMode === "dark" ? "light" : "dark")
}
const { url_prefix } = useConstants()
return (
<QueryClientProvider client={queryClient}>
<RecoilRoot>
@@ -66,7 +69,7 @@ export const App: FC = () => {
<Router>
<Routes>
<Route
path={URL_PREFIX + "/studies/:studyId/analytics"}
path={url_prefix + "/studies/:studyId/analytics"}
element={
<StudyDetail
toggleColorMode={toggleColorMode}
@@ -75,7 +78,7 @@ export const App: FC = () => {
}
/>
<Route
path={URL_PREFIX + "/studies/:studyId/trials"}
path={url_prefix + "/studies/:studyId/trials"}
element={
<StudyDetail
toggleColorMode={toggleColorMode}
@@ -84,7 +87,7 @@ export const App: FC = () => {
}
/>
<Route
path={URL_PREFIX + "/studies/:studyId/trialTable"}
path={url_prefix + "/studies/:studyId/trialTable"}
element={
<StudyDetail
toggleColorMode={toggleColorMode}
@@ -93,7 +96,7 @@ export const App: FC = () => {
}
/>
<Route
path={URL_PREFIX + "/studies/:studyId/note"}
path={url_prefix + "/studies/:studyId/note"}
element={
<StudyDetail
toggleColorMode={toggleColorMode}
@@ -102,7 +105,7 @@ export const App: FC = () => {
}
/>
<Route
path={URL_PREFIX + "/studies/:studyId/graph"}
path={url_prefix + "/studies/:studyId/graph"}
element={
<StudyDetail
toggleColorMode={toggleColorMode}
@@ -111,7 +114,7 @@ export const App: FC = () => {
}
/>
<Route
path={URL_PREFIX + "/studies/:studyId"}
path={url_prefix + "/studies/:studyId"}
element={
<StudyDetail
toggleColorMode={toggleColorMode}
@@ -120,7 +123,7 @@ export const App: FC = () => {
}
/>
<Route
path={URL_PREFIX + "/studies/:studyId/preference-history"}
path={url_prefix + "/studies/:studyId/preference-history"}
element={
<StudyDetail
toggleColorMode={toggleColorMode}
@@ -129,13 +132,13 @@ export const App: FC = () => {
}
/>
<Route
path={URL_PREFIX + "/compare-studies"}
path={url_prefix + "/compare-studies"}
element={
<CompareStudies toggleColorMode={toggleColorMode} />
}
/>
<Route
path={URL_PREFIX + "/"}
path={url_prefix + "/"}
element={<StudyList toggleColorMode={toggleColorMode} />}
/>
</Routes>
+27 -9
View File
@@ -21,7 +21,13 @@ import ListItemIcon from "@mui/material/ListItemIcon"
import ListItemText from "@mui/material/ListItemText"
import Modal from "@mui/material/Modal"
import Toolbar from "@mui/material/Toolbar"
import { CSSObject, Theme, styled, useTheme } from "@mui/material/styles"
import {
CSSObject,
SxProps,
Theme,
styled,
useTheme,
} from "@mui/material/styles"
import React, { FC } from "react"
import { Link } from "react-router-dom"
import { useRecoilState, useRecoilValue } from "recoil"
@@ -41,6 +47,7 @@ import QueryStatsIcon from "@mui/icons-material/QueryStats"
import ThumbUpAltIcon from "@mui/icons-material/ThumbUpAlt"
import { Switch } from "@mui/material"
import { actionCreator } from "../action"
import { useConstants } from "../constantsProvider"
const drawerWidth = 240
@@ -129,7 +136,10 @@ export const AppDrawer: FC<{
toolbar: React.ReactNode
children?: React.ReactNode
}> = ({ studyId, toggleColorMode, page, toolbar, children }) => {
const { url_prefix } = useConstants()
const theme = useTheme()
const constants = useConstants()
const action = actionCreator()
const [open, setOpen] = useRecoilState<boolean>(drawerOpenState)
const reloadInterval = useRecoilValue<number>(reloadIntervalState)
@@ -155,6 +165,14 @@ export const AppDrawer: FC<{
const styleSwitch = {
display: open ? "inherit" : "none",
}
const mainSx: SxProps = {
flexGrow: 1,
}
if (constants.environment === "jupyterlab") {
// 100vh - (the height of Optuna Dashboard toolbar) - (the height of JupyterLab toolbar)
mainSx.height = `calc(100vh - ${theme.mixins.toolbar.minHeight}px - 29px)`
mainSx.overflow = "auto"
}
const handleDrawerOpen = () => {
setOpen(true)
@@ -209,7 +227,7 @@ export const AppDrawer: FC<{
<ListItem key="Top" disablePadding sx={styleListItem}>
<ListItemButton
component={Link}
to={`${URL_PREFIX}/studies/${studyId}`}
to={`${url_prefix}/studies/${studyId}`}
sx={styleListItemButton}
selected={page === "top"}
>
@@ -230,7 +248,7 @@ export const AppDrawer: FC<{
>
<ListItemButton
component={Link}
to={`${URL_PREFIX}/studies/${studyId}/preference-history`}
to={`${url_prefix}/studies/${studyId}/preference-history`}
sx={styleListItemButton}
selected={page === "preferenceHistory"}
>
@@ -247,7 +265,7 @@ export const AppDrawer: FC<{
<ListItem key="Analytics" disablePadding sx={styleListItem}>
<ListItemButton
component={Link}
to={`${URL_PREFIX}/studies/${studyId}/analytics`}
to={`${url_prefix}/studies/${studyId}/analytics`}
sx={styleListItemButton}
selected={page === "analytics"}
>
@@ -261,7 +279,7 @@ export const AppDrawer: FC<{
<ListItem key="PreferenceGraph" disablePadding sx={styleListItem}>
<ListItemButton
component={Link}
to={`${URL_PREFIX}/studies/${studyId}/graph`}
to={`${url_prefix}/studies/${studyId}/graph`}
sx={styleListItemButton}
selected={page === "graph"}
>
@@ -278,7 +296,7 @@ export const AppDrawer: FC<{
<ListItem key="TableList" disablePadding sx={styleListItem}>
<ListItemButton
component={Link}
to={`${URL_PREFIX}/studies/${studyId}/trials`}
to={`${url_prefix}/studies/${studyId}/trials`}
sx={styleListItemButton}
selected={page === "trialList"}
>
@@ -291,7 +309,7 @@ export const AppDrawer: FC<{
<ListItem key="TrialTable" disablePadding sx={styleListItem}>
<ListItemButton
component={Link}
to={`${URL_PREFIX}/studies/${studyId}/trialTable`}
to={`${url_prefix}/studies/${studyId}/trialTable`}
sx={styleListItemButton}
selected={page === "trialTable"}
>
@@ -304,7 +322,7 @@ export const AppDrawer: FC<{
<ListItem key="Note" disablePadding sx={styleListItem}>
<ListItemButton
component={Link}
to={`${URL_PREFIX}/studies/${studyId}/note`}
to={`${url_prefix}/studies/${studyId}/note`}
sx={styleListItemButton}
selected={page === "note"}
>
@@ -416,7 +434,7 @@ export const AppDrawer: FC<{
</ListItem>
</List>
</Drawer>
<Box component="main" sx={{ flexGrow: 1 }}>
<Box component="main" sx={mainSx}>
<DrawerHeader />
{children || null}
</Box>
@@ -15,6 +15,7 @@ import {
import React, { FC, ReactNode, useMemo } from "react"
import { Link } from "react-router-dom"
import { StudyDetail, Trial } from "ts/types/optuna"
import { useConstants } from "../constantsProvider"
const useBestTrials = (studyDetail: StudyDetail | null): Trial[] => {
return useMemo(() => studyDetail?.best_trials || [], [studyDetail])
@@ -23,6 +24,8 @@ const useBestTrials = (studyDetail: StudyDetail | null): Trial[] => {
export const BestTrialsCard: FC<{
studyDetail: StudyDetail | null
}> = ({ studyDetail }) => {
const { url_prefix } = useConstants()
const theme = useTheme()
const bestTrials = useBestTrials(studyDetail)
@@ -61,7 +64,7 @@ export const BestTrialsCard: FC<{
variant="outlined"
startIcon={<LinkIcon />}
component={Link}
to={`${URL_PREFIX}/studies/${bestTrial.study_id}/trials?numbers=${bestTrial.number}`}
to={`${url_prefix}/studies/${bestTrial.study_id}/trials?numbers=${bestTrial.number}`}
sx={{ margin: theme.spacing(1) }}
>
Details
@@ -89,7 +92,7 @@ export const BestTrialsCard: FC<{
<ListItemButton
component={Link}
to={
URL_PREFIX +
url_prefix +
`/studies/${trial.study_id}/trials?numbers=${trial.number}`
}
sx={{ flexDirection: "column", alignItems: "flex-start" }}
@@ -28,6 +28,7 @@ import { useRecoilValue } from "recoil"
import { useNavigate } from "react-router-dom"
import { StudyDetails, StudySummary } from "ts/types/optuna"
import { actionCreator } from "../action"
import { useConstants } from "../constantsProvider"
import { studyDetailsState, studySummariesState } from "../state"
import { useQuery } from "../urlQuery"
import { AppDrawer } from "./AppDrawer"
@@ -51,8 +52,8 @@ const useQueriedStudies = (
}, [studies, query])
}
const getStudyListLink = (ids: number[]): string => {
const base = URL_PREFIX + "/compare-studies"
const getStudyListLink = (ids: number[], url_prefix: string): string => {
const base = url_prefix + "/compare-studies"
if (ids.length > 0) {
return base + "?ids=" + ids.map((n) => n.toString()).join(",")
}
@@ -75,6 +76,8 @@ const isEqualDirections = (
export const CompareStudies: FC<{
toggleColorMode: () => void
}> = ({ toggleColorMode }) => {
const { url_prefix } = useConstants()
const { enqueueSnackbar } = useSnackbar()
const theme = useTheme()
const query = useQuery()
@@ -98,7 +101,7 @@ export const CompareStudies: FC<{
<>
<IconButton
component={Link}
to={URL_PREFIX + "/"}
to={url_prefix + "/"}
sx={{ marginRight: theme.spacing(1) }}
color="inherit"
title="Return to the top page"
@@ -186,9 +189,11 @@ export const CompareStudies: FC<{
next = [...selectedIds, study.study_id]
}
}
navigate(getStudyListLink(next))
navigate(getStudyListLink(next, url_prefix))
} else {
navigate(getStudyListLink([study.study_id]))
navigate(
getStudyListLink([study.study_id], url_prefix)
)
}
}}
selected={
@@ -23,6 +23,7 @@ import * as plotly from "plotly.js-dist-min"
import React, { ChangeEvent, FC, useEffect, useState } from "react"
import { useNavigate } from "react-router-dom"
import { StudyDetail } from "ts/types/optuna"
import { useConstants } from "../constantsProvider"
import { usePlotlyColorTheme } from "../state"
const plotDomId = "graph-history"
@@ -39,6 +40,8 @@ export const GraphHistory: FC<{
logScale: boolean
includePruned: boolean
}> = ({ studies, logScale, includePruned }) => {
const { url_prefix } = useConstants()
const theme = useTheme()
const colorTheme = usePlotlyColorTheme(theme.palette.mode)
const navigate = useNavigate()
@@ -100,7 +103,7 @@ export const GraphHistory: FC<{
studyId = studies[Math.floor(data.points[0].curveNumber / 2)].id
}
navigate(
URL_PREFIX +
url_prefix +
`/studies/${studyId}/trials?numbers=${data.points[0].x}`
)
}
@@ -15,6 +15,7 @@ import React, { FC, useEffect, useState } from "react"
import { useNavigate } from "react-router-dom"
import { StudyDetail, Trial } from "ts/types/optuna"
import { PlotType } from "../apiClient"
import { useConstants } from "../constantsProvider"
import { makeHovertext } from "../graphUtil"
import { usePlot } from "../hooks/usePlot"
import { usePlotlyColorTheme } from "../state"
@@ -61,6 +62,8 @@ const GraphParetoFrontBackend: FC<{
const GraphParetoFrontFrontend: FC<{
study: StudyDetail | null
}> = ({ study = null }) => {
const { url_prefix } = useConstants()
const theme = useTheme()
const colorTheme = usePlotlyColorTheme(theme.palette.mode)
const navigate = useNavigate()
@@ -93,7 +96,7 @@ const GraphParetoFrontFrontend: FC<{
data.points[0].text.replace(/<br>/g, "")
)
navigate(
URL_PREFIX +
url_prefix +
`/studies/${study.id}/trials?numbers=${plotTextInfo.number}`
)
})
@@ -14,6 +14,7 @@ import { Link, useParams } from "react-router-dom"
import { useRecoilValue } from "recoil"
import { actionCreator } from "../action"
import { useConstants } from "../constantsProvider"
import {
reloadIntervalState,
useStudyDetailValue,
@@ -49,6 +50,8 @@ export const StudyDetail: FC<{
toggleColorMode: () => void
page: PageId
}> = ({ toggleColorMode, page }) => {
const { url_prefix } = useConstants()
const theme = useTheme()
const action = actionCreator()
const studyId = useURLVars()
@@ -223,7 +226,7 @@ export const StudyDetail: FC<{
<>
<IconButton
component={Link}
to={URL_PREFIX + "/"}
to={url_prefix + "/"}
sx={{ marginRight: theme.spacing(1) }}
color="inherit"
title="Return to the top page"
+5 -2
View File
@@ -34,6 +34,7 @@ import { useRecoilValue } from "recoil"
import { styled } from "@mui/system"
import { StudySummary } from "ts/types/optuna"
import { actionCreator } from "../action"
import { useConstants } from "../constantsProvider"
import { studySummariesLoadingState, studySummariesState } from "../state"
import { useQuery } from "../urlQuery"
import { AppDrawer } from "./AppDrawer"
@@ -44,6 +45,8 @@ import { useRenameStudyDialog } from "./RenameStudyDialog"
export const StudyList: FC<{
toggleColorMode: () => void
}> = ({ toggleColorMode }) => {
const { url_prefix } = useConstants()
const theme = useTheme()
const action = actionCreator()
@@ -152,7 +155,7 @@ export const StudyList: FC<{
>
<CardActionArea
component={Link}
to={`${URL_PREFIX}/studies/${study.study_id}`}
to={`${url_prefix}/studies/${study.study_id}`}
>
<CardContent>
<Typography variant="h5" sx={{ wordBreak: "break-all" }}>
@@ -257,7 +260,7 @@ export const StudyList: FC<{
variant="outlined"
startIcon={<CompareIcon />}
component={Link}
to={`${URL_PREFIX}/compare-studies`}
to={`${url_prefix}/compare-studies`}
sx={{ marginRight: theme.spacing(2), minWidth: "120px" }}
>
Compare
+23 -6
View File
@@ -27,6 +27,7 @@ import { useNavigate } from "react-router-dom"
import { useRecoilValue } from "recoil"
import { FormWidgets, StudyDetail, Trial } from "ts/types/optuna"
import { actionCreator } from "../action"
import { useConstants } from "../constantsProvider"
import { artifactIsAvailable } from "../state"
import { useQuery } from "../urlQuery"
import { TrialArtifactCards } from "./Artifact/TrialArtifactCards"
@@ -312,7 +313,8 @@ export const TrialListDetail: FC<{
const getTrialListLink = (
studyId: number,
exclude: Optuna.TrialState[],
numbers: number[]
numbers: number[],
URL_PREFIX: string
): string => {
const base = URL_PREFIX + `/studies/${studyId}/trials`
if (exclude.length > 0 && numbers.length > 0) {
@@ -333,6 +335,8 @@ const getTrialListLink = (
export const TrialList: FC<{ studyDetail: StudyDetail | null }> = ({
studyDetail,
}) => {
const { url_prefix } = useConstants()
const theme = useTheme()
const query = useQuery()
const navigate = useNavigate()
@@ -417,7 +421,12 @@ export const TrialList: FC<{ studyDetail: StudyDetail | null }> = ({
}
const numbers = selected.map((t) => t.number)
navigate(
getTrialListLink(studyDetail.id, excludedStates, numbers)
getTrialListLink(
studyDetail.id,
excludedStates,
numbers,
url_prefix
)
)
}}
disabled={trialCounts[i] === 0}
@@ -476,13 +485,21 @@ export const TrialList: FC<{ studyDetail: StudyDetail | null }> = ({
next = [...selectedNumbers, trial.number]
}
navigate(
getTrialListLink(trial.study_id, excludedStates, next)
getTrialListLink(
trial.study_id,
excludedStates,
next,
url_prefix
)
)
} else {
navigate(
getTrialListLink(trial.study_id, excludedStates, [
trial.number,
])
getTrialListLink(
trial.study_id,
excludedStates,
[trial.number],
url_prefix
)
)
}
}}
@@ -14,6 +14,7 @@ import {
Row,
createColumnHelper,
} from "@tanstack/react-table"
import { useConstants } from "../constantsProvider"
const multiValueFilter: FilterFn<Trial> = <D extends object>(
row: Row<D>,
@@ -27,6 +28,8 @@ const multiValueFilter: FilterFn<Trial> = <D extends object>(
export const TrialTable: FC<{
studyDetail: StudyDetail | null
}> = ({ studyDetail }) => {
const { url_prefix } = useConstants()
const theme = useTheme()
const trials: Trial[] = studyDetail !== null ? studyDetail.trials : []
const objectiveNames: string[] = studyDetail?.objective_names || []
@@ -124,7 +127,7 @@ export const TrialTable: FC<{
<IconButton
component={Link}
to={
URL_PREFIX +
url_prefix +
`/studies/${info.getValue().study_id}/trials?numbers=${
info.getValue().number
}`
+15
View File
@@ -0,0 +1,15 @@
import React from "react"
type ConstantsContextType = {
environment: "jupyterlab" | "optuna-dashboard"
url_prefix: string
}
export const ConstantsContext = React.createContext<ConstantsContextType>({
environment: "optuna-dashboard",
url_prefix: "",
})
export const useConstants = (): ConstantsContextType => {
return React.useContext(ConstantsContext)
}
+20 -3
View File
@@ -1,15 +1,32 @@
import React from "react"
import React, { FC, ReactNode } from "react"
import ReactDOM from "react-dom/client"
import { APIClientProvider } from "./apiClientProvider"
import { AxiosClient } from "./axiosClient"
import { App } from "./components/App"
import { ConstantsContext } from "./constantsProvider"
const axiosAPIClient = new AxiosClient()
declare const API_ENDPOINT: string
declare const URL_PREFIX: string
const axiosAPIClient = new AxiosClient(API_ENDPOINT)
const ConstantsProvider: FC<{ children: ReactNode }> = ({ children }) => (
<ConstantsContext.Provider
value={{
environment: "optuna-dashboard",
url_prefix: URL_PREFIX,
}}
>
{children}
</ConstantsContext.Provider>
)
ReactDOM.createRoot(document.getElementById("dashboard") as HTMLElement).render(
<React.StrictMode>
<APIClientProvider apiClient={axiosAPIClient}>
<App />
<ConstantsProvider>
<App />
</ConstantsProvider>
</APIClientProvider>
</React.StrictMode>
)
+61 -1
View File
@@ -1,5 +1,65 @@
import {
APIClient,
APIMeta,
CompareStudiesPlotType,
CreateNewStudyResponse,
ParamImportancesResponse,
PlotResponse,
PlotType,
PreferenceHistoryResponse,
RenameStudyResponse,
StudyDetailResponse,
StudySummariesResponse,
TrialResponse,
UploadArtifactAPIResponse,
} from "./apiClient"
import { APIClientProvider } from "./apiClientProvider"
import { AxiosClient } from "./axiosClient"
import { App } from "./components/App"
import { ConstantsContext } from "./constantsProvider"
import {
Artifact,
FeedbackComponentType,
FormWidgets,
Note,
PlotlyGraphObject,
PreferenceFeedbackMode,
PreferenceHistory,
SearchSpaceItem,
StudyDetail,
StudySummary,
Trial,
TrialParam,
} from "./types/optuna"
export { AxiosClient, APIClientProvider, App }
export {
AxiosClient,
APIClientProvider,
App,
APIClient,
ConstantsContext,
Artifact,
FeedbackComponentType,
FormWidgets,
Note,
PlotlyGraphObject,
PreferenceFeedbackMode,
PreferenceHistory,
SearchSpaceItem,
TrialResponse,
PreferenceHistoryResponse,
StudyDetailResponse,
StudySummariesResponse,
CreateNewStudyResponse,
RenameStudyResponse,
UploadArtifactAPIResponse,
ParamImportancesResponse,
APIMeta,
StudyDetail,
StudySummary,
Trial,
TrialParam,
CompareStudiesPlotType,
PlotType,
PlotResponse,
}
-4
View File
@@ -2,7 +2,3 @@ declare module "*.css"
declare module "*.png"
declare module "*.jpg"
declare module "*.svg"
declare const APP_BAR_TITLE: string
declare const API_ENDPOINT: string
declare const URL_PREFIX: string
+1 -1
View File
@@ -4,7 +4,7 @@
"rootDir": "./ts",
"outDir": "./pkg",
"declaration": true,
"declarationDir": "./types",
"declarationDir": "./pkg",
},
"files": [
"./ts/pkg_index.tsx",
-3
View File
@@ -54,9 +54,6 @@ var config = {
},
plugins: [
new webpack.DefinePlugin({
APP_BAR_TITLE: JSON.stringify(
process.env.APP_BAR_TITLE || "Optuna Dashboard"
),
API_ENDPOINT: JSON.stringify(process.env.API_ENDPOINT),
URL_PREFIX: JSON.stringify(process.env.URL_PREFIX || "/dashboard"),
}),