Reference

Contents

Index

    Mica.DifferenceModelSpecType

    Specification 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).
    source
    Mica.ModelManagerType

    ModelManager{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.

    source
    Mica.ODEModelSpecType

    Specification 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.
    source
    Mica.RegressionModelSpecType

    Specification 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.
    source
    Mica.call_penalty_fnMethod
    call_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 parameters
    • n: total data length
    • CP: vector of change points
    • segment_lengths: vector of segment lengths (computed as diff([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 by methods(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.

    source
    Mica.detect_changepointsFunction
    detect_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
    source
    Mica.evaluate_segmentMethod
    evaluate_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.

    source
    Mica.example_difference_modelMethod

    Example: 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.
    source
    Mica.example_regression_modelMethod

    Example: 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.
    source
    Mica.exponential_ode_modelMethod

    Example: 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.
    source
    Mica.extract_parametersMethod
    extract_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)
    source
    Mica.get_initial_conditionMethod

    get_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).
    source
    Mica.get_model_typeMethod

    get_model_type(manager::ModelManager) -> String

    Returns a string identifier for the model type: "ODE", "Difference", or "Regression". Useful for logging or conditional logic.

    source
    Mica.objective_functionMethod
    objective_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 of ModelManager, 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 using loss_function.
    • data: The full observed data (e.g., vector, matrix, or tuple of vectors).

    Returns

    • Total loss across all segments.
    source
    Mica.optimize_with_changepointsMethod
    optimize_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.

    source
    Mica.plot_parameter_changesFunction
    plot_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 of params).
    • 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)
    source
    Mica.segment_modelMethod

    segment_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 names parnames
    • 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.

    source
    Mica.simulate_full_modelMethod
    simulate_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. If nothing, 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 (from data) where available.
    • data_indices::Union{Nothing,Vector{Int}}=nothing: Row indices mapping data to model compartments. For example, [5,6,7] means rows 1–3 of data 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])
    
    source
    Mica.simulate_modelMethod

    Simulates a DifferenceModelSpec by iterating the discrete equation.

    Arguments

    • model::DifferenceModelSpec: A Difference model specification.

    Returns

    • Simulated results over discrete time steps.
    source
    Mica.simulate_modelMethod

    Simulates an ODEModelSpec by solving the ODE system.

    Arguments

    • model::ODEModelSpec: An ODE model specification.

    Returns

    • Simulated results over time.
    source
    Mica.simulate_modelMethod

    Simulates a RegressionModelSpec by evaluating the regression model.

    Arguments

    • model::RegressionModelSpec: A Regression model specification.

    Returns

    • Simulated outputs.
    source
    Mica.update_bounds!Method
    update_bounds!(chromosome, bounds, n_global, n_segment_specific, extract_parameters)

    Update bounds and chromosome by appending segment-specific parameters.

    source
    Mica.update_initial_conditionMethod

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

    source