src/fb.rs

Mon, 17 Feb 2025 14:10:52 -0500

author
Tuomo Valkonen <tuomov@iki.fi>
date
Mon, 17 Feb 2025 14:10:52 -0500
changeset 54
b3312eee105c
parent 51
0693cc9ba9f0
permissions
-rw-r--r--

Make some math in documentation render

/*!
Solver for the point source localisation problem using a forward-backward splitting method.

This corresponds to the manuscript

 * Valkonen T. - _Proximal methods for point source localisation_,
   [arXiv:2212.02991](https://arxiv.org/abs/2212.02991).

The main routine is [`pointsource_fb_reg`].

## Problem

<p>
Our objective is to solve
$$
    \min_{μ ∈ ℳ(Ω)}~ F_0(Aμ-b) + α \|μ\|_{ℳ(Ω)} + δ_{≥ 0}(μ),
$$
where $F_0(y)=\frac{1}{2}\|y\|_2^2$ and the forward operator $A \in 𝕃(ℳ(Ω); ℝ^n)$.
</p>

## Approach

<p>
As documented in more detail in the paper, on each step we approximately solve
$$
    \min_{μ ∈ ℳ(Ω)}~ F(x) + α \|μ\|_{ℳ(Ω)} + δ_{≥ 0}(x) + \frac{1}{2}\|μ-μ^k|_𝒟^2,
$$
where $𝒟: 𝕃(ℳ(Ω); C_c(Ω))$ is typically a convolution operator.
</p>

## Finite-dimensional subproblems.

With $C$ a projection from [`DiscreteMeasure`] to the weights, and $x^k$ such that $x^k=Cμ^k$, we
form the discretised linearised inner problem
<p>
$$
    \min_{x ∈ ℝ^n}~ τ\bigl(F(Cx^k) + [C^*∇F(Cx^k)]^⊤(x-x^k) + α {\vec 1}^⊤ x\bigr)
                    + δ_{≥ 0}(x) + \frac{1}{2}\|x-x^k\|_{C^*𝒟C}^2,
$$
equivalently
$$
    \begin{aligned}
    \min_x~ & τF(Cx^k) - τ[C^*∇F(Cx^k)]^⊤x^k + \frac{1}{2} (x^k)^⊤ C^*𝒟C x^k
            \\
            &
            - [C^*𝒟C x^k - τC^*∇F(Cx^k)]^⊤ x
            \\
            &
            + \frac{1}{2} x^⊤ C^*𝒟C x
            + τα {\vec 1}^⊤ x + δ_{≥ 0}(x),
    \end{aligned}
$$
In other words, we obtain the quadratic non-negativity constrained problem
$$
    \min_{x ∈ ℝ^n}~ \frac{1}{2} x^⊤ Ã x - b̃^⊤ x + c + τα {\vec 1}^⊤ x + δ_{≥ 0}(x).
$$
where
$$
   \begin{aligned}
    Ã & = C^*𝒟C,
    \\
    g̃ & = C^*𝒟C x^k - τ C^*∇F(Cx^k)
        = C^* 𝒟 μ^k - τ C^*A^*(Aμ^k - b)
    \\
    c & = τ F(Cx^k) - τ[C^*∇F(Cx^k)]^⊤x^k + \frac{1}{2} (x^k)^⊤ C^*𝒟C x^k
        \\
        &
        = \frac{τ}{2} \|Aμ^k-b\|^2 - τ[Aμ^k-b]^⊤Aμ^k + \frac{1}{2} \|μ_k\|_{𝒟}^2
        \\
        &
        = -\frac{τ}{2} \|Aμ^k-b\|^2 + τ[Aμ^k-b]^⊤ b + \frac{1}{2} \|μ_k\|_{𝒟}^2.
   \end{aligned}
$$
</p>

We solve this with either SSN or FB as determined by
[`crate::subproblem::InnerSettings`] in [`FBGenericConfig::inner`].
*/

use colored::Colorize;
use numeric_literals::replace_float_literals;
use serde::{Deserialize, Serialize};

