Wed, 06 Nov 2024 21:40:54 -0500
Multiple trajectories
13 | 1 | /*! |
2 | Optimisation on non-Riemannian manifolds. | |
3 | */ | |
4 | 4 | |
5 | // We use unicode. We would like to use much more of it than Rust allows. | |
6 | // Live with it. Embrace it. | |
7 | #![allow(uncommon_codepoints)] | |
8 | #![allow(mixed_script_confusables)] | |
9 | #![allow(confusable_idents)] | |
1 | 10 | |
19 | 11 | mod manifold; |
12 | mod fb; | |
13 | mod cube; | |
14 | mod dist; | |
15 | mod zero; | |
16 | mod scaled; | |
17 | ||
20 | 18 | use serde::{Serialize, Deserialize}; |
16 | 19 | use alg_tools::logger::Logger; |
20 | use alg_tools::tabledump::{TableDump, write_csv}; | |
21 | use alg_tools::error::DynError; | |
22 | use alg_tools::lingrid::LinSpace; | |
23 | use alg_tools::loc::Loc; | |
24 | use alg_tools::types::*; | |
25 | use alg_tools::mapping::{Sum, Apply}; | |
26 | use alg_tools::iterate::{AlgIteratorOptions, AlgIteratorFactory, Verbose}; | |
24 | 27 | use alg_tools::mapping::Mapping; |
16 | 28 | use image::{ImageFormat, ImageBuffer, Rgb}; |
29 | ||
19 | 30 | use dist::{DistTo, DistToSquaredDiv2}; |
24 | 31 | use fb::{forward_backward, IterInfo, Desc, Prox}; |
7 | 32 | use manifold::EmbeddedManifoldPoint; |
11 | 33 | use cube::*; |
16 | 34 | use Face::*; |
19 | 35 | #[allow(unused_imports)] |
16 | 36 | use zero::ZeroFn; |
19 | 37 | use scaled::Scaled; |
1 | 38 | |
13 | 39 | /// Program entry point |
1 | 40 | fn main() { |
12 | 41 | simple_cube_test().unwrap() |
7 | 42 | } |
1 | 43 | |
20 | 44 | /// Helper structure for saving a point on a cube into a CSV file |
45 | #[derive(Serialize,Deserialize,Debug)] | |
46 | struct CSVPoint { | |
12 | 47 | face : Face, |
48 | x : f64, | |
49 | y : f64, | |
50 | z : f64 | |
51 | } | |
52 | ||
20 | 53 | impl From<&OnCube> for CSVPoint { |
54 | fn from(point : &OnCube) -> Self { | |
55 | let Loc([x,y,z]) = point.embedded_coords(); | |
56 | let face = point.face(); | |
57 | CSVPoint { face, x, y, z } | |
58 | } | |
59 | } | |
60 | ||
61 | /// Helper structure for saving the log into a CSV file | |
62 | #[derive(Serialize,Deserialize,Debug)] | |
63 | struct CSVLog { | |
64 | iter : usize, | |
65 | value : f64, | |
66 | // serde is junk | |
67 | //#[serde(flatten)] | |
68 | //point : CSVPoint | |
69 | face : Face, | |
70 | x : f64, | |
71 | y : f64, | |
72 | z : f64 | |
73 | } | |
74 | ||
75 | ||
13 | 76 | /// Location for saving results |
12 | 77 | static PREFIX : &str = "res"; |
78 | ||
79 | /// A simple test on the cube | |
80 | fn simple_cube_test() -> DynError { | |
7 | 81 | |
82 | let points = [ | |
9 | 83 | //OnCube::new(F1, Loc([0.5, 0.5])), |
84 | //OnCube::new(F2, Loc([0.5, 0.5])), | |
85 | //OnCube::new(F4, Loc([0.1, 0.1])), | |
20 | 86 | OnCube::new(F1, Loc([0.5, 0.7])), |
87 | OnCube::new(F2, Loc([0.3, 0.5])), | |
88 | OnCube::new(F4, Loc([0.9, 0.9])), | |
89 | OnCube::new(F6, Loc([0.4, 0.3])), | |
90 | OnCube::new(F4, Loc([0.3, 0.7])), | |
91 | OnCube::new(F3, Loc([0.3, 0.7])), | |
7 | 92 | ]; |
93 | ||
20 | 94 | let origin = OnCube::new(F4, Loc([0.5, 0.5])); |
95 | ||
96 | write_points(format!("{PREFIX}/data"), points.iter())?; | |
97 | write_points(format!("{PREFIX}/origin"), std::iter::once(&origin))?; | |
98 | ||
7 | 99 | //let x = points[0].clone(); |
9 | 100 | // OnCube::new(F3, Loc([0.5, 0.5])); goes to opposite side |
7 | 101 | let f = Sum::new(points.into_iter().map(DistToSquaredDiv2)); |
19 | 102 | //let g = ZeroFn::new(); |
20 | 103 | let g = Scaled::new(0.5, DistTo(origin)); |
104 | let τ = 0.05; | |
12 | 105 | |
24 | 106 | std::fs::create_dir_all(PREFIX)?; |
107 | for face in Face::all() { | |
108 | write_face_csv(format!("{PREFIX}/{face}"), face, 32, |x| f.apply(x) + g.apply(x))?; | |
109 | write_face_img(format!("{PREFIX}/{face}"), face, 128, |x| f.apply(x) + g.apply(x))?; | |
110 | } | |
111 | ||
112 | run_and_save("x1", &f, &g, OnCube::new(F3, Loc([0.1, 0.7])), τ)?; | |
113 | run_and_save("x2", &f, &g, OnCube::new(F2, Loc([0.1, 0.7])), τ)?; | |
114 | run_and_save("x3", &f, &g, OnCube::new(F6, Loc([0.6, 0.2])), τ) | |
115 | } | |
116 | ||
117 | pub fn run_and_save<F, G>( | |
118 | name : &str, | |
119 | f : &F, | |
120 | g : &G, | |
121 | x : OnCube, | |
122 | τ : f64, | |
123 | ) -> DynError | |
124 | where F : Desc<OnCube> + Mapping<OnCube, Codomain = f64>, | |
125 | G : Prox<OnCube> + Mapping<OnCube, Codomain = f64> { | |
126 | ||
12 | 127 | let mut logger = Logger::new(); |
128 | let logmap = |iter, IterInfo { value, point } : IterInfo<OnCube>| { | |
20 | 129 | let CSVPoint {x , y, z, face} = CSVPoint::from(&point); |
130 | CSVLog { | |
131 | iter, value, //point : CSVPoint::from(&point) | |
132 | x, y, z, face | |
133 | } | |
12 | 134 | }; |
7 | 135 | let iter = AlgIteratorOptions{ |
136 | max_iter : 100, | |
137 | verbose_iter : Verbose::Every(1), | |
138 | .. Default::default() | |
12 | 139 | }.mapped(logmap) |
140 | .into_log(&mut logger); | |
7 | 141 | |
24 | 142 | let x̂ = forward_backward(f, g, x, τ, iter); |
7 | 143 | println!("result = {}\n{:?}", x̂.embedded_coords(), &x̂); |
11 | 144 | |
24 | 145 | logger.write_csv(format!("{PREFIX}/{name}_log.csv"))?; |
12 | 146 | |
147 | Ok(()) | |
1 | 148 | } |
11 | 149 | |
12 | 150 | /// Writes the values of `f` on `face` of a [`OnCube`] into a PNG file |
151 | /// with resolution `n × n`. | |
16 | 152 | fn write_face_img(filename : String, face : Face, n : usize, mut f : impl FnMut(&OnCube) -> f64) -> DynError { |
11 | 153 | let mut img = ImageBuffer::new(n as u32, n as u32); |
154 | let grid = LinSpace { | |
155 | start : Loc([0.0, 0.0]), | |
156 | end : Loc([1.0, 1.0]), | |
157 | count : [n, n] | |
158 | }; | |
159 | let rawdata : Vec<_> = grid.into_iter() | |
160 | .map(|x| f(&OnCube::new(face, x))) | |
161 | .collect(); | |
162 | let a = rawdata.iter().copied().reduce(f64::max).unwrap(); | |
163 | img.pixels_mut() | |
164 | .zip(rawdata) | |
165 | .for_each(|(p, v)| { | |
166 | let t = v/a; | |
167 | let rgb = [1.0-t, 1.0-t, 1.0]; | |
168 | *p = Rgb(rgb.map(|v| (v*(u8::RANGE_MAX as f64)) as u8)) | |
169 | }); | |
170 | ||
12 | 171 | img.save_with_format(format!("{filename}.png"), ImageFormat::Png)?; |
172 | ||
173 | Ok(()) | |
11 | 174 | } |
16 | 175 | |
176 | /// Writes the values of `f` on `face` of a [`OnCube`] into a CSV file | |
177 | /// with resolution `n × n`. | |
178 | fn write_face_csv(filename : String, face : Face, n : usize, mut f : impl FnMut(&OnCube) -> f64) -> DynError { | |
179 | ||
180 | #[derive(Serialize)] | |
181 | struct CSVFace { u : f64, v : f64, value : f64 } | |
182 | ||
183 | let grid = LinSpace { | |
184 | start : Loc([0.0, 0.0]), | |
185 | end : Loc([1.0, 1.0]), | |
186 | count : [n, n] | |
187 | }; | |
188 | ||
189 | let data = grid.into_iter() | |
190 | .map(|p@Loc([u,v])| CSVFace{ u, v, value : f(&OnCube::new(face, p)) }); | |
191 | ||
192 | write_csv(data, format!("{filename}.csv"))?; | |
193 | ||
194 | Ok(()) | |
195 | } | |
20 | 196 | |
197 | /// Writes a list of points on a [`OnCube`] into a CSV file | |
198 | fn write_points<'a, I : Iterator<Item=&'a OnCube>>(filename : String, list : I) -> DynError { | |
199 | ||
200 | write_csv(list.map(CSVPoint::from), format!("{filename}.csv"))?; | |
201 | Ok(()) | |
202 | } | |
203 |