Reference
Contents
Index
Mica.AbstractModelSpec
— TypeAbstract base type for all model specifications.
Mica.DifferenceModelSpec
— TypeSpecification for a discrete Difference Equation model.
Fields
model_function::Function
: A function that defines the difference dynamics.params::Dict{Symbol, Any}
: Parameters needed for the model.initial_conditions::Float64
: Initial state of the system.num_steps::Int
: Number of time steps for the simulation.extra_data::Tuple{Vector{Float64}, Vector{Float64}}
: Additional inputs (e.g., external variables).
Mica.ModelManager
— TypeModelManager{T<:AbstractModelSpec}
A wrapper around any model specification (ODE, Difference, or Regression) that provides a unified interface to:
- Access the initial condition
- Segment model-specific data for a given intervalyes
- Generate per-segment models with updated parameters
- Identify the model type for dispatching logic
This allows the objective function and other algorithms to remain model-agnostic.
Mica.ODEModelSpec
— TypeSpecification for an ODE (Ordinary Differential Equation) model.
Fields
model_function::Function
: A function that defines the ODE dynamics.params::Dict{Symbol, Any}
: Parameters needed for the model.initial_conditions::Vector{Float64}
: Initial conditions for the ODE system.tspan::Tuple{Float64, Float64}
: Time span over which to simulate the model.
Mica.RegressionModelSpec
— TypeSpecification for a simple Regression model (e.g., linear).
Fields
model_function::Function
: A function that defines the regression output.params::Dict{Symbol, Any}
: Parameters needed for the model.time_steps::Int
: Number of time steps or observations.
Mica.BIC_penalty
— MethodBIC_penalty(p, n)
Bayesian Information Criterion-style penalty.
Mica.call_penalty_fn
— Methodcall_penalty_fn(f::Function; kwargs...) -> Real
Safely call a user-provided penalty function f
with only the arguments it accepts, using the last defined method of fn
.
This allows users to define custom penalty functions that take any subset of the following:
p
: number of segment-specific parametersn
: total data lengthCP
: vector of change pointssegment_lengths
: vector of segment lengths (computed asdiff([0; CP; n])
)num_segments
: number of segments (length(CP) + 1
)
Important Note
Due to Julia's multiple dispatch behavior, defining multiple methods for the same function name accumulates methods rather than replacing them. This means:
call_penalty_fn
uses the last method returned bymethods(fn)
.- To test different penalty functions, use different function names (e.g.,
my_penalty1
,my_penalty2
,my_penalty3
) to avoid ambiguity.
Examples
```julia my_penalty(p, n) = 2 * p * log(n)
callpenaltyfn(mypenalty; p=3, n=250, CP=[50, 100], segmentlengths=[50, 50, 150], num_segments=3 )
=> 33.21
More complex example: function imbalancepenalty(p, n, CP) seglengths = diff([0; CP; n]) imbalance = std(seg_lengths) return 3.3 * p * length(CP) * log(n) + 0.12 * imbalance end
callpenaltyfn(imbalancepenalty; p=3, n=250, CP=[60, 130], segmentlengths=[60, 70, 120], num_segments=3 ) If the user omits some arguments, only those required by their function are passed.
Mica.default_penalty
— Methoddefault_penalty(p, n)
A basic penalty proportional to BIC.
Mica.detect_changepoints
— Functiondetect_changepoints(
objective_function, n, n_global, n_segment_specific, parnames,
model_manager, loss_function, data,
initial_chromosome, bounds, ga, min_length, step; pen=log(n)
)
Detect optimal change points using a greedy search strategy and regularized loss.
Returns:
- Vector of change point indices (CP)
- Best parameter vector found
Mica.evaluate_segment
— Methodevaluate_segment(...)
Evaluate candidate change points in a segment [a, b] by inserting change points and computing the new loss for each.
Returns a tuple of loss values and corresponding best chromosomes.
Mica.example_difference_model
— MethodExample: Discrete difference equation model.
Simulates a difference equation influenced by external variables.
Arguments
params::Dict
: Model parameters.initial_conditions::Float64
: Initial state.num_steps::Int
: Number of steps.extra_data::Tuple
: (windspeeds, ambienttemperatures).
Returns
DataFrame
: Time and state variable evolution.
Mica.example_regression_model
— MethodExample: Simple linear regression model.
Simulates a linear trend y = a * t + b
.
Arguments
params::Dict
: Model parameters, expects:a
and:b
.time_steps::Int
: Number of time steps.
Returns
DataFrame
: Time and simulated values.
Mica.exponential_ode_model
— MethodExample: Simple exponential decay ODE model.
Defines the dynamics du/dt = -p * u
.
Arguments
params::Dict
: Model parameters, expects key:p
.tspan::Tuple
: (starttime, endtime).u0::Vector{Float64}
: Initial condition vector.
Returns
Matrix
: state variable evolution.
Mica.extract_parameters
— Methodextract_parameters(chromosome, n_global, n_segment_specific)
Splits a chromosome vector into global and segment-specific parameters.
Arguments
chromosome
: Flat vector of all parameters.n_global
: Number of global parameters.n_segment_specific
: Number of segment parameters for each segment.
Returns
(global_parameters, segment_parameters)
Mica.get_initial_condition
— Methodget_initial_condition(manager::ModelManager) -> Any
Returns the initial condition used by the model. For:
- ODE models: returns the vector of initial states.
- Difference models: returns the scalar initial value.
- Regression models: returns
nothing
(no initial condition concept).
Mica.get_model_type
— Methodget_model_type(manager::ModelManager) -> String
Returns a string identifier for the model type: "ODE", "Difference", or "Regression". Useful for logging or conditional logic.
Mica.objective_function
— Methodobjective_function(...)
Computes the total loss for the current chromosome, simulating each segment separately.
Arguments
chromosome
: The vector of model parameters (includes global and segment-specific).change_points
: Vector of indices defining segmentation boundaries.n_global
: Number of global parameters.n_segment_specific
: Number of parameters specific to each segment.extract_parameters
: A function that extracts global and per-segment parameters from the chromosome.parnames
: Names of the model parameters (used to construct LArray or Dict).model_manager
: An instance ofModelManager
, holding model type and base config.simulate_model
: A function to simulate the model (multi-dispatch on model type).loss_function
: Loss function applied to a single segment.segment_loss
: Function that computes the loss given true vs simulated data usingloss_function
.data
: The full observed data (e.g., vector, matrix, or tuple of vectors).
Returns
- Total loss across all segments.
Mica.optimize_with_changepoints
— Methodoptimize_with_changepoints(
objective_function, chromosome, CP, bounds, ga,
n_global, n_segment_specific, parnames,
model_manager, loss_function, data; options=...
)
Optimize model parameters for a fixed set of change points using Evolutionary.jl.
Returns the minimum loss and the best parameter set.
Mica.plot_parameter_changes
— Functionplot_parameter_changes(params, param_labels, change_points,
base_date, end_date;
n_segment_specific, n_global, color=:blues)
Visualize relative changes of segment-specific parameters compared to the first segment, using heatmaps stacked vertically.
Arguments
params::Vector{Float64}
: Flattened parameter vector from optimization.param_labels::Vector{String}
: Human-readable labels for each parameter (e.g."β (Infection rate)"
).change_points::Vector{Date}
: Detected change point dates.base_date::Date
: Start date of the first segment.end_date::Date
: End date of the last segment.
Keyword Arguments
n_segment_specific::Int
: Number of segment-specific parameters per segment.n_global::Int
: Number of global parameters (to skip over at the start ofparams
).color=:blues
: Colormap for the heatmaps.
Returns
Plots.Plot
: A composite plot object with one heatmap per parameter.
Details
- Each row corresponds to one parameter, and columns correspond to segments.
- Parameter values are normalized relative to the first segment (
data_rel = data ./ data[:,1]
). - X-axis ticks mark change points, labeled as
"cp1"
,"cp2"
, …, plus start and end dates. - Colorbar ranges are adjusted per parameter, and only the last subplot includes the legend.
Examples
param_labels = ["p₁
(Detection rate)", "β
(Infection rate)",
"p₁₂
(Hospitalization rate)", "p₂₃
(ICU admission rate)",
"p₁D
(Infection death rate)", "p₂D
(Hospital death rate)",
"p₃D
(ICU death rate)"]
p2 = plot_parameter_changes(params, param_labels,
cases_CP_date[detected_cp],
Date("2020-01-27"),
Date("2021-03-02")
n_global=8, n_segment_specific=8)
Mica.segment_model
— Methodsegment_model(manager, seg_pars, parnames, idx_start, idx_end, u0) -> AbstractModelSpec
Builds a new per-segment model specification using:
- The segment-specific parameters
seg_pars
and their namesparnames
- The index range
[idx_start:idx_end]
defining the segment - The initial condition
u0
passed from the last segment
Dispatches based on model type to slice and prepare data correctly.
Mica.simulate_full_model
— Methodsimulate_full_model(chromosome, change_points, parnames,
n_global, n_segment_specific,
model_manager, data;
plot_results=false,
compartments=nothing,
show_change_points=false,
show_data=false,
data_indices=nothing)
Simulate a model across multiple change-point segments and optionally visualize the results.
Arguments
chromosome::AbstractVector
: Flattened parameter vector containing both global and segment-specific parameters.change_points::Vector{Int}
: Detected change point positions (time indices).parnames
: Names of parameters (e.g.(:β, :γ, ...)
).n_global::Int
: Number of global parameters (shared across segments).n_segment_specific::Int
: Number of parameters that are specific to each segment.model_manager::ModelManager
: Wrapper managing the model type from ModelSimulation module and simulation setup.data::Matrix{Float64}
: Observed data matrix (rows = compartments, columns = time steps).
Keyword Arguments
plot_results::Bool=false
: Whether to generate plots of the simulation.compartments::Union{Nothing,Vector{String}}
: Subset of compartments to plot by name. Ifnothing
, all compartments are plotted.show_change_points::Bool=false
: If true, vertical dashed lines mark detected change points.show_data::Bool=false
: If true, overlays observed data (fromdata
) where available.data_indices::Union{Nothing,Vector{Int}}=nothing
: Row indices mappingdata
to model compartments. For example,[5,6,7]
means rows 1–3 ofdata
correspond to compartments 5,6,7.
Returns
Matrix{Float64}
: Simulation results with rows = compartments, columns = time steps concatenated across all segments.
Notes
- Simulation segments are concatenated with
hcat
, so time is continuous across change points. - If plotting is enabled, a grid of subplots is shown with
"Simulated"
,"Data"
, and"Change points"
in the legend.
Examples
detected_cp = CSV.read("examples/Covid-mode/results_detected_cp_penalty40_ts10_pop150.csv", DataFrame)[:,1]
params = CSV.read("examples/Covid-model/results_params_penalty40__ts10_pop150.csv", DataFrame)[:,1]
parnames = (:δ, :ᴺε₀, :ᴺε₁, :ᴺγ₀, :ᴺγ₁, :ᴺγ₂, :ᴺγ₃, :ω, :ᴺp₁, :ᴺβ,:ᴺp₁₂, :ᴺp₂₃, :ᴺp₁D, :ᴺp₂D, :ᴺp₃D, :ν)
u0 = [83129285-1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]
tspan = (0.0, 399.0)
ode_spec = ODEModelSpec(example_ode_model, initial_chromosome, u0, tspan)
model_manager = ModelManager(ode_spec)
n_global = 8
n_segment_specific = 8
# Simulate without plotting
sim = simulate_full_model(params, detected_cp, parnames,
n_global, n_segment_specific,
model_manager, data_CP)
# Simulate and plot all compartments with change points and data overlay
sim = simulate_full_model(params, detected_cp, parnames,
n_global, n_segment_specific,
model_manager, data_CP;
plot_results=true,
show_change_points=true,
show_data=true,
data_indices=[5, 6, 7, 9, 11])
Mica.simulate_model
— MethodSimulates a DifferenceModelSpec by iterating the discrete equation.
Arguments
model::DifferenceModelSpec
: A Difference model specification.
Returns
- Simulated results over discrete time steps.
Mica.simulate_model
— MethodSimulates an ODEModelSpec by solving the ODE system.
Arguments
model::ODEModelSpec
: An ODE model specification.
Returns
- Simulated results over time.
Mica.simulate_model
— MethodSimulates a RegressionModelSpec by evaluating the regression model.
Arguments
model::RegressionModelSpec
: A Regression model specification.
Returns
- Simulated outputs.
Mica.update_bounds!
— Methodupdate_bounds!(chromosome, bounds, n_global, n_segment_specific, extract_parameters)
Update bounds and chromosome by appending segment-specific parameters.
Mica.update_initial_condition
— Methodupdate_initial_condition(manager::ModelManager, sim_data::DataFrame)
Returns the updated initial condition for the next segment based on the output of the last segment's simulation.
Mica.wrapped_obj_function
— Methodwrapped_obj_function(chromosome)
Convenient closure to call objective_function
with fixed outer parameters.