use alg_tools::euclidean::Euclidean;
use alg_tools::instance::Instance;
use alg_tools::iterate::AlgIteratorFactory;
use alg_tools::linops::{Mapping, GEMV};
use alg_tools::mapping::RealMapping;
use alg_tools::nalgebra_support::ToNalgebraRealField;

use crate::dataterm::{calculate_residual, DataTerm, L2Squared};
use crate::forward_model::{AdjointProductBoundedBy, ForwardModel};
use crate::measures::merging::SpikeMerging;
use crate::measures::{DiscreteMeasure, RNDM};
use crate::plot::{PlotLookup, Plotting, SeqPlotter};
pub use crate::prox_penalty::{FBGenericConfig, ProxPenalty};
use crate::regularisation::RegTerm;
use crate::types::*;

/// Settings for [`pointsource_fb_reg`].
#[derive(Clone, Copy, Eq, PartialEq, Serialize, Deserialize, Debug)]
#[serde(default)]
pub struct FBConfig<F: Float> {
    /// Step length scaling
    pub τ0: F,
    /// Generic parameters
    pub generic: FBGenericConfig<F>,
}

#[replace_float_literals(F::cast_from(literal))]
impl<F: Float> Default for FBConfig<F> {
    fn default() -> Self {
        FBConfig {
            τ0: 0.99,
            generic: Default::default(),
        }
    }
}

pub(crate) fn prune_with_stats<F: Float, const N: usize>(μ: &mut RNDM<F, N>) -> usize {
    let n_before_prune = μ.len();
    μ.prune();
    debug_assert!(μ.len() <= n_before_prune);
    n_before_prune - μ.len()
}

#[replace_float_literals(F::cast_from(literal))]
pub(crate) fn postprocess<
    F: Float,
    V: Euclidean<F> + Clone,
    A: GEMV<F, RNDM<F, N>, Codomain = V>,
    D: DataTerm<F, V, N>,
    const N: usize,
>(
    mut μ: RNDM<F, N>,
    config: &FBGenericConfig<F>,
    dataterm: D,
    opA: &A,
    b: &V,
) -> RNDM<F, N>
where
    RNDM<F, N>: SpikeMerging<F>,
    for<'a> &'a RNDM<F, N>: Instance<RNDM<F, N>>,
{
    μ.merge_spikes_fitness(
        config.final_merging_method(),
        |μ̃| dataterm.calculate_fit_op(μ̃, opA, b),
        |&v| v,
    );
    μ.prune();
    μ
}

/// Iteratively solve the pointsource localisation problem using forward-backward splitting.
///
/// The settings in `config` have their [respective documentation](FBConfig). `opA` is the
/// forward operator $A$, $b$ the observable, and $\lambda$ the regularisation weight.
/// The operator `op𝒟` is used for forming the proximal term. Typically it is a convolution
/// operator. Finally, the `iterator` is an outer loop verbosity and iteration count control
/// as documented in [`alg_tools::iterate`].
///
/// For details on the mathematical formulation, see the [module level](self) documentation.
///
/// The implementation relies on [`alg_tools::bisection_tree::BTFN`] presentations of
/// sums of simple functions usign bisection trees, and the related
/// [`alg_tools::bisection_tree::Aggregator`]s, to efficiently search for component functions
/// active at a specific points, and to maximise their sums. Through the implementation of the
/// [`alg_tools::bisection_tree::BT`] bisection trees, it also relies on the copy-on-write features
/// of [`std::sync::Arc`] to only update relevant parts of the bisection tree when adding functions.
///
/// Returns the final iterate.
#[replace_float_literals(F::cast_from(literal))]
pub fn pointsource_fb_reg<F, I, A, Reg, P, const N: usize>(
    opA: &A,
    b: &A::Observable,
    reg: Reg,
    prox_penalty: &P,
    fbconfig: &FBConfig<F>,
    iterator: I,
    mut plotter: SeqPlotter<F, N>,
) -> RNDM<F, N>
where
    F: Float + ToNalgebraRealField,
    I: AlgIteratorFactory<IterInfo<F, N>>,
    for<'b> &'b A::Observable: std::ops::Neg<Output = A::Observable>,
    A: ForwardModel<RNDM<F, N>, F> + AdjointProductBoundedBy<RNDM<F, N>, P, FloatType = F>,
    A::PreadjointCodomain: RealMapping<F, N>,
    PlotLookup: Plotting<N>,
    RNDM<F, N>: SpikeMerging<F>,
    Reg: RegTerm<F, N>,
    P: ProxPenalty<F, A::PreadjointCodomain, Reg, N>,
{
    // Set up parameters
    let config = &fbconfig.generic;
    let τ = fbconfig.τ0 / opA.adjoint_product_bound(prox_penalty).unwrap();
    // We multiply tolerance by τ for FB since our subproblems depending on tolerances are scaled
    // by τ compared to the conditional gradient approach.
    let tolerance = config.tolerance * τ * reg.tolerance_scaling();
    let mut ε = tolerance.initial();

    // Initialise iterates
    let mut μ = DiscreteMeasure::new();
    let mut residual = -b;

    // Statistics
    let full_stats = |residual: &A::Observable, μ: &RNDM<F, N>, ε, stats| IterInfo {
        value: residual.norm2_squared_div2() + reg.apply(μ),
        n_spikes: μ.len(),
        ε,
        //postprocessing: config.postprocessing.then(|| μ.clone()),
        ..stats
    };
    let mut stats = IterInfo::new();

    // Run the algorithm
    for state in iterator.iter_init(|| full_stats(&residual, &μ, ε, stats.clone())) {
        // Calculate smooth part of surrogate model.
        let mut τv = opA.preadjoint().apply(residual * τ);

        // Save current base point
        let μ_base = μ.clone();

        // Insert and reweigh
        let (maybe_d, _within_tolerances) = prox_penalty.insert_and_reweigh(
            &mut μ, &mut τv, &μ_base, None, τ, ε, config, &reg, &state, &mut stats,
        );

        // Prune and possibly merge spikes
        if config.merge_now(&state) {
            stats.merged += prox_penalty.merge_spikes(
                &mut μ,
                &mut τv,
                &μ_base,
                None,
                τ,
                ε,
                config,
                &reg,
                Some(|μ̃: &RNDM<F, N>| L2Squared.calculate_fit_op(μ̃, opA, b)),
            );
        }

        stats.pruned += prune_with_stats(&mut μ);

        // Update residual
        residual = calculate_residual(&μ, opA, b);

        let iter = state.iteration();
        stats.this_iters += 1;

        // Give statistics if needed
        state.if_verbose(|| {
            plotter.plot_spikes(iter, maybe_d.as_ref(), Some(&τv), &μ);
            full_stats(
                &residual,
                &μ,
                ε,
                std::mem::replace(&mut stats, IterInfo::new()),
            )
        });

        // Update main tolerance for next iteration
        ε = tolerance.update(ε, iter);
    }

    postprocess(μ, config, L2Squared, opA, b)
}

/// Iteratively solve the pointsource localisation problem using inertial forward-backward splitting.
///
/// The settings in `config` have their [respective documentation](FBConfig). `opA` is the
/// forward operator $A$, $b$ the observable, and $\lambda$ the regularisation weight.
/// The operator `op𝒟` is used for forming the proximal term. Typically it is a convolution
/// operator. Finally, the `iterator` is an outer loop verbosity and iteration count control
/// as documented in [`alg_tools::iterate`].
///
/// For details on the mathematical formulation, see the [module level](self) documentation.
///
/// The implementation relies on [`alg_tools::bisection_tree::BTFN`] presentations of
/// sums of simple functions usign bisection trees, and the related
/// [`alg_tools::bisection_tree::Aggregator`]s, to efficiently search for component functions
/// active at a specific points, and to maximise their sums. Through the implementation of the
/// [`alg_tools::bisection_tree::BT`] bisection trees, it also relies on the copy-on-write features
/// of [`std::sync::Arc`] to only update relevant parts of the bisection tree when adding functions.
///
/// Returns the final iterate.
#[replace_float_literals(F::cast_from(literal))]
pub fn pointsource_fista_reg<F, I, A, Reg, P, const N: usize>(
    opA: &A,
    b: &A::Observable,
    reg: Reg,
    prox_penalty: &P,
    fbconfig: &FBConfig<F>,
    iterator: I,
    mut plotter: SeqPlotter<F, N>,
) -> RNDM<F, N>
where
    F: Float + ToNalgebraRealField,
    I: AlgIteratorFactory<IterInfo<F, N>>,
    for<'b> &'b A::Observable: std::ops::Neg<Output = A::Observable>,
    A: ForwardModel<RNDM<F, N>, F> + AdjointProductBoundedBy<RNDM<F, N>, P, FloatType = F>,
    A::PreadjointCodomain: RealMapping<F, N>,
    PlotLookup: Plotting<N>,
    RNDM<F, N>: SpikeMerging<F>,
    Reg: RegTerm<F, N>,
    P: ProxPenalty<F, A::PreadjointCodomain, Reg, N>,
{
    // Set up parameters
    let config = &fbconfig.generic;
    let τ = fbconfig.τ0 / opA.adjoint_product_bound(prox_penalty).unwrap();
    let mut λ = 1.0;
    // We multiply tolerance by τ for FB since our subproblems depending on tolerances are scaled
    // by τ compared to the conditional gradient approach.
    let tolerance = config.tolerance * τ * reg.tolerance_scaling();
    let mut ε = tolerance.initial();

    // Initialise iterates
    let mut μ = DiscreteMeasure::new();
    let mut μ_prev = DiscreteMeasure::new();
    let mut residual = -b;
    let mut warned_merging = false;

    // Statistics
    let full_stats = |ν: &RNDM<F, N>, ε, stats| IterInfo {
        value: L2Squared.calculate_fit_op(ν, opA, b) + reg.apply(ν),
        n_spikes: ν.len(),
        ε,
        // postprocessing: config.postprocessing.then(|| ν.clone()),
        ..stats
    };
    let mut stats = IterInfo::new();

    // Run the algorithm
    for state in iterator.iter_init(|| full_stats(&μ, ε, stats.clone())) {
        // Calculate smooth part of surrogate model.
        let mut τv = opA.preadjoint().apply(residual * τ);

        // Save current base point
        let μ_base = μ.clone();

        // Insert new spikes and reweigh
        let (maybe_d, _within_tolerances) = prox_penalty.insert_and_reweigh(
            &mut μ, &mut τv, &μ_base, None, τ, ε, config, &reg, &state, &mut stats,
        );

        // (Do not) merge spikes.
        if config.merge_now(&state) && !warned_merging {
            let err = format!("Merging not supported for μFISTA");
            println!("{}", err.red());
            warned_merging = true;
        }

        // Update inertial prameters
        let λ_prev = λ;
        λ = 2.0 * λ_prev / (λ_prev + (4.0 + λ_prev * λ_prev).sqrt());
        let θ = λ / λ_prev - λ;

        // Perform inertial update on μ.
        // This computes μ ← (1 + θ) * μ - θ * μ_prev, pruning spikes where both μ
        // and μ_prev have zero weight. Since both have weights from the finite-dimensional
        // subproblem with a proximal projection step, this is likely to happen when the
        // spike is not needed. A copy of the pruned μ without artithmetic performed is
        // stored in μ_prev.
        let n_before_prune = μ.len();
        μ.pruning_sub(1.0 + θ, θ, &mut μ_prev);
        //let μ_new = (&μ * (1.0 + θ)).sub_matching(&(&μ_prev * θ));
        // μ_prev = μ;
        // μ = μ_new;
        debug_assert!(μ.len() <= n_before_prune);
        stats.pruned += n_before_prune - μ.len();

        // Update residual
        residual = calculate_residual(&μ, opA, b);

        let iter = state.iteration();
        stats.this_iters += 1;

        // Give statistics if needed
        state.if_verbose(|| {
            plotter.plot_spikes(iter, maybe_d.as_ref(), Some(&τv), &μ_prev);
            full_stats(&μ_prev, ε, std::mem::replace(&mut stats, IterInfo::new()))
        });

        // Update main tolerance for next iteration
        ε = tolerance.update(ε, iter);
    }

    postprocess(μ_prev, config, L2Squared, opA, b)
}

mercurial