API Reference

GlobtimPlots is organized by what you want to draw:

AreaFunctions
Level setscairo_plot_polyapprox_levelset, plot_polyapprox_3d (GLMakie / WGLMakie), create_level_set_visualization, create_level_set_animation, plot_level_set
Morse diagnosticsplot_critical_eigenvalues, plot_condition_numbers, plot_hessian_norms, plot_all_eigenvalues, plot_raw_vs_refined_eigenvalues
Degree sweepsplot_discrete_l2, plot_convergence_analysis, plot_l2_convergence_trials, plot_distance_statistics, plot_convergence_captured, plot_theoretical_minimizer_distances
Subdivisionplot_subdivision_partition, plot_subdivision_on_levelset, plot_subdivision_on_levelset_from_bounds, plot_subdivision_error_heatmap, plot_subdivision_tree, print_tree_summary, plot_2d_partition, plot_l2_trajectories, interactive_error_explorer, interactive_levelset_explorer
1D approximationplot_1d_polynomial_approximation, plot_1d_comparison
Experiments & campaignscreate_experiment_plots, create_campaign_comparison_plot, create_single_plot, generate_experiment_labels, save_plot, plot_experiment_results_static, plot_experiment_results_interactive
Capture analysisplot_capture_convergence, plot_capture_sparsification_combined, plot_refinement_trajectories!
Benchmark outcomesplot_verdict_shares, plot_predicate_pareto

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:

BackendUse forExtension
CairoMakieStatic, publication-quality PNG / PDF / SVG (save_plot's :pdf / :svg)—
GLMakieInteractive windows, plot_polyapprox_3d with a recorded rotation, the explorersGlobtimPlotsGLMakieExt
WGLMakieBrowser-embedded / Documenter-rendered interactive figuresGlobtimPlotsWGLMakieExt
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:

LoadExtensionAdds
using GraphMakieGlobtimPlotsGraphMakieExt (triggers GraphMakie, Graphs, NetworkLayout; the last two load with GraphMakie)plot_subdivision_tree
using GlobtimPostProcessingGlobtimPlotsPostProcessingExtplot_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_TABLE

Canonical 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.

source
GlobtimPlots.AbstractCriticalPointData — Type
AbstractCriticalPointData

Abstract type for critical point data used in visualization.

Subtypes should provide critical point locations and classifications for scatter plots and overlays.

source
GlobtimPlots.BalancedTreeLayout — Type
BalancedTreeLayout

Custom layout type for GraphMakie that uses split positions to determine child placement. Supports configurable horizontal scaling and vertical spacing.

source
GlobtimPlots.GenericPolynomialData — Type
GenericPolynomialData <: AbstractPolynomialData

Concrete implementation of polynomial data for plotting.

Fields

  • coeffs::Any: Polynomial coefficients
  • basis::Symbol: Basis type (:chebyshev, :monomial, etc.), default :chebyshev
  • scale_factor::Union{Float64, Vector{Float64}}: Domain scaling factor(s), default 1.0
  • grid::Matrix{Float64}: Evaluation grid points
  • z::Vector{Float64}: Function values at grid points
  • precision::Any: Numerical precision information
  • normalized::Bool: Whether the approximation is normalized, default false

See also: AbstractPolynomialData, adapt_polynomial_data

source
GlobtimPlots.GenericProblemInput — Type
GenericProblemInput <: AbstractProblemInput

Concrete implementation of problem input data for plotting.

Fields

  • dim::Int: Problem dimension (number of variables), default 2
  • center::Vector{Float64}: Domain center point, default [0.0, 0.0]
  • sample_range::Union{Float64, Vector{Float64}}: Domain sampling range(s), default 1.0

See also: AbstractProblemInput, adapt_problem_input

source
GlobtimPlots.RefinementTrajectoryStyle — Type
RefinementTrajectoryStyle

Visual 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)
source
GlobtimPlots.SubdivisionPartitionStyle — Type
SubdivisionPartitionStyle

