API Reference
GlobtimPlots is organized by what you want to draw:
Backends
GlobtimPlots draws through the abstract Makie API and depends on no backend: functions return a Figure, and displaying or saving it needs a backend loaded in the session (without one, save stops with Makie's "No backend available!" error). GLMakie and WGLMakie also enable package extensions:
| Backend | Use for | Extension |
|---|---|---|
CairoMakie | Static, publication-quality PNG / PDF / SVG (save_plot's :pdf / :svg) | — |
GLMakie | Interactive windows, plot_polyapprox_3d with a recorded rotation, the explorers | GlobtimPlotsGLMakieExt |
WGLMakie | Browser-embedded / Documenter-rendered interactive figures | GlobtimPlotsWGLMakieExt |
using GlobtimPlots, CairoMakie # CairoMakie active
fig = cairo_plot_polyapprox_levelset(apol, ainp, df_cp, df_min)
save("levelset.png", fig)
using GLMakie # switches to GLMakie and loads the extension
plot_polyapprox_3d(apol, ainp, df_cp, df_min)Two more extensions enable functions that need a further package:
| Load | Extension | Adds |
|---|---|---|
using GraphMakie | GlobtimPlotsGraphMakieExt (triggers GraphMakie, Graphs, NetworkLayout; the last two load with GraphMakie) | plot_subdivision_tree |
using GlobtimPostProcessing | GlobtimPlotsPostProcessingExt | plot_capture_convergence, plot_capture_sparsification_combined, plot_refinement_trajectories! |
Without the package these functions raise an error naming it.
Data interface
The level-set functions take the approximant and problem description through two small abstract interfaces, AbstractPolynomialData and AbstractProblemInput. adapt_polynomial_data and adapt_problem_input wrap Globtim's ApproxPoly and TestInput; GenericPolynomialData and GenericProblemInput let you plot an approximation produced elsewhere. All other functions are duck-typed over DataFrames and the result types of GlobtimPostProcessing (the capture-analysis plots, which take its types in their signatures, are in the GlobtimPostProcessing extension).
Docstrings
GlobtimPlots.CP_TYPE_TABLE — Constant
CP_TYPE_TABLECanonical named tuple mapping CP type keys (:min, :saddle, :max) to their visual appearance (color, marker, label). All visualization code should use this table (or the cp_type_appearance helper) instead of defining local color/marker constants.
GlobtimPlots.AbstractCriticalPointData — Type
AbstractCriticalPointDataAbstract type for critical point data used in visualization.
Subtypes should provide critical point locations and classifications for scatter plots and overlays.
GlobtimPlots.AbstractPolynomialData — Type
AbstractPolynomialDataAbstract type for polynomial approximation data used in visualization.
Subtypes should provide access to polynomial coefficients, basis information, and grid data needed for plotting level sets and surfaces.
See also: GenericPolynomialData, adapt_polynomial_data
GlobtimPlots.AbstractProblemInput — Type
AbstractProblemInputAbstract type for problem input data used in visualization.
Subtypes should provide dimension, center, and domain range information needed for coordinate transformations in plots.
See also: GenericProblemInput, adapt_problem_input
GlobtimPlots.BalancedTreeLayout — Type
BalancedTreeLayoutCustom layout type for GraphMakie that uses split positions to determine child placement. Supports configurable horizontal scaling and vertical spacing.
GlobtimPlots.GenericPolynomialData — Type
GenericPolynomialData <: AbstractPolynomialDataConcrete implementation of polynomial data for plotting.
Fields
coeffs::Any: Polynomial coefficientsbasis::Symbol: Basis type (:chebyshev,:monomial, etc.), default:chebyshevscale_factor::Union{Float64, Vector{Float64}}: Domain scaling factor(s), default1.0grid::Matrix{Float64}: Evaluation grid pointsz::Vector{Float64}: Function values at grid pointsprecision::Any: Numerical precision informationnormalized::Bool: Whether the approximation is normalized, defaultfalse
See also: AbstractPolynomialData, adapt_polynomial_data
GlobtimPlots.GenericProblemInput — Type
GenericProblemInput <: AbstractProblemInputConcrete implementation of problem input data for plotting.
Fields
dim::Int: Problem dimension (number of variables), default2center::Vector{Float64}: Domain center point, default[0.0, 0.0]sample_range::Union{Float64, Vector{Float64}}: Domain sampling range(s), default1.0
See also: AbstractProblemInput, adapt_problem_input
GlobtimPlots.PartitionStyle — Type
PartitionStyleStyling configuration for 2D partition visualization.
GlobtimPlots.PlotBackend — Type
PlotBackendEnum for plot backend selection.
GlobtimPlots.RefinementTrajectoryStyle — Type
RefinementTrajectoryStyleVisual style for refinement trajectory overlays.
Fields
linewidth::Float64: Path line width (default 1.5)markersize_start::Float64: Start marker (circle) size (default 6.0)markersize_end::Float64: End marker (triangle) size (default 8.0)marker_start::Symbol: Marker for raw CP (default:circle)marker_end::Symbol: Marker for refined CP (default:dtriangle)stroke_color: Marker stroke color (default:black)stroke_width::Float64: Marker stroke width (default 0.5)line_alpha::Float64: Line opacity (default 0.8)colors::Vector{Symbol}: Palette for trajectory coloring (cycled)
GlobtimPlots.SubdivisionPartitionStyle — Type
SubdivisionPartitionStyleStyling configuration for subdivision domain partition visualization. Controls colormap, degree labels, CP markers, convergence borders, colorbar, and legend.
GlobtimPlots.SubdomainNodeInfo — Type
SubdomainNodeInfoExtracted information about a single subdomain node for visualization. Uses duck typing to work with Globtim's SubdivisionTree without hard dependency.
GlobtimPlots.TreeVizStyle — Type
TreeVizStyleStyling configuration for subdivision tree visualization.
GlobtimPlots._apply_levelset_display_transform! — Method
_apply_levelset_display_transform!(raw_Z_ref, Z_display_obs, log_scale_obs, n_levels)Apply log₁₀ transform (if enabled) to the raw Z grid and push result to the display observable.
GlobtimPlots._build_experiment_results_figure — Method
_build_experiment_results_figure(experiment_name, metrics; fig_size) → FigureInternal: build the 4-panel experiment results figure using backend-agnostic Makie calls. Both the interactive and static entry points delegate here.
GlobtimPlots._build_legend_entries — Method
_build_legend_entries(style) → (entries, labels)Build standard legend entries for CP types, convergence borders, and p*.
GlobtimPlots._build_levelset_base! — Method
_build_levelset_base!(ax, tree, f; resolution, n_levels, colormap,
l2_tolerance, cp_points, cp_types, p_true, style) → contourf_plotDraw the shared levelset base onto ax: filled contour of f, subdivision convergence boundaries, refined CPs, and p*. Returns the contourf! plot object for colorbar binding.
Does NOT draw raw CPs — callers handle raw CPs differently (static: _scatter_raw_cps!; interactive: named scatter for pick()).
GlobtimPlots._compute_error_grid_in_window — Method
_compute_error_grid_in_window(tree, f, xs, ys) → Matrix{Float64}Evaluate |f(p) - poly(p)| on the grid defined by xs × ys. Returns raw (unscaled) error values; NaN for points outside any leaf or leaves without a polynomial.
GlobtimPlots._create_tree_legend! — Method
_create_tree_legend!(fig, nodes, style, error_range)Add legend to the figure showing dimension colors, leaf status, and error colorbar.
GlobtimPlots._domain_bbox — Method
_domain_bbox(leaf_bounds) → (lo::Vector{Float64}, hi::Vector{Float64})Compute the axis-aligned bounding box of the domain from leaf bounds. leaf_bounds is Vector{Vector{Vector{Float64}}} — [leaf][dim] → [lo, hi].
GlobtimPlots._draw_boundary_segments! — Method
_draw_boundary_segments!(ax, tree; color, linewidth)Draw subdomain boundary line segments for all leaves in the tree.
GlobtimPlots._draw_convergence_boundaries! — Method
_draw_convergence_boundaries!(ax, leaf_bounds, leaf_l2_errors; l2_tolerance, style)Draw per-leaf boundary line segments colored by convergence status. Green for converged leaves (l2_error ≤ l2_tolerance), gray for unconverged.
Uses two batched linesegments! calls (one per status) for efficiency.
GlobtimPlots._draw_convergence_boundaries! — Method
_draw_convergence_boundaries!(ax, tree::SubdivisionTree; l2_tolerance, style)Tree-based dispatch: extracts leaf bounds and L2 errors from the tree, then delegates to the data-based method.
GlobtimPlots._draw_degree_labels! — Method
_draw_degree_labels!(ax, leaf_bounds, leaf_degrees, l2_errors, cmin, cmax; style)Annotate degree inside each box with luminance-aware text color.
GlobtimPlots._draw_partition_rects! — Method
_draw_partition_rects!(ax, leaf_bounds, l2_errors, cmin, cmax; style, l2_tolerance)Draw colored rectangles for leaf subdomains, colored by log₁₀(L2 error).
GlobtimPlots._gradient_method_label — Method
_gradient_method_label(method::Symbol) -> StringHuman-readable label for the differentiation backend.
GlobtimPlots._gradient_method_short — Method
_gradient_method_short(method::Symbol) -> StringShort tag for log lines, e.g. "[FD] " or "[AD] ". Includes trailing space so it concatenates cleanly with -> cp_type in log output.
GlobtimPlots._in_domain — Method
_in_domain(p, lo, hi) → BoolCheck whether point p lies within the axis-aligned box [lo, hi].
GlobtimPlots._log_l2_colorrange — Method
_log_l2_colorrange(error_vecs...) → (cmin, cmax)Compute a shared (cmin, cmax) color range from one or more vectors of L2 errors. Applies log10 and filters Inf/NaN.
GlobtimPlots._make_float_slider! — Method
_make_float_slider!(layout, row, label_text, range, default_val, fmt)Create a labeled slider with floating-point display format in layout[row, :]. Returns the Observable holding the slider value.
GlobtimPlots._make_info_button! — Method
_make_info_button!(layout, row, col, tooltip, log_lines)Create a small "?" button that logs tooltip to the log panel when clicked.
GlobtimPlots._make_linear_slider! — Method
_make_linear_slider!(layout, row, label_text, range, default_val)Create a labeled linear slider in layout[row, :]. Returns the Observable holding the slider value.
GlobtimPlots._make_log_slider! — Method
_make_log_slider!(layout, row, label_text, exponent_range, default_exp)Create a labeled log₁₀-scale slider in layout[row, :]. Returns the Observable holding the actual value (10^exponent).
GlobtimPlots._plot_polyapprox_3d_impl — Method
_plot_polyapprox_3d_impl(pol, TR, df, df_min; kwargs...) -> FigureCore implementation of 3D polynomial approximation visualization. Returns a Figure with a 3D surface plot + critical point markers.
Backend-agnostic: uses abstract Makie API (Figure, Axis3, surface!, scatter!). The GLMakie extension wraps this to add rotate animation support.
Arguments
pol::AbstractPolynomialData: Polynomial approximation dataTR::AbstractProblemInput: Problem domain specificationdf::DataFrame: All critical points (must have columnsx1,x2,z; optionalclosefor:proximitymode orcritical_point_typefor:hessian_typemode)df_min::DataFrame: Minima points (must have columnsx1,x2,value,captured)
Keyword Arguments
figure_size::Tuple{Int,Int}=(1000,800): Figure dimensionsz_limits::Union{Nothing,Tuple{Float64,Float64}}=nothing: Z-axis limits (auto-computed if nothing)show_captured::Bool=true: Whether to show captured minima markersalpha_surface::Float64=0.7: Surface transparencyfade::Bool=false: Enable fade effect for top portion of z-rangez_cut::Float64=0.25: Fraction of z-range to fade (whenfade=true)color_by::Symbol=:proximity: How to color/group CP markers.:proximity(default) splits ondf.close;:hessian_typegroups bydf.critical_point_typeusingCP_TYPE_TABLEpalette + markers (min/saddle/max/degenerate).
GlobtimPlots._prepare_contourf_args — Method
_prepare_contourf_args(Z::Matrix, n_levels::Int, style) → (Z_display, levels_kw)Apply optional log₁₀ transform and/or quantile-based level breaks to a raw objective grid Z. Returns (Z_display, levels_kw) where levels_kw is either n_levels (Int) or a Vector{Float64} of explicit breakpoints.
GlobtimPlots._refine_error! — Method
_refine_error!(obs_state, ax; resolution)Re-sample the error grid at full resolution within the current zoom window of ax.
GlobtimPlots._resolve_makie_backend — Method
Resolve the module whose API builds the figure: Makie for Static, GLMakie (loaded lazily) for Interactive.
GlobtimPlots._scatter_cps_by_type! — Method
_scatter_cps_by_type!(ax, cp_points, cp_types; domain_lo, domain_hi, style)Overlay verified critical points colored by type (min/saddle/max). Points outside the domain are excluded when domain_lo and domain_hi are provided.
GlobtimPlots._scatter_p_true! — Method
_scatter_p_true!(ax, p_true; style)Plot the true parameter as a gold star.
GlobtimPlots._scatter_raw_cps! — Method
_scatter_raw_cps!(ax, raw_cp_points; domain_lo, domain_hi, style)Overlay raw (pre-refinement) critical points as thin white crosses. Drawn before refined CPs so refined markers render on top.
GlobtimPlots.adapt_polynomial_data — Method
adapt_polynomial_data(globtim_poly) → GenericPolynomialDataAdapt a polynomial approximation object to the GlobtimPlots plotting interface.
This function extracts common fields from polynomial types (like ApproxPoly from globtim) and wraps them in GenericPolynomialData which implements the AbstractPolynomialData interface.
Why Use This?
This adapter maintains clean package separation:
globtimdefines concrete types (ApproxPoly) without depending on plotting packagesglobtimplotsdefines abstract interfaces (AbstractPolynomialData)- Users explicitly convert when crossing package boundaries
Arguments
globtim_poly: Any object with polynomial approximation data (typicallyApproxPoly)
Extracted Fields
coeffs: Polynomial coefficientsbasis: Basis type (:chebyshev,:monomial, etc.)scale_factor: Domain scaling factorgrid: Evaluation grid points (Matrix)z: Function values at grid pointsprecision: Numerical precision informationnormalized: Whether the approximation is normalized
Returns
GenericPolynomialData <: AbstractPolynomialData: Wrapped data for plotting
Example
using Globtim
using GlobtimPlots: adapt_polynomial_data
# Create polynomial approximation in globtim
pol = ApproxPoly(...)
# Adapt for plotting
pol_adapted = adapt_polynomial_data(pol)
# Now can use with plotting functions
fig = cairo_plot_polyapprox_levelset(pol_adapted, ...)See also: adapt_problem_input, GenericPolynomialData, AbstractPolynomialData
GlobtimPlots.adapt_problem_input — Method
adapt_problem_input(globtim_input) → GenericProblemInputAdapt a problem input object to the GlobtimPlots plotting interface.
This function extracts common fields from problem input types (like TestInput from globtim) and wraps them in GenericProblemInput which implements the AbstractProblemInput interface.
Why Use This?
This adapter maintains clean package separation:
globtimdefines concrete types (TestInput) without depending on plotting packagesglobtimplotsdefines abstract interfaces (AbstractProblemInput)- Users explicitly convert when crossing package boundaries
Arguments
globtim_input: Any object with problem input data (typicallyTestInput)
Extracted Fields
dim: Problem dimension (number of variables)center: Domain center point (Vector)sample_range: Domain sampling range
Returns
GenericProblemInput <: AbstractProblemInput: Wrapped data for plotting
Example
using Globtim
using GlobtimPlots: adapt_problem_input
# Create problem input in globtim
TR = TestInput(
f = x -> sum(x.^2),
dim = 2,
center = [0.0, 0.0],
sample_range = 2.0,
degree = 6
)
# Adapt for plotting
tr_adapted = adapt_problem_input(TR)
# Now can use with plotting functions
fig = cairo_plot_polyapprox_levelset(..., tr_adapted, ...)See also: adapt_polynomial_data, GenericProblemInput, AbstractProblemInput
GlobtimPlots.analyze_captured_distances — Method
Analyze distances between captured points and reference points. Returns statistics about minimum distances from each point in df to closest point in df_check.
GlobtimPlots.analyze_convergence_distances — Method
Analyze convergence distances for a DataFrame of critical points. Returns statistics about the distances between points.
GlobtimPlots.balanced_tree_layout — Method
balanced_tree_layout(nodes::Vector{SubdomainNodeInfo}, root_id::Int; h_scale=10.0, v_spacing=1.5)Custom tree layout where horizontal child positions reflect split positions.
Split position p ∈ [-1,1] maps to:
- Left child: positioned at relative offset -(1-p)/2 (closer to parent if split right)
- Right child: positioned at relative offset +(1+p)/2 (closer to parent if split left)
This visually shows WHERE in the domain each split occurred.
Arguments
h_scale: Horizontal scaling factor (default 10.0) - spreads tree horizontallyv_spacing: Vertical spacing between levels (default 1.5)
GlobtimPlots.cairo_plot_polyapprox_levelset — Method
cairo_plot_polyapprox_levelset(pol, TR, df, df_min; kwargs...)Plot polynomial approximation level sets with critical points overlaid.
Handles per-coordinate scaling factors. Creates a Makie contour plot with scattered critical points (near/far, captured/uncaptured).
Keyword arguments
figure_size::Tuple{Int,Int} = (1000, 600): figure dimensionsz_limits::Union{Nothing, Tuple{Float64,Float64}} = nothing: contour z range (auto if nothing)chebyshev_levels::Bool = false: use Chebyshev-spaced contour levelsnum_levels::Int = 30: number of contour levelsshow_captured::Bool = true: whether to show captured minima
GlobtimPlots.compute_auto_scale — Method
compute_auto_scale(nodes::Vector{SubdomainNodeInfo}, style::TreeVizStyle) -> NamedTupleCompute scaling factors for nodes, fonts, and layout based on tree size. Returns named tuple with scaled values ready to use.
GlobtimPlots.compute_error_grid — Method
compute_error_grid(tree::SubdivisionTree, f;
resolution::Int = 200, log_scale::Bool = true)
→ (xs, ys, error_matrix)Evaluate |f(p) - poly(p)| on a uniform grid over the tree's domain. Returns x-coordinates, y-coordinates, and the error matrix.
If log_scale, applies log10 to the error values (clamped to a minimum of 1e-20).
GlobtimPlots.compute_error_range — Method
compute_error_range(nodes::Vector{SubdomainNodeInfo}) -> Tuple{Float64,Float64}Compute min/max error range for active leaves (used for error gradient coloring).
GlobtimPlots.compute_error_reduction — Method
compute_error_reduction(nodes, node::SubdomainNodeInfo) -> Union{Float64,Nothing}Compute percentage error reduction from this node to its children. Returns Nothing for leaf nodes or if children have Inf error.
GlobtimPlots.compute_figure_size — Method
compute_figure_size(nodes::Vector{SubdomainNodeInfo}, style::TreeVizStyle) -> Tuple{Int,Int}Calculate optimal figure size based on tree structure.
GlobtimPlots.cp_type_appearance — Method
cp_type_appearance(cp_type) → (color::Symbol, marker::Symbol)Look up color and marker for a CP type (Symbol or String). Accepts both short (:min) and long (:minimum) key forms. Returns (:magenta, :diamond) for unknown types.
GlobtimPlots.create_approximation_plot! — Method
create_approximation_plot!(gridpos, Makie, stats::Dict, title::String)Plot L2 approximation error vs degree.
GlobtimPlots.create_campaign_comparison_plot — Method
create_campaign_comparison_plot(campaign, stats::Vector; backend::PlotBackend=Static) -> Figure or Vector{Figure}Create comparison plots across multiple experiments in a campaign. For Interactive backend, returns a vector of separate figures (one per window). For Static backend, returns a single combined figure.
Works with any campaign object that has the field: experiments. Typically used with CampaignResults from GlobtimPostProcessing.
GlobtimPlots.create_convergence_trajectory_plot! — Method
create_convergence_trajectory_plot!(gridpos, Makie, stats::Dict, title::String)Plot convergence trajectories showing improvement rates across degrees.
GlobtimPlots.create_critical_points_plot! — Method
create_critical_points_plot!(gridpos, Makie, stats::Dict, title::String)Plot critical point counts vs degree.
GlobtimPlots.create_experiment_plots — Method
create_experiment_plots(result, stats::Dict; backend::PlotBackend=Static) -> FigureCreate adaptive plots based on available tracking labels.
Works with any result object that has the fields: enabledtracking, experimentid, metadata. Typically used with ExperimentResult from GlobtimPostProcessing.
GlobtimPlots.create_level_set_animation — Method
create_level_set_animation(
f,
grid::Array{SVector{3,T},3},
df::Union{DataFrame,Nothing},
z_range::Tuple{T,T},
params::VisualizationParameters{T} = VisualizationParameters{T}();
fps::Int = 30,
duration::Int = 20,
output_file::String = "level_set_animation.mp4"
) where {T<:AbstractFloat}Create an animated level set visualization that sweeps through levels while rotating the camera.
Arguments
f: Objective functiongrid: 3D array of sample pointsdf: Optional DataFrame with critical pointsz_range: Range of level values to animateparams: Visualization parametersfps: Frames per second for animationduration: Animation duration in secondsoutput_file: Path to save the animation
Returns
- GLMakie Figure object
Example
fig = create_level_set_animation(
f, grid, df, (-3.0, 6.0);
fps = 30,
duration = 10,
output_file = "my_animation.mp4"
)GlobtimPlots.create_level_set_animation — Method
create_level_set_animation(
values::Array{T},
grid::Array{SVector{3,T},3},
df::Union{DataFrame,Nothing},
z_range::Tuple{T,T},
params::VisualizationParameters{T} = VisualizationParameters{T}();
fps::Int = 30,
duration::Int = 20,
output_file::String = "level_set_animation.mp4"
) where {T<:AbstractFloat}Create an animated level set visualization from pre-computed grid values.
Same as the f-based overload, but skips function evaluation — uses the provided values array directly. The values array must have the same shape as grid.
overlays (keyword): point sets drawn while their value is within params.point_window of the level, e.g. the critical points of several surrogates. A vector of (; df, label, marker = :circle, markersize = 16, color), where df has columns x1, x2, x3, z on the scale of values, and optionally index, in which case the points are coloured by Morse index. Sources and indices get a legend at fig[1, 2]. title and axis_labels label the Axis3; level_markersize sets the size of the level-set points (default 6 here, 2 in the animation).
level_style picks the level-set points: :shell (default), the grid points within params.point_tolerance of the level, or :crossings, the interpolated crossings of the grid's edges (level_set_crossings): uniform density on the level set, no tolerance, about three points per cell the surface passes through.
levels: an explicit level per frame (e.g. from level_schedule, to dwell on the critical values); then the film has length(levels) frames and duration is ignored. patches (:crossings only): finer grids (; grid, values) on the same value scale, drawn in place of the coarse grid inside their bounding boxes (the coarse grid must be a tensor grid with increasing axes; where two patches overlap both are drawn). With patch_taper (default) a patch keeps every crossing in its inner 40 % and thins them towards its edge, down to the coarse grid's density, so the patch does not show as a denser rectangle. A patch may carry its own taper::Bool (overrides patch_taper) and skip mask (its shape; an edge between two skipped nodes is not drawn), so tiles that share a face, each skipping its upper faces, draw that face once. shading (:crossings only) colours each point by 0.2 + 0.8 |n · l|, n the unit gradient at the point and l a light beside the camera (the eye direction tilted up), through level_colormap; both sides of a sheet shade alike.
GlobtimPlots.create_level_set_sweep_animation — Method
create_level_set_sweep_animation(frames, grid, level, params = VisualizationParameters();
frame_overlays = nothing, frame_labels = nothing, substeps = 8, fps = 30,
output_file = "level_set_sweep.mp4", title = "", axis_labels = ("x₁", "x₂", "x₃"),
level_markersize = 2, rotate = true) -> FigureAnimate a family of functions on one grid, e.g. slices f(·; t) of a higher-dimensional objective at parameter values t₁ < … < tK, at the fixed level. frames[j] holds the values of the j-th member on grid. Between consecutive members the values are interpolated linearly in substeps steps, so the level shell moves continuously. `frameoverlays[j](overlay vectors as increatelevelsetvisualization, the same sources in the same order in every frame) is drawn while frame j is the nearest member, so critical points appear and vanish where the family has a fold.params.pointwindowdecides which overlay points are shown (use a large window to show them all).frame_labels[j]` is shown under the axis.
GlobtimPlots.create_level_set_visualization — Method
create_level_set_visualization(
f,
grid::Array{SVector{3,T},3},
df::Union{DataFrame,Nothing},
z_range::Tuple{T,T},
params::VisualizationParameters{T} = VisualizationParameters{T}()
) where {T<:AbstractFloat}Create an interactive 3D level set visualization with a slider.
Arguments
f: Objective function to visualizegrid: 3D array of sample pointsdf: Optional DataFrame with critical points (columns: x1, x2, x3, z)z_range: Tuple (min, max) for level valuesparams: Visualization parameters
Returns
- GLMakie Figure with interactive slider
Example
using GLMakie, StaticArrays, GlobtimPlots
# Create a simple test function
f(x) = x[1]^2 + x[2]^2 + x[3]^2
# Create grid
grid = [SVector{3,Float64}(x, y, z)
for x in range(-1, 1, 50),
y in range(-1, 1, 50),
z in range(-1, 1, 50)]
# Visualize
fig = create_level_set_visualization(f, grid, nothing, (0.0, 3.0))GlobtimPlots.create_level_set_visualization — Method
create_level_set_visualization(
values::Array{T},
grid::Array{SVector{3,T},3},
df::Union{DataFrame,Nothing},
z_range::Tuple{T,T},
params::VisualizationParameters{T} = VisualizationParameters{T}()
) where {T<:AbstractFloat}Create an interactive 3D level set visualization from pre-computed grid values.
Same as the f-based overload, but skips function evaluation — uses the provided values array directly. The values array must have the same shape as grid.
overlays (keyword): point sets drawn while their value is within params.point_window of the level, e.g. the critical points of several surrogates. A vector of (; df, label, marker = :circle, markersize = 16, color), where df has columns x1, x2, x3, z on the scale of values, and optionally index, in which case the points are coloured by Morse index. Sources and indices get a legend at fig[1, 2]. title and axis_labels label the Axis3; level_markersize sets the size of the level-set points (default 6 here, 2 in the animation).
Inf and NaN entries in values are treated as missing (excluded from level sets).
GlobtimPlots.create_parameter_recovery_plot! — Method
create_parameter_recovery_plot!(gridpos, Makie, stats::Dict, title::String)Plot parameter recovery error vs degree.
GlobtimPlots.create_residual_distribution_plot! — Method
create_residual_distribution_plot!(gridpos, Makie, stats::Dict, title::String)Plot histogram of residuals/errors to show distribution quality.
GlobtimPlots.create_single_plot — Method
create_single_plot(result, stats::Dict, plot_type::Symbol, title::String; backend::PlotBackend=Interactive) -> FigureCreate a single plot window for a specific plot type.
Works with any result object that has the relevant fields for the specified plot_type. Typically used with ExperimentResult from GlobtimPostProcessing.
GlobtimPlots.create_stability_plot! — Method
create_stability_plot!(gridpos, Makie, stats::Dict, title::String)Plot condition numbers vs degree.
GlobtimPlots.create_sublevel_animation — Method
create_sublevel_animation(values, grid, z_range, params = VisualizationParameters();
overlays = nothing, fps = 30, duration = 20, output_file = "sublevel_animation.mp4",
title = "Sublevel sets", axis_labels = ("x₁", "x₂", "x₃"), level_markersize = 2,
rotate = true) -> FigureAnimate the sublevel sets {values ≤ c} as c sweeps z_range. The sets are grown by union–find over the grid's 6-neighbourhood (the H₀ merge tree), so each connected component is known at every level. The boundary shell (c − params.point_tolerance ≤ values ≤ c) is drawn in the colour of its component. A component's colour is fixed by the rank of its minimum, and when two components merge the one with the lower minimum keeps its colour (elder rule), so a merge shows as one colour swallowing another. The number of components is shown under the axis and, with barcode = true, the H₀ barcode (sublevel_barcode, bars shorter than min_persistence dropped) with a cursor at c. overlays are as in create_level_set_visualization (drawn within params.point_window of c): saddles of index 1 light up at the merge levels.
GlobtimPlots.create_timing_plot! — Method
create_timing_plot!(gridpos, Makie, stats::Dict, title::String)Plot timing breakdown by degree.
GlobtimPlots.draw_depth_bands! — Method
draw_depth_bands!(ax, nodes, positions, style)Draw alternating horizontal bands at each tree depth for visual hierarchy.
GlobtimPlots.effective_degree — Method
effective_degree(d) → IntEffective (maximum) degree: scalar as-is, vector → maximum(d).
GlobtimPlots.extract_tree_data — Method
extract_tree_data(tree) -> (Vector{SubdomainNodeInfo}, Set{Int}, Set{Int}, Int)Extract node information from a SubdivisionTree using duck typing. Returns node info vector, converged leaf IDs, active leaf IDs, and root_id.
GlobtimPlots.find_containing_leaf — Method
find_containing_leaf(tree::SubdivisionTree, point::AbstractVector{Float64}) → SubdomainFind the leaf subdomain containing point. Errors if no leaf contains the point.
GlobtimPlots.format_degree_label — Method
format_degree_label(d) → StringFormat a degree value for display: scalar 4 → "4", vector [4,8] → "(4,8)".
GlobtimPlots.format_node_label — Method
format_node_label(node::SubdomainNodeInfo, nodes::Vector{SubdomainNodeInfo}, style::TreeVizStyle; balanced_layout::Bool=true) -> StringFormat node label for display. When balancedlayout is true, split position is encoded in edge lengths so we skip the ASCII viz. Labels are truncated to style.labelmax_chars.
GlobtimPlots.format_param_value — Method
format_param_value(param_name::String, value::Any, prefix::String) -> StringFormat a parameter value for display in labels.
GlobtimPlots.generate_experiment_labels — Method
generate_experiment_labels(campaign) -> Vector{String}Generate concise, informative labels for experiments in a campaign. Automatically detects which parameter varies and creates labels accordingly.
Arguments
campaign: Campaign results object with.experimentsfield
Strategy
- Identify which parameters vary across experiments
- If only one parameter varies, label by that parameter value
- If multiple parameters vary, create compact multi-parameter labels
- Handle common parameter types (domainsizeparam, parameter_set, etc.)
GlobtimPlots.get_dim_color — Method
get_dim_color(dim::Int, style::TreeVizStyle)Get color for a dimension, cycling through available colors.
GlobtimPlots.get_node_color — Function
get_node_color(node::SubdomainNodeInfo, style::TreeVizStyle, error_range::Tuple{Float64,Float64})Determine node color based on node type, with error gradient for active leaves.
GlobtimPlots.get_node_marker — Method
get_node_marker(node::SubdomainNodeInfo) -> SymbolDetermine node marker shape based on node type.
GlobtimPlots.get_param_label_prefix — Method
get_param_label_prefix(param_name::String) -> StringGet a human-readable prefix for a parameter name.
GlobtimPlots.getfield_or_index — Method
Helper to get field from struct or NamedTuple by symbol. Works with both field access and getindex for Dict-like objects.
GlobtimPlots.interactive_error_explorer — Method
interactive_error_explorer(
tree::SubdivisionTree, f;
resolution::Int = 200,
log_scale::Bool = true,
colormap::Symbol = :viridis,
) → FigureLaunch an interactive GLMakie window showing |f(p) - poly(p)| across the subdivision domain. Requires GLMakie to be loaded and active.
Interaction
- Zoom into a region with the mouse scroll / drag
- "Refine View" re-renders at full
resolutionwithin the current zoom window - "Reset" restores the full domain view
- "Toggle log/linear" switches between log₁₀ and raw error display (instant, no recompute)
Arguments
tree: SubdivisionTree with populated polynomials (runtime only)f: Objective functionf(x::Vector{Float64}) → Float64
Keyword Arguments
resolution: Grid points per axis (default 200)log_scale: Start with log₁₀ scale (default true)colormap: Makie colormap (default:viridis)
GlobtimPlots.interactive_levelset_explorer — Method
interactive_levelset_explorer(
f, bounds::Vector;
refine_newton::Function,
refine_optim::Function,
leaf_bounds::Vector,
leaf_l2_errors::Vector{Float64},
raw_cp_points::Vector = Vector{Float64}[],
cp_points::Vector = Vector{Float64}[],
cp_types::Vector = String[],
p_true = nothing,
l2_tolerance::Union{Nothing, Float64} = nothing,
resolution::Int = 200,
n_levels::Int = 30,
colormap::Symbol = :viridis,
style::SubdivisionPartitionStyle = SubdivisionPartitionStyle(),
title::String = "Interactive Levelset Explorer",
) → Vector{Figure}Launch an interactive GLMakie explorer as two windows: a plot window (axis + colorbar) and a controls window (buttons + log panel). This avoids layout conflicts between DataAspect() and fixed-height controls that cause vertical size constraints on macOS.
Shows the objective function as a filled contour with subdivision boundaries overlaid. Right-click raw critical points (white crosses) to select/deselect them, then click "Refine Selected" to batch-refine all selected CPs.
Interaction
- Right-click a raw CP → toggle selection (highlighted in yellow)
- Refine Selected (N) batch-refines all selected CPs, draws trajectories + markers
- Refine: dropdown menu selects refinement mode (Newton ∇f=0 or Optim f-min)
- Log₁₀ toggle switch enables/disables log₁₀ scale on the contour
- Levels slider adjusts contour density (5–100 levels)
- Clear removes all refined markers, trajectories, and selection
- Refine View re-evaluates the contour at full resolution within the current zoom window
- Reset returns to the full domain view
Keyboard shortcuts (plot window)
| Key | Action |
|---|---|
r | Refine Selected |
c | Clear Refined |
v | Refine View |
z | Reset View |
l | Toggle Log₁₀ |
Callback contract
Both refine_newton and refine_optim must accept (point::Vector{Float64}; kwargs...) and return a NamedTuple with fields:
(; point::Vector{Float64}, objective_value::Float64, gradient_norm::Float64,
cp_type::Symbol, converged::Bool, iterations::Int, trace::Vector{Vector{Float64}})Keyword arguments forwarded from sliders:
- Newton:
tol,accept_tol,max_iterations,hessian_tol,trust_radius_fraction - Optim:
f_abstol,max_iterations,hessian_tol,method(:neldermeador:lbfgs),x_abstolandstep_size(LBFGS only; NelderMead's single stop is the simplex spread, set byf_abstol)
Arguments
f: Objective functionf(x::Vector{Float64}) → Float64bounds: Domain bounds as[collect(dim1_bounds), collect(dim2_bounds)]refine_newton: Callback for trust-region Newton on ∇f=0 (all CP types)refine_optim: Callback for NelderMead f-minimizationleaf_bounds: Per-leaf domain bounds from subdivisionleaf_l2_errors: Per-leaf L2 approximation errors
Keyword Arguments
raw_cp_points: Raw (pre-refinement) critical points — pickable targetscp_points, cp_types: Already-refined CPs and their typesp_true: True parameter vector (gold star)l2_tolerance: For convergence border coloringresolution: Grid points per axis for contour evaluationn_levels: Number of contour levelscolormap: Colormap for filled contourstyle:SubdivisionPartitionStylefor marker/border stylingtitle: Plot title
GlobtimPlots.interactive_levelset_explorer — Method
interactive_levelset_explorer(
tree::SubdivisionTree, f;
refine_newton::Function,
refine_optim::Function,
kwargs...
) → Vector{Figure}Tree-based overload — extracts bounds, leafbounds, and leafl2_errors from the tree, then delegates to the data-based method.
Returns [plot_fig, controls_fig] (two separate windows).
GlobtimPlots.level_schedule — Method
level_schedule(events, n, z_range; window, share = 0.6, cap = 3) -> Vector{T}n levels from z_range[1] to z_range[2], one per frame, that dwell on the events (e.g. the critical values, where the level set's topology changes) and sweep between them. The frame density is w(r) = 1 + A · min(Σ_k K((r − r_k) / window), cap) with a Gaussian K; A is set so the bumps carry the fraction share of the frames, and a cluster of events is capped at cap bumps so it cannot stall the film. Events outside the range are ignored; share = 0 or no event gives the uniform sweep. Pass the result as levels to create_level_set_animation.
GlobtimPlots.level_set_crossings — Method
level_set_crossings(grid, values, level; normals = false, skip = nothing)The points where the grid's edges cross the level: for every edge in the three axis directions whose endpoint values straddle level, the linearly interpolated crossing. These are the vertices of the piecewise-linear isosurface (marching cubes without the triangles), so every cell the level set passes through contributes about three points and the density on the surface is uniform. The shell of prepare_level_set_data has thickness tolerance / |∇f| instead, one grid point thick where f is steep. Non-finite values are skipped.
skip, a Bool array of the grid's shape, drops every edge whose two endpoints are both marked (used to cut the coarse grid out under finer patches). With normals = true the result is (points, normals): the unit gradient of values at each crossing, from the central-difference gradient at the two endpoint nodes (one-sided at the boundary) interpolated like the point; a vanishing gradient gives (0, 0, 1). The gradient of a monotone transform of f (ranks, logs) has the direction of ∇f, so transformed values shade the same.
GlobtimPlots.min_degree — Method
min_degree(d) → IntMinimum degree: scalar as-is, vector → minimum(d).
GlobtimPlots.normalize_cp_key — Method
normalize_cp_key(k::Symbol) → SymbolNormalize verbose CP type keys to the canonical short form used by CP_TYPE_TABLE: :minimum → :min, :maximum → :max. All other keys pass through unchanged.
GlobtimPlots.plot_1d_comparison — Method
plot_1d_comparison(
f::Function,
results::Dict{Int, NamedTuple};
poly_eval_factory::Function,
n_plot_points::Int = 500,
figsize::Tuple{Int, Int} = (1200, 400),
save_path::Union{String, Nothing} = nothing
) -> FigureCreate a multi-panel comparison figure showing polynomial approximations at different degrees.
Arguments
f: Original function (scalar input, scalar output)results: Dict mapping degree => (poly=..., df=..., TR=...) NamedTuplepoly_eval_factory: Function that takes a poly and returns evaluation function:poly -> (xi -> evaluate(poly, [xi]))func_latex: LaTeX string for function label in legend (default: "Original f(x)")n_samples: Number of sample points used in construction (shown in legend)
Returns
Figure: Makie Figure with one panel per degree
GlobtimPlots.plot_1d_polynomial_approximation — Method
plot_1d_polynomial_approximation(
f::Function,
poly,
critical_points::DataFrame;
poly_eval::Function = nothing,
n_plot_points::Int = 500,
title::String = "1D Polynomial Approximation",
show_l2_error::Bool = true,
save_path::Union{String, Nothing} = nothing,
figsize::Tuple{Int, Int} = (800, 600)
) -> FigurePlot a 1D function with its polynomial approximation and critical points.
Arguments
f: Original function (scalar input, scalar output)poly: ApproxPoly object from globtim (used for metadata: center, scale_factor, nrm, degree)critical_points: DataFrame withx1andzcolumns fromprocess_crit_pts
Keyword Arguments
poly_eval: Function to evaluate polynomial at a pointx -> evaluate(poly, [x]). Required.n_plot_points: Number of points for smooth curve plotting (default: 500)title: Plot titleshow_l2_error: Whether to annotate L2 approximation error (default: true)func_latex: LaTeX string for function label in legend (default: "Original f(x)")n_samples: Number of sample points used in construction (shown as annotation)save_path: If provided, save figure to this pathfigsize: Figure size in pixels (default: (800, 600))
Returns
Figure: Makie Figure object
Example
using Globtim, GlobtimPlots, DynamicPolynomials, DataFrames
f = x -> 0.5 * (x^4 - 16*x^2 + 5*x)
TR = TestInput(f, dim=1, center=[0.0], sample_range=5.0, GN=16)
poly = Constructor(TR, 12)
@polyvar x
solutions = solve_polynomial_system(x, poly)
df = process_crit_pts(solutions, f, TR)
fig = plot_1d_polynomial_approximation(
f, poly, df,
poly_eval = xi -> evaluate(poly, [xi]),
title = "Styblinski-Tang 1D"
)GlobtimPlots.plot_2d_partition — Method
plot_2d_partition(subdomains; kwargs...)Plot 2D subdomain partition on domain [-1,1]².
Arguments
subdomains: Iterable of objects with fieldscenter,half_widths,l2_error,degree,id
Keyword Arguments
color_by::Symbol = :l2_error: Color by:l2_error(log scale) or:degreetitle::String = "Domain Partition": Plot titlestyle::PartitionStyle = PartitionStyle(): Styling configurationfig = nothing: Existing Figure to plot into (creates new if nothing)ax = nothing: Existing Axis to plot into (creates new if nothing)
Returns
Figure: The Makie figure
Example
# Collect subdomains from episode
final_subs = collect_final_subdomains(env)
# Plot colored by L2 error
fig = plot_2d_partition(final_subs, color_by=:l2_error, title="AdaptiveL2 Policy")
save("partition.pdf", fig)
# Plot colored by degree
fig = plot_2d_partition(final_subs, color_by=:degree, title="Polynomial Degrees")GlobtimPlots.plot_all_eigenvalues — Method
plot_all_eigenvalues(f, df; sort_by=:magnitude, fig_size=nothing)Complete eigenvalue spectrum visualization separated by critical-point type, with multiple sort options (:magnitude, :abs_magnitude, :smallest, :largest, :spread, :index).
GlobtimPlots.plot_capture_convergence — Method
plot_capture_convergence(
degree_capture_results::Vector{Tuple{Int, CaptureResult}},
known::KnownCriticalPoints;
fig_size = (900, 900),
l2_errors = nothing,
show_l2 = false,
support_sizes = nothing,
save_path = nothing,
) -> FigureNeeds using GlobtimPostProcessing: the method is in the GlobtimPostProcessing package extension. Without it the call raises an error saying so.
Create a multi-panel figure showing capture analysis convergence.
When support_sizes is provided, the x-axis shows the number of nonzero polynomial coefficients (support size) instead of polynomial degree. All spacing and bar widths adapt automatically to the data via _adaptive_spacing.
Panels (top to bottom)
- Distance distribution: One sub-panel per CP type (min/max/saddle), each with its own y-range and log y-scale. Boxplots + jittered scatter of distances from each known CP to its nearest computed CP. Horizontal dashed lines at tolerance levels.
- Capture rate: Grouped bars showing fraction of known CPs captured at each tolerance level.
- L2 approximation error (optional): Only shown when both
l2_errorsdata is provided ANDshow_l2=true. Not displayed by default.
Arguments
degree_capture_results: Vector of(degree, CaptureResult)tuples, one per degree. All CaptureResults must use the sametolerance_fractions.known:KnownCriticalPointswith the ground truth.
Keyword Arguments
fig_size: Figure dimensions in pixels.l2_errors: OptionalVector{Tuple{Int, Float64}}of(degree, l2_error)pairs.show_l2: Whether to display the L2 error panel. Defaultfalse. Requiresl2_errorsto be provided as well.support_sizes: OptionalDict{Int, Int}mapping degree -> support size (nonzero coefficients). When provided, x-axis shows support size instead of degree.save_path: Optional file path to save the figure (e.g.,"capture_convergence.png").
Returns
Figure: Makie figure object.
Example
using GlobtimPlots, GlobtimPostProcessing, CairoMakie
# With support size on x-axis
support_sizes = Dict(dr.degree => dr.support_size
for dr in degree_results if dr.status == "success")
fig = plot_capture_convergence(
degree_capture_results, known_cps;
support_sizes = support_sizes,
l2_errors = [(dr.degree, dr.l2_approx_error) for dr in degree_results if dr.status == "success"],
)
display(fig)GlobtimPlots.plot_capture_sparsification_combined — Method
plot_capture_sparsification_combined(
entries,
known::KnownCriticalPoints;
fig_size = (1400, 700),
save_path = nothing,
) -> FigureNeeds using GlobtimPostProcessing: the method is in the GlobtimPostProcessing package extension. Without it the call raises an error saying so.
Two-panel side-by-side figure showing the sparsification speed vs accuracy tradeoff.
The x-axis uses support size (number of nonzero coefficients) from the Full variant at each degree, so the axis reflects actual polynomial complexity. All spacing and bar widths adapt automatically via _adaptive_spacing.
Panel A (left) – CP Accuracy: Distance to Known CPs
Stacked per-type subpanels with dodged boxplots for each support size x variant. Log-y scale, tolerance reference lines. Shows how much CP accuracy degrades with sparsification.
Panel B (right) – HC Solve Time
Grouped bar chart: x-axis = support size, bars dodged by variant. Y-axis = solve time (seconds). Each sparsified bar is annotated with absolute time saved. Shows how much faster the HC solve is with sparsification.
Arguments
entries: Vector of NamedTuples, each with fields:degree::Int– polynomial degreevariant_label::String– "Full", "1e-5 (mild)", etc.threshold::Float64– sparsification threshold (0.0 for full polynomial)capture_result::CaptureResult– full capture analysisn_nonzero_coeffs::Int– number of non-zero coefficientsl2_ratio::Float64– ratio of sparsified L2 norm to original (1.0 for full)solve_time::Float64– HC solve wall-clock time in seconds
known::KnownCriticalPoints: Ground truth critical points.
Keyword Arguments
fig_size: Figure dimensions in pixels.save_path: Optional file path to save the figure.
Returns
Figure: Makie figure object.
GlobtimPlots.plot_condition_numbers — Method
plot_condition_numbers(df; fig_size=(800,600))Log-scale scatter plot of Hessian condition numbers κ(H) = |λmax|/|λmin|.
GlobtimPlots.plot_convergence_analysis — Method
Plot summary of convergence distances for a range of degrees –> for each captured "x", compute the distance to "y", the optimized point.
GlobtimPlots.plot_convergence_captured — Method
plot_convergence_captured(results, df_check, start_degree, end_degree, step; kwargs...) -> FigureDistance from the critical points found at each degree to the nearest reference point of df_check (e.g. known minimizers), as maximum and average against the degree. results is a Dict keyed by degree whose values carry the critical-point frame in .df; degrees missing from it are skipped.
GlobtimPlots.plot_critical_eigenvalues — Method
plot_critical_eigenvalues(df; fig_size=(1200,500))Two-panel plot: smallest positive eigenvalues (minima) and largest negative eigenvalues (maxima).
GlobtimPlots.plot_discrete_l2 — Method
Plot the discrete L2-norm approximation error attained by the polynomial approximant.
GlobtimPlots.plot_distance_statistics — Method
Plot the outputs ofanalyze_converged_points function.
GlobtimPlots.plot_experiment_results_interactive — Method
plot_experiment_results_interactive(experiment_name, metrics; fig_size)Create interactive window showing experiment results. Delegates to the shared figure builder, then calls display.
Parameters:
experiment_name: Name of experiment for titlemetrics: NamedTuple with fields: degrees, l2norms, mindistances, meandistances, conditionnumbers
GlobtimPlots.plot_experiment_results_static — Method
plot_experiment_results_static(experiment_name, metrics; output_file, fig_size)Create static PNG/PDF/SVG plot and save to file.
Parameters:
experiment_name: Name of experiment for titlemetrics: NamedTuple with fields: degrees, l2norms, mindistances, meandistances, conditionnumbersoutput_file: Path to save file (extension determines format: .png, .pdf, .svg)
Returns:
- Path to saved file
GlobtimPlots.plot_hessian_norms — Method
plot_hessian_norms(df; fig_size=(800,600))Scatter plot of Hessian Frobenius norms, colored by critical-point type.
GlobtimPlots.plot_l2_convergence_trials — Method
plot_l2_convergence_trials(df::DataFrame; kwargs...)Plot L2 approximation error vs polynomial degree with individual trial paths.
Arguments
df::DataFrame: Must have columns:degree,:l2_error,:seed,:method
Keyword Arguments
domain_filter::Union{Nothing, Float64}=nothing: Filter to specific domaintitle::String="L2 Approximation Error by Degree": Plot titlefig_size::Tuple{Int,Int}=(800, 500): Figure sizeshow_median::Bool=true: Overlay median line per methodtrial_alpha::Float64=0.3: Alpha for individual trial linescolors::Tuple=(Makie.wong_colors()[1], Makie.wong_colors()[2]): (standard, log) colors
Returns
Figure: Makie figure object
GlobtimPlots.plot_l2_trajectories — Method
plot_l2_trajectories(trajectories; kwargs...)Plot L2 error trajectories for multiple policies.
Arguments
trajectories::Dict{String, Vector{Float64}}: Policy name → L2 error vector
Keyword Arguments
title::String = "L2 Error Evolution": Plot titleyscale = log10: Y-axis scale (log10 or identity)xlabel::String = "Step": X-axis labelylabel::String = "L2 Error": Y-axis labelfig_size::Tuple{Int,Int} = (800, 500): Figure size
Returns
Figure: The Makie figure
Example
trajectories = Dict(
"AdaptiveL2" => run_episode(env, AdaptiveL2Policy()).l2_trajectory,
"GreedyDegree" => run_episode(env, GreedyDegreePolicy()).l2_trajectory
)
fig = plot_l2_trajectories(trajectories)GlobtimPlots.plot_level_set — Method
plot_level_set(
formatted_data;
fig_size = (800, 600),
marker_size = 4,
title = "Level Set Visualization"
)Create a basic 3D scatter plot of level set points.
Arguments
formatted_data: Output fromto_makie_formatfig_size: Figure dimensionsmarker_size: Size of scatter markerstitle: Plot title
Returns
- GLMakie Figure object
GlobtimPlots.plot_polyapprox_3d — Function
plot_polyapprox_3d(pol, TR, df, df_min; kwargs...) -> Figure3D surface of the polynomial approximant pol over the domain described by TR, with the critical points of df and the refined minima of df_min drawn on it. pol and TR implement AbstractPolynomialData / AbstractProblemInput (see adapt_polynomial_data, adapt_problem_input).
The methods live in the backend extensions: load GLMakie (adds rotate = true / filename for a recorded turntable animation) or WGLMakie (WebGL widget) first. Without one of them the call raises a MethodError. The backend-agnostic drawing code is _plot_polyapprox_3d_impl in src/polyapprox_3d.jl.
Keyword arguments
figure_size = (1000, 800),z_limits = nothing,alpha_surface = 0.7show_captured = true: draw the refined minima ofdf_minfade = false,z_cut = 0.25: fade the surface above a value cutcolor_by = :proximity: marker coloring of the critical points
GlobtimPlots.plot_predicate_pareto — Method
plot_predicate_pareto(df::DataFrame;
x_col=:mean_evals, y_col=:mean_recovery,
score_col=:pareto_score, label_col=nothing,
front_col=nothing,
title="Predicate sweep — evals/recovery Pareto")
-> FigureScatter of predicate-sweep trials in the (cost, error) plane — both axes minimized — colored by score_col, with the Pareto front drawn as a staircase through the non-dominated points. If front_col names a Bool column, the front membership computed by the analyzer is used verbatim; otherwise the non-dominated set is derived here purely for display. label_col (optional) annotates front points.
GlobtimPlots.plot_raw_vs_refined_eigenvalues — Method
plot_raw_vs_refined_eigenvalues(f, df_raw, df_refined; sort_by=:euclidean_distance, fig_size=nothing)Before/after BFGS comparison of eigenvalues at matched critical points. Sort options: :euclidean_distance, :function_value_diff, :eigenvalue_change.
GlobtimPlots.plot_refinement_trajectories! — Method
plot_refinement_trajectories!(ax, refine_results, raw_points; kwargs...) -> IntNeeds using GlobtimPostProcessing: the method is in the GlobtimPostProcessing package extension. Without it the call raises an error saying so.
Overlay refinement trajectories on an existing Axis.
Each trajectory visualizes how a local solver (Newton / trust-region / NelderMead) moved a raw polynomial critical point toward the refined result. Paths are drawn as colored lines from circle (start) to triangle (end), with intermediate iterates when the solver recorded a full trace.
Arguments
ax::Axis: Makie axis to draw on (mutated in place)refine_results::Vector{CriticalPointRefinementResult}: Per-CP refinement results (must have.tracefield — aVector{Vector{Float64}}of iterates)raw_points::Vector{Vector{Float64}}: Starting points (same length & ordering asrefine_results)
Keyword Arguments
Selection — which trajectories to show
p_target::Union{Nothing, Vector{Float64}} = nothing: Sort raw CPs by distance to this point and show then_showclosest. Mutually exclusive withindices.n_show::Int = 10: Number of trajectories to show when usingp_targetsorting.indices::Union{Nothing, Vector{Int}} = nothing: Explicit 1-based indices intorefine_results/raw_pointsto plot. Overridesp_target/n_show.
Projection — for N-D problems
dim_x::Int = 1: Parameter dimension to map to the x-axis.dim_y::Int = 2: Parameter dimension to map to the y-axis.
Clipping
clip_bounds::Union{Nothing, Vector{Vector{Float64}}} = nothing: If provided, only draw trajectories that have at least one iterate inside this bounding box (format[[lo1, hi1], [lo2, hi2], ...]— checked ondim_xanddim_yonly).
Visual style
style::RefinementTrajectoryStyle = RefinementTrajectoryStyle(): Full style config.label::Union{String, Nothing} = "refinement paths": Legend label for the first trajectory group. Passnothingto suppress legend entries.
Returns
Int: Number of trajectories actually drawn.
Example
using GlobtimPlots, GlobtimPostProcessing, CairoMakie
fig = Figure()
ax = Axis(fig[1,1])
contourf!(ax, x_range, y_range, Z; colormap=:inferno)
n_drawn = plot_refinement_trajectories!(ax, results, raw_cps;
p_target = p_true, n_show = 15,
style = RefinementTrajectoryStyle(linewidth=2.0))GlobtimPlots.plot_subdivision_error_heatmap — Method
plot_subdivision_error_heatmap(
tree::SubdivisionTree, f;
resolution::Int = 200,
log_scale::Bool = true,
colormap::Symbol = :viridis,
show_boundaries::Bool = true,
boundary_color = :white,
boundary_width::Float64 = 1.0,
title::String = "Polynomial Approximation Error",
cp_points::Vector = Vector{Float64}[],
cp_types::Vector = String[],
raw_cp_points::Vector = Vector{Float64}[],
p_true = nothing,
style::SubdivisionPartitionStyle = SubdivisionPartitionStyle(),
fig = nothing,
ax = nothing,
) → FigureCreate a 2D filled heatmap of |f(p) - poly(p)| across the subdivision domain, with subdomain boundaries overlaid.
Requires the SubdivisionTree with populated polynomials (runtime only — polynomials are not serialized to JSON).
Arguments
tree: The subdivision tree with polynomial approximations per leaff: The objective functionf(x::Vector{Float64}) → Float64
Keyword Arguments
resolution: Grid points per axis (default 200)log_scale: If true, plot log₁₀(error) (default true)colormap: Makie colormap (default:viridis)show_boundaries: Overlay subdomain boundaries (default true)boundary_color: Color for boundary lines (default:white)boundary_width: Line width for boundaries (default 1.0)title: Plot titlecp_points, cp_types: Refined critical points and their typesraw_cp_points: Raw (pre-refinement) critical pointsp_true: True parameter vectorstyle: SubdivisionPartitionStyle for CP marker stylingfig, ax: Plot into existing Figure/Axis
GlobtimPlots.plot_subdivision_on_levelset — Method
plot_subdivision_on_levelset(tree::SubdivisionTree, f; kwargs...) → FigurePlot the objective function f as a filled contour (level set) with subdivision boundaries overlaid, colored by convergence status. Critical points and p* are scattered on top.
Requires the SubdivisionTree and objective function to be in memory (runtime only).
Arguments
tree: The subdivision tree (provides domain bounds and per-leaf L2 errors)f: The objective functionf(x::Vector{Float64}) → Float64
Keyword Arguments
resolution::Int = 200: Grid points per axis for contour evaluationn_levels::Int = 30: Number of contour levelscolormap::Symbol = :viridis: Colormap for the filled contourl2_tolerance: L2 tolerance for convergence border coloringcp_points, cp_types: Refined critical points and their typesraw_cp_points: Raw (pre-refinement) critical pointsp_true: True parameter vectortitle: Plot titlestyle:SubdivisionPartitionStylefor marker/border stylingfig, ax: Plot into existing Figure/Axis
GlobtimPlots.plot_subdivision_on_levelset_from_bounds — Method
plot_subdivision_on_levelset_from_bounds(f, bounds; leaf_bounds, leaf_l2_errors, kwargs...) → FigureData-based version for when the tree is not available but leaf geometry and L2 errors have been extracted (e.g. from JSON results).
Arguments
f: The objective functionf(x::Vector{Float64}) → Float64bounds: Domain bounds[[x_lo, x_hi], [y_lo, y_hi]]or[(x_lo, x_hi), (y_lo, y_hi)]leaf_bounds: Per-leaf bounds[leaf][dim] → [lo, hi]or tuplesleaf_l2_errors::Vector{Float64}: L2 error per leaf
All other keyword arguments are the same as the tree-based version.
GlobtimPlots.plot_subdivision_partition — Method
plot_subdivision_partition(leaf_bounds, leaf_l2_errors, leaf_degrees; kwargs...) → FigureCreate a domain partition visualization for a subdivision experiment result.
Arguments
leaf_bounds::Vector: Per-leaf bounds,[leaf][dim] → [lo, hi]leaf_l2_errors::Vector{Float64}: L2 error per leafleaf_degrees::Vector: Degree per leaf (Int or Vector{Int} for anisotropic)
Keyword Arguments
cp_points::Vector = []: Refined critical points (Vector{Float64}[])cp_types::Vector = []: CP type strings ("min"/"saddle"/"max")raw_cp_points::Vector = []: Raw (pre-refinement) critical points (Vector{Float64}[])p_true = nothing: True parameter vectorl2_tolerance = nothing: L2 tolerance for convergence border coloringcolorrange = nothing: Explicit(cmin, cmax)for color scale; auto-computed if nothingtitle::String = "Domain Partition": Plot titlesubtitle::String = "": Plot subtitlestyle::SubdivisionPartitionStyle = SubdivisionPartitionStyle(): Styling configfig = nothing: Plot into existing Figureax = nothing: Plot into existing Axis
Returns
Figure: The Makie figure (backend-agnostic — display with GLMakie for interactive, save with CairoMakie)
Example
using GlobtimPlots
fig = plot_subdivision_partition(
leaf_bounds, leaf_l2_errors, leaf_degrees;
cp_points=cps, cp_types=types, p_true=[1.0, 1.5],
l2_tolerance=1e-4, title="LV2D subdivision"
)
save("partition.png", fig; px_per_unit=2)GlobtimPlots.plot_subdivision_tree — Method
plot_subdivision_tree(tree; kwargs...) -> FigureNeeds using GraphMakie: the method is in the GraphMakie package extension (its triggers Graphs and NetworkLayout are GraphMakie dependencies and load with it). Without it the call raises an error saying so.
Create publication-quality visualization of a subdivision tree.
Arguments
tree: SubdivisionTree from Globtim (uses duck typing)
Keyword Arguments
style::TreeVizStyle = TreeVizStyle(): Visual styling configurationtitle::String = "": Optional figure titleshow_legend::Bool = true: Whether to show dimension color legendbalanced_layout::Bool = true: Use split-position-aware layout (recommended)
Returns
Figure: Makie Figure; save it as PDF/SVG with CairoMakie loaded
Notes
- Auto-scaling is enabled by default: node sizes, fonts, and figure dimensions adapt to tree size for optimal readability.
- Set
style=TreeVizStyle(auto_scale=false, auto_fig_size=false)for fixed sizing.
Example
using Globtim, GlobtimPlots, CairoMakie, GraphMakie
tree = adaptive_refine(f, bounds, 4) # uses default relative L2 tolerance of 0.03
fig = plot_subdivision_tree(tree)
save("tree.pdf", fig)GlobtimPlots.plot_theoretical_minimizer_distances — Function
Plot distance from theoretical minimizers to nearest computed critical points.
For each theoretical minimizer, computes the distance to the nearest critical point found by the polynomial method. Shows both average and maximum distances by degree.
Arguments
results: Dictionary mapping degrees to analysis resultsdf_theoretical_mins: DataFrame containing theoretical minimizer coordinates (x1, x2, ...)start_degree: Minimum polynomial degreeend_degree: Maximum polynomial degreestep: Step size between degrees (default: 1)show_legend: Whether to display legend (default: true)
Returns
fig: Makie Figure object
GlobtimPlots.plot_verdict_shares — Method
plot_verdict_shares(df::DataFrame;
winner_col=:winner, family_col=:family,
strat_cols=[:base_degree, :budget],
title="Per-axis cut counterfactual — winner shares")
-> FigureStacked-bar shares of counterfactual winners per stratum, one panel per value of family_col. Each row of df is one verdict record; winner_col values are "per_axis" / "global" / "tie". Strata are the distinct combinations of strat_cols within a family, labeled "col=val col=val" and annotated with the record count n.
GlobtimPlots.prepare_level_set_data — Method
prepare_level_set_data(
grid::Array{SVector{3,T},3},
values::Array{T},
level::T;
tolerance::T = T(0.01)
) where {T<:AbstractFloat}Identify points in the grid that are close to the specified level.
Arguments
grid: 3D array of grid pointsvalues: Function values at each grid pointlevel: Target level valuetolerance: Maximum distance from level to include point
Returns
LevelSetData{T}: Container with filtered points and values
GlobtimPlots.print_tree_summary — Method
print_tree_summary(tree; io=stdout)Print summary statistics for a subdivision tree.
GlobtimPlots.save_plot — Method
save_plot(fig::Figure, output_path::String; format=:png)Save a Makie figure to file with the active Makie backend. PNG works with any file-capable backend; :pdf and :svg need CairoMakie (using CairoMakie).
GlobtimPlots.split_position_label — Function
split_position_label(split_pos::Float64, width::Int=10) -> StringCreate ASCII split position visualization: [—-|———]
GlobtimPlots.sublevel_barcode — Method
sublevel_barcode(values::AbstractArray{<:Real,3}) -> Vector{NamedTuple}The H₀ barcode of the sublevel filtration of values on its grid (6-neighbourhood): one (; birth, death, argmin) per connected component that ever appears, where birth is its minimum value, argmin the linear index of that minimum, and death the value at which it merges into a component with a lower minimum (elder rule); the component of the global minimum has death = Inf. Non-finite values are skipped. Sorted by birth.
GlobtimPlots.to_makie_format — Method
to_makie_format(level_set::LevelSetData{T}) where {T<:AbstractFloat}Convert LevelSetData to format suitable for Makie plotting.
Returns
Named tuple with:
points: 3×N matrix of coordinatesvalues: vector of function valuesxyz: tuple of (x, y, z) coordinate vectors