-
Notifications
You must be signed in to change notification settings - Fork 56
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #216 from alyst/optional_http
Refactor real-time plots, make HTTP.jl optional
- Loading branch information
Showing
7 changed files
with
226 additions
and
173 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
using BlackBoxOptim, HTTP, Sockets | ||
|
||
# Create the fitness plot object and serve it | ||
const vlplot = BlackBoxOptim.VegaLiteMetricOverTimePlot(verbose=false) | ||
HTTP.serve!(vlplot) | ||
|
||
# Func to optimize. | ||
function rosenbrock(x) | ||
sum(i -> 100*abs2(x[i+1] - x[i]^2) + abs2(x[i] - 1), Base.OneTo(length(x)-1)) | ||
end | ||
|
||
# Now optimize for 2 minutes. | ||
# Go to http://127.0.0.1:8081 to view fitness progress! | ||
res = bboptimize(rosenbrock; | ||
SearchRange=(-10.0,10.0), NumDimensions = 500, | ||
PopulationSize=100, MaxTime=2*60.0, | ||
CallbackFunction = Base.Fix1(BlackBoxOptim.fitness_plot_callback, vlplot), | ||
CallbackInterval = 2.0); | ||
println("Best fitness = ", best_fitness(res)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,90 @@ | ||
module BlackBoxOptimRealtimePlotServerExt | ||
|
||
using HTTP, Sockets, JSON | ||
using BlackBoxOptim: RealtimePlot, replace_template_param, hasnewdata, printmsg | ||
|
||
const VegaLiteWebsocketFrontEndTemplate = """ | ||
<!DOCTYPE html> | ||
<head> | ||
<meta charset="utf-8"> | ||
<script src="https://cdn.jsdelivr.net/npm/vega@3"></script> | ||
<script src="https://cdn.jsdelivr.net/npm/vega-lite@2"></script> | ||
<script src="https://cdn.jsdelivr.net/npm/vega-embed@3"></script> | ||
</head> | ||
<body> | ||
<div id="vis"></div> | ||
<script> | ||
const vegalitespec = %%VEGALITESPEC%%; | ||
vegaEmbed('#vis', vegalitespec, {defaultStyle: true}) | ||
.then(function(result) { | ||
const view = result.view; | ||
const port = %%SOCKETPORT%%; | ||
const conn = new WebSocket("ws://127.0.0.1:" + port); | ||
conn.onopen = function(event) { | ||
// insert data as it arrives from the socket | ||
conn.onmessage = function(event) { | ||
console.log(event.data); | ||
// Use the Vega view api to insert data | ||
var newentries = JSON.parse(event.data); | ||
view.insert("table", newentries).run(); | ||
} | ||
} | ||
}) | ||
.catch(console.warn); | ||
</script> | ||
</body> | ||
""" | ||
|
||
rand_websocket_port() = 9000 + rand(0:42) | ||
|
||
frontend_html(vegalitespec::String, socketport::Integer) = | ||
reduce(replace_template_param, [ | ||
:SOCKETPORT => string(socketport), | ||
:VEGALITESPEC => vegalitespec, | ||
], init = VegaLiteWebsocketFrontEndTemplate) | ||
|
||
function static_content_handler(content::AbstractString, request::HTTP.Request) | ||
try | ||
return HTTP.Response(content) | ||
catch e | ||
return HTTP.Response(404, "Error: $e") | ||
end | ||
end | ||
|
||
function HTTP.serve(plot::RealtimePlot{:VegaLite}, | ||
host=Sockets.localhost, port::Integer = 8081; | ||
websocketport::Integer = rand_websocket_port(), | ||
mindelay::Number = 1.0, | ||
kwargs... | ||
) | ||
@assert mindelay > 0.0 | ||
@async websocket_serve(plot, websocketport, mindelay) | ||
printmsg(plot, "Serving VegaLite frontend on http://$(host):$(port)") | ||
return HTTP.serve(Base.Fix1(static_content_handler, frontend_html(plot.spec, websocketport)), | ||
host, port; kwargs...) | ||
end | ||
|
||
HTTP.serve!(plot::RealtimePlot, args...; kwargs...) = | ||
@async(HTTP.serve(plot, args...; kwargs...)) | ||
|
||
function websocket_serve(plot::RealtimePlot, port::Integer, mindelay::Number) | ||
HTTP.WebSockets.listen(Sockets.localhost, UInt16(port)) do ws | ||
while true | ||
if hasnewdata(plot) | ||
len = length(plot.data) | ||
newdata = plot.data[(plot.last_sent_index+1):len] | ||
printmsg(plot, "Sending data $newdata") | ||
HTTP.WebSockets.send(ws, JSON.json(newdata)) | ||
plot.last_sent_index = len | ||
end | ||
isnothing(plot.stoptime) || break | ||
sleep(mindelay + rand()) | ||
end | ||
end | ||
printmsg(plot, "RealtimePlot websocket stopped") | ||
end | ||
|
||
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,91 @@ | ||
replace_template_param(template::AbstractString, param_to_value::Pair{Symbol, <:Any}) = | ||
replace(template, string("%%", first(param_to_value), "%%") => string(last(param_to_value))) | ||
|
||
""" | ||
Specification of a plot for the real-time tracking of the fitness progress. | ||
To use the [*VegaLite*](https://vega.github.io/vega-lite/) front-end via | ||
*BlackBoxOptimRealtimePlotServerExt* extension, *HTTP.jl* and *Sockets.jl* are required. | ||
""" | ||
mutable struct RealtimePlot{E} | ||
spec::String | ||
verbose::Bool | ||
data::Vector{Any} | ||
last_sent_index::Int | ||
starttime::Float64 | ||
stoptime::Union{Float64, Nothing} | ||
|
||
function RealtimePlot{E}(template::AbstractString; | ||
verbose::Bool = false, | ||
spec_kwargs... | ||
) where E | ||
@assert E isa Symbol | ||
spec = reduce(replace_template_param, spec_kwargs, | ||
init = template) | ||
new{E}(spec, verbose, Any[], 0, 0.0, nothing) | ||
end | ||
end | ||
|
||
timestamp(t = time()) = Libc.strftime("%Y-%m-%d %H:%M.%S", t) | ||
printmsg(plot::RealtimePlot, msg) = plot.verbose ? println(timestamp(), ": ", msg) : nothing | ||
|
||
function shutdown!(plot::RealtimePlot) | ||
plot.stoptime = time() | ||
end | ||
|
||
function Base.push!(plot::RealtimePlot, newentry::AbstractDict) | ||
if length(plot.data) < 1 | ||
plot.starttime = time() | ||
end | ||
if !haskey(newentry, "Time") | ||
newentry["Time"] = time() - plot.starttime | ||
end | ||
printmsg(plot, "Adding data $newentry") | ||
push!(plot.data, newentry) | ||
end | ||
|
||
hasnewdata(plot::RealtimePlot) = length(plot.data) > plot.last_sent_index | ||
|
||
const VegaLiteMetricOverTimePlotTemplate = """ | ||
{ | ||
"\$schema": "https://vega.github.io/schema/vega-lite/v4.json", | ||
"description": "%%metric%% value over time", | ||
"width": %%width%%, | ||
"height": %%height%%, | ||
"padding": {"left": 20, "top": 10, "right": 10, "bottom": 20}, | ||
"data": { | ||
"name": "table" | ||
}, | ||
"mark": "line", | ||
"encoding": { | ||
"x": { | ||
"field": "Time", | ||
"type": "quantitative" | ||
}, | ||
"y": { | ||
"field": "%%metric%%", | ||
"type": "quantitative", | ||
"scale": {"type": "log"} | ||
} | ||
} | ||
} | ||
""" | ||
|
||
VegaLiteMetricOverTimePlot(; metric::String = "Fitness", | ||
width::Integer = 800, height::Integer = 600, | ||
kwargs...) = | ||
RealtimePlot{:VegaLite}(VegaLiteMetricOverTimePlotTemplate; metric, width, height, kwargs...) | ||
|
||
""" | ||
fitness_plot_callback(plot::RealtimePlot, oc::OptRunController) | ||
[OptController](@ref) callback function that updates the real-time fitness plot. | ||
""" | ||
function fitness_plot_callback(plot::RealtimePlot, oc::OptRunController) | ||
push!(plot, Dict("num_steps" => num_steps(oc), | ||
"Fitness" => best_fitness(oc))) | ||
if oc.stop_reason != "" | ||
@info "Shutting down realtime plot" | ||
shutdown!(plot) | ||
end | ||
end |
Oops, something went wrong.