Plotting and I/O
RecipesBase.plot Function
plot(
sol::CTModels.Solutions.AbstractSolution,
description::Symbol...;
kwargs...
) -> AnyStub for RecipesBase.plot for CTModels solutions.
Loaded and specialised by the CTModelsPlots extension when Plots is available. Without that extension, calling this throws an CTBase.Exceptions.ExtensionError pointing to Plots.
plot(
sol::CTFlows.Trajectories.AbstractVectorFieldTrajectory;
kwargs...
) -> AnyPlot stub — throws error if Plots extension not loaded.
Arguments
sol::AbstractVectorFieldTrajectory: The vector field solution.kwargs...: Additional plotting keyword arguments (ignored).
Throws
CTBase.Exceptions.ExtensionError: If Plots extension is not loaded.
See also: CTFlows.Trajectories.VectorFieldTrajectory, CTFlows.Trajectories.AbstractVectorFieldTrajectory.
plot(
sol::CTFlows.Trajectories.AbstractHamiltonianVectorFieldTrajectory;
kwargs...
) -> AnyPlot stub — throws error if Plots extension not loaded.
Arguments
sol::AbstractHamiltonianVectorFieldTrajectory: The Hamiltonian vector field solution.kwargs...: Additional plotting keyword arguments (ignored).
Throws
CTBase.Exceptions.ExtensionError: If Plots extension is not loaded.
See also: CTFlows.Trajectories.HamiltonianVectorFieldTrajectory, CTFlows.Trajectories.AbstractHamiltonianVectorFieldTrajectory.
The main plot command. Use plot to create a new plot object, and plot! to add to an existing one:
plot(args...; kw...) # creates a new plot window, and sets it to be the current
plot!(args...; kw...) # adds to the `current`
plot!(plotobj, args...; kw...) # adds to the plot `plotobj`There are lots of ways to pass in data, and lots of keyword arguments... just try it and it will likely work as expected. When you pass in matrices, it splits by columns. To see the list of available attributes, use the plotattr(attr) function, where attr is the symbol :Series, :Subplot, :Plot, or :Axis. Pass any attribute to plotattr as a String to look up its docstring, e.g., plotattr("seriestype").
Extended help
Series attributes
arrow
bar_edges
bar_position
bar_width
bins
colorbar_entry
connections
contour_labels
contours
extra_kwargs
fill
fill_z
fillalpha
fillcolor
fillrange
fillstyle
group
hover
label
levels
line
line_z
linealpha
linecolor
linestyle
linewidth
marker
marker_z
markeralpha
markercolor
markershape
markersize
markerstrokealpha
markerstrokecolor
markerstrokestyle
markerstrokewidth
normalize
orientation
permute
primary
quiver
ribbon
series_annotations
seriesalpha
seriescolor
seriestype
show_empty_bins
smooth
stride
subplot
weights
x
xerror
y
yerror
z
z_order
zerror
Axis attributes
Prepend these with the axis letter (x, y or z)
axis
discrete_values
draw_arrow
flip
foreground_color_axis
foreground_color_border
foreground_color_grid
foreground_color_guide
foreground_color_minor_grid
foreground_color_text
formatter
grid
gridalpha
gridlinewidth
gridstyle
guide
guide_position
guidefont
guidefontcolor
guidefontfamily
guidefonthalign
guidefontrotation
guidefontsize
guidefontvalign
lims
link
minorgrid
minorgridalpha
minorgridlinewidth
minorgridstyle
minorticks
mirror
rotation
scale
showaxis
tick_direction
tickfont
tickfontcolor
tickfontfamily
tickfonthalign
tickfontrotation
tickfontsize
tickfontvalign
ticks
unit
unitformat
widen
Subplot attributes
annotationcolor
annotationfontfamily
annotationfontsize
annotationhalign
annotationrotation
annotations
annotationvalign
aspect_ratio
background_color_inside
background_color_subplot
bottom_margin
camera
clims
color_palette
colorbar
colorbar_continuous_values
colorbar_discrete_values
colorbar_fontfamily
colorbar_formatter
colorbar_scale
colorbar_tickfontcolor
colorbar_tickfontfamily
colorbar_tickfonthalign
colorbar_tickfontrotation
colorbar_tickfontsize
colorbar_tickfontvalign
colorbar_ticks
colorbar_title
colorbar_title_location
colorbar_titlefont
colorbar_titlefontcolor
colorbar_titlefontfamily
colorbar_titlefonthalign
colorbar_titlefontrotation
colorbar_titlefontsize
colorbar_titlefontvalign
extra_kwargs
fontfamily_subplot
foreground_color_subplot
foreground_color_title
framestyle
left_margin
legend_background_color
legend_column
legend_font
legend_font_color
legend_font_family
legend_font_halign
legend_font_pointsize
legend_font_rotation
legend_font_valign
legend_foreground_color
legend_position
legend_title
legend_title_font
legend_title_font_color
legend_title_font_family
legend_title_font_halign
legend_title_font_pointsize
legend_title_font_rotation
legend_title_font_valign
margin
plot_title_font
projection
projection_type
right_margin
subplot_index
title
title_font
titlefontcolor
titlefontfamily
titlefonthalign
titlefontrotation
titlefontsize
titlefontvalign
titlelocation
top_margin
Plot attributes
background_color
background_color_outside
display_type
dpi
extra_kwargs
extra_plot_kwargs
fontfamily
foreground_color
html_output_format
inset_subplots
layout
link
overwrite_figure
plot_title
plot_titlefontcolor
plot_titlefontfamily
plot_titlefonthalign
plot_titlefontrotation
plot_titlefontsize
plot_titlefontvalign
plot_titleindex
plot_titlelocation
plot_titlevspan
pos
show
size
tex_output_standalone
thickness_scaling
warn_on_unsupported
window_title
Extract a subplot from an existing plot.
Examples
julia> p1, p2 = plot(1:2), plot(10:20)
julia> pl = plot(p1, p2) # plot containing 2 subplots
julia> plot(pl.subplots[1]) # extract 1st subplot as a standalone plot
julia> plot(pl.subplots[2]) # extract 2nd subplot as a standalone plotplot(
sol::CTModels.Solutions.Solution,
description::Symbol...;
kwargs...
) -> AnyPlot the components of an optimal control CTModels.Solution.
Generates a set of subplots showing the state, control, costate, path constraints and dual variables over time, depending on the problem and the given description.
Arguments
sol: the optimal control solution to visualise.description: symbols selecting which groups to include; any of:state,:costate,:control,:path(path constraints),:dual(their multipliers). If none is given, a default set is used based on the problem.
Keyword arguments
layout::Symbol = :split::split(one subplot per component) or:group(group each signal into a single subplot with a legend).control::Symbol = :components::components(a curve per control component),:norm(the Euclidean norm‖u(t)‖) or:all(both).time::Symbol = :default::default(real time) or:normalize/:normalise([0, 1]).color: colour applied to every curve.size: figure size; defaults to a heuristic based on the layout.
Style options
Each *_style keyword is a NamedTuple of plotting attributes, or :none to hide the group/decoration: state_style, costate_style, control_style, path_style, dual_style, time_style (initial/final time markers), and the bounds decorations state_bounds_style, control_bounds_style, path_bounds_style.
Returns
A Plots.Plot. All layout and rendering is delegated to CTBase.Plotting.
Example
julia> plot(sol)
julia> plot(sol, :state, :control; layout=:group, control=:all)
julia> plot(sol; state_style=(color=:blue,), costate_style=:none)RecipesBase.plot! Function
plot!(
p::Plots.Plot,
sol::CTModels.Solutions.Solution,
description::Symbol...;
kwargs...
) -> Plots.PlotOverlay the optimal control solution sol onto the existing plot p. Same behaviour and keyword arguments as Plots.plot(::CTModels.Solution); an empty p is filled as if by plot.
plot!(
sol::CTModels.Solutions.Solution,
description::Symbol...;
kwargs...
) -> Plots.PlotOverlay the optimal control solution sol onto the current plot (Plots.current()).
CTModels.Serialization.export_ocp_solution Function
export_ocp_solution(
sol::CTModels.Solutions.AbstractSolution;
format,
filename
)Export an optimal control solution to a file.
Arguments
sol::AbstractSolution: The solution to export.
Keyword Arguments
format::Symbol=:JLD: Export format, either:JLDor:JSON.filename::String="solution": Base filename (extension added automatically).
Returns
Nothing: This function writes to a file and returns nothing.
Notes
Requires loading the appropriate package (JLD2 or JSON3) before use.
See also: CTModels.Serialization.import_ocp_solution.
export_ocp_solution(
::CTModels.Serialization.JSON3Tag,
sol::CTModels.Solutions.Solution;
filename
)Export an optimal control solution to a .json file using the JSON3 format.
This function serializes a CTModels.Solution into a structured JSON dictionary, including all primal and dual information, which can be read by external tools.
Arguments
::CTModels.JSON3Tag: A tag used to dispatch the export method for JSON3.sol::CTModels.Solution: The solution to be saved.
Keyword Arguments
filename::String = "solution": Base filename. The.jsonextension is automatically appended.
Notes
The exported JSON includes the time grid, state, control, costate, objective, solver info, and all constraint duals (if available).
Example
julia> using JSON3, CTModels
julia> CTModels.export_ocp_solution(CTModels.JSON3Tag(), sol; filename="mysolution")
# → creates "mysolution.json"export_ocp_solution(
::CTModels.Serialization.JLD2Tag,
sol::CTModels.Solutions.Solution;
filename
)Export an optimal control solution to a .jld2 file using the JLD2 format.
This function serializes and saves a CTModels.Solution object to disk, allowing it to be reloaded later. The solution is discretized to avoid serialization warnings for function objects.
Arguments
::CTModels.JLD2Tag: A tag used to dispatch the export method for JLD2.sol::CTModels.Solution: The optimal control solution to be saved.
Keyword Arguments
filename::String = "solution": Base name of the file. The.jld2extension is automatically appended.
Example
julia> using JLD2, CTModels
julia> CTModels.export_ocp_solution(CTModels.JLD2Tag(), sol; filename="mysolution")
# → creates "mysolution.jld2"Notes
Functions are discretized on the time grid to avoid JLD2 serialization warnings
The solution can be perfectly reconstructed via
import_ocp_solutionUses the same discretization logic as JSON export for consistency
CTModels.Serialization.import_ocp_solution Function
import_ocp_solution(
ocp::CTModels.Models.AbstractModel;
format,
filename
) -> CTModels.Solutions.Solution{TimeGridModelType, TimesModelType, StateModelType, ControlModelType, VariableModelType, ModelType, CostateModelType, Float64, DualModelType, CTModels.Solutions.SolverInfos{Any, Dict{Symbol, Any}}} where {TimeGridModelType<:Union{CTModels.Solutions.MultipleTimeGridModel, CTModels.Solutions.UnifiedTimeGridModel{Vector{Float64}}}, TimesModelType<:CTModels.Components.TimesModel, StateModelType<:(CTModels.Components.StateModelSolution{TS} where TS<:CTModels.Components.CoercedTrajectory), ControlModelType<:(CTModels.Components.ControlModelSolution{TS} where TS<:CTModels.Components.CoercedTrajectory), VariableModelType<:Union{CTModels.Components.VariableModelSolution{Vector{Float64}}, CTModels.Components.VariableModelSolution{Float64}}, ModelType<:(CTModels.Models.Model{<:CTBase.Traits.TimeDependence, T} where T<:CTModels.Components.TimesModel), CostateModelType<:CTModels.Components.CoercedTrajectory, DualModelType<:Union{CTModels.Solutions.EmptyDualModel, CTModels.Solutions.DualModel{PC_Dual, BC_Dual, SC_LB_Dual, SC_UB_Dual, CC_LB_Dual, CC_UB_Dual, VC_LB_Dual, VC_UB_Dual} where {PC_Dual<:Union{Nothing, CTModels.Components.CoercedTrajectory}, BC_Dual<:Union{Nothing, Vector{Float64}}, SC_LB_Dual<:Union{Nothing, CTModels.Components.CoercedTrajectory}, SC_UB_Dual<:Union{Nothing, CTModels.Components.CoercedTrajectory}, CC_LB_Dual<:Union{Nothing, CTModels.Components.CoercedTrajectory}, CC_UB_Dual<:Union{Nothing, CTModels.Components.CoercedTrajectory}, VC_LB_Dual<:Union{Nothing, Vector{Float64}}, VC_UB_Dual<:Union{Nothing, Vector{Float64}}}}}Import an optimal control solution from a file.
Arguments
ocp::AbstractModel: The model associated with the solution.
Keyword Arguments
format::Symbol=:JLD: Import format, either:JLDor:JSON.filename::String="solution": Base filename (extension added automatically).
Returns
Solution: The imported solution.
Notes
Requires loading the appropriate package (JLD2 or JSON3) before use.
See also: CTModels.Serialization.export_ocp_solution.
import_ocp_solution(
::CTModels.Serialization.JSON3Tag,
ocp::CTModels.Models.Model;
filename
)Import an optimal control solution from a .json file exported with export_ocp_solution.
This function reads the JSON contents and reconstructs a CTModels.Solution object, including the discretized primal and dual trajectories.
Arguments
::CTModels.JSON3Tag: A tag used to dispatch the import method for JSON3.ocp::CTModels.Model: The model associated with the optimal control problem. Used to rebuild the full solution.
Keyword Arguments
filename::String = "solution": Base filename. The.jsonextension is automatically appended.
Returns
CTModels.Solution: A reconstructed solution instance.
Notes
Handles both vector and matrix encodings of signals. If dual fields are missing or null, the corresponding attributes are set to nothing.
Example
julia> using JSON3, CTModels
julia> sol = CTModels.import_ocp_solution(CTModels.JSON3Tag(), model; filename="mysolution")import_ocp_solution(
::CTModels.Serialization.JLD2Tag,
ocp::CTModels.Models.Model;
filename
)Import an optimal control solution from a .jld2 file.
This function loads a previously saved CTModels.Solution from disk and reconstructs it using build_solution from the discretized data.
Arguments
::CTModels.JLD2Tag: A tag used to dispatch the import method for JLD2.ocp::CTModels.Model: The associated optimal control problem model.
Keyword Arguments
filename::String = "solution": Base name of the file. The.jld2extension is automatically appended.
Returns
CTModels.Solution: The reconstructed solution object.
Example
julia> using JLD2, CTModels
julia> sol = CTModels.import_ocp_solution(CTModels.JLD2Tag(), model; filename="mysolution")Notes
The solution is reconstructed from discretized data via
build_solutionThis ensures perfect round-trip consistency with the export
The OCP model from the file is used if the provided one is not compatible