Tue, 06 Dec 2022 14:12:20 +0200
v1.0.0-pre-arxiv (missing arXiv links)
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, | |
29 | }; | |
30 | use alg_tools::logger::Logger; | |
31 | use alg_tools::error::DynError; | |
32 | use alg_tools::tabledump::TableDump; | |
33 | use alg_tools::sets::Cube; | |
34 | use alg_tools::mapping::RealMapping; | |
35 | use alg_tools::nalgebra_support::ToNalgebraRealField; | |
36 | use alg_tools::euclidean::Euclidean; | |
37 | use alg_tools::norms::{Norm, L1}; | |
38 | use alg_tools::lingrid::lingrid; | |
39 | use alg_tools::sets::SetOrd; | |
40 | ||
41 | use crate::kernels::*; | |
42 | use crate::types::*; | |
43 | use crate::measures::*; | |
44 | use crate::measures::merging::SpikeMerging; | |
45 | use crate::forward_model::*; | |
46 | use crate::fb::{ | |
47 | FBConfig, | |
48 | pointsource_fb, | |
49 | FBMetaAlgorithm, FBGenericConfig, | |
50 | }; | |
51 | use crate::pdps::{ | |
52 | PDPSConfig, | |
53 | L2Squared, | |
54 | pointsource_pdps, | |
55 | }; | |
56 | use crate::frank_wolfe::{ | |
57 | FWConfig, | |
58 | FWVariant, | |
59 | pointsource_fw, | |
60 | prepare_optimise_weights, | |
61 | optimise_weights, | |
62 | }; | |
63 | use crate::subproblem::InnerSettings; | |
64 | use crate::seminorms::*; | |
65 | use crate::plot::*; | |
9
21b0e537ac0e
Command line parameter passing simplifications and make `-o` required.
Tuomo Valkonen <tuomov@iki.fi>
parents:
0
diff
changeset
|
66 | use crate::{AlgorithmOverrides, CommandLineArgs}; |
0 | 67 | |
68 | /// Available algorithms and their configurations | |
69 | #[derive(Copy, Clone, Debug, Serialize, Deserialize)] | |
70 | pub enum AlgorithmConfig<F : Float> { | |
71 | FB(FBConfig<F>), | |
72 | FW(FWConfig<F>), | |
73 | PDPS(PDPSConfig<F>), | |
74 | } | |
75 | ||
76 | impl<F : ClapFloat> AlgorithmConfig<F> { | |
77 | /// Override supported parameters based on the command line. | |
78 | pub fn cli_override(self, cli : &AlgorithmOverrides<F>) -> Self { | |
79 | let override_fb_generic = |g : FBGenericConfig<F>| { | |
80 | FBGenericConfig { | |
81 | bootstrap_insertions : cli.bootstrap_insertions | |
82 | .as_ref() | |
83 | .map_or(g.bootstrap_insertions, | |
84 | |n| Some((n[0], n[1]))), | |
85 | merge_every : cli.merge_every.unwrap_or(g.merge_every), | |
86 | merging : cli.merging.clone().unwrap_or(g.merging), | |
87 | final_merging : cli.final_merging.clone().unwrap_or(g.final_merging), | |
88 | .. g | |
89 | } | |
90 | }; | |
91 | ||
92 | use AlgorithmConfig::*; | |
93 | match self { | |
94 | FB(fb) => FB(FBConfig { | |
95 | τ0 : cli.tau0.unwrap_or(fb.τ0), | |
96 | insertion : override_fb_generic(fb.insertion), | |
97 | .. fb | |
98 | }), | |
99 | PDPS(pdps) => PDPS(PDPSConfig { | |
100 | τ0 : cli.tau0.unwrap_or(pdps.τ0), | |
101 | σ0 : cli.sigma0.unwrap_or(pdps.σ0), | |
102 | acceleration : cli.acceleration.unwrap_or(pdps.acceleration), | |
103 | insertion : override_fb_generic(pdps.insertion), | |
104 | .. pdps | |
105 | }), | |
106 | FW(fw) => FW(FWConfig { | |
107 | merging : cli.merging.clone().unwrap_or(fw.merging), | |
108 | .. fw | |
109 | }) | |
110 | } | |
111 | } | |
112 | } | |
113 | ||
114 | /// Helper struct for tagging and [`AlgorithmConfig`] or [`Experiment`] with a name. | |
115 | #[derive(Clone, Debug, Serialize, Deserialize)] | |
116 | pub struct Named<Data> { | |
117 | pub name : String, | |
118 | #[serde(flatten)] | |
119 | pub data : Data, | |
120 | } | |
121 | ||
122 | /// 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
|
123 | #[derive(ValueEnum, Debug, Copy, Clone, Eq, PartialEq, Hash, Serialize, Deserialize)] |
0 | 124 | pub enum DefaultAlgorithm { |
125 | /// The μFB forward-backward method | |
126 | #[clap(name = "fb")] | |
127 | FB, | |
128 | /// The μFISTA inertial forward-backward method | |
129 | #[clap(name = "fista")] | |
130 | FISTA, | |
131 | /// The “fully corrective” conditional gradient method | |
132 | #[clap(name = "fw")] | |
133 | FW, | |
134 | /// The “relaxed conditional gradient method | |
135 | #[clap(name = "fwrelax")] | |
136 | FWRelax, | |
137 | /// The μPDPS primal-dual proximal splitting method | |
138 | #[clap(name = "pdps")] | |
139 | PDPS, | |
140 | } | |
141 | ||
142 | impl DefaultAlgorithm { | |
143 | /// Returns the algorithm configuration corresponding to the algorithm shorthand | |
144 | pub fn default_config<F : Float>(&self) -> AlgorithmConfig<F> { | |
145 | use DefaultAlgorithm::*; | |
146 | match *self { | |
147 | FB => AlgorithmConfig::FB(Default::default()), | |
148 | FISTA => AlgorithmConfig::FB(FBConfig{ | |
149 | meta : FBMetaAlgorithm::InertiaFISTA, | |
150 | .. Default::default() | |
151 | }), | |
152 | FW => AlgorithmConfig::FW(Default::default()), | |
153 | FWRelax => AlgorithmConfig::FW(FWConfig{ | |
154 | variant : FWVariant::Relaxed, | |
155 | .. Default::default() | |
156 | }), | |
157 | PDPS => AlgorithmConfig::PDPS(Default::default()), | |
158 | } | |
159 | } | |
160 | ||
161 | /// Returns the [`Named`] algorithm corresponding to the algorithm shorthand | |
162 | pub fn get_named<F : Float>(&self) -> Named<AlgorithmConfig<F>> { | |
163 | self.to_named(self.default_config()) | |
164 | } | |
165 | ||
166 | pub fn to_named<F : Float>(self, alg : AlgorithmConfig<F>) -> Named<AlgorithmConfig<F>> { | |
167 | let name = self.to_possible_value().unwrap().get_name().to_string(); | |
168 | Named{ name , data : alg } | |
169 | } | |
170 | } | |
171 | ||
172 | ||
173 | // // Floats cannot be hashed directly, so just hash the debug formatting | |
174 | // // for use as file identifier. | |
175 | // impl<F : Float> Hash for AlgorithmConfig<F> { | |
176 | // fn hash<H: Hasher>(&self, state: &mut H) { | |
177 | // format!("{:?}", self).hash(state); | |
178 | // } | |
179 | // } | |
180 | ||
181 | /// Plotting level configuration | |
182 | #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Serialize, ValueEnum, Debug)] | |
183 | pub enum PlotLevel { | |
184 | /// Plot nothing | |
185 | #[clap(name = "none")] | |
186 | None, | |
187 | /// Plot problem data | |
188 | #[clap(name = "data")] | |
189 | Data, | |
190 | /// Plot iterationwise state | |
191 | #[clap(name = "iter")] | |
192 | Iter, | |
193 | } | |
194 | ||
195 | type DefaultBT<F, const N : usize> = BT< | |
196 | DynamicDepth, | |
197 | F, | |
198 | usize, | |
199 | Bounds<F>, | |
200 | N | |
201 | >; | |
202 | type DefaultSeminormOp<F, K, const N : usize> = ConvolutionOp<F, K, DefaultBT<F, N>, N>; | |
203 | type DefaultSG<F, Sensor, Spread, const N : usize> = SensorGrid::< | |
204 | F, | |
205 | Sensor, | |
206 | Spread, | |
207 | DefaultBT<F, N>, | |
208 | N | |
209 | >; | |
210 | ||
211 | /// This is a dirty workaround to rust-csv not supporting struct flattening etc. | |
212 | #[derive(Serialize)] | |
213 | struct CSVLog<F> { | |
214 | iter : usize, | |
215 | cpu_time : f64, | |
216 | value : F, | |
217 | post_value : F, | |
218 | n_spikes : usize, | |
219 | inner_iters : usize, | |
220 | merged : usize, | |
221 | pruned : usize, | |
222 | this_iters : usize, | |
223 | } | |
224 | ||
225 | /// Collected experiment statistics | |
226 | #[derive(Clone, Debug, Serialize)] | |
227 | struct ExperimentStats<F : Float> { | |
228 | /// Signal-to-noise ratio in decibels | |
229 | ssnr : F, | |
230 | /// Proportion of noise in the signal as a number in $[0, 1]$. | |
231 | noise_ratio : F, | |
232 | /// When the experiment was run (UTC) | |
233 | when : DateTime<Utc>, | |
234 | } | |
235 | ||
236 | #[replace_float_literals(F::cast_from(literal))] | |
237 | impl<F : Float> ExperimentStats<F> { | |
238 | /// Calculate [`ExperimentStats`] based on a noisy `signal` and the separated `noise` signal. | |
239 | fn new<E : Euclidean<F>>(signal : &E, noise : &E) -> Self { | |
240 | let s = signal.norm2_squared(); | |
241 | let n = noise.norm2_squared(); | |
242 | let noise_ratio = (n / s).sqrt(); | |
243 | let ssnr = 10.0 * (s / n).log10(); | |
244 | ExperimentStats { | |
245 | ssnr, | |
246 | noise_ratio, | |
247 | when : Utc::now(), | |
248 | } | |
249 | } | |
250 | } | |
251 | /// Collected algorithm statistics | |
252 | #[derive(Clone, Debug, Serialize)] | |
253 | struct AlgorithmStats<F : Float> { | |
254 | /// Overall CPU time spent | |
255 | cpu_time : F, | |
256 | /// Real time spent | |
257 | elapsed : F | |
258 | } | |
259 | ||
260 | ||
261 | /// A wrapper for [`serde_json::to_writer_pretty`] that takes a filename as input | |
262 | /// and outputs a [`DynError`]. | |
263 | fn write_json<T : Serialize>(filename : String, data : &T) -> DynError { | |
264 | serde_json::to_writer_pretty(std::fs::File::create(filename)?, data)?; | |
265 | Ok(()) | |
266 | } | |
267 | ||
268 | ||
269 | /// Struct for experiment configurations | |
270 | #[derive(Debug, Clone, Serialize)] | |
271 | pub struct Experiment<F, NoiseDistr, S, K, P, const N : usize> | |
272 | where F : Float, | |
273 | [usize; N] : Serialize, | |
274 | NoiseDistr : Distribution<F>, | |
275 | S : Sensor<F, N>, | |
276 | P : Spread<F, N>, | |
277 | K : SimpleConvolutionKernel<F, N>, | |
278 | { | |
279 | /// Domain $Ω$. | |
280 | pub domain : Cube<F, N>, | |
281 | /// Number of sensors along each dimension | |
282 | pub sensor_count : [usize; N], | |
283 | /// Noise distribution | |
284 | pub noise_distr : NoiseDistr, | |
285 | /// Seed for random noise generation (for repeatable experiments) | |
286 | pub noise_seed : u64, | |
287 | /// Sensor $θ$; $θ * ψ$ forms the forward operator $𝒜$. | |
288 | pub sensor : S, | |
289 | /// Spread $ψ$; $θ * ψ$ forms the forward operator $𝒜$. | |
290 | pub spread : P, | |
291 | /// Kernel $ρ$ of $𝒟$. | |
292 | pub kernel : K, | |
293 | /// True point sources | |
294 | pub μ_hat : DiscreteMeasure<Loc<F, N>, F>, | |
295 | /// Regularisation parameter | |
296 | pub α : F, | |
297 | /// For plotting : how wide should the kernels be plotted | |
298 | pub kernel_plot_width : F, | |
299 | /// Data term | |
300 | pub dataterm : DataTerm, | |
301 | /// A map of default configurations for algorithms | |
302 | #[serde(skip)] | |
303 | pub algorithm_defaults : HashMap<DefaultAlgorithm, AlgorithmConfig<F>>, | |
304 | } | |
305 | ||
306 | /// Trait for runnable experiments | |
307 | 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
|
308 | /// 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
|
309 | fn runall(&self, cli : &CommandLineArgs, |
21b0e537ac0e
Command line parameter passing simplifications and make `-o` required.
Tuomo Valkonen <tuomov@iki.fi>
parents:
0
diff
changeset
|
310 | algs : Option<Vec<Named<AlgorithmConfig<F>>>>) -> DynError; |
0 | 311 | |
312 | /// Return algorithm default config | |
313 | fn algorithm_defaults(&self, alg : DefaultAlgorithm, cli : &AlgorithmOverrides<F>) | |
314 | -> Named<AlgorithmConfig<F>>; | |
315 | } | |
316 | ||
317 | impl<F, NoiseDistr, S, K, P, const N : usize> RunnableExperiment<F> for | |
318 | Named<Experiment<F, NoiseDistr, S, K, P, N>> | |
319 | where F : ClapFloat + nalgebra::RealField + ToNalgebraRealField<MixedType=F>, | |
320 | [usize; N] : Serialize, | |
321 | S : Sensor<F, N> + Copy + Serialize, | |
322 | P : Spread<F, N> + Copy + Serialize, | |
323 | Convolution<S, P>: Spread<F, N> + Bounded<F> + LocalAnalysis<F, Bounds<F>, N> + Copy, | |
324 | AutoConvolution<P> : BoundedBy<F, K>, | |
325 | K : SimpleConvolutionKernel<F, N> + LocalAnalysis<F, Bounds<F>, N> + Copy + Serialize, | |
326 | Cube<F, N>: P2Minimise<Loc<F, N>, F> + SetOrd, | |
327 | PlotLookup : Plotting<N>, | |
328 | DefaultBT<F, N> : SensorGridBT<F, S, P, N, Depth=DynamicDepth> + BTSearch<F, N>, | |
329 | BTNodeLookup: BTNode<F, usize, Bounds<F>, N>, | |
330 | DiscreteMeasure<Loc<F, N>, F> : SpikeMerging<F>, | |
331 | NoiseDistr : Distribution<F> + Serialize { | |
332 | ||
333 | fn algorithm_defaults(&self, alg : DefaultAlgorithm, cli : &AlgorithmOverrides<F>) | |
334 | -> Named<AlgorithmConfig<F>> { | |
335 | alg.to_named( | |
336 | self.data | |
337 | .algorithm_defaults | |
338 | .get(&alg) | |
339 | .map_or_else(|| alg.default_config(), | |
340 | |config| config.clone()) | |
341 | .cli_override(cli) | |
342 | ) | |
343 | } | |
344 | ||
9
21b0e537ac0e
Command line parameter passing simplifications and make `-o` required.
Tuomo Valkonen <tuomov@iki.fi>
parents:
0
diff
changeset
|
345 | fn runall(&self, cli : &CommandLineArgs, |
21b0e537ac0e
Command line parameter passing simplifications and make `-o` required.
Tuomo Valkonen <tuomov@iki.fi>
parents:
0
diff
changeset
|
346 | 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
|
347 | // Get experiment configuration |
0 | 348 | let &Named { |
349 | name : ref experiment_name, | |
350 | data : Experiment { | |
351 | domain, sensor_count, ref noise_distr, sensor, spread, kernel, | |
352 | ref μ_hat, α, kernel_plot_width, dataterm, noise_seed, | |
353 | .. | |
354 | } | |
355 | } = self; | |
356 | ||
9
21b0e537ac0e
Command line parameter passing simplifications and make `-o` required.
Tuomo Valkonen <tuomov@iki.fi>
parents:
0
diff
changeset
|
357 | // Set up output directory |
21b0e537ac0e
Command line parameter passing simplifications and make `-o` required.
Tuomo Valkonen <tuomov@iki.fi>
parents:
0
diff
changeset
|
358 | let prefix = format!("{}/{}/", cli.outdir, self.name); |
21b0e537ac0e
Command line parameter passing simplifications and make `-o` required.
Tuomo Valkonen <tuomov@iki.fi>
parents:
0
diff
changeset
|
359 | |
21b0e537ac0e
Command line parameter passing simplifications and make `-o` required.
Tuomo Valkonen <tuomov@iki.fi>
parents:
0
diff
changeset
|
360 | // Set up algorithms |
21b0e537ac0e
Command line parameter passing simplifications and make `-o` required.
Tuomo Valkonen <tuomov@iki.fi>
parents:
0
diff
changeset
|
361 | let iterator_options = AlgIteratorOptions{ |
21b0e537ac0e
Command line parameter passing simplifications and make `-o` required.
Tuomo Valkonen <tuomov@iki.fi>
parents:
0
diff
changeset
|
362 | max_iter : cli.max_iter, |
21b0e537ac0e
Command line parameter passing simplifications and make `-o` required.
Tuomo Valkonen <tuomov@iki.fi>
parents:
0
diff
changeset
|
363 | verbose_iter : cli.verbose_iter |
21b0e537ac0e
Command line parameter passing simplifications and make `-o` required.
Tuomo Valkonen <tuomov@iki.fi>
parents:
0
diff
changeset
|
364 | .map_or(Verbose::Logarithmic(10), |
21b0e537ac0e
Command line parameter passing simplifications and make `-o` required.
Tuomo Valkonen <tuomov@iki.fi>
parents:
0
diff
changeset
|
365 | |n| Verbose::Every(n)), |
21b0e537ac0e
Command line parameter passing simplifications and make `-o` required.
Tuomo Valkonen <tuomov@iki.fi>
parents:
0
diff
changeset
|
366 | quiet : cli.quiet, |
21b0e537ac0e
Command line parameter passing simplifications and make `-o` required.
Tuomo Valkonen <tuomov@iki.fi>
parents:
0
diff
changeset
|
367 | }; |
21b0e537ac0e
Command line parameter passing simplifications and make `-o` required.
Tuomo Valkonen <tuomov@iki.fi>
parents:
0
diff
changeset
|
368 | let algorithms = match (algs, self.data.dataterm) { |
21b0e537ac0e
Command line parameter passing simplifications and make `-o` required.
Tuomo Valkonen <tuomov@iki.fi>
parents:
0
diff
changeset
|
369 | (Some(algs), _) => algs, |
21b0e537ac0e
Command line parameter passing simplifications and make `-o` required.
Tuomo Valkonen <tuomov@iki.fi>
parents:
0
diff
changeset
|
370 | (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
|
371 | (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
|
372 | }; |
0 | 373 | |
374 | // Set up operators | |
9
21b0e537ac0e
Command line parameter passing simplifications and make `-o` required.
Tuomo Valkonen <tuomov@iki.fi>
parents:
0
diff
changeset
|
375 | let depth = DynamicDepth(8); |
0 | 376 | let opA = DefaultSG::new(domain, sensor_count, sensor, spread, depth); |
377 | let op𝒟 = DefaultSeminormOp::new(depth, domain, kernel); | |
378 | ||
379 | // Set up random number generator. | |
380 | let mut rng = StdRng::seed_from_u64(noise_seed); | |
381 | ||
382 | // Generate the data and calculate SSNR statistic | |
383 | let b_hat = opA.apply(μ_hat); | |
384 | let noise = DVector::from_distribution(b_hat.len(), &noise_distr, &mut rng); | |
385 | let b = &b_hat + &noise; | |
386 | // Need to wrap calc_ssnr into a function to hide ultra-lame nalgebra::RealField | |
387 | // overloading log10 and conflicting with standard NumTraits one. | |
388 | let stats = ExperimentStats::new(&b, &noise); | |
389 | ||
390 | // Save experiment configuration and statistics | |
391 | let mkname_e = |t| format!("{prefix}{t}.json", prefix = prefix, t = t); | |
392 | std::fs::create_dir_all(&prefix)?; | |
393 | write_json(mkname_e("experiment"), self)?; | |
9
21b0e537ac0e
Command line parameter passing simplifications and make `-o` required.
Tuomo Valkonen <tuomov@iki.fi>
parents:
0
diff
changeset
|
394 | write_json(mkname_e("config"), cli)?; |
0 | 395 | write_json(mkname_e("stats"), &stats)?; |
396 | ||
9
21b0e537ac0e
Command line parameter passing simplifications and make `-o` required.
Tuomo Valkonen <tuomov@iki.fi>
parents:
0
diff
changeset
|
397 | plotall(cli, &prefix, &domain, &sensor, &kernel, &spread, |
0 | 398 | &μ_hat, &op𝒟, &opA, &b_hat, &b, kernel_plot_width)?; |
399 | ||
400 | // Run the algorithm(s) | |
9
21b0e537ac0e
Command line parameter passing simplifications and make `-o` required.
Tuomo Valkonen <tuomov@iki.fi>
parents:
0
diff
changeset
|
401 | for named @ Named { name : alg_name, data : alg } in algorithms.iter() { |
0 | 402 | let this_prefix = format!("{}{}/", prefix, alg_name); |
403 | ||
9
21b0e537ac0e
Command line parameter passing simplifications and make `-o` required.
Tuomo Valkonen <tuomov@iki.fi>
parents:
0
diff
changeset
|
404 | let running = || if !cli.quiet { |
0 | 405 | println!("{}\n{}\n{}", |
406 | format!("Running {} on experiment {}…", alg_name, experiment_name).cyan(), | |
9
21b0e537ac0e
Command line parameter passing simplifications and make `-o` required.
Tuomo Valkonen <tuomov@iki.fi>
parents:
0
diff
changeset
|
407 | format!("{:?}", iterator_options).bright_black(), |
0 | 408 | format!("{:?}", alg).bright_black()); |
409 | }; | |
410 | ||
411 | // Create Logger and IteratorFactory | |
412 | let mut logger = Logger::new(); | |
413 | let findim_data = prepare_optimise_weights(&opA); | |
414 | let inner_config : InnerSettings<F> = Default::default(); | |
415 | let inner_it = inner_config.iterator_options; | |
416 | let logmap = |iter, Timed { cpu_time, data }| { | |
417 | let IterInfo { | |
418 | value, | |
419 | n_spikes, | |
420 | inner_iters, | |
421 | merged, | |
422 | pruned, | |
423 | postprocessing, | |
424 | this_iters, | |
425 | .. | |
426 | } = data; | |
427 | let post_value = match postprocessing { | |
428 | None => value, | |
429 | Some(mut μ) => { | |
430 | match dataterm { | |
431 | DataTerm::L2Squared => { | |
432 | optimise_weights( | |
433 | &mut μ, &opA, &b, α, &findim_data, &inner_config, | |
434 | inner_it | |
435 | ); | |
436 | dataterm.value_at_residual(opA.apply(&μ) - &b) + α * μ.norm(Radon) | |
437 | }, | |
438 | _ => value, | |
439 | } | |
440 | } | |
441 | }; | |
442 | CSVLog { | |
443 | iter, | |
444 | value, | |
445 | post_value, | |
446 | n_spikes, | |
447 | cpu_time : cpu_time.as_secs_f64(), | |
448 | inner_iters, | |
449 | merged, | |
450 | pruned, | |
451 | this_iters | |
452 | } | |
453 | }; | |
9
21b0e537ac0e
Command line parameter passing simplifications and make `-o` required.
Tuomo Valkonen <tuomov@iki.fi>
parents:
0
diff
changeset
|
454 | let iterator = iterator_options.instantiate() |
21b0e537ac0e
Command line parameter passing simplifications and make `-o` required.
Tuomo Valkonen <tuomov@iki.fi>
parents:
0
diff
changeset
|
455 | .timed() |
21b0e537ac0e
Command line parameter passing simplifications and make `-o` required.
Tuomo Valkonen <tuomov@iki.fi>
parents:
0
diff
changeset
|
456 | .mapped(logmap) |
21b0e537ac0e
Command line parameter passing simplifications and make `-o` required.
Tuomo Valkonen <tuomov@iki.fi>
parents:
0
diff
changeset
|
457 | .into_log(&mut logger); |
0 | 458 | let plotgrid = lingrid(&domain, &[if N==1 { 1000 } else { 100 }; N]); |
459 | ||
460 | // Create plotter and directory if needed. | |
9
21b0e537ac0e
Command line parameter passing simplifications and make `-o` required.
Tuomo Valkonen <tuomov@iki.fi>
parents:
0
diff
changeset
|
461 | let plot_count = if cli.plot >= PlotLevel::Iter { 2000 } else { 0 }; |
0 | 462 | let plotter = SeqPlotter::new(this_prefix, plot_count, plotgrid); |
463 | ||
464 | // Run the algorithm | |
465 | let start = Instant::now(); | |
466 | let start_cpu = ProcessTime::now(); | |
467 | let μ : DiscreteMeasure<Loc<F, N>, F> = match (alg, dataterm) { | |
468 | (AlgorithmConfig::FB(ref algconfig), DataTerm::L2Squared) => { | |
469 | running(); | |
470 | pointsource_fb(&opA, &b, α, &op𝒟, &algconfig, iterator, plotter) | |
471 | }, | |
472 | (AlgorithmConfig::FW(ref algconfig), DataTerm::L2Squared) => { | |
473 | running(); | |
474 | pointsource_fw(&opA, &b, α, &algconfig, iterator, plotter) | |
475 | }, | |
476 | (AlgorithmConfig::PDPS(ref algconfig), DataTerm::L2Squared) => { | |
477 | running(); | |
478 | pointsource_pdps(&opA, &b, α, &op𝒟, &algconfig, iterator, plotter, L2Squared) | |
479 | }, | |
480 | (AlgorithmConfig::PDPS(ref algconfig), DataTerm::L1) => { | |
481 | running(); | |
482 | pointsource_pdps(&opA, &b, α, &op𝒟, &algconfig, iterator, plotter, L1) | |
483 | }, | |
484 | _ => { | |
9
21b0e537ac0e
Command line parameter passing simplifications and make `-o` required.
Tuomo Valkonen <tuomov@iki.fi>
parents:
0
diff
changeset
|
485 | let msg = format!("Algorithm “{alg_name}” not implemented for \ |
21b0e537ac0e
Command line parameter passing simplifications and make `-o` required.
Tuomo Valkonen <tuomov@iki.fi>
parents:
0
diff
changeset
|
486 | dataterm {dataterm:?}. Skipping.").red(); |
0 | 487 | eprintln!("{}", msg); |
488 | continue | |
489 | } | |
490 | }; | |
491 | let elapsed = start.elapsed().as_secs_f64(); | |
492 | let cpu_time = start_cpu.elapsed().as_secs_f64(); | |
493 | ||
494 | println!("{}", format!("Elapsed {elapsed}s (CPU time {cpu_time}s)… ").yellow()); | |
495 | ||
496 | // Save results | |
497 | println!("{}", "Saving results…".green()); | |
498 | ||
9
21b0e537ac0e
Command line parameter passing simplifications and make `-o` required.
Tuomo Valkonen <tuomov@iki.fi>
parents:
0
diff
changeset
|
499 | let mkname = |t| format!("{prefix}{alg_name}_{t}"); |
0 | 500 | |
501 | write_json(mkname("config.json"), &named)?; | |
502 | write_json(mkname("stats.json"), &AlgorithmStats { cpu_time, elapsed })?; | |
503 | μ.write_csv(mkname("reco.txt"))?; | |
504 | logger.write_csv(mkname("log.txt"))?; | |
505 | } | |
506 | ||
507 | Ok(()) | |
508 | } | |
509 | } | |
510 | ||
511 | /// Plot experiment setup | |
512 | #[replace_float_literals(F::cast_from(literal))] | |
513 | 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
|
514 | cli : &CommandLineArgs, |
0 | 515 | prefix : &String, |
516 | domain : &Cube<F, N>, | |
517 | sensor : &Sensor, | |
518 | kernel : &Kernel, | |
519 | spread : &Spread, | |
520 | μ_hat : &DiscreteMeasure<Loc<F, N>, F>, | |
521 | op𝒟 : &𝒟, | |
522 | opA : &A, | |
523 | b_hat : &A::Observable, | |
524 | b : &A::Observable, | |
525 | kernel_plot_width : F, | |
526 | ) -> DynError | |
527 | where F : Float + ToNalgebraRealField, | |
528 | Sensor : RealMapping<F, N> + Support<F, N> + Clone, | |
529 | Spread : RealMapping<F, N> + Support<F, N> + Clone, | |
530 | Kernel : RealMapping<F, N> + Support<F, N>, | |
531 | Convolution<Sensor, Spread> : RealMapping<F, N> + Support<F, N>, | |
532 | 𝒟 : DiscreteMeasureOp<Loc<F, N>, F>, | |
533 | 𝒟::Codomain : RealMapping<F, N>, | |
534 | A : ForwardModel<Loc<F, N>, F>, | |
535 | A::PreadjointCodomain : RealMapping<F, N> + Bounded<F>, | |
536 | PlotLookup : Plotting<N>, | |
537 | Cube<F, N> : SetOrd { | |
538 | ||
9
21b0e537ac0e
Command line parameter passing simplifications and make `-o` required.
Tuomo Valkonen <tuomov@iki.fi>
parents:
0
diff
changeset
|
539 | if cli.plot < PlotLevel::Data { |
0 | 540 | return Ok(()) |
541 | } | |
542 | ||
543 | let base = Convolution(sensor.clone(), spread.clone()); | |
544 | ||
545 | let resolution = if N==1 { 100 } else { 40 }; | |
546 | let pfx = |n| format!("{}{}", prefix, n); | |
547 | let plotgrid = lingrid(&[[-kernel_plot_width, kernel_plot_width]; N].into(), &[resolution; N]); | |
548 | ||
549 | PlotLookup::plot_into_file(sensor, plotgrid, pfx("sensor"), "sensor".to_string()); | |
550 | PlotLookup::plot_into_file(kernel, plotgrid, pfx("kernel"), "kernel".to_string()); | |
551 | PlotLookup::plot_into_file(spread, plotgrid, pfx("spread"), "spread".to_string()); | |
552 | PlotLookup::plot_into_file(&base, plotgrid, pfx("base_sensor"), "base_sensor".to_string()); | |
553 | ||
554 | let plotgrid2 = lingrid(&domain, &[resolution; N]); | |
555 | ||
556 | let ω_hat = op𝒟.apply(μ_hat); | |
557 | let noise = opA.preadjoint().apply(opA.apply(μ_hat) - b); | |
558 | PlotLookup::plot_into_file(&ω_hat, plotgrid2, pfx("omega_hat"), "ω̂".to_string()); | |
559 | PlotLookup::plot_into_file(&noise, plotgrid2, pfx("omega_noise"), | |
560 | "noise Aᵀ(Aμ̂ - b)".to_string()); | |
561 | ||
562 | let preadj_b = opA.preadjoint().apply(b); | |
563 | let preadj_b_hat = opA.preadjoint().apply(b_hat); | |
564 | //let bounds = preadj_b.bounds().common(&preadj_b_hat.bounds()); | |
565 | PlotLookup::plot_into_file_spikes( | |
566 | "Aᵀb".to_string(), &preadj_b, | |
567 | "Aᵀb̂".to_string(), Some(&preadj_b_hat), | |
568 | plotgrid2, None, &μ_hat, | |
569 | pfx("omega_b") | |
570 | ); | |
571 | ||
572 | // Save true solution and observables | |
573 | let pfx = |n| format!("{}{}", prefix, n); | |
574 | μ_hat.write_csv(pfx("orig.txt"))?; | |
575 | opA.write_observable(&b_hat, pfx("b_hat"))?; | |
576 | opA.write_observable(&b, pfx("b_noisy")) | |
577 | } | |
578 |