-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathsmcmc.rs
1366 lines (1258 loc) · 49.4 KB
/
smcmc.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::integrators::mcmc::*;
use crate::integrators::*;
use crate::samplers::mcmc::*;
use rayon::prelude::*;
pub const BORROW: bool = true;
// Mutator what uses random on the first dimension (AA pixel)
pub struct MutatorSMCMC {
pub kel: MutatorKelemen,
}
impl Default for MutatorSMCMC {
fn default() -> Self {
Self {
kel: MutatorKelemen::default(),
}
}
}
impl Mutator for MutatorSMCMC {
fn mutate(&self, v: f32, r: f32, i: usize) -> f32 {
match i {
0 | 1 => r,
_ => self.kel.mutate(v, r, i),
}
}
fn clone_box(&self) -> Box<dyn Mutator> {
Box::new(MutatorSMCMC {
kel: MutatorKelemen {
s1: self.kel.s1,
s2: self.kel.s2,
log_ratio: self.kel.log_ratio,
},
})
}
}
#[derive(Debug)]
pub struct PixelValue {
/// Position on the image plane
pub p: Point2<u32>,
/// Pixel's estimate by MCMC
pub value: Color,
/// Pixel's estimate by MC
pub value_mc: Color,
}
impl PixelValue {
pub fn new(p: Point2<u32>) -> Self {
Self {
p,
value: Color::zero(),
value_mc: Color::zero(),
}
}
}
pub struct Tile {
pub pixels: Vec<PixelValue>,
pub nb_samples: usize,
// Normalization
pub b: f32,
pub nb_uniform: usize,
// Scaling factor (reconstruction)
pub scale: Color,
// MCMC state
pub state: Option<MCMCState>,
// Sampler
pub sampler: Box<crate::samplers::mcmc::IndependentSamplerReplay>,
}
impl Tile {
fn pixels(p: Point2<u32>, img_size: &Vector2<u32>) -> Vec<PixelValue> {
// FIXME: This function can be largely optimized
// by passing a mut vector or using &mut self
// Create cross shape from the position p
// we remove pixels that are outside the image-plane
let mut pixels = vec![PixelValue::new(p)];
if p.x > 0 {
pixels.push(PixelValue::new(Point2::new(p.x - 1, p.y)));
}
if p.y > 0 {
pixels.push(PixelValue::new(Point2::new(p.x, p.y - 1)));
}
if p.x != img_size.x - 1 {
pixels.push(PixelValue::new(Point2::new(p.x + 1, p.y)));
}
if p.y != img_size.y - 1 {
pixels.push(PixelValue::new(Point2::new(p.x, p.y + 1)));
};
pixels
}
pub fn new(p: Point2<u32>, img_size: &Vector2<u32>) -> Self {
let mut pixels = Tile::pixels(p, img_size);
pixels.shrink_to_fit();
// Change the mutator to the one used in SMCMC
let mut sampler = Box::new(crate::samplers::mcmc::IndependentSamplerReplay::default());
sampler.mutator = Box::new(MutatorSMCMC::default());
// Construct the object with default parameters
Self {
pixels,
nb_samples: 0,
b: 0.0,
nb_uniform: 0,
scale: Color::one(),
state: None,
sampler,
}
}
/// Get the tile position (equivalent to the cross center)
pub fn center_pos(&self) -> Point2<u32> {
// By construction, the center pixel is always the first one
self.pixels[0].p
}
pub fn reallocate(&mut self, p_new: Point2<u32>, img_size: &Vector2<u32>) {
self.pixels.clear();
self.pixels = Tile::pixels(p_new, img_size);
}
/// Method that given the tile generate a state
pub fn generate_state<F>(&mut self, int: F) -> MCMCState
where
F: Fn((u32, u32), &mut dyn Sampler) -> Color,
{
assert_eq!(self.sampler.indice, 0);
let mut state = MCMCState::empty();
for (i, p) in self.pixels.iter().enumerate() {
if i != 0 {
self.sampler.reset_index();
}
let c = int((p.p.x, p.p.y), self.sampler.as_mut());
// Uses channel max
state.append_with_tf(c, c.channel_max(), p.p);
}
state
}
pub fn splat_state_uni(&mut self, s: &MCMCState) {
if !self.sampler.large_step {
panic!("Try to splat a state for normalization factor estimation generated from MCMC?");
}
self.b += s.tf;
self.nb_uniform += 1;
let w = s.weight / s.tf;
for (i, p) in self.pixels.iter_mut().enumerate() {
p.value_mc += s.values[i].0 * w;
}
}
// This function is a duplicate of splat_state
// to fix borrow checker issues (mut ref and ref)
pub fn splat_state_current(&mut self) {
let s = self.state.as_ref().unwrap();
let w = s.weight / s.tf;
for (i, p) in self.pixels.iter_mut().enumerate() {
p.value += s.values[i].0 * w;
}
self.nb_samples += 1;
}
pub fn splat_state(&mut self, s: &MCMCState) {
let w = s.weight / s.tf;
for (i, p) in self.pixels.iter_mut().enumerate() {
p.value += s.values[i].0 * w;
}
self.nb_samples += 1;
}
}
fn chain_non_init<F>(t: &mut Tile, technique: F)
where
F: Fn((u32, u32), &mut dyn Sampler) -> Color,
{
t.sampler.large_step = true;
let state = t.generate_state(technique);
// Always accept (as it does not matter)
t.sampler.accept();
// Estimate normalization factor
t.splat_state_uni(&state);
// If we found one valid path, use it!
if state.tf != 0.0 {
t.state = Some(state);
}
}
fn independent_mcmc<F>(t: &mut Tile, large_prob: f32, technique: F)
where
F: Fn((u32, u32), &mut dyn Sampler) -> Color,
{
t.sampler.large_step = large_prob >= t.sampler.rand();
let mut proposed_state = t.generate_state(technique);
if t.sampler.large_step {
t.splat_state_uni(&proposed_state);
}
let accept_prob = (proposed_state.tf / t.state.as_ref().unwrap().tf).min(1.0);
// Do waste reclycling
t.state.as_mut().unwrap().weight += 1.0 - accept_prob;
proposed_state.weight += accept_prob;
let accepted = accept_prob > t.sampler.rand();
if accepted {
t.splat_state_current();
t.sampler.accept();
t.state = Some(proposed_state);
} else {
t.splat_state(&proposed_state);
t.sampler.reject();
}
}
fn independent_mcmc_safe<F>(t: &mut Tile, large_prob: f32, technique: F)
where
F: Fn((u32, u32), &mut dyn Sampler) -> Color,
{
if t.state.is_none() {
chain_non_init(t, technique);
} else {
independent_mcmc(t, large_prob, technique);
}
}
fn replica_exchange<F>(t0: &mut Tile, t1: &mut Tile, technique: F)
where
F: Fn((u32, u32), &mut dyn Sampler) -> Color,
{
// Swap the samplers
std::mem::swap(&mut t0.sampler, &mut t1.sampler);
// Evaluate the swapped states
t0.sampler.large_step = false;
t1.sampler.large_step = false;
let mut proposed_state0 = t0.generate_state(&technique);
let mut proposed_state1 = t1.generate_state(&technique);
// Compute acceptance
let accept_prob = ((proposed_state0.tf * proposed_state1.tf)
/ (t0.state.as_ref().unwrap().tf * t1.state.as_ref().unwrap().tf))
.min(1.0);
let accepted = accept_prob > t1.sampler.rand();
// Do waste recycling
proposed_state0.weight += accept_prob;
proposed_state1.weight += accept_prob;
t0.state.as_mut().unwrap().weight += 1.0 - accept_prob;
t1.state.as_mut().unwrap().weight += 1.0 - accept_prob;
if accepted {
t0.splat_state_current();
t1.splat_state_current();
t0.sampler.accept();
t1.sampler.accept();
t0.state = Some(proposed_state0);
t1.state = Some(proposed_state1);
} else {
t0.splat_state(&proposed_state0);
t1.splat_state(&proposed_state1);
t0.sampler.reject();
t1.sampler.reject();
std::mem::swap(&mut t0.sampler, &mut t1.sampler);
}
}
fn replica_exchange_safe<F>(t0: &mut Tile, t1: &mut Tile, large_prob: f32, technique: F)
where
F: Fn((u32, u32), &mut dyn Sampler) -> Color,
{
if t0.state.is_none() && t1.state.is_none() {
chain_non_init(t0, &technique);
chain_non_init(t1, &technique);
} else if t0.state.is_some() && t1.state.is_some() {
replica_exchange(t0, t1, technique);
} else {
if BORROW {
// One is initialized and another one not
let (init, non_init) = if t1.state.is_some() {
(t1, t0)
} else {
(t0, t1)
};
assert!(init.state.is_some());
assert!(non_init.state.is_none());
// For the non init, we will borrow the state of the init
// one and try to generate a path
// FIXME: This is dangerous code as a bad copy of the internal
// states can leads to bugs
non_init.sampler.values = init.sampler.values.clone();
non_init.sampler.time = init.sampler.time;
non_init.sampler.time_large = init.sampler.time_large;
non_init.sampler.large_step = false;
{
let state = non_init.generate_state(&technique);
// Always accept (as it does not matter)
non_init.sampler.accept();
if state.tf != 0.0 {
non_init.state = Some(state);
}
}
// For the other sampler, we just continue :)
independent_mcmc(init, large_prob, technique);
} else {
independent_mcmc_safe(t0, large_prob, &technique);
independent_mcmc_safe(t1, large_prob, &technique);
}
}
}
pub trait Reconstruction: Send + Sync {
fn reconstruction(&self, tiles: &Vec<Tile>, img_size: Vector2<u32>) -> BufferCollection;
}
pub struct ReconstructionNaive;
impl Reconstruction for ReconstructionNaive {
fn reconstruction(&self, tiles: &Vec<Tile>, img_size: Vector2<u32>) -> BufferCollection {
let buffer_names = vec!["primal".to_string()];
let mut img = BufferCollection::new(Point2::new(0, 0), img_size, &buffer_names);
let mut accum = vec![Color::zero(); (img_size.x * img_size.y) as usize];
let mut sample_count = vec![0; (img_size.x * img_size.y) as usize];
for t in tiles {
// Skip if no normalization
if t.b == 0.0 {
continue;
}
assert!(t.nb_uniform > 0);
let norm = t.b / t.nb_uniform as f32;
if t.nb_samples > 0 {
for p in &t.pixels {
let i = (p.p.y * img_size.x + p.p.x) as usize;
accum[i] += p.value * norm;
sample_count[i] += t.nb_samples;
}
}
}
// Splat inside the bitmap
for y in 0..img_size.y {
for x in 0..img_size.x {
let i = (y * img_size.x + x) as usize;
if sample_count[i] > 0 {
img.accumulate(
Point2::new(x, y),
accum[i] / sample_count[i] as f32,
&buffer_names[0],
);
}
}
}
img
}
}
pub struct ReconstructionIRLS {
pub irls_iter: usize,
pub internal_iter: usize,
pub alpha: f32,
}
mod irls {
// These structure is to store the tile information
// efficiently, avoiding recomputing operation
pub struct TileSumStats {
pub mcmc: f32,
pub mc: f32,
}
pub struct CacheTile {
pub center: f32,
pub left: f32,
pub right: f32,
pub top: f32,
pub down: f32,
}
impl Default for CacheTile {
fn default() -> Self {
Self {
center: 0.0,
left: 0.0,
right: 0.0,
top: 0.0,
down: 0.0,
}
}
}
// This is a structure to helps
// to compute stats for reconstruction
const CUSTOM_W: bool = false;
pub trait Op {
// p = (b, v, w)
fn update(&mut self, p1: (f32, f32, f32), p2: (f32, f32, f32));
fn value(self, curr_b: f32) -> f32;
}
pub struct ReconsOp {
pub force: f32,
pub pos: f32,
}
impl Default for ReconsOp {
fn default() -> Self {
Self {
force: 0.0,
pos: 0.0,
}
}
}
impl Op for ReconsOp {
fn update(&mut self, (b1, v1, w1): (f32, f32, f32), (b2, v2, w2): (f32, f32, f32)) {
let w = w1.min(w2);
let e1 = v1 * b1;
let e2 = v2 * b2;
let f = 0.5 * (e1 - e2);
let align = if crate::integrators::mcmc::smcmc::BORROW {
v1 != 0.0 && v2 != 0.0
} else {
e1 != 0.0 && e2 != 0.0
};
if align {
let wc = if CUSTOM_W {
(v1.min(v2) / v1.max(v2)).powi(2)
} else {
1.0
};
self.force += w * wc * f;
self.pos += w * wc * v1;
}
}
fn value(self, curr_b: f32) -> f32 {
if self.pos == 0.0 {
curr_b
} else {
let b = curr_b - self.force / self.pos;
if b.is_finite() {
b
} else {
curr_b
}
}
}
}
pub struct ErrorOp {
pub error: f32,
}
impl Default for ErrorOp {
fn default() -> Self {
Self { error: 0.0 }
}
}
impl Op for ErrorOp {
fn update(&mut self, (b1, v1, _w1): (f32, f32, f32), (b2, v2, _w2): (f32, f32, f32)) {
let e1 = v1 * b1;
let e2 = v2 * b2;
let f = 0.5 * (e1 - e2);
let align = if crate::integrators::mcmc::smcmc::BORROW {
v1 != 0.0 && v2 != 0.0
} else {
e1 != 0.0 && e2 != 0.0
};
if align {
let w = if CUSTOM_W {
(v1.min(v2) / v1.max(v2)).powi(2)
} else {
1.0
};
self.error += f.abs() * w;
}
}
fn value(self, _curr_b: f32) -> f32 {
self.error
}
}
}
impl ReconstructionIRLS {
pub fn apply_op<F>(
&self,
pixel_order: &Vec<Point2<u32>>,
sums: &Vec<irls::TileSumStats>,
cache: &Vec<irls::CacheTile>,
b: &Vec<f32>,
w: &Vec<f32>,
img_size: &Vector2<u32>,
) -> Vec<f32>
where
F: irls::Op + Default,
{
pixel_order
.par_iter()
.map(|p| {
let curr_id = (p.y * img_size.x + p.x) as usize;
let curr_cache = &cache[curr_id];
let curr_sums = &sums[curr_id];
let curr_b = b[curr_id];
let curr_w = w[curr_id];
// If no MCMC estimates, just finish to process
// this tile!
if curr_sums.mcmc == 0.0 {
return curr_b;
}
// Build the object where we will accumulate stats
let mut res = F::default();
// Regularisation factor
res.update(
(curr_b, curr_sums.mcmc, self.alpha * curr_w),
(1.0, curr_sums.mc, self.alpha * curr_w),
);
// +X, -X, +Y, -Y
if p.x != 0 {
// Overlap center and left
let next_id = curr_id - 1;
let next_cache = &cache[next_id];
let next_b = b[next_id];
let next_w = w[next_id];
res.update(
(curr_b, curr_cache.center, curr_w),
(next_b, next_cache.right, next_w),
);
res.update(
(curr_b, curr_cache.left, curr_w),
(next_b, next_cache.center, next_w),
);
}
if p.x != img_size.x - 1 {
// Overlap center and right
let next_id = curr_id + 1;
let next_cache = &cache[next_id];
let next_b = b[next_id];
let next_w = w[next_id];
res.update(
(curr_b, curr_cache.center, curr_w),
(next_b, next_cache.left, next_w),
);
res.update(
(curr_b, curr_cache.right, curr_w),
(next_b, next_cache.center, next_w),
);
}
if p.y != 0 {
// Overlap center and top
let next_id = curr_id - img_size.x as usize;
let next_cache = &cache[next_id];
let next_b = b[next_id];
let next_w = w[next_id];
res.update(
(curr_b, curr_cache.center, curr_w),
(next_b, next_cache.down, next_w),
);
res.update(
(curr_b, curr_cache.top, curr_w),
(next_b, next_cache.center, next_w),
);
}
if p.y != img_size.y - 1 {
// Overlap center and down
let next_id = curr_id + img_size.x as usize;
let next_cache = &cache[next_id];
let next_b = b[next_id];
let next_w = w[next_id];
res.update(
(curr_b, curr_cache.center, curr_w),
(next_b, next_cache.top, next_w),
);
res.update(
(curr_b, curr_cache.down, curr_w),
(next_b, next_cache.center, next_w),
);
}
// Diagonals
if p.x != 0 && p.y != 0 {
// Overlap top and left
let next_id = curr_id - 1 - img_size.x as usize;
let next_cache = &cache[next_id];
let next_b = b[next_id];
let next_w = w[next_id];
res.update(
(curr_b, curr_cache.top, curr_w),
(next_b, next_cache.right, next_w),
);
res.update(
(curr_b, curr_cache.left, curr_w),
(next_b, next_cache.down, next_w),
);
}
if p.x != img_size.x - 1 && p.y != img_size.y - 1 {
// Overlap bottom and right
let next_id = curr_id + 1 + img_size.x as usize;
let next_cache = &cache[next_id];
let next_b = b[next_id];
let next_w = w[next_id];
res.update(
(curr_b, curr_cache.down, curr_w),
(next_b, next_cache.left, next_w),
);
res.update(
(curr_b, curr_cache.right, curr_w),
(next_b, next_cache.top, next_w),
);
}
if p.x != 0 && p.y != img_size.y - 1 {
// Overlap bottom and left
let next_id = curr_id - 1 + img_size.x as usize;
let next_cache = &cache[next_id];
let next_b = b[next_id];
let next_w = w[next_id];
res.update(
(curr_b, curr_cache.down, curr_w),
(next_b, next_cache.right, next_w),
);
res.update(
(curr_b, curr_cache.left, curr_w),
(next_b, next_cache.top, next_w),
);
}
if p.x != img_size.x - 1 && p.y != 0 {
// Overlap top and right
let next_id = curr_id + 1 - img_size.x as usize;
let next_cache = &cache[next_id];
let next_b = b[next_id];
let next_w = w[next_id];
res.update(
(curr_b, curr_cache.top, curr_w),
(next_b, next_cache.left, next_w),
);
res.update(
(curr_b, curr_cache.right, curr_w),
(next_b, next_cache.down, next_w),
);
}
// Only one overlap
if p.x > 1 {
// Overlap left-right
let next_id = curr_id - 2;
let next_cache = &cache[next_id];
let next_b = b[next_id];
let next_w = w[next_id];
res.update(
(curr_b, curr_cache.left, curr_w),
(next_b, next_cache.right, next_w),
);
}
if p.x < img_size.x - 2 {
// Overlap right-left
let next_id = curr_id + 2;
let next_cache = &cache[next_id];
let next_b = b[next_id];
let next_w = w[next_id];
res.update(
(curr_b, curr_cache.right, curr_w),
(next_b, next_cache.left, next_w),
);
}
if p.y > 1 {
// Overlap top-down
let next_id = curr_id - 2 * img_size.x as usize;
let next_cache = &cache[next_id];
let next_b = b[next_id];
let next_w = w[next_id];
res.update(
(curr_b, curr_cache.top, curr_w),
(next_b, next_cache.down, next_w),
);
}
if p.y < img_size.y - 2 {
// Overlap down-top
let next_id = curr_id + 2 * img_size.x as usize;
let next_cache = &cache[next_id];
let next_b = b[next_id];
let next_w = w[next_id];
res.update(
(curr_b, curr_cache.down, curr_w),
(next_b, next_cache.top, next_w),
);
}
res.value(curr_b)
})
.collect::<Vec<_>>()
}
// Note that the reconstruction is independent per wavelength
// This improve reconstruction by removing color noise
// This way is valid as color channels are correlated.
pub fn weighted_reconstruction_channel<F>(
&self,
tiles: &Vec<Tile>,
channel: F,
img_size: Vector2<u32>,
) -> Vec<f32>
where
F: Fn(&Color) -> f32,
{
// Compute the MC estimates by combining all tiles estimates
let mc_estimates = {
let mut accum = vec![0.0; (img_size.x * img_size.y) as usize];
let mut sample_count = vec![0; (img_size.x * img_size.y) as usize];
for t in tiles {
// Skip if no normalization
if t.b == 0.0 {
continue;
}
assert!(t.nb_uniform > 0);
for p in &t.pixels {
let i = (p.p.y * img_size.x + p.p.x) as usize;
accum[i] += channel(&p.value_mc);
sample_count[i] += t.nb_uniform;
}
}
accum
.iter()
.zip(sample_count.iter())
.map(|(a, i)| if *i == 0 { 0.0 } else { a / *i as f32 })
.collect::<Vec<_>>()
};
// Collect tiles sums stats
// these will be useful for to compute the regularisation term
let sums = tiles
.iter()
.map(|t| {
// For mc estimate, we uses the robust estimate
// instead of the chain own estimates. This improve
// the quality of the reconstruction as the regularisation term
// is more robustly estimated.
let mc = t
.pixels
.iter()
.map(|p| {
let i = p.p.y * img_size.x + p.p.x;
// TODO: Check MCMC estimates?
mc_estimates[i as usize]
})
.sum();
let mcmc = t.pixels.iter().map(|p| channel(&p.value)).sum();
// TODO: Normally, we should normalize it
// But it seems uncessary for the first implementation
// However, we need to be careful as different number of pixels
// will implies different regularisation "force"
irls::TileSumStats { mcmc, mc }
})
.collect::<Vec<_>>();
// Compute cache efficient reconstruction
let cache = tiles
.iter()
.map(|t| {
let c = t.center_pos();
let mut cache = irls::CacheTile::default();
for p in &t.pixels {
let x = c.x as i32 - p.p.x as i32;
let y = c.y as i32 - p.p.y as i32;
let v = channel(&p.value);
match (x, y) {
(0, 0) => cache.center = v,
(1, 0) => cache.left = v,
(-1, 0) => cache.right = v,
(0, -1) => cache.down = v,
(0, 1) => cache.top = v,
_ => panic!("Wrong tile mapping x={} y={} ({:?})", x, y, &t.pixels),
};
}
cache
})
.collect::<Vec<_>>();
// Build the pixel indice pattern
// This is usefull for the paralelisation
let pixel_order = {
let mut pixel_order = Vec::with_capacity((img_size.x * img_size.y) as usize);
for y in 0..img_size.y {
for x in 0..img_size.x {
pixel_order.push(Point2::new(x, y));
}
}
pixel_order
};
// Do the optimization (iterative reweight LS)
let mut w = vec![1.0; (img_size.x * img_size.y) as usize];
// Get the normalization factor for each tiles
let mut b = tiles
.iter()
.map(|t| match t.nb_uniform {
0 => 0.0,
v => t.b / v as f32,
})
.collect::<Vec<_>>();
//let b0 = b.clone();
for iter in 0..self.irls_iter {
//b.iter_mut().zip(b0.iter()).for_each(|(b, b0)| *b = *b0);
for _internal_iter in 0..self.internal_iter {
// TODO: This allocation can be slow!
// it might be possible to pre-alloc b_next
// and zip the two vectors (or pixel_order store the results)
let b_next =
self.apply_op::<irls::ReconsOp>(&pixel_order, &sums, &cache, &b, &w, &img_size);
// Update inplace
b.iter_mut()
.zip(b_next.into_iter())
.for_each(|(b, b_next)| {
assert!(b_next >= 0.0, "b_next negative {}", b_next);
*b = b_next;
});
}
// Compute weights
let mut w_new =
self.apply_op::<irls::ErrorOp>(&pixel_order, &sums, &cache, &b, &w, &img_size);
for w in &mut w_new {
*w = 1.0 / (*w + (0.05 * (0.5f32).powi(iter as i32)).max(0.0001))
}
// Compute normalization and update w
let w_sum = w_new.iter().sum::<f32>();
w.iter_mut().zip(w_new).for_each(|(w, w_new)| {
*w = w_new * (img_size.x * img_size.y) as f32 / w_sum;
assert!(w.is_finite());
});
}
// FIXME: Check if we can make b stay the same
// for efficient reconstruction
// b.iter_mut().zip(b0.iter()).for_each(|(b, b0)| *b = *b0);
// for _internal_iter in 0..200 {
// let b_next = apply_op::<ReconsOp>(&pixel_order, &sums, &cache, &b, &w, &img_size);
// // Update inplace
// b.iter_mut()
// .zip(b_next.into_iter())
// .for_each(|(b, b_next)| {
// assert!(b_next >= 0.0, "b_next negative {}", b_next);
// *b = b_next;
// });
// }
b
}
}
impl Reconstruction for ReconstructionIRLS {
fn reconstruction(&self, tiles: &Vec<Tile>, img_size: Vector2<u32>) -> BufferCollection {
let buffer_names = vec!["primal".to_string()];
let mut img = BufferCollection::new(Point2::new(0, 0), img_size, &buffer_names);
let b_r = self.weighted_reconstruction_channel(tiles, |c: &Color| -> f32 { c.r }, img_size);
let b_g = self.weighted_reconstruction_channel(tiles, |c: &Color| -> f32 { c.g }, img_size);
let b_b = self.weighted_reconstruction_channel(tiles, |c: &Color| -> f32 { c.b }, img_size);
let mut accum = vec![Color::zero(); (img_size.x * img_size.y) as usize];
let mut sample_count = vec![0; (img_size.x * img_size.y) as usize];
for (i, t) in tiles.iter().enumerate() {
// Skip if no normalization
if b_r[i] == 0.0 && b_g[i] == 0.0 && b_b[i] == 0.0 {
continue;
}
if t.nb_samples > 0 {
for p in &t.pixels {
let i = (p.p.y * img_size.x + p.p.x) as usize;
accum[i] +=
Color::new(p.value.r * b_r[i], p.value.g * b_g[i], p.value.b * b_b[i]);
sample_count[i] += t.nb_samples;
}
}
}
// Splat inside the bitmap
for y in 0..img_size.y {
for x in 0..img_size.x {
let i = (y * img_size.x + x) as usize;
if sample_count[i] > 0 {
img.accumulate(
Point2::new(x, y),
accum[i] / sample_count[i] as f32,
&buffer_names[0],
);
}
}
}
img
}
}
pub trait Initialization: Send + Sync {
fn init(
&self,
img_size: &Vector2<u32>,
accel: &dyn Acceleration,
scene: &Scene,
int: &dyn IntegratorMC,
pool: &rayon::ThreadPool,
) -> Vec<Tile>;
}
pub struct IndependentInit {
pub nb_spp: usize,
}
impl Initialization for IndependentInit {
fn init(
&self,
img_size: &Vector2<u32>,
accel: &dyn Acceleration,
scene: &Scene,
int: &dyn IntegratorMC,
pool: &rayon::ThreadPool,
) -> Vec<Tile> {
let mut chains = Vec::with_capacity((img_size.x * img_size.y) as usize);
for y in 0..img_size.y {
for x in 0..img_size.x {
chains.push(Tile::new(Point2::new(x, y), img_size));
}
}
let nb_initialized_total = Mutex::new(0);
pool.install(|| {
chains
.par_chunks_mut(img_size.y as usize)
.for_each(|tiles| {
let technique = |p: (u32, u32), s: &mut dyn Sampler| -> Color {
int.compute_pixel((p.0, p.1), accel, scene, s)
};
let mut nb_initialized = 0;
for tile in &mut tiles[..] {
// Initialize the state from uniform sampling
// This is the most naive approach.
// We should uses a global chain to initialize the states
tile.sampler.large_step = true;
// Naively estimate the normalization factor
tile.b = 0.0;
tile.nb_uniform = 0;
for p in &mut tile.pixels {
p.value_mc = Color::zero();
}
for _ in 0..self.nb_spp {
chain_non_init(tile, technique);
if tile.state.is_some() {
nb_initialized += 1;
break; // Finish for now
}
}
}
*nb_initialized_total.lock().unwrap() += nb_initialized;
});
});
let nb_initialized_total = nb_initialized_total.into_inner().unwrap();
info!(
"Number of tile initialized: {} %",
100.0 * nb_initialized_total as f32 / (img_size.x * img_size.y) as f32
);
chains
}
}
pub struct MCMCInit {
pub spp_mc: usize,
pub spp_mcmc: usize,
pub chain_length: usize,
}
impl Initialization for MCMCInit {
fn init(
&self,
img_size: &Vector2<u32>,
accel: &dyn Acceleration,
scene: &Scene,
int: &dyn IntegratorMC,
pool: &rayon::ThreadPool,
) -> Vec<Tile> {
// Create protected tiles
let mut entries = Vec::with_capacity((img_size.x * img_size.y) as usize);
pub struct TileEntry {
nb_visit: usize,
tile: Tile,
}
for y in 0..img_size.y {
for x in 0..img_size.x {
entries.push(Mutex::new(TileEntry {
nb_visit: 0,
tile: Tile::new(Point2::new(x, y), img_size),
}));
}