Styling configuration for subdivision domain partition visualization. Controls colormap, degree labels, CP markers, convergence borders, colorbar, and legend.

source
GlobtimPlots.SubdomainNodeInfo — Type
SubdomainNodeInfo

Extracted information about a single subdomain node for visualization. Uses duck typing to work with Globtim's SubdivisionTree without hard dependency.

source
GlobtimPlots._build_experiment_results_figure — Method
_build_experiment_results_figure(experiment_name, metrics; fig_size) → Figure

Internal: build the 4-panel experiment results figure using backend-agnostic Makie calls. Both the interactive and static entry points delegate here.

source
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_plot

Draw 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()).

source
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.

source
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].

source
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.

source
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.

source
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.

source
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).

source
GlobtimPlots._gradient_method_short — Method
_gradient_method_short(method::Symbol) -> String

Short tag for log lines, e.g. "[FD] " or "[AD] ". Includes trailing space so it concatenates cleanly with -> cp_type in log output.

source
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.

source
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.

source
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.

source
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).

source
GlobtimPlots._plot_polyapprox_3d_impl — Method
_plot_polyapprox_3d_impl(pol, TR, df, df_min; kwargs...) -> Figure

Core 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 data
  • TR::AbstractProblemInput: Problem domain specification
  • df::DataFrame: All critical points (must have columns x1, x2, z; optional close for :proximity mode or critical_point_type for :hessian_type mode)
  • df_min::DataFrame: Minima points (must have columns x1, x2, value, captured)

Keyword Arguments

  • figure_size::Tuple{Int,Int}=(1000,800): Figure dimensions
  • z_limits::Union{Nothing,Tuple{Float64,Float64}}=nothing: Z-axis limits (auto-computed if nothing)
  • show_captured::Bool=true: Whether to show captured minima markers
  • alpha_surface::Float64=0.7: Surface transparency
  • fade::Bool=false: Enable fade effect for top portion of z-range
  • z_cut::Float64=0.25: Fraction of z-range to fade (when fade=true)
  • color_by::Symbol=:proximity: How to color/group CP markers. :proximity (default) splits on df.close; :hessian_type groups by df.critical_point_type using CP_TYPE_TABLE palette + markers (min/saddle/max/degenerate).
source
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.

source
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.

source
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.

source
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.

source
GlobtimPlots.adapt_polynomial_data — Method
adapt_polynomial_data(globtim_poly) → GenericPolynomialData

Adapt 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:

  • globtim defines concrete types (ApproxPoly) without depending on plotting packages
  • globtimplots defines abstract interfaces (AbstractPolynomialData)
  • Users explicitly convert when crossing package boundaries

Arguments

  • globtim_poly: Any object with polynomial approximation data (typically ApproxPoly)

Extracted Fields

  • coeffs: Polynomial coefficients
  • basis: Basis type (:chebyshev, :monomial, etc.)
  • scale_factor: Domain scaling factor
  • grid: Evaluation grid points (Matrix)
  • z: Function values at grid points
  • precision: Numerical precision information
  • normalized: 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

source
GlobtimPlots.adapt_problem_input — Method
adapt_problem_input(globtim_input) → GenericProblemInput

Adapt 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:

  • globtim defines concrete types (TestInput) without depending on plotting packages
  • globtimplots defines abstract interfaces (AbstractProblemInput)
  • Users explicitly convert when crossing package boundaries

Arguments

  • globtim_input: Any object with problem input data (typically TestInput)

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

source
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 horizontally
  • v_spacing: Vertical spacing between levels (default 1.5)
source
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 dimensions
  • z_limits::Union{Nothing, Tuple{Float64,Float64}} = nothing: contour z range (auto if nothing)
  • chebyshev_levels::Bool = false: use Chebyshev-spaced contour levels
  • num_levels::Int = 30: number of contour levels
  • show_captured::Bool = true: whether to show captured minima
source
GlobtimPlots.compute_auto_scale — Method
compute_auto_scale(nodes::Vector{SubdomainNodeInfo}, style::TreeVizStyle) -> NamedTuple

Compute scaling factors for nodes, fonts, and layout based on tree size. Returns named tuple with scaled values ready to use.

source
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).

source
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).

source
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.

source
GlobtimPlots.compute_figure_size — Method
compute_figure_size(nodes::Vector{SubdomainNodeInfo}, style::TreeVizStyle) -> Tuple{Int,Int}

Calculate optimal figure size based on tree structure.

source
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.

source
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.

source
GlobtimPlots.create_experiment_plots — Method
create_experiment_plots(result, stats::Dict; backend::PlotBackend=Static) -> Figure

Create 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.

source
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 function
  • grid: 3D array of sample points
  • df: Optional DataFrame with critical points
  • z_range: Range of level values to animate
  • params: Visualization parameters
  • fps: Frames per second for animation
  • duration: Animation duration in seconds
  • output_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"
)
source
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.

source
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) -> Figure

Animate 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.

source
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 visualize
  • grid: 3D array of sample points
  • df: Optional DataFrame with critical points (columns: x1, x2, x3, z)
  • z_range: Tuple (min, max) for level values
  • params: 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))
source
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).

source
GlobtimPlots.create_single_plot — Method
create_single_plot(result, stats::Dict, plot_type::Symbol, title::String; backend::PlotBackend=Interactive) -> Figure

Create 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.

source
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) -> Figure

Animate 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.

source
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.

source
GlobtimPlots.find_containing_leaf — Method
find_containing_leaf(tree::SubdivisionTree, point::AbstractVector{Float64}) → Subdomain

Find the leaf subdomain containing point. Errors if no leaf contains the point.

source
GlobtimPlots.format_node_label — Method
format_node_label(node::SubdomainNodeInfo, nodes::Vector{SubdomainNodeInfo}, style::TreeVizStyle; balanced_layout::Bool=true) -> String

Format 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.

source
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 .experiments field

Strategy

  1. Identify which parameters vary across experiments
  2. If only one parameter varies, label by that parameter value
  3. If multiple parameters vary, create compact multi-parameter labels
  4. Handle common parameter types (domainsizeparam, parameter_set, etc.)
source
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.

source
GlobtimPlots.interactive_error_explorer — Method
interactive_error_explorer(
    tree::SubdivisionTree, f;
    resolution::Int = 200,
    log_scale::Bool = true,
    colormap::Symbol = :viridis,
) → Figure

Launch 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 resolution within 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 function f(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)
source
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)

KeyAction
rRefine Selected
cClear Refined
vRefine View
zReset View
lToggle 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 (:neldermead or :lbfgs), x_abstol and step_size (LBFGS only; NelderMead's single stop is the simplex spread, set by f_abstol)

Arguments

  • f: Objective function f(x::Vector{Float64}) → Float64
  • bounds: 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-minimization
  • leaf_bounds: Per-leaf domain bounds from subdivision
  • leaf_l2_errors: Per-leaf L2 approximation errors

Keyword Arguments

  • raw_cp_points: Raw (pre-refinement) critical points — pickable targets
  • cp_points, cp_types: Already-refined CPs and their types
  • p_true: True parameter vector (gold star)
  • l2_tolerance: For convergence border coloring
  • resolution: Grid points per axis for contour evaluation
  • n_levels: Number of contour levels
  • colormap: Colormap for filled contour
  • style: SubdivisionPartitionStyle for marker/border styling
  • title: Plot title
source
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).

source
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.

source
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.

source
GlobtimPlots.normalize_cp_key — Method
normalize_cp_key(k::Symbol) → Symbol

Normalize verbose CP type keys to the canonical short form used by CP_TYPE_TABLE: :minimum → :min, :maximum → :max. All other keys pass through unchanged.

source
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
) -> Figure

Create 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=...) NamedTuple
  • poly_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
source
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)
) -> Figure

Plot 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 with x1 and z columns from process_crit_pts

Keyword Arguments

  • poly_eval: Function to evaluate polynomial at a point x -> evaluate(poly, [x]). Required.
  • n_plot_points: Number of points for smooth curve plotting (default: 500)
  • title: Plot title
  • show_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 path
  • figsize: 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"
)
source
GlobtimPlots.plot_2d_partition — Method
plot_2d_partition(subdomains; kwargs...)

Plot 2D subdomain partition on domain [-1,1]².

Arguments

  • subdomains: Iterable of objects with fields center, half_widths, l2_error, degree, id

Keyword Arguments

  • color_by::Symbol = :l2_error: Color by :l2_error (log scale) or :degree
  • title::String = "Domain Partition": Plot title
  • style::PartitionStyle = PartitionStyle(): Styling configuration
  • fig = 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")
source
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).

source
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,
) -> Figure

Needs 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)

  1. 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.
  2. Capture rate: Grouped bars showing fraction of known CPs captured at each tolerance level.
  3. L2 approximation error (optional): Only shown when both l2_errors data is provided AND show_l2=true. Not displayed by default.

Arguments

  • degree_capture_results: Vector of (degree, CaptureResult) tuples, one per degree. All CaptureResults must use the same tolerance_fractions.
  • known: KnownCriticalPoints with the ground truth.

Keyword Arguments

  • fig_size: Figure dimensions in pixels.
  • l2_errors: Optional Vector{Tuple{Int, Float64}} of (degree, l2_error) pairs.
  • show_l2: Whether to display the L2 error panel. Default false. Requires l2_errors to be provided as well.
  • support_sizes: Optional Dict{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)
source
GlobtimPlots.plot_capture_sparsification_combined — Method
plot_capture_sparsification_combined(
    entries,
    known::KnownCriticalPoints;
    fig_size = (1400, 700),
    save_path = nothing,
) -> Figure

Needs 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 degree
    • variant_label::String – "Full", "1e-5 (mild)", etc.
    • threshold::Float64 – sparsification threshold (0.0 for full polynomial)
    • capture_result::CaptureResult – full capture analysis
    • n_nonzero_coeffs::Int – number of non-zero coefficients
    • l2_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.
source
GlobtimPlots.plot_convergence_captured — Method
plot_convergence_captured(results, df_check, start_degree, end_degree, step; kwargs...) -> Figure

Distance 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.

source
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 title
  • metrics: NamedTuple with fields: degrees, l2norms, mindistances, meandistances, conditionnumbers
source
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 title
  • metrics: NamedTuple with fields: degrees, l2norms, mindistances, meandistances, conditionnumbers
  • output_file: Path to save file (extension determines format: .png, .pdf, .svg)

Returns:

  • Path to saved file
source
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 domain
  • title::String="L2 Approximation Error by Degree": Plot title
  • fig_size::Tuple{Int,Int}=(800, 500): Figure size
  • show_median::Bool=true: Overlay median line per method
  • trial_alpha::Float64=0.3: Alpha for individual trial lines
  • colors::Tuple=(Makie.wong_colors()[1], Makie.wong_colors()[2]): (standard, log) colors

Returns

  • Figure: Makie figure object
source
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 title
  • yscale = log10: Y-axis scale (log10 or identity)
  • xlabel::String = "Step": X-axis label
  • ylabel::String = "L2 Error": Y-axis label
  • fig_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)
source
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 from to_makie_format
  • fig_size: Figure dimensions
  • marker_size: Size of scatter markers
  • title: Plot title

Returns

  • GLMakie Figure object
source
GlobtimPlots.plot_polyapprox_3d — Function
plot_polyapprox_3d(pol, TR, df, df_min; kwargs...) -> Figure

3D 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.7
  • show_captured = true: draw the refined minima of df_min
  • fade = false, z_cut = 0.25: fade the surface above a value cut
  • color_by = :proximity: marker coloring of the critical points
source
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")
    -> Figure

Scatter 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.

source
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.

source
GlobtimPlots.plot_refinement_trajectories! — Method
plot_refinement_trajectories!(ax, refine_results, raw_points; kwargs...) -> Int

Needs 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 .trace field — a Vector{Vector{Float64}} of iterates)
  • raw_points::Vector{Vector{Float64}}: Starting points (same length & ordering as refine_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 the n_show closest. Mutually exclusive with indices.
  • n_show::Int = 10: Number of trajectories to show when using p_target sorting.
  • indices::Union{Nothing, Vector{Int}} = nothing: Explicit 1-based indices into refine_results / raw_points to plot. Overrides p_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 on dim_x and dim_y only).

Visual style

  • style::RefinementTrajectoryStyle = RefinementTrajectoryStyle(): Full style config.
  • label::Union{String, Nothing} = "refinement paths": Legend label for the first trajectory group. Pass nothing to 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))
source
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,
) → Figure

Create 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 leaf
  • f: The objective function f(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 title
  • cp_points, cp_types: Refined critical points and their types
  • raw_cp_points: Raw (pre-refinement) critical points
  • p_true: True parameter vector
  • style: SubdivisionPartitionStyle for CP marker styling
  • fig, ax: Plot into existing Figure/Axis
source
GlobtimPlots.plot_subdivision_on_levelset — Method
plot_subdivision_on_levelset(tree::SubdivisionTree, f; kwargs...) → Figure

Plot 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 function f(x::Vector{Float64}) → Float64

Keyword Arguments

  • resolution::Int = 200: Grid points per axis for contour evaluation
  • n_levels::Int = 30: Number of contour levels
  • colormap::Symbol = :viridis: Colormap for the filled contour
  • l2_tolerance: L2 tolerance for convergence border coloring
  • cp_points, cp_types: Refined critical points and their types
  • raw_cp_points: Raw (pre-refinement) critical points
  • p_true: True parameter vector
  • title: Plot title
  • style: SubdivisionPartitionStyle for marker/border styling
  • fig, ax: Plot into existing Figure/Axis
source
GlobtimPlots.plot_subdivision_on_levelset_from_bounds — Method
plot_subdivision_on_levelset_from_bounds(f, bounds; leaf_bounds, leaf_l2_errors, kwargs...) → Figure

Data-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 function f(x::Vector{Float64}) → Float64
  • bounds: 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 tuples
  • leaf_l2_errors::Vector{Float64}: L2 error per leaf

All other keyword arguments are the same as the tree-based version.

source
GlobtimPlots.plot_subdivision_partition — Method
plot_subdivision_partition(leaf_bounds, leaf_l2_errors, leaf_degrees; kwargs...) → Figure

Create 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 leaf
  • leaf_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 vector
  • l2_tolerance = nothing: L2 tolerance for convergence border coloring
  • colorrange = nothing: Explicit (cmin, cmax) for color scale; auto-computed if nothing
  • title::String = "Domain Partition": Plot title
  • subtitle::String = "": Plot subtitle
  • style::SubdivisionPartitionStyle = SubdivisionPartitionStyle(): Styling config
  • fig = nothing: Plot into existing Figure
  • ax = 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)
source
GlobtimPlots.plot_subdivision_tree — Method
plot_subdivision_tree(tree; kwargs...) -> Figure

Needs 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 configuration
  • title::String = "": Optional figure title
  • show_legend::Bool = true: Whether to show dimension color legend
  • balanced_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)
source
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 results
  • df_theoretical_mins: DataFrame containing theoretical minimizer coordinates (x1, x2, ...)
  • start_degree: Minimum polynomial degree
  • end_degree: Maximum polynomial degree
  • step: Step size between degrees (default: 1)
  • show_legend: Whether to display legend (default: true)

Returns

  • fig: Makie Figure object
source
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")
    -> Figure

Stacked-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.

source
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 points
  • values: Function values at each grid point
  • level: Target level value
  • tolerance: Maximum distance from level to include point

Returns

  • LevelSetData{T}: Container with filtered points and values
source
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).

source
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.

source
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 coordinates
  • values: vector of function values
  • xyz: tuple of (x, y, z) coordinate vectors
source