Tue, 31 Dec 2024 09:25:45 -0500
New version of sliding.
| 0 | 1 | /*! |
| 2 | This module provides [`RunnableExperiment`] for running chosen algorithms on a chosen experiment. | |
| 3 | */ | |
| 4 | ||
| 5 | use numeric_literals::replace_float_literals; | |
| 6 | use colored::Colorize; | |
| 7 | use serde::{Serialize, Deserialize}; | |
| 8 | use serde_json; | |
| 9 | use nalgebra::base::DVector; | |
| 10 | use std::hash::Hash; | |
| 11 | use chrono::{DateTime, Utc}; | |
| 12 | use cpu_time::ProcessTime; | |
| 13 | use clap::ValueEnum; | |
| 14 | use std::collections::HashMap; | |
| 15 | use std::time::Instant; | |
| 16 | ||
| 17 | use rand::prelude::{ | |
| 18 | StdRng, | |
| 19 | SeedableRng | |
| 20 | }; | |
| 21 | use rand_distr::Distribution; | |
| 22 | ||
| 23 | use alg_tools::bisection_tree::*; | |
| 24 | use alg_tools::iterate::{ | |
| 25 | Timed, | |
| 26 | AlgIteratorOptions, | |
| 27 | Verbose, | |
| 28 | AlgIteratorFactory, | |
| 35 | 29 | LoggingIteratorFactory, |
| 30 | TimingIteratorFactory, | |
| 31 | BasicAlgIteratorFactory, | |
| 0 | 32 | }; |
| 33 | use alg_tools::logger::Logger; | |
| 35 | 34 | use alg_tools::error::{ |
| 35 | DynError, | |
| 36 | DynResult, | |
| 37 | }; | |
| 0 | 38 | use alg_tools::tabledump::TableDump; |
| 39 | use alg_tools::sets::Cube; | |
|
34
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
40 | use alg_tools::mapping::{ |
|
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
41 | RealMapping, |
| 35 | 42 | DifferentiableMapping, |
| 43 | DifferentiableRealMapping, | |
| 44 | Instance | |
|
34
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
45 | }; |
| 0 | 46 | use alg_tools::nalgebra_support::ToNalgebraRealField; |
| 47 | use alg_tools::euclidean::Euclidean; | |
| 35 | 48 | use alg_tools::lingrid::{lingrid, LinSpace}; |
| 0 | 49 | use alg_tools::sets::SetOrd; |
| 35 | 50 | use alg_tools::linops::{RowOp, IdOp /*, ZeroOp*/}; |
| 51 | use alg_tools::discrete_gradient::{Grad, ForwardNeumann}; | |
| 52 | use alg_tools::convex::Zero; | |
| 53 | use alg_tools::maputil::map3; | |
| 54 | use alg_tools::direct_product::Pair; | |
| 0 | 55 | |
| 56 | use crate::kernels::*; | |
| 57 | use crate::types::*; | |
| 58 | use crate::measures::*; | |
| 59 | use crate::measures::merging::SpikeMerging; | |
| 60 | use crate::forward_model::*; | |
| 35 | 61 | use crate::forward_model::sensor_grid::{ |
| 62 | SensorGrid, | |
| 63 | SensorGridBT, | |
| 64 | //SensorGridBTFN, | |
| 65 | Sensor, | |
| 66 | Spread, | |
| 67 | }; | |
| 68 | ||
| 0 | 69 | use crate::fb::{ |
| 70 | FBConfig, | |
| 32 | 71 | FBGenericConfig, |
|
24
d29d1fcf5423
Support arbitrary regularisation terms; implement non-positivity-constrained regularisation.
Tuomo Valkonen <tuomov@iki.fi>
parents:
23
diff
changeset
|
72 | pointsource_fb_reg, |
| 32 | 73 | pointsource_fista_reg, |
| 74 | }; | |
|
34
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
75 | use crate::radon_fb::{ |
|
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
76 | RadonFBConfig, |
|
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
77 | pointsource_radon_fb_reg, |
|
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
78 | pointsource_radon_fista_reg, |
|
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
79 | }; |
| 32 | 80 | use crate::sliding_fb::{ |
| 81 | SlidingFBConfig, | |
| 35 | 82 | TransportConfig, |
| 32 | 83 | pointsource_sliding_fb_reg |
| 0 | 84 | }; |
| 35 | 85 | use crate::sliding_pdps::{ |
| 86 | SlidingPDPSConfig, | |
| 87 | pointsource_sliding_pdps_pair | |
| 88 | }; | |
| 89 | use crate::forward_pdps::{ | |
| 90 | ForwardPDPSConfig, | |
| 91 | pointsource_forward_pdps_pair | |
| 92 | }; | |
| 0 | 93 | use crate::pdps::{ |
| 94 | PDPSConfig, | |
|
24
d29d1fcf5423
Support arbitrary regularisation terms; implement non-positivity-constrained regularisation.
Tuomo Valkonen <tuomov@iki.fi>
parents:
23
diff
changeset
|
95 | pointsource_pdps_reg, |
| 0 | 96 | }; |
| 97 | use crate::frank_wolfe::{ | |
| 98 | FWConfig, | |
| 99 | FWVariant, | |
|
25
79943be70720
Implement non-negativity constraints for the conditional gradient methods
Tuomo Valkonen <tuomov@iki.fi>
parents:
24
diff
changeset
|
100 | pointsource_fw_reg, |
| 35 | 101 | //WeightOptim, |
| 0 | 102 | }; |
| 35 | 103 | //use crate::subproblem::InnerSettings; |
| 0 | 104 | use crate::seminorms::*; |
| 105 | use crate::plot::*; | |
|
9
21b0e537ac0e
Command line parameter passing simplifications and make `-o` required.
Tuomo Valkonen <tuomov@iki.fi>
parents:
0
diff
changeset
|
106 | use crate::{AlgorithmOverrides, CommandLineArgs}; |
|
20
90f77ad9a98d
Added command line option for (power) tolerance
Tuomo Valkonen <tuomov@iki.fi>
parents:
9
diff
changeset
|
107 | use crate::tolerance::Tolerance; |
| 32 | 108 | use crate::regularisation::{ |
| 109 | Regularisation, | |
| 110 | RadonRegTerm, | |
| 111 | NonnegRadonRegTerm | |
| 112 | }; | |
| 113 | use crate::dataterm::{ | |
| 114 | L1, | |
| 35 | 115 | L2Squared, |
| 32 | 116 | }; |
| 35 | 117 | use alg_tools::norms::{L2, NormExponent}; |
| 118 | use alg_tools::operator_arithmetic::Weighted; | |
| 119 | use anyhow::anyhow; | |
| 0 | 120 | |
| 121 | /// Available algorithms and their configurations | |
| 122 | #[derive(Copy, Clone, Debug, Serialize, Deserialize)] | |
| 123 | pub enum AlgorithmConfig<F : Float> { | |
| 124 | FB(FBConfig<F>), | |
| 32 | 125 | FISTA(FBConfig<F>), |
| 0 | 126 | FW(FWConfig<F>), |
| 127 | PDPS(PDPSConfig<F>), | |
|
34
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
128 | RadonFB(RadonFBConfig<F>), |
|
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
129 | RadonFISTA(RadonFBConfig<F>), |
| 32 | 130 | SlidingFB(SlidingFBConfig<F>), |
| 35 | 131 | ForwardPDPS(ForwardPDPSConfig<F>), |
| 132 | SlidingPDPS(SlidingPDPSConfig<F>), | |
| 0 | 133 | } |
| 134 | ||
|
20
90f77ad9a98d
Added command line option for (power) tolerance
Tuomo Valkonen <tuomov@iki.fi>
parents:
9
diff
changeset
|
135 | fn unpack_tolerance<F : Float>(v : &Vec<F>) -> Tolerance<F> { |
|
90f77ad9a98d
Added command line option for (power) tolerance
Tuomo Valkonen <tuomov@iki.fi>
parents:
9
diff
changeset
|
136 | assert!(v.len() == 3); |
|
90f77ad9a98d
Added command line option for (power) tolerance
Tuomo Valkonen <tuomov@iki.fi>
parents:
9
diff
changeset
|
137 | Tolerance::Power { initial : v[0], factor : v[1], exponent : v[2] } |
|
90f77ad9a98d
Added command line option for (power) tolerance
Tuomo Valkonen <tuomov@iki.fi>
parents:
9
diff
changeset
|
138 | } |
|
90f77ad9a98d
Added command line option for (power) tolerance
Tuomo Valkonen <tuomov@iki.fi>
parents:
9
diff
changeset
|
139 | |
| 0 | 140 | impl<F : ClapFloat> AlgorithmConfig<F> { |
| 141 | /// Override supported parameters based on the command line. | |
| 142 | pub fn cli_override(self, cli : &AlgorithmOverrides<F>) -> Self { | |
| 143 | let override_fb_generic = |g : FBGenericConfig<F>| { | |
| 144 | FBGenericConfig { | |
| 145 | bootstrap_insertions : cli.bootstrap_insertions | |
| 146 | .as_ref() | |
| 147 | .map_or(g.bootstrap_insertions, | |
| 148 | |n| Some((n[0], n[1]))), | |
| 149 | merge_every : cli.merge_every.unwrap_or(g.merge_every), | |
| 150 | merging : cli.merging.clone().unwrap_or(g.merging), | |
| 151 | final_merging : cli.final_merging.clone().unwrap_or(g.final_merging), | |
|
20
90f77ad9a98d
Added command line option for (power) tolerance
Tuomo Valkonen <tuomov@iki.fi>
parents:
9
diff
changeset
|
152 | tolerance: cli.tolerance.as_ref().map(unpack_tolerance).unwrap_or(g.tolerance), |
| 0 | 153 | .. g |
| 154 | } | |
| 155 | }; | |
| 35 | 156 | let override_transport = |g : TransportConfig<F>| { |
| 157 | TransportConfig { | |
| 158 | θ0 : cli.theta0.unwrap_or(g.θ0), | |
| 159 | tolerance_ω: cli.transport_tolerance_omega.unwrap_or(g.tolerance_ω), | |
| 160 | tolerance_dv: cli.transport_tolerance_dv.unwrap_or(g.tolerance_dv), | |
| 161 | adaptation: cli.transport_adaptation.unwrap_or(g.adaptation), | |
| 162 | .. g | |
| 163 | } | |
| 164 | }; | |
| 0 | 165 | |
| 166 | use AlgorithmConfig::*; | |
| 167 | match self { | |
| 168 | FB(fb) => FB(FBConfig { | |
| 169 | τ0 : cli.tau0.unwrap_or(fb.τ0), | |
|
34
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
170 | generic : override_fb_generic(fb.generic), |
| 0 | 171 | .. fb |
| 172 | }), | |
| 32 | 173 | FISTA(fb) => FISTA(FBConfig { |
| 174 | τ0 : cli.tau0.unwrap_or(fb.τ0), | |
|
34
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
175 | generic : override_fb_generic(fb.generic), |
| 32 | 176 | .. fb |
| 177 | }), | |
| 0 | 178 | PDPS(pdps) => PDPS(PDPSConfig { |
| 179 | τ0 : cli.tau0.unwrap_or(pdps.τ0), | |
| 180 | σ0 : cli.sigma0.unwrap_or(pdps.σ0), | |
| 181 | acceleration : cli.acceleration.unwrap_or(pdps.acceleration), | |
|
34
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
182 | generic : override_fb_generic(pdps.generic), |
| 0 | 183 | .. pdps |
| 184 | }), | |
| 185 | FW(fw) => FW(FWConfig { | |
| 186 | merging : cli.merging.clone().unwrap_or(fw.merging), | |
|
20
90f77ad9a98d
Added command line option for (power) tolerance
Tuomo Valkonen <tuomov@iki.fi>
parents:
9
diff
changeset
|
187 | tolerance : cli.tolerance.as_ref().map(unpack_tolerance).unwrap_or(fw.tolerance), |
| 0 | 188 | .. fw |
| 32 | 189 | }), |
|
34
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
190 | RadonFB(fb) => RadonFB(RadonFBConfig { |
|
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
191 | τ0 : cli.tau0.unwrap_or(fb.τ0), |
|
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
192 | insertion : override_fb_generic(fb.insertion), |
|
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
193 | .. fb |
|
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
194 | }), |
|
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
195 | RadonFISTA(fb) => RadonFISTA(RadonFBConfig { |
|
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
196 | τ0 : cli.tau0.unwrap_or(fb.τ0), |
|
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
197 | insertion : override_fb_generic(fb.insertion), |
|
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
198 | .. fb |
|
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
199 | }), |
| 32 | 200 | SlidingFB(sfb) => SlidingFB(SlidingFBConfig { |
| 201 | τ0 : cli.tau0.unwrap_or(sfb.τ0), | |
| 35 | 202 | transport : override_transport(sfb.transport), |
| 32 | 203 | insertion : override_fb_generic(sfb.insertion), |
| 204 | .. sfb | |
| 205 | }), | |
| 35 | 206 | SlidingPDPS(spdps) => SlidingPDPS(SlidingPDPSConfig { |
| 207 | τ0 : cli.tau0.unwrap_or(spdps.τ0), | |
| 208 | σp0 : cli.sigmap0.unwrap_or(spdps.σp0), | |
| 209 | σd0 : cli.sigma0.unwrap_or(spdps.σd0), | |
| 210 | //acceleration : cli.acceleration.unwrap_or(pdps.acceleration), | |
| 211 | transport : override_transport(spdps.transport), | |
| 212 | insertion : override_fb_generic(spdps.insertion), | |
| 213 | .. spdps | |
| 214 | }), | |
| 215 | ForwardPDPS(fpdps) => ForwardPDPS(ForwardPDPSConfig { | |
| 216 | τ0 : cli.tau0.unwrap_or(fpdps.τ0), | |
| 217 | σp0 : cli.sigmap0.unwrap_or(fpdps.σp0), | |
| 218 | σd0 : cli.sigma0.unwrap_or(fpdps.σd0), | |
| 219 | //acceleration : cli.acceleration.unwrap_or(pdps.acceleration), | |
| 220 | insertion : override_fb_generic(fpdps.insertion), | |
| 221 | .. fpdps | |
| 222 | }), | |
| 0 | 223 | } |
| 224 | } | |
| 225 | } | |
| 226 | ||
| 35 | 227 | /// Helper struct for tagging and [`AlgorithmConfig`] or [`ExperimentV2`] with a name. |
| 0 | 228 | #[derive(Clone, Debug, Serialize, Deserialize)] |
| 229 | pub struct Named<Data> { | |
| 230 | pub name : String, | |
| 231 | #[serde(flatten)] | |
| 232 | pub data : Data, | |
| 233 | } | |
| 234 | ||
| 235 | /// Shorthand algorithm configurations, to be used with the command line parser | |
|
9
21b0e537ac0e
Command line parameter passing simplifications and make `-o` required.
Tuomo Valkonen <tuomov@iki.fi>
parents:
0
diff
changeset
|
236 | #[derive(ValueEnum, Debug, Copy, Clone, Eq, PartialEq, Hash, Serialize, Deserialize)] |
| 0 | 237 | pub enum DefaultAlgorithm { |
| 238 | /// The μFB forward-backward method | |
| 239 | #[clap(name = "fb")] | |
| 240 | FB, | |
| 241 | /// The μFISTA inertial forward-backward method | |
| 242 | #[clap(name = "fista")] | |
| 243 | FISTA, | |
| 244 | /// The “fully corrective” conditional gradient method | |
| 245 | #[clap(name = "fw")] | |
| 246 | FW, | |
| 247 | /// The “relaxed conditional gradient method | |
| 248 | #[clap(name = "fwrelax")] | |
| 249 | FWRelax, | |
| 250 | /// The μPDPS primal-dual proximal splitting method | |
| 251 | #[clap(name = "pdps")] | |
| 252 | PDPS, | |
|
34
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
253 | /// The RadonFB forward-backward method |
|
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
254 | #[clap(name = "radon_fb")] |
|
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
255 | RadonFB, |
|
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
256 | /// The RadonFISTA inertial forward-backward method |
|
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
257 | #[clap(name = "radon_fista")] |
|
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
258 | RadonFISTA, |
| 35 | 259 | /// The sliding FB method |
| 32 | 260 | #[clap(name = "sliding_fb", alias = "sfb")] |
| 261 | SlidingFB, | |
| 35 | 262 | /// The sliding PDPS method |
| 263 | #[clap(name = "sliding_pdps", alias = "spdps")] | |
| 264 | SlidingPDPS, | |
| 265 | /// The PDPS method with a forward step for the smooth function | |
| 266 | #[clap(name = "forward_pdps", alias = "fpdps")] | |
| 267 | ForwardPDPS, | |
| 0 | 268 | } |
| 269 | ||
| 270 | impl DefaultAlgorithm { | |
| 271 | /// Returns the algorithm configuration corresponding to the algorithm shorthand | |
| 272 | pub fn default_config<F : Float>(&self) -> AlgorithmConfig<F> { | |
| 273 | use DefaultAlgorithm::*; | |
| 274 | match *self { | |
| 275 | FB => AlgorithmConfig::FB(Default::default()), | |
| 32 | 276 | FISTA => AlgorithmConfig::FISTA(Default::default()), |
| 0 | 277 | FW => AlgorithmConfig::FW(Default::default()), |
| 278 | FWRelax => AlgorithmConfig::FW(FWConfig{ | |
| 279 | variant : FWVariant::Relaxed, | |
| 280 | .. Default::default() | |
| 281 | }), | |
| 282 | PDPS => AlgorithmConfig::PDPS(Default::default()), | |
|
34
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
283 | RadonFB => AlgorithmConfig::RadonFB(Default::default()), |
|
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
284 | RadonFISTA => AlgorithmConfig::RadonFISTA(Default::default()), |
| 32 | 285 | SlidingFB => AlgorithmConfig::SlidingFB(Default::default()), |
| 35 | 286 | SlidingPDPS => AlgorithmConfig::SlidingPDPS(Default::default()), |
| 287 | ForwardPDPS => AlgorithmConfig::ForwardPDPS(Default::default()), | |
| 0 | 288 | } |
| 289 | } | |
| 290 | ||
| 291 | /// Returns the [`Named`] algorithm corresponding to the algorithm shorthand | |
| 292 | pub fn get_named<F : Float>(&self) -> Named<AlgorithmConfig<F>> { | |
| 293 | self.to_named(self.default_config()) | |
| 294 | } | |
| 295 | ||
| 296 | pub fn to_named<F : Float>(self, alg : AlgorithmConfig<F>) -> Named<AlgorithmConfig<F>> { | |
| 297 | let name = self.to_possible_value().unwrap().get_name().to_string(); | |
| 298 | Named{ name , data : alg } | |
| 299 | } | |
| 300 | } | |
| 301 | ||
| 302 | ||
| 303 | // // Floats cannot be hashed directly, so just hash the debug formatting | |
| 304 | // // for use as file identifier. | |
| 305 | // impl<F : Float> Hash for AlgorithmConfig<F> { | |
| 306 | // fn hash<H: Hasher>(&self, state: &mut H) { | |
| 307 | // format!("{:?}", self).hash(state); | |
| 308 | // } | |
| 309 | // } | |
| 310 | ||
| 311 | /// Plotting level configuration | |
| 312 | #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Serialize, ValueEnum, Debug)] | |
| 313 | pub enum PlotLevel { | |
| 314 | /// Plot nothing | |
| 315 | #[clap(name = "none")] | |
| 316 | None, | |
| 317 | /// Plot problem data | |
| 318 | #[clap(name = "data")] | |
| 319 | Data, | |
| 320 | /// Plot iterationwise state | |
| 321 | #[clap(name = "iter")] | |
| 322 | Iter, | |
| 323 | } | |
| 324 | ||
| 325 | type DefaultBT<F, const N : usize> = BT< | |
| 326 | DynamicDepth, | |
| 327 | F, | |
| 328 | usize, | |
| 329 | Bounds<F>, | |
| 330 | N | |
| 331 | >; | |
| 332 | type DefaultSeminormOp<F, K, const N : usize> = ConvolutionOp<F, K, DefaultBT<F, N>, N>; | |
| 333 | type DefaultSG<F, Sensor, Spread, const N : usize> = SensorGrid::< | |
| 334 | F, | |
| 335 | Sensor, | |
| 336 | Spread, | |
| 337 | DefaultBT<F, N>, | |
| 338 | N | |
| 339 | >; | |
| 340 | ||
| 341 | /// This is a dirty workaround to rust-csv not supporting struct flattening etc. | |
| 342 | #[derive(Serialize)] | |
| 343 | struct CSVLog<F> { | |
| 344 | iter : usize, | |
| 345 | cpu_time : f64, | |
| 346 | value : F, | |
| 35 | 347 | relative_value : F, |
| 348 | //post_value : F, | |
| 0 | 349 | n_spikes : usize, |
| 350 | inner_iters : usize, | |
| 351 | merged : usize, | |
| 352 | pruned : usize, | |
| 353 | this_iters : usize, | |
| 354 | } | |
| 355 | ||
| 356 | /// Collected experiment statistics | |
| 357 | #[derive(Clone, Debug, Serialize)] | |
| 358 | struct ExperimentStats<F : Float> { | |
| 359 | /// Signal-to-noise ratio in decibels | |
| 360 | ssnr : F, | |
| 361 | /// Proportion of noise in the signal as a number in $[0, 1]$. | |
| 362 | noise_ratio : F, | |
| 363 | /// When the experiment was run (UTC) | |
| 364 | when : DateTime<Utc>, | |
| 365 | } | |
| 366 | ||
| 367 | #[replace_float_literals(F::cast_from(literal))] | |
| 368 | impl<F : Float> ExperimentStats<F> { | |
| 369 | /// Calculate [`ExperimentStats`] based on a noisy `signal` and the separated `noise` signal. | |
| 370 | fn new<E : Euclidean<F>>(signal : &E, noise : &E) -> Self { | |
| 371 | let s = signal.norm2_squared(); | |
| 372 | let n = noise.norm2_squared(); | |
| 373 | let noise_ratio = (n / s).sqrt(); | |
| 374 | let ssnr = 10.0 * (s / n).log10(); | |
| 375 | ExperimentStats { | |
| 376 | ssnr, | |
| 377 | noise_ratio, | |
| 378 | when : Utc::now(), | |
| 379 | } | |
| 380 | } | |
| 381 | } | |
| 382 | /// Collected algorithm statistics | |
| 383 | #[derive(Clone, Debug, Serialize)] | |
| 384 | struct AlgorithmStats<F : Float> { | |
| 385 | /// Overall CPU time spent | |
| 386 | cpu_time : F, | |
| 387 | /// Real time spent | |
| 388 | elapsed : F | |
| 389 | } | |
| 390 | ||
| 391 | ||
| 392 | /// A wrapper for [`serde_json::to_writer_pretty`] that takes a filename as input | |
| 393 | /// and outputs a [`DynError`]. | |
| 394 | fn write_json<T : Serialize>(filename : String, data : &T) -> DynError { | |
| 395 | serde_json::to_writer_pretty(std::fs::File::create(filename)?, data)?; | |
| 396 | Ok(()) | |
| 397 | } | |
| 398 | ||
| 399 | ||
| 400 | /// Struct for experiment configurations | |
| 401 | #[derive(Debug, Clone, Serialize)] | |
|
24
d29d1fcf5423
Support arbitrary regularisation terms; implement non-positivity-constrained regularisation.
Tuomo Valkonen <tuomov@iki.fi>
parents:
23
diff
changeset
|
402 | pub struct ExperimentV2<F, NoiseDistr, S, K, P, const N : usize> |
| 0 | 403 | where F : Float, |
| 404 | [usize; N] : Serialize, | |
| 405 | NoiseDistr : Distribution<F>, | |
| 406 | S : Sensor<F, N>, | |
| 407 | P : Spread<F, N>, | |
| 408 | K : SimpleConvolutionKernel<F, N>, | |
| 409 | { | |
| 410 | /// Domain $Ω$. | |
| 411 | pub domain : Cube<F, N>, | |
| 412 | /// Number of sensors along each dimension | |
| 413 | pub sensor_count : [usize; N], | |
| 414 | /// Noise distribution | |
| 415 | pub noise_distr : NoiseDistr, | |
| 416 | /// Seed for random noise generation (for repeatable experiments) | |
| 417 | pub noise_seed : u64, | |
| 418 | /// Sensor $θ$; $θ * ψ$ forms the forward operator $𝒜$. | |
| 419 | pub sensor : S, | |
| 420 | /// Spread $ψ$; $θ * ψ$ forms the forward operator $𝒜$. | |
| 421 | pub spread : P, | |
| 422 | /// Kernel $ρ$ of $𝒟$. | |
| 423 | pub kernel : K, | |
| 424 | /// True point sources | |
| 35 | 425 | pub μ_hat : RNDM<F, N>, |
|
24
d29d1fcf5423
Support arbitrary regularisation terms; implement non-positivity-constrained regularisation.
Tuomo Valkonen <tuomov@iki.fi>
parents:
23
diff
changeset
|
426 | /// Regularisation term and parameter |
|
d29d1fcf5423
Support arbitrary regularisation terms; implement non-positivity-constrained regularisation.
Tuomo Valkonen <tuomov@iki.fi>
parents:
23
diff
changeset
|
427 | pub regularisation : Regularisation<F>, |
| 0 | 428 | /// For plotting : how wide should the kernels be plotted |
| 429 | pub kernel_plot_width : F, | |
| 430 | /// Data term | |
| 431 | pub dataterm : DataTerm, | |
| 432 | /// A map of default configurations for algorithms | |
| 433 | #[serde(skip)] | |
| 434 | pub algorithm_defaults : HashMap<DefaultAlgorithm, AlgorithmConfig<F>>, | |
| 435 | } | |
| 436 | ||
| 35 | 437 | #[derive(Debug, Clone, Serialize)] |
| 438 | pub struct ExperimentBiased<F, NoiseDistr, S, K, P, B, const N : usize> | |
| 439 | where F : Float, | |
| 440 | [usize; N] : Serialize, | |
| 441 | NoiseDistr : Distribution<F>, | |
| 442 | S : Sensor<F, N>, | |
| 443 | P : Spread<F, N>, | |
| 444 | K : SimpleConvolutionKernel<F, N>, | |
| 445 | B : Mapping<Loc<F, N>, Codomain = F> + Serialize + std::fmt::Debug, | |
| 446 | { | |
| 447 | /// Basic setup | |
| 448 | pub base : ExperimentV2<F, NoiseDistr, S, K, P, N>, | |
| 449 | /// Weight of TV term | |
| 450 | pub λ : F, | |
| 451 | /// Bias function | |
| 452 | pub bias : B, | |
| 453 | } | |
| 454 | ||
| 0 | 455 | /// Trait for runnable experiments |
| 456 | pub trait RunnableExperiment<F : ClapFloat> { | |
|
9
21b0e537ac0e
Command line parameter passing simplifications and make `-o` required.
Tuomo Valkonen <tuomov@iki.fi>
parents:
0
diff
changeset
|
457 | /// Run all algorithms provided, or default algorithms if none provided, on the experiment. |
|
21b0e537ac0e
Command line parameter passing simplifications and make `-o` required.
Tuomo Valkonen <tuomov@iki.fi>
parents:
0
diff
changeset
|
458 | fn runall(&self, cli : &CommandLineArgs, |
|
21b0e537ac0e
Command line parameter passing simplifications and make `-o` required.
Tuomo Valkonen <tuomov@iki.fi>
parents:
0
diff
changeset
|
459 | algs : Option<Vec<Named<AlgorithmConfig<F>>>>) -> DynError; |
| 0 | 460 | |
| 461 | /// Return algorithm default config | |
| 35 | 462 | fn algorithm_defaults(&self, alg : DefaultAlgorithm) -> Option<AlgorithmConfig<F>>; |
| 463 | } | |
| 464 | ||
| 465 | /// Helper function to print experiment start message and save setup. | |
| 466 | /// Returns saving prefix. | |
| 467 | fn start_experiment<E, S>( | |
| 468 | experiment : &Named<E>, | |
| 469 | cli : &CommandLineArgs, | |
| 470 | stats : S, | |
| 471 | ) -> DynResult<String> | |
| 472 | where | |
| 473 | E : Serialize + std::fmt::Debug, | |
| 474 | S : Serialize, | |
| 475 | { | |
| 476 | let Named { name : experiment_name, data } = experiment; | |
| 477 | ||
| 478 | println!("{}\n{}", | |
| 479 | format!("Performing experiment {}…", experiment_name).cyan(), | |
| 480 | format!("{:?}", data).bright_black()); | |
| 481 | ||
| 482 | // Set up output directory | |
| 483 | let prefix = format!("{}/{}/", cli.outdir, experiment_name); | |
| 484 | ||
| 485 | // Save experiment configuration and statistics | |
| 486 | let mkname_e = |t| format!("{prefix}{t}.json", prefix = prefix, t = t); | |
| 487 | std::fs::create_dir_all(&prefix)?; | |
| 488 | write_json(mkname_e("experiment"), experiment)?; | |
| 489 | write_json(mkname_e("config"), cli)?; | |
| 490 | write_json(mkname_e("stats"), &stats)?; | |
| 491 | ||
| 492 | Ok(prefix) | |
| 493 | } | |
| 494 | ||
| 495 | /// Error codes for running an algorithm on an experiment. | |
| 496 | enum RunError { | |
| 497 | /// Algorithm not implemented for this experiment | |
| 498 | NotImplemented, | |
| 0 | 499 | } |
| 500 | ||
| 35 | 501 | use RunError::*; |
| 502 | ||
| 503 | type DoRunAllIt<'a, F, const N : usize> = LoggingIteratorFactory< | |
| 504 | 'a, | |
| 505 | Timed<IterInfo<F, N>>, | |
| 506 | TimingIteratorFactory<BasicAlgIteratorFactory<IterInfo<F, N>>> | |
| 507 | >; | |
| 508 | ||
| 509 | /// Helper function to run all algorithms on an experiment. | |
| 510 | fn do_runall<F : Float, Z, const N : usize>( | |
| 511 | experiment_name : &String, | |
| 512 | prefix : &String, | |
| 513 | cli : &CommandLineArgs, | |
| 514 | algorithms : Vec<Named<AlgorithmConfig<F>>>, | |
| 515 | plotgrid : LinSpace<Loc<F, N>, [usize; N]>, | |
| 516 | mut save_extra : impl FnMut(String, Z) -> DynError, | |
| 517 | mut do_alg : impl FnMut( | |
| 518 | &AlgorithmConfig<F>, | |
| 519 | DoRunAllIt<F, N>, | |
| 520 | SeqPlotter<F, N>, | |
| 521 | String, | |
| 522 | ) -> Result<(RNDM<F, N>, Z), RunError>, | |
| 523 | ) -> DynError | |
| 524 | where | |
| 525 | PlotLookup : Plotting<N>, | |
| 526 | { | |
| 527 | let mut logs = Vec::new(); | |
| 528 | ||
| 529 | let iterator_options = AlgIteratorOptions{ | |
| 530 | max_iter : cli.max_iter, | |
| 531 | verbose_iter : cli.verbose_iter | |
| 532 | .map_or(Verbose::Logarithmic(10), | |
| 533 | |n| Verbose::Every(n)), | |
| 534 | quiet : cli.quiet, | |
| 535 | }; | |
| 536 | ||
| 537 | // Run the algorithm(s) | |
| 538 | for named @ Named { name : alg_name, data : alg } in algorithms.iter() { | |
| 539 | let this_prefix = format!("{}{}/", prefix, alg_name); | |
| 540 | ||
| 541 | // Create Logger and IteratorFactory | |
| 542 | let mut logger = Logger::new(); | |
| 543 | let iterator = iterator_options.instantiate() | |
| 544 | .timed() | |
| 545 | .into_log(&mut logger); | |
| 546 | ||
| 547 | let running = if !cli.quiet { | |
| 548 | format!("{}\n{}\n{}\n", | |
| 549 | format!("Running {} on experiment {}…", alg_name, experiment_name).cyan(), | |
| 550 | format!("{:?}", iterator_options).bright_black(), | |
| 551 | format!("{:?}", alg).bright_black()) | |
| 552 | } else { | |
| 553 | "".to_string() | |
| 554 | }; | |
| 555 | // | |
| 556 | // The following is for postprocessing, which has been disabled anyway. | |
| 557 | // | |
| 558 | // let reg : Box<dyn WeightOptim<_, _, _, N>> = match regularisation { | |
| 559 | // Regularisation::Radon(α) => Box::new(RadonRegTerm(α)), | |
| 560 | // Regularisation::NonnegRadon(α) => Box::new(NonnegRadonRegTerm(α)), | |
| 561 | // }; | |
| 562 | //let findim_data = reg.prepare_optimise_weights(&opA, &b); | |
| 563 | //let inner_config : InnerSettings<F> = Default::default(); | |
| 564 | //let inner_it = inner_config.iterator_options; | |
| 565 | ||
| 566 | // Create plotter and directory if needed. | |
| 567 | let plot_count = if cli.plot >= PlotLevel::Iter { 2000 } else { 0 }; | |
| 568 | let plotter = SeqPlotter::new(this_prefix, plot_count, plotgrid.clone()); | |
| 569 | ||
| 570 | let start = Instant::now(); | |
| 571 | let start_cpu = ProcessTime::now(); | |
| 572 | ||
| 573 | let (μ, z) = match do_alg(alg, iterator, plotter, running) { | |
| 574 | Ok(μ) => μ, | |
| 575 | Err(RunError::NotImplemented) => { | |
| 576 | let msg = format!("Algorithm “{alg_name}” not implemented for {experiment_name}. \ | |
| 577 | Skipping.").red(); | |
| 578 | eprintln!("{}", msg); | |
| 579 | continue | |
| 580 | } | |
| 581 | }; | |
| 582 | ||
| 583 | let elapsed = start.elapsed().as_secs_f64(); | |
| 584 | let cpu_time = start_cpu.elapsed().as_secs_f64(); | |
| 585 | ||
| 586 | println!("{}", format!("Elapsed {elapsed}s (CPU time {cpu_time}s)… ").yellow()); | |
| 587 | ||
| 588 | // Save results | |
| 589 | println!("{}", "Saving results …".green()); | |
| 590 | ||
| 591 | let mkname = |t| format!("{prefix}{alg_name}_{t}"); | |
| 592 | ||
| 593 | write_json(mkname("config.json"), &named)?; | |
| 594 | write_json(mkname("stats.json"), &AlgorithmStats { cpu_time, elapsed })?; | |
| 595 | μ.write_csv(mkname("reco.txt"))?; | |
| 596 | save_extra(mkname(""), z)?; | |
| 597 | //logger.write_csv(mkname("log.txt"))?; | |
| 598 | logs.push((mkname("log.txt"), logger)); | |
| 599 | } | |
| 600 | ||
| 601 | save_logs(logs) | |
| 602 | } | |
| 603 | ||
| 604 | #[replace_float_literals(F::cast_from(literal))] | |
| 0 | 605 | impl<F, NoiseDistr, S, K, P, const N : usize> RunnableExperiment<F> for |
| 35 | 606 | Named<ExperimentV2<F, NoiseDistr, S, K, P, N>> |
| 607 | where | |
| 608 | F : ClapFloat + nalgebra::RealField + ToNalgebraRealField<MixedType=F>, | |
| 609 | [usize; N] : Serialize, | |
| 610 | S : Sensor<F, N> + Copy + Serialize + std::fmt::Debug, | |
| 611 | P : Spread<F, N> + Copy + Serialize + std::fmt::Debug, | |
| 612 | Convolution<S, P>: Spread<F, N> + Bounded<F> + LocalAnalysis<F, Bounds<F>, N> + Copy | |
| 613 | // TODO: shold not have differentiability as a requirement, but | |
| 614 | // decide availability of sliding based on it. | |
| 615 | //+ for<'b> Differentiable<&'b Loc<F, N>, Output = Loc<F, N>>, | |
| 616 | // TODO: very weird that rust only compiles with Differentiable | |
| 617 | // instead of the above one on references, which is required by | |
| 618 | // poitsource_sliding_fb_reg. | |
| 619 | + DifferentiableRealMapping<F, N> | |
| 620 | + Lipschitz<L2, FloatType=F>, | |
| 621 | for<'b> <Convolution<S, P> as DifferentiableMapping<Loc<F,N>>>::Differential<'b> : Lipschitz<L2, FloatType=F>, // TODO: should not be required generally, only for sliding_fb. | |
| 622 | AutoConvolution<P> : BoundedBy<F, K>, | |
| 623 | K : SimpleConvolutionKernel<F, N> | |
| 624 | + LocalAnalysis<F, Bounds<F>, N> | |
| 625 | + Copy + Serialize + std::fmt::Debug, | |
| 626 | Cube<F, N>: P2Minimise<Loc<F, N>, F> + SetOrd, | |
| 627 | PlotLookup : Plotting<N>, | |
| 628 | DefaultBT<F, N> : SensorGridBT<F, S, P, N, Depth=DynamicDepth> + BTSearch<F, N>, | |
| 629 | BTNodeLookup: BTNode<F, usize, Bounds<F>, N>, | |
| 630 | RNDM<F, N> : SpikeMerging<F>, | |
| 631 | NoiseDistr : Distribution<F> + Serialize + std::fmt::Debug | |
| 632 | { | |
| 0 | 633 | |
| 35 | 634 | fn algorithm_defaults(&self, alg : DefaultAlgorithm) -> Option<AlgorithmConfig<F>> { |
| 635 | self.data.algorithm_defaults.get(&alg).cloned() | |
| 0 | 636 | } |
| 637 | ||
|
9
21b0e537ac0e
Command line parameter passing simplifications and make `-o` required.
Tuomo Valkonen <tuomov@iki.fi>
parents:
0
diff
changeset
|
638 | fn runall(&self, cli : &CommandLineArgs, |
|
21b0e537ac0e
Command line parameter passing simplifications and make `-o` required.
Tuomo Valkonen <tuomov@iki.fi>
parents:
0
diff
changeset
|
639 | algs : Option<Vec<Named<AlgorithmConfig<F>>>>) -> DynError { |
|
21b0e537ac0e
Command line parameter passing simplifications and make `-o` required.
Tuomo Valkonen <tuomov@iki.fi>
parents:
0
diff
changeset
|
640 | // Get experiment configuration |
| 0 | 641 | let &Named { |
| 642 | name : ref experiment_name, | |
| 35 | 643 | data : ExperimentV2 { |
| 0 | 644 | domain, sensor_count, ref noise_distr, sensor, spread, kernel, |
| 35 | 645 | ref μ_hat, regularisation, kernel_plot_width, dataterm, noise_seed, |
| 0 | 646 | .. |
| 647 | } | |
| 648 | } = self; | |
|
9
21b0e537ac0e
Command line parameter passing simplifications and make `-o` required.
Tuomo Valkonen <tuomov@iki.fi>
parents:
0
diff
changeset
|
649 | |
|
21b0e537ac0e
Command line parameter passing simplifications and make `-o` required.
Tuomo Valkonen <tuomov@iki.fi>
parents:
0
diff
changeset
|
650 | // Set up algorithms |
| 35 | 651 | let algorithms = match (algs, dataterm) { |
|
9
21b0e537ac0e
Command line parameter passing simplifications and make `-o` required.
Tuomo Valkonen <tuomov@iki.fi>
parents:
0
diff
changeset
|
652 | (Some(algs), _) => algs, |
|
21b0e537ac0e
Command line parameter passing simplifications and make `-o` required.
Tuomo Valkonen <tuomov@iki.fi>
parents:
0
diff
changeset
|
653 | (None, DataTerm::L2Squared) => vec![DefaultAlgorithm::FB.get_named()], |
|
21b0e537ac0e
Command line parameter passing simplifications and make `-o` required.
Tuomo Valkonen <tuomov@iki.fi>
parents:
0
diff
changeset
|
654 | (None, DataTerm::L1) => vec![DefaultAlgorithm::PDPS.get_named()], |
|
21b0e537ac0e
Command line parameter passing simplifications and make `-o` required.
Tuomo Valkonen <tuomov@iki.fi>
parents:
0
diff
changeset
|
655 | }; |
| 0 | 656 | |
| 657 | // Set up operators | |
|
9
21b0e537ac0e
Command line parameter passing simplifications and make `-o` required.
Tuomo Valkonen <tuomov@iki.fi>
parents:
0
diff
changeset
|
658 | let depth = DynamicDepth(8); |
| 0 | 659 | let opA = DefaultSG::new(domain, sensor_count, sensor, spread, depth); |
| 660 | let op𝒟 = DefaultSeminormOp::new(depth, domain, kernel); | |
| 661 | ||
| 662 | // Set up random number generator. | |
| 663 | let mut rng = StdRng::seed_from_u64(noise_seed); | |
| 664 | ||
| 665 | // Generate the data and calculate SSNR statistic | |
| 35 | 666 | let b_hat : DVector<_> = opA.apply(μ_hat); |
| 0 | 667 | let noise = DVector::from_distribution(b_hat.len(), &noise_distr, &mut rng); |
| 668 | let b = &b_hat + &noise; | |
| 669 | // Need to wrap calc_ssnr into a function to hide ultra-lame nalgebra::RealField | |
| 670 | // overloading log10 and conflicting with standard NumTraits one. | |
| 671 | let stats = ExperimentStats::new(&b, &noise); | |
| 672 | ||
| 35 | 673 | let prefix = start_experiment(&self, cli, stats)?; |
| 0 | 674 | |
|
9
21b0e537ac0e
Command line parameter passing simplifications and make `-o` required.
Tuomo Valkonen <tuomov@iki.fi>
parents:
0
diff
changeset
|
675 | plotall(cli, &prefix, &domain, &sensor, &kernel, &spread, |
| 0 | 676 | &μ_hat, &op𝒟, &opA, &b_hat, &b, kernel_plot_width)?; |
| 677 | ||
| 35 | 678 | let plotgrid = lingrid(&domain, &[if N==1 { 1000 } else { 100 }; N]); |
| 679 | ||
| 680 | let save_extra = |_, ()| Ok(()); | |
| 0 | 681 | |
| 35 | 682 | do_runall(experiment_name, &prefix, cli, algorithms, plotgrid, save_extra, |
| 683 | |alg, iterator, plotter, running| | |
| 684 | { | |
|
24
d29d1fcf5423
Support arbitrary regularisation terms; implement non-positivity-constrained regularisation.
Tuomo Valkonen <tuomov@iki.fi>
parents:
23
diff
changeset
|
685 | let μ = match alg { |
|
d29d1fcf5423
Support arbitrary regularisation terms; implement non-positivity-constrained regularisation.
Tuomo Valkonen <tuomov@iki.fi>
parents:
23
diff
changeset
|
686 | AlgorithmConfig::FB(ref algconfig) => { |
|
d29d1fcf5423
Support arbitrary regularisation terms; implement non-positivity-constrained regularisation.
Tuomo Valkonen <tuomov@iki.fi>
parents:
23
diff
changeset
|
687 | match (regularisation, dataterm) { |
| 35 | 688 | (Regularisation::NonnegRadon(α), DataTerm::L2Squared) => Ok({ |
| 689 | print!("{running}"); | |
|
24
d29d1fcf5423
Support arbitrary regularisation terms; implement non-positivity-constrained regularisation.
Tuomo Valkonen <tuomov@iki.fi>
parents:
23
diff
changeset
|
690 | pointsource_fb_reg( |
|
d29d1fcf5423
Support arbitrary regularisation terms; implement non-positivity-constrained regularisation.
Tuomo Valkonen <tuomov@iki.fi>
parents:
23
diff
changeset
|
691 | &opA, &b, NonnegRadonRegTerm(α), &op𝒟, algconfig, |
|
d29d1fcf5423
Support arbitrary regularisation terms; implement non-positivity-constrained regularisation.
Tuomo Valkonen <tuomov@iki.fi>
parents:
23
diff
changeset
|
692 | iterator, plotter |
|
d29d1fcf5423
Support arbitrary regularisation terms; implement non-positivity-constrained regularisation.
Tuomo Valkonen <tuomov@iki.fi>
parents:
23
diff
changeset
|
693 | ) |
| 35 | 694 | }), |
| 695 | (Regularisation::Radon(α), DataTerm::L2Squared) => Ok({ | |
| 696 | print!("{running}"); | |
|
24
d29d1fcf5423
Support arbitrary regularisation terms; implement non-positivity-constrained regularisation.
Tuomo Valkonen <tuomov@iki.fi>
parents:
23
diff
changeset
|
697 | pointsource_fb_reg( |
|
d29d1fcf5423
Support arbitrary regularisation terms; implement non-positivity-constrained regularisation.
Tuomo Valkonen <tuomov@iki.fi>
parents:
23
diff
changeset
|
698 | &opA, &b, RadonRegTerm(α), &op𝒟, algconfig, |
|
d29d1fcf5423
Support arbitrary regularisation terms; implement non-positivity-constrained regularisation.
Tuomo Valkonen <tuomov@iki.fi>
parents:
23
diff
changeset
|
699 | iterator, plotter |
|
d29d1fcf5423
Support arbitrary regularisation terms; implement non-positivity-constrained regularisation.
Tuomo Valkonen <tuomov@iki.fi>
parents:
23
diff
changeset
|
700 | ) |
| 35 | 701 | }), |
| 702 | _ => Err(NotImplemented) | |
|
24
d29d1fcf5423
Support arbitrary regularisation terms; implement non-positivity-constrained regularisation.
Tuomo Valkonen <tuomov@iki.fi>
parents:
23
diff
changeset
|
703 | } |
| 0 | 704 | }, |
| 32 | 705 | AlgorithmConfig::FISTA(ref algconfig) => { |
| 706 | match (regularisation, dataterm) { | |
| 35 | 707 | (Regularisation::NonnegRadon(α), DataTerm::L2Squared) => Ok({ |
| 708 | print!("{running}"); | |
| 32 | 709 | pointsource_fista_reg( |
| 710 | &opA, &b, NonnegRadonRegTerm(α), &op𝒟, algconfig, | |
| 711 | iterator, plotter | |
| 712 | ) | |
| 35 | 713 | }), |
| 714 | (Regularisation::Radon(α), DataTerm::L2Squared) => Ok({ | |
| 715 | print!("{running}"); | |
| 32 | 716 | pointsource_fista_reg( |
| 717 | &opA, &b, RadonRegTerm(α), &op𝒟, algconfig, | |
| 718 | iterator, plotter | |
| 719 | ) | |
| 35 | 720 | }), |
| 721 | _ => Err(NotImplemented), | |
| 32 | 722 | } |
| 723 | }, | |
|
34
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
724 | AlgorithmConfig::RadonFB(ref algconfig) => { |
|
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
725 | match (regularisation, dataterm) { |
| 35 | 726 | (Regularisation::NonnegRadon(α), DataTerm::L2Squared) => Ok({ |
| 727 | print!("{running}"); | |
|
34
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
728 | pointsource_radon_fb_reg( |
|
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
729 | &opA, &b, NonnegRadonRegTerm(α), algconfig, |
|
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
730 | iterator, plotter |
|
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
731 | ) |
| 35 | 732 | }), |
| 733 | (Regularisation::Radon(α), DataTerm::L2Squared) => Ok({ | |
| 734 | print!("{running}"); | |
|
34
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
735 | pointsource_radon_fb_reg( |
|
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
736 | &opA, &b, RadonRegTerm(α), algconfig, |
|
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
737 | iterator, plotter |
|
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
738 | ) |
| 35 | 739 | }), |
| 740 | _ => Err(NotImplemented), | |
|
34
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
741 | } |
|
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
742 | }, |
|
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
743 | AlgorithmConfig::RadonFISTA(ref algconfig) => { |
|
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
744 | match (regularisation, dataterm) { |
| 35 | 745 | (Regularisation::NonnegRadon(α), DataTerm::L2Squared) => Ok({ |
| 746 | print!("{running}"); | |
|
34
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
747 | pointsource_radon_fista_reg( |
|
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
748 | &opA, &b, NonnegRadonRegTerm(α), algconfig, |
|
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
749 | iterator, plotter |
|
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
750 | ) |
| 35 | 751 | }), |
| 752 | (Regularisation::Radon(α), DataTerm::L2Squared) => Ok({ | |
| 753 | print!("{running}"); | |
|
34
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
754 | pointsource_radon_fista_reg( |
|
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
755 | &opA, &b, RadonRegTerm(α), algconfig, |
|
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
756 | iterator, plotter |
|
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
757 | ) |
| 35 | 758 | }), |
| 759 | _ => Err(NotImplemented), | |
|
34
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
760 | } |
|
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
761 | }, |
| 32 | 762 | AlgorithmConfig::SlidingFB(ref algconfig) => { |
| 763 | match (regularisation, dataterm) { | |
| 35 | 764 | (Regularisation::NonnegRadon(α), DataTerm::L2Squared) => Ok({ |
| 765 | print!("{running}"); | |
| 32 | 766 | pointsource_sliding_fb_reg( |
| 767 | &opA, &b, NonnegRadonRegTerm(α), &op𝒟, algconfig, | |
| 768 | iterator, plotter | |
| 769 | ) | |
| 35 | 770 | }), |
| 771 | (Regularisation::Radon(α), DataTerm::L2Squared) => Ok({ | |
| 772 | print!("{running}"); | |
| 32 | 773 | pointsource_sliding_fb_reg( |
| 774 | &opA, &b, RadonRegTerm(α), &op𝒟, algconfig, | |
| 775 | iterator, plotter | |
| 776 | ) | |
| 35 | 777 | }), |
| 778 | _ => Err(NotImplemented), | |
| 32 | 779 | } |
| 780 | }, | |
|
24
d29d1fcf5423
Support arbitrary regularisation terms; implement non-positivity-constrained regularisation.
Tuomo Valkonen <tuomov@iki.fi>
parents:
23
diff
changeset
|
781 | AlgorithmConfig::PDPS(ref algconfig) => { |
| 35 | 782 | print!("{running}"); |
|
24
d29d1fcf5423
Support arbitrary regularisation terms; implement non-positivity-constrained regularisation.
Tuomo Valkonen <tuomov@iki.fi>
parents:
23
diff
changeset
|
783 | match (regularisation, dataterm) { |
| 35 | 784 | (Regularisation::NonnegRadon(α), DataTerm::L2Squared) => Ok({ |
|
24
d29d1fcf5423
Support arbitrary regularisation terms; implement non-positivity-constrained regularisation.
Tuomo Valkonen <tuomov@iki.fi>
parents:
23
diff
changeset
|
785 | pointsource_pdps_reg( |
|
d29d1fcf5423
Support arbitrary regularisation terms; implement non-positivity-constrained regularisation.
Tuomo Valkonen <tuomov@iki.fi>
parents:
23
diff
changeset
|
786 | &opA, &b, NonnegRadonRegTerm(α), &op𝒟, algconfig, |
|
d29d1fcf5423
Support arbitrary regularisation terms; implement non-positivity-constrained regularisation.
Tuomo Valkonen <tuomov@iki.fi>
parents:
23
diff
changeset
|
787 | iterator, plotter, L2Squared |
|
d29d1fcf5423
Support arbitrary regularisation terms; implement non-positivity-constrained regularisation.
Tuomo Valkonen <tuomov@iki.fi>
parents:
23
diff
changeset
|
788 | ) |
| 35 | 789 | }), |
| 790 | (Regularisation::Radon(α),DataTerm::L2Squared) => Ok({ | |
|
24
d29d1fcf5423
Support arbitrary regularisation terms; implement non-positivity-constrained regularisation.
Tuomo Valkonen <tuomov@iki.fi>
parents:
23
diff
changeset
|
791 | pointsource_pdps_reg( |
|
d29d1fcf5423
Support arbitrary regularisation terms; implement non-positivity-constrained regularisation.
Tuomo Valkonen <tuomov@iki.fi>
parents:
23
diff
changeset
|
792 | &opA, &b, RadonRegTerm(α), &op𝒟, algconfig, |
|
d29d1fcf5423
Support arbitrary regularisation terms; implement non-positivity-constrained regularisation.
Tuomo Valkonen <tuomov@iki.fi>
parents:
23
diff
changeset
|
793 | iterator, plotter, L2Squared |
|
d29d1fcf5423
Support arbitrary regularisation terms; implement non-positivity-constrained regularisation.
Tuomo Valkonen <tuomov@iki.fi>
parents:
23
diff
changeset
|
794 | ) |
| 35 | 795 | }), |
| 796 | (Regularisation::NonnegRadon(α), DataTerm::L1) => Ok({ | |
|
24
d29d1fcf5423
Support arbitrary regularisation terms; implement non-positivity-constrained regularisation.
Tuomo Valkonen <tuomov@iki.fi>
parents:
23
diff
changeset
|
797 | pointsource_pdps_reg( |
|
d29d1fcf5423
Support arbitrary regularisation terms; implement non-positivity-constrained regularisation.
Tuomo Valkonen <tuomov@iki.fi>
parents:
23
diff
changeset
|
798 | &opA, &b, NonnegRadonRegTerm(α), &op𝒟, algconfig, |
|
d29d1fcf5423
Support arbitrary regularisation terms; implement non-positivity-constrained regularisation.
Tuomo Valkonen <tuomov@iki.fi>
parents:
23
diff
changeset
|
799 | iterator, plotter, L1 |
|
d29d1fcf5423
Support arbitrary regularisation terms; implement non-positivity-constrained regularisation.
Tuomo Valkonen <tuomov@iki.fi>
parents:
23
diff
changeset
|
800 | ) |
| 35 | 801 | }), |
| 802 | (Regularisation::Radon(α), DataTerm::L1) => Ok({ | |
|
24
d29d1fcf5423
Support arbitrary regularisation terms; implement non-positivity-constrained regularisation.
Tuomo Valkonen <tuomov@iki.fi>
parents:
23
diff
changeset
|
803 | pointsource_pdps_reg( |
|
d29d1fcf5423
Support arbitrary regularisation terms; implement non-positivity-constrained regularisation.
Tuomo Valkonen <tuomov@iki.fi>
parents:
23
diff
changeset
|
804 | &opA, &b, RadonRegTerm(α), &op𝒟, algconfig, |
|
d29d1fcf5423
Support arbitrary regularisation terms; implement non-positivity-constrained regularisation.
Tuomo Valkonen <tuomov@iki.fi>
parents:
23
diff
changeset
|
805 | iterator, plotter, L1 |
|
d29d1fcf5423
Support arbitrary regularisation terms; implement non-positivity-constrained regularisation.
Tuomo Valkonen <tuomov@iki.fi>
parents:
23
diff
changeset
|
806 | ) |
| 35 | 807 | }), |
|
24
d29d1fcf5423
Support arbitrary regularisation terms; implement non-positivity-constrained regularisation.
Tuomo Valkonen <tuomov@iki.fi>
parents:
23
diff
changeset
|
808 | } |
| 0 | 809 | }, |
|
24
d29d1fcf5423
Support arbitrary regularisation terms; implement non-positivity-constrained regularisation.
Tuomo Valkonen <tuomov@iki.fi>
parents:
23
diff
changeset
|
810 | AlgorithmConfig::FW(ref algconfig) => { |
|
d29d1fcf5423
Support arbitrary regularisation terms; implement non-positivity-constrained regularisation.
Tuomo Valkonen <tuomov@iki.fi>
parents:
23
diff
changeset
|
811 | match (regularisation, dataterm) { |
| 35 | 812 | (Regularisation::Radon(α), DataTerm::L2Squared) => Ok({ |
| 813 | print!("{running}"); | |
|
25
79943be70720
Implement non-negativity constraints for the conditional gradient methods
Tuomo Valkonen <tuomov@iki.fi>
parents:
24
diff
changeset
|
814 | pointsource_fw_reg(&opA, &b, RadonRegTerm(α), |
|
79943be70720
Implement non-negativity constraints for the conditional gradient methods
Tuomo Valkonen <tuomov@iki.fi>
parents:
24
diff
changeset
|
815 | algconfig, iterator, plotter) |
| 35 | 816 | }), |
| 817 | (Regularisation::NonnegRadon(α), DataTerm::L2Squared) => Ok({ | |
| 818 | print!("{running}"); | |
|
25
79943be70720
Implement non-negativity constraints for the conditional gradient methods
Tuomo Valkonen <tuomov@iki.fi>
parents:
24
diff
changeset
|
819 | pointsource_fw_reg(&opA, &b, NonnegRadonRegTerm(α), |
|
79943be70720
Implement non-negativity constraints for the conditional gradient methods
Tuomo Valkonen <tuomov@iki.fi>
parents:
24
diff
changeset
|
820 | algconfig, iterator, plotter) |
| 35 | 821 | }), |
| 822 | _ => Err(NotImplemented), | |
|
24
d29d1fcf5423
Support arbitrary regularisation terms; implement non-positivity-constrained regularisation.
Tuomo Valkonen <tuomov@iki.fi>
parents:
23
diff
changeset
|
823 | } |
| 35 | 824 | }, |
| 825 | _ => Err(NotImplemented), | |
| 826 | }?; | |
| 827 | Ok((μ, ())) | |
| 828 | }) | |
| 0 | 829 | } |
| 830 | } | |
| 35 | 831 | |
| 832 | ||
| 833 | #[replace_float_literals(F::cast_from(literal))] | |
| 834 | impl<F, NoiseDistr, S, K, P, B, const N : usize> RunnableExperiment<F> for | |
| 835 | Named<ExperimentBiased<F, NoiseDistr, S, K, P, B, N>> | |
| 836 | where | |
| 837 | F : ClapFloat + nalgebra::RealField + ToNalgebraRealField<MixedType=F>, | |
| 838 | [usize; N] : Serialize, | |
| 839 | S : Sensor<F, N> + Copy + Serialize + std::fmt::Debug, | |
| 840 | P : Spread<F, N> + Copy + Serialize + std::fmt::Debug, | |
| 841 | Convolution<S, P>: Spread<F, N> + Bounded<F> + LocalAnalysis<F, Bounds<F>, N> + Copy | |
| 842 | // TODO: shold not have differentiability as a requirement, but | |
| 843 | // decide availability of sliding based on it. | |
| 844 | //+ for<'b> Differentiable<&'b Loc<F, N>, Output = Loc<F, N>>, | |
| 845 | // TODO: very weird that rust only compiles with Differentiable | |
| 846 | // instead of the above one on references, which is required by | |
| 847 | // poitsource_sliding_fb_reg. | |
| 848 | + DifferentiableRealMapping<F, N> | |
| 849 | + Lipschitz<L2, FloatType=F>, | |
| 850 | for<'b> <Convolution<S, P> as DifferentiableMapping<Loc<F,N>>>::Differential<'b> : Lipschitz<L2, FloatType=F>, // TODO: should not be required generally, only for sliding_fb. | |
| 851 | AutoConvolution<P> : BoundedBy<F, K>, | |
| 852 | K : SimpleConvolutionKernel<F, N> | |
| 853 | + LocalAnalysis<F, Bounds<F>, N> | |
| 854 | + Copy + Serialize + std::fmt::Debug, | |
| 855 | Cube<F, N>: P2Minimise<Loc<F, N>, F> + SetOrd, | |
| 856 | PlotLookup : Plotting<N>, | |
| 857 | DefaultBT<F, N> : SensorGridBT<F, S, P, N, Depth=DynamicDepth> + BTSearch<F, N>, | |
| 858 | BTNodeLookup: BTNode<F, usize, Bounds<F>, N>, | |
| 859 | RNDM<F, N> : SpikeMerging<F>, | |
| 860 | NoiseDistr : Distribution<F> + Serialize + std::fmt::Debug, | |
| 861 | B : Mapping<Loc<F, N>, Codomain = F> + Serialize + std::fmt::Debug, | |
| 862 | { | |
| 863 | ||
| 864 | fn algorithm_defaults(&self, alg : DefaultAlgorithm) -> Option<AlgorithmConfig<F>> { | |
| 865 | self.data.base.algorithm_defaults.get(&alg).cloned() | |
| 866 | } | |
| 867 | ||
| 868 | fn runall(&self, cli : &CommandLineArgs, | |
| 869 | algs : Option<Vec<Named<AlgorithmConfig<F>>>>) -> DynError { | |
| 870 | // Get experiment configuration | |
| 871 | let &Named { | |
| 872 | name : ref experiment_name, | |
| 873 | data : ExperimentBiased { | |
| 874 | λ, | |
| 875 | ref bias, | |
| 876 | base : ExperimentV2 { | |
| 877 | domain, sensor_count, ref noise_distr, sensor, spread, kernel, | |
| 878 | ref μ_hat, regularisation, kernel_plot_width, dataterm, noise_seed, | |
| 879 | .. | |
| 880 | } | |
| 881 | } | |
| 882 | } = self; | |
| 883 | ||
| 884 | // Set up algorithms | |
| 885 | let algorithms = match (algs, dataterm) { | |
| 886 | (Some(algs), _) => algs, | |
| 887 | _ => vec![DefaultAlgorithm::SlidingPDPS.get_named()], | |
| 888 | }; | |
| 889 | ||
| 890 | // Set up operators | |
| 891 | let depth = DynamicDepth(8); | |
| 892 | let opA = DefaultSG::new(domain, sensor_count, sensor, spread, depth); | |
| 893 | let op𝒟 = DefaultSeminormOp::new(depth, domain, kernel); | |
| 894 | let opAext = RowOp(opA.clone(), IdOp::new()); | |
| 895 | let fnR = Zero::new(); | |
| 896 | let h = map3(domain.span_start(), domain.span_end(), sensor_count, | |
| 897 | |a, b, n| (b-a)/F::cast_from(n)) | |
| 898 | .into_iter() | |
| 899 | .reduce(NumTraitsFloat::max) | |
| 900 | .unwrap(); | |
| 901 | let z = DVector::zeros(sensor_count.iter().product()); | |
| 902 | let opKz = Grad::new_for(&z, h, sensor_count, ForwardNeumann).unwrap(); | |
| 903 | let y = opKz.apply(&z); | |
| 904 | let fnH = Weighted{ base_fn : L1.as_mapping(), weight : λ}; // TODO: L_{2,1} | |
| 905 | // let zero_y = y.clone(); | |
| 906 | // let zeroBTFN = opA.preadjoint().apply(&zero_y); | |
| 907 | // let opKμ = ZeroOp::new(&zero_y, zeroBTFN); | |
| 908 | ||
| 909 | // Set up random number generator. | |
| 910 | let mut rng = StdRng::seed_from_u64(noise_seed); | |
| 911 | ||
| 912 | // Generate the data and calculate SSNR statistic | |
| 913 | let bias_vec = DVector::from_vec(opA.grid() | |
| 914 | .into_iter() | |
| 915 | .map(|v| bias.apply(v)) | |
| 916 | .collect::<Vec<F>>()); | |
| 917 | let b_hat : DVector<_> = opA.apply(μ_hat) + &bias_vec; | |
| 918 | let noise = DVector::from_distribution(b_hat.len(), &noise_distr, &mut rng); | |
| 919 | let b = &b_hat + &noise; | |
| 920 | // Need to wrap calc_ssnr into a function to hide ultra-lame nalgebra::RealField | |
| 921 | // overloading log10 and conflicting with standard NumTraits one. | |
| 922 | let stats = ExperimentStats::new(&b, &noise); | |
| 923 | ||
| 924 | let prefix = start_experiment(&self, cli, stats)?; | |
| 925 | ||
| 926 | plotall(cli, &prefix, &domain, &sensor, &kernel, &spread, | |
| 927 | &μ_hat, &op𝒟, &opA, &b_hat, &b, kernel_plot_width)?; | |
| 928 | ||
| 929 | opA.write_observable(&bias_vec, format!("{prefix}bias"))?; | |
| 930 | ||
| 931 | let plotgrid = lingrid(&domain, &[if N==1 { 1000 } else { 100 }; N]); | |
| 932 | ||
| 933 | let save_extra = |prefix, z| opA.write_observable(&z, format!("{prefix}z")); | |
|
24
d29d1fcf5423
Support arbitrary regularisation terms; implement non-positivity-constrained regularisation.
Tuomo Valkonen <tuomov@iki.fi>
parents:
23
diff
changeset
|
934 | |
| 35 | 935 | // Run the algorithms |
| 936 | do_runall(experiment_name, &prefix, cli, algorithms, plotgrid, save_extra, | |
| 937 | |alg, iterator, plotter, running| | |
| 938 | { | |
| 939 | let Pair(μ, z) = match alg { | |
| 940 | AlgorithmConfig::ForwardPDPS(ref algconfig) => { | |
| 941 | match (regularisation, dataterm) { | |
| 942 | (Regularisation::NonnegRadon(α), DataTerm::L2Squared) => Ok({ | |
| 943 | print!("{running}"); | |
| 944 | pointsource_forward_pdps_pair( | |
| 945 | &opAext, &b, NonnegRadonRegTerm(α), &op𝒟, algconfig, | |
| 946 | iterator, plotter, | |
| 947 | /* opKμ, */ &opKz, &fnR, &fnH, z.clone(), y.clone(), | |
| 948 | ) | |
| 949 | }), | |
| 950 | (Regularisation::Radon(α), DataTerm::L2Squared) => Ok({ | |
| 951 | print!("{running}"); | |
| 952 | pointsource_forward_pdps_pair( | |
| 953 | &opAext, &b, RadonRegTerm(α), &op𝒟, algconfig, | |
| 954 | iterator, plotter, | |
| 955 | /* opKμ, */ &opKz, &fnR, &fnH, z.clone(), y.clone(), | |
| 956 | ) | |
| 957 | }), | |
| 958 | _ => Err(NotImplemented) | |
| 959 | } | |
| 960 | }, | |
| 961 | AlgorithmConfig::SlidingPDPS(ref algconfig) => { | |
| 962 | match (regularisation, dataterm) { | |
| 963 | (Regularisation::NonnegRadon(α), DataTerm::L2Squared) => Ok({ | |
| 964 | print!("{running}"); | |
| 965 | pointsource_sliding_pdps_pair( | |
| 966 | &opAext, &b, NonnegRadonRegTerm(α), &op𝒟, algconfig, | |
| 967 | iterator, plotter, | |
| 968 | /* opKμ, */ &opKz, &fnR, &fnH, z.clone(), y.clone(), | |
| 969 | ) | |
| 970 | }), | |
| 971 | (Regularisation::Radon(α), DataTerm::L2Squared) => Ok({ | |
| 972 | print!("{running}"); | |
| 973 | pointsource_sliding_pdps_pair( | |
| 974 | &opAext, &b, RadonRegTerm(α), &op𝒟, algconfig, | |
| 975 | iterator, plotter, | |
| 976 | /* opKμ, */ &opKz, &fnR, &fnH, z.clone(), y.clone(), | |
| 977 | ) | |
| 978 | }), | |
| 979 | _ => Err(NotImplemented) | |
| 980 | } | |
| 981 | }, | |
| 982 | _ => Err(NotImplemented) | |
| 983 | }?; | |
| 984 | Ok((μ, z)) | |
| 985 | }) | |
| 986 | } | |
| 987 | } | |
| 988 | ||
| 989 | ||
| 990 | /// Calculative minimum and maximum values of all the `logs`, and save them into | |
| 991 | /// corresponding file names given as the first elements of the tuples in the vectors. | |
| 992 | fn save_logs<F : Float, const N : usize>( | |
| 993 | logs : Vec<(String, Logger<Timed<IterInfo<F, N>>>)> | |
| 994 | ) -> DynError { | |
| 995 | // Process logs for relative values | |
| 996 | println!("{}", "Processing logs…"); | |
| 997 | ||
| 998 | ||
| 999 | // Find minimum value and initial value within a single log | |
| 1000 | let proc_single_log = |log : &Logger<Timed<IterInfo<F, N>>>| { | |
| 1001 | let d = log.data(); | |
| 1002 | let mi = d.iter() | |
| 1003 | .map(|i| i.data.value) | |
| 1004 | .reduce(NumTraitsFloat::min); | |
| 1005 | d.first() | |
| 1006 | .map(|i| i.data.value) | |
| 1007 | .zip(mi) | |
| 1008 | }; | |
| 1009 | ||
| 1010 | // Find minimum and maximum value over all logs | |
| 1011 | let (v_ini, v_min) = logs.iter() | |
| 1012 | .filter_map(|&(_, ref log)| proc_single_log(log)) | |
| 1013 | .reduce(|(i1, m1), (i2, m2)| (i1.max(i2), m1.min(m2))) | |
| 1014 | .ok_or(anyhow!("No algorithms found"))?; | |
| 1015 | ||
| 1016 | let logmap = |Timed { cpu_time, iter, data }| { | |
| 1017 | let IterInfo { | |
| 1018 | value, | |
| 1019 | n_spikes, | |
| 1020 | inner_iters, | |
| 1021 | merged, | |
| 1022 | pruned, | |
| 1023 | //postprocessing, | |
| 1024 | this_iters, | |
| 1025 | .. | |
| 1026 | } = data; | |
| 1027 | // let post_value = match (postprocessing, dataterm) { | |
| 1028 | // (Some(mut μ), DataTerm::L2Squared) => { | |
| 1029 | // // Comparison postprocessing is only implemented for the case handled | |
| 1030 | // // by the FW variants. | |
| 1031 | // reg.optimise_weights( | |
| 1032 | // &mut μ, &opA, &b, &findim_data, &inner_config, | |
| 1033 | // inner_it | |
| 1034 | // ); | |
| 1035 | // dataterm.value_at_residual(opA.apply(&μ) - &b) | |
| 1036 | // + regularisation.apply(&μ) | |
| 1037 | // }, | |
| 1038 | // _ => value, | |
| 1039 | // }; | |
| 1040 | let relative_value = (value - v_min)/(v_ini - v_min); | |
| 1041 | CSVLog { | |
| 1042 | iter, | |
| 1043 | value, | |
| 1044 | relative_value, | |
| 1045 | //post_value, | |
| 1046 | n_spikes, | |
| 1047 | cpu_time : cpu_time.as_secs_f64(), | |
| 1048 | inner_iters, | |
| 1049 | merged, | |
| 1050 | pruned, | |
| 1051 | this_iters | |
| 1052 | } | |
| 1053 | }; | |
| 1054 | ||
| 1055 | println!("{}", "Saving logs …".green()); | |
| 1056 | ||
| 1057 | for (name, logger) in logs { | |
| 1058 | logger.map(logmap).write_csv(name)?; | |
| 1059 | } | |
| 1060 | ||
| 1061 | Ok(()) | |
| 1062 | } | |
| 1063 | ||
| 0 | 1064 | |
| 1065 | /// Plot experiment setup | |
| 1066 | #[replace_float_literals(F::cast_from(literal))] | |
| 1067 | fn plotall<F, Sensor, Kernel, Spread, 𝒟, A, const N : usize>( | |
|
9
21b0e537ac0e
Command line parameter passing simplifications and make `-o` required.
Tuomo Valkonen <tuomov@iki.fi>
parents:
0
diff
changeset
|
1068 | cli : &CommandLineArgs, |
| 0 | 1069 | prefix : &String, |
| 1070 | domain : &Cube<F, N>, | |
| 1071 | sensor : &Sensor, | |
| 1072 | kernel : &Kernel, | |
| 1073 | spread : &Spread, | |
| 35 | 1074 | μ_hat : &RNDM<F, N>, |
| 0 | 1075 | op𝒟 : &𝒟, |
| 1076 | opA : &A, | |
| 1077 | b_hat : &A::Observable, | |
| 1078 | b : &A::Observable, | |
| 1079 | kernel_plot_width : F, | |
| 1080 | ) -> DynError | |
| 1081 | where F : Float + ToNalgebraRealField, | |
| 1082 | Sensor : RealMapping<F, N> + Support<F, N> + Clone, | |
| 1083 | Spread : RealMapping<F, N> + Support<F, N> + Clone, | |
| 1084 | Kernel : RealMapping<F, N> + Support<F, N>, | |
|
34
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
1085 | Convolution<Sensor, Spread> : DifferentiableRealMapping<F, N> + Support<F, N>, |
| 0 | 1086 | 𝒟 : DiscreteMeasureOp<Loc<F, N>, F>, |
| 1087 | 𝒟::Codomain : RealMapping<F, N>, | |
| 35 | 1088 | A : ForwardModel<RNDM<F, N>, F>, |
| 1089 | for<'a> &'a A::Observable : Instance<A::Observable>, | |
|
34
efa60bc4f743
Radon FB + sliding improvements
Tuomo Valkonen <tuomov@iki.fi>
parents:
32
diff
changeset
|
1090 | A::PreadjointCodomain : DifferentiableRealMapping<F, N> + Bounded<F>, |
| 0 | 1091 | PlotLookup : Plotting<N>, |
| 1092 | Cube<F, N> : SetOrd { | |
| 1093 | ||
|
9
21b0e537ac0e
Command line parameter passing simplifications and make `-o` required.
Tuomo Valkonen <tuomov@iki.fi>
parents:
0
diff
changeset
|
1094 | if cli.plot < PlotLevel::Data { |
| 0 | 1095 | return Ok(()) |
| 1096 | } | |
| 1097 | ||
| 1098 | let base = Convolution(sensor.clone(), spread.clone()); | |
| 1099 | ||
| 1100 | let resolution = if N==1 { 100 } else { 40 }; | |
| 35 | 1101 | let pfx = |n| format!("{prefix}{n}"); |
| 0 | 1102 | let plotgrid = lingrid(&[[-kernel_plot_width, kernel_plot_width]; N].into(), &[resolution; N]); |
| 1103 | ||
| 35 | 1104 | PlotLookup::plot_into_file(sensor, plotgrid, pfx("sensor")); |
| 1105 | PlotLookup::plot_into_file(kernel, plotgrid, pfx("kernel")); | |
| 1106 | PlotLookup::plot_into_file(spread, plotgrid, pfx("spread")); | |
| 1107 | PlotLookup::plot_into_file(&base, plotgrid, pfx("base_sensor")); | |
| 0 | 1108 | |
| 1109 | let plotgrid2 = lingrid(&domain, &[resolution; N]); | |
| 1110 | ||
| 1111 | let ω_hat = op𝒟.apply(μ_hat); | |
| 1112 | let noise = opA.preadjoint().apply(opA.apply(μ_hat) - b); | |
| 35 | 1113 | PlotLookup::plot_into_file(&ω_hat, plotgrid2, pfx("omega_hat")); |
| 1114 | PlotLookup::plot_into_file(&noise, plotgrid2, pfx("omega_noise")); | |
| 0 | 1115 | |
| 1116 | let preadj_b = opA.preadjoint().apply(b); | |
| 1117 | let preadj_b_hat = opA.preadjoint().apply(b_hat); | |
| 1118 | //let bounds = preadj_b.bounds().common(&preadj_b_hat.bounds()); | |
| 1119 | PlotLookup::plot_into_file_spikes( | |
| 35 | 1120 | Some(&preadj_b), |
| 1121 | Some(&preadj_b_hat), | |
| 1122 | plotgrid2, | |
| 1123 | &μ_hat, | |
| 0 | 1124 | pfx("omega_b") |
| 1125 | ); | |
| 35 | 1126 | PlotLookup::plot_into_file(&preadj_b, plotgrid2, pfx("preadj_b")); |
| 1127 | PlotLookup::plot_into_file(&preadj_b_hat, plotgrid2, pfx("preadj_b_hat")); | |
| 0 | 1128 | |
| 1129 | // Save true solution and observables | |
| 1130 | μ_hat.write_csv(pfx("orig.txt"))?; | |
| 1131 | opA.write_observable(&b_hat, pfx("b_hat"))?; | |
| 1132 | opA.write_observable(&b, pfx("b_noisy")) | |
| 1133 | } |