/
NoiseTesterFilter.java
2173 lines (1972 loc) · 93.7 KB
/
NoiseTesterFilter.java
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
/*
* Copyright (C) 2020 tobid.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package net.sf.jaer.eventprocessing.filter;
import com.google.common.collect.EvictingQueue;
import com.jogamp.opengl.GL;
import com.jogamp.opengl.GL2;
import com.jogamp.opengl.GLAutoDrawable;
import com.jogamp.opengl.GLException;
import com.jogamp.opengl.util.awt.TextRenderer;
import com.jogamp.opengl.util.gl2.GLUT;
import java.awt.Color;
import java.awt.Desktop;
import java.awt.Font;
import java.beans.PropertyChangeEvent;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import net.sf.jaer.Description;
import net.sf.jaer.DevelopmentStatus;
import net.sf.jaer.chip.AEChip;
import net.sf.jaer.event.ApsDvsEvent;
import net.sf.jaer.event.EventPacket;
import net.sf.jaer.event.OutputEventIterator;
import net.sf.jaer.event.PolarityEvent;
import net.sf.jaer.eventio.AEInputStream;
import static net.sf.jaer.eventprocessing.EventFilter.log;
import net.sf.jaer.eventprocessing.EventFilter2D;
import net.sf.jaer.eventprocessing.FilterChain;
import net.sf.jaer.graphics.AEViewer;
import net.sf.jaer.graphics.FrameAnnotater;
import net.sf.jaer.util.RemoteControlCommand;
import net.sf.jaer.util.RemoteControlled;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import net.sf.jaer.aemonitor.AEPacketRaw;
import net.sf.jaer.chip.TypedEventExtractor;
import net.sf.jaer.event.ApsDvsEventPacket;
import net.sf.jaer.event.BasicEvent;
import net.sf.jaer.event.PolarityEvent;
import net.sf.jaer.event.PolarityEvent.Polarity;
import net.sf.jaer.eventio.AEFileInputStream;
import static net.sf.jaer.eventprocessing.EventFilter.log;
import net.sf.jaer.graphics.ChipDataFilePreview;
import net.sf.jaer.graphics.DavisRenderer;
import net.sf.jaer.util.DATFileFilter;
import net.sf.jaer.util.DrawGL;
/**
* Filter for testing noise filters
*
* @author Tobi Delbruck, Shasha Guo, Oct-Jan 2020
*/
@Description("Tests background BA denoising filters by injecting known noise and measuring how much signal and noise is filtered")
@DevelopmentStatus(DevelopmentStatus.Status.Stable)
public class NoiseTesterFilter extends AbstractNoiseFilter implements FrameAnnotater, RemoteControlled {
public static final int MAX_NUM_RECORDED_EVENTS = 10_0000_0000;
public static final float MAX_TOTAL_NOISE_RATE_HZ = 50e6f;
public static final float RATE_LIMIT_HZ = 25; //per pixel, separately for leak and shot rates
private FilterChain chain;
private boolean disableAddingNoise = getBoolean("disableAddingNoise", false);
private float shotNoiseRateHz = getFloat("shotNoiseRateHz", .1f);
protected boolean photoreceptorNoiseSimulation = getBoolean("photoreceptorNoiseSimulation", true);
private float leakNoiseRateHz = getFloat("leakNoiseRateHz", .1f);
private float noiseRateCoVDecades = getFloat("noiseRateCoVDecades", 0);
private float leakJitterFraction = getFloat("leakJitterFraction", 0.1f); // fraction of interval to jitter leak events
private float[] noiseRateArray = null;
private float[] noiseRateIntervals = null; // stored by column, with y changing fastest
private PriorityQueue<PolarityEvent> leakNoiseQueue = null; // stored by column, with y changing fastest
private double poissonDtUs = 1;
private float shotOffThresholdProb; // bounds for samppling Poisson noise, factor 0.5 so total rate is shotNoiseRateHz
private float shotOnThresholdProb; // for shot noise sample both sides, for leak events just generate ON events
private float leakOnThresholdProb; // bounds for samppling Poisson noise
private PrerecordedNoise prerecordedNoise = null;
private ROCHistory rocHistory = new ROCHistory();
private static String DEFAULT_CSV_FILENAME_BASE = "NoiseTesterFilter";
private String csvFileName = getString("csvFileName", DEFAULT_CSV_FILENAME_BASE);
private File csvFile = null;
private BufferedWriter csvWriter = null;
private int csvNumEventsWritten = 0, csvSignalCount = 0, csvNoiseCount = 0;
private int[][] timestampImage = null; // image of last event timestamps
private int[][] lastPolMap;
private float[][] photoreceptorNoiseArray; // see https://github.com/SensorsINI/v2e/blob/565f6991daabbe0ad79d68b50d084d5dc82d6426/v2ecore/emulator_utils.py#L177
/**
* Chip dimensions in pixels MINUS ONE, set in initFilter()
*/
private int sx = 0, sy = 0;
private Integer lastTimestampPreviousPacket = null, firstSignalTimestmap = null; // use Integer Object so it can be null to signify no value yet
private float TPR = 0;
private float TPO = 0;
private float TNR = 0;
private float accuracy = 0;
private float BR = 0;
float inSignalRateHz = 0, inNoiseRateHz = 0, outSignalRateHz = 0, outNoiseRateHz = 0;
// private EventPacket<ApsDvsEvent> signalAndNoisePacket = null;
private final Random random = new Random();
private EventPacket<PolarityEvent> signalAndNoisePacket = null;
// private EventList<PolarityEvent> noiseList = new EventList();
private AbstractNoiseFilter[] noiseFilters = null;
private AbstractNoiseFilter selectedFilter = null;
protected boolean resetCalled = true; // flag to reset on next event
// private float annotateAlpha = getFloat("annotateAlpha", 0.5f);
private DavisRenderer renderer = null;
private boolean overlayPositives = getBoolean("overlayPositives", false);
private boolean overlayNegatives = getBoolean("overlayNegatives", false);
private boolean overlayTP = getBoolean("overlayTP", false);
private boolean overlayTN = getBoolean("overlayTN", false);
private boolean overlayFP = getBoolean("overlayFP", false);
private boolean overlayFN = getBoolean("overlayFN", false);
final float[] NOISE_COLOR = {1f, 0, 0, 1}, SIG_COLOR = {0, 1f, 0, 1};
final int LABEL_OFFSET_PIX = 1; // how many pixels LABEL_OFFSET_PIX is the annnotation overlay, so we can see original signal/noise event and its label
private boolean outputTrainingData = getBoolean("outputTrainingData", false);
private boolean recordPureNoise = false;
private boolean outputFilterStatistic = false;
private int rocHistoryLength = getInt("rocHistoryLength", 1);
private final int LIST_LENGTH = 10000;
private ArrayList<FilteredEventWithNNb> tpList = new ArrayList(LIST_LENGTH),
fnList = new ArrayList(LIST_LENGTH),
fpList = new ArrayList(LIST_LENGTH),
tnList = new ArrayList(LIST_LENGTH); // output of classification
private ArrayList<PolarityEvent> noiseList = new ArrayList<PolarityEvent>(LIST_LENGTH); // TODO make it lazy, when filter is enabled
/**
* How time is split up for Poisson sampling using bounds trick
*/
public static final int POISSON_DIVIDER = 30;
/**
* Add AbstractNoiseFilter here to include in NTF
*/
public enum NoiseFilterEnum {
None, BackgroundActivityFilter, DensityFilter, SpatioTemporalCorrelationFilter, DoubleWindowFilter, OrderNBackgroundActivityFilter, MedianDtFilter, MLPNoiseFilter
}
private NoiseFilterEnum selectedNoiseFilterEnum = null; // set in constructor to wrap with try/catch to handle renames by code changes
private float correlationTimeS = getFloat("correlationTimeS", 20e-3f);
private volatile boolean stopMe = false; // to interrupt if filterPacket takes too long
// https://stackoverflow.com/questions/1109019/determine-if-a-java-application-is-in-debug-mode-in-eclipse
private final boolean isDebug = java.lang.management.ManagementFactory.getRuntimeMXBean().getInputArguments().toString().contains("debug");
;
private final long MAX_FILTER_PROCESSING_TIME_MS = 500000; // times out to avoid using up all heap
private TextRenderer textRenderer = null;
public NoiseTesterFilter(AEChip chip) {
super(chip);
try {
selectedNoiseFilterEnum = NoiseFilterEnum.valueOf(getString("selectedNoiseFilter", NoiseFilterEnum.BackgroundActivityFilter.toString())); //default is BAF
} catch (java.lang.IllegalArgumentException e) {
selectedNoiseFilterEnum = NoiseFilterEnum.BackgroundActivityFilter;
}
String out = "5. Output";
String noise = "0. Noise";
setPropertyTooltip(noise, "disableAddingNoise", "Disable adding noise; use if labeled noise is present in the AEDAT, e.g. from v2e");
setPropertyTooltip(noise, "shotNoiseRateHz", "rate per pixel of shot noise events");
setPropertyTooltip(noise, "photoreceptorNoiseSimulation", "<html>Generate shot noise from simulated bandlimited photoreceptor noise.<p>The <i>shotNoiseRateHz</i> will only be a guide to the actual generated noise rate. ");
setPropertyTooltip(noise, "noiseRateCoVDecades", "Coefficient of Variation of noise rates (shot and leak) in log normal distribution decades across pixel array");
setPropertyTooltip(noise, "leakJitterFraction", "Jitter of leak noise events relative to the (FPN) interval, drawn from normal distribution");
setPropertyTooltip(noise, "leakNoiseRateHz", "rate per pixel of leak noise events");
setPropertyTooltip(noise, "openNoiseSourceRecording", "Open a pre-recorded AEDAT file as noise source.");
setPropertyTooltip(noise, "closeNoiseSourceRecording", "Closes the pre-recorded noise input.");
setPropertyTooltip(out, "closeCsvFile", "Closes the output CSV spreadsheet data file.");
setPropertyTooltip(out, "openCsvFile", "Opens the output spreadsheet data file named csvFileName (see " + out + " section). Set switches there to determine output columns.");
setPropertyTooltip(out, "csvFileName", "Enter a filename base here to open CSV output file (appending to it if it already exists). Information written determined by Output switches.");
setPropertyTooltip(out, "outputTrainingData", "<html>Output data for training MLP. <p>Outputs CSV file that has a single row with most recent event information (timestamp and polarity) for 25x25 neighborhood of each event. <p>Each row thus has about 1000 columns.");
setPropertyTooltip(out, "recordPureNoise", "Output pure noise data for training MLP.");
setPropertyTooltip(out, "outputFilterStatistic", "Output analyzable data of a filter.");
setPropertyTooltip(TT_FILT_CONTROL, "selectedNoiseFilterEnum", "Choose a noise filter to test");
// setPropertyTooltip(ann, "annotateAlpha", "Sets the transparency for the annotated pixels. Only works for Davis renderer.");
setPropertyTooltip(TT_DISP, "overlayPositives", "<html><p>Overlay positives (passed input events)<p>FPs (red) are noise in output.<p>TPs (green) are signal in output.");
setPropertyTooltip(TT_DISP, "overlayNegatives", "<html><p>Overlay negatives (rejected input events)<p>FNs (green) are signal filtered out.<p>TNs (red) are noise filtered out.");
setPropertyTooltip(TT_DISP, "overlayTP", "<html><p>Overlay TP in green <br>(signal events correctly classified)");
setPropertyTooltip(TT_DISP, "overlayTN", "<html><p>Overlay TN in red <br>(noise events correctly classified)");
setPropertyTooltip(TT_DISP, "overlayFP", "<html><p>Overlay FP in red <br>(noise events incorrectly classified as signal)");
setPropertyTooltip(TT_DISP, "overlayFN", "<html><p>Overlay FN in green <br>(signal events incorrectly classified as noise)");
setPropertyTooltip(TT_DISP, "rocHistoryLength", "Number of samples of ROC point to show.");
setPropertyTooltip(TT_DISP, "clearROCHistory", "Clears samples from display.");
}
@Override
public synchronized void setFilterEnabled(boolean yes) {
boolean wasEnabled = this.filterEnabled;
this.filterEnabled = yes;
if (yes) {
resetFilter();
for (EventFilter2D f : chain) {
if (selectedFilter != null && selectedFilter == f) {
f.setFilterEnabled(yes);
} else {
f.setSelected(!yes);
}
}
} else {
for (EventFilter2D f : chain) {
f.setFilterEnabled(false);
}
if (renderer != null) {
renderer.clearAnnotationMap();
}
}
if (!isEnclosed()) {
String key = prefsEnabledKey();
getPrefs().putBoolean(key, this.filterEnabled);
}
support.firePropertyChange("filterEnabled", wasEnabled, this.filterEnabled);
}
private int rocSampleCounter = 0;
private final int ROC_LABEL_TAU_INTERVAL = 30;
@Override
synchronized public void annotate(GLAutoDrawable drawable) {
String s = null;
float x, y;
if (!showFilteringStatistics) {
return;
}
if (textRenderer == null) {
textRenderer = new TextRenderer(new Font("SansSerif", Font.PLAIN, 10));
}
final GLUT glut = new GLUT();
GL2 gl = drawable.getGL().getGL2();
rocHistory.draw(gl);
gl.glPushMatrix();
gl.glColor3f(.2f, .2f, .8f); // must set color before raster position (raster position is like glVertex)
gl.glRasterPos3f(0, sy * .9f, 0);
String overlayString = "Overlay ";
if (overlayNegatives) {
overlayString += "negatives: FN (green), TN (red)";
}
if (overlayPositives) {
overlayString += "positives: TP (green), FP (red)";
}
if (overlayFN) {
overlayString += " FN (green) ";
}
if (overlayFP) {
overlayString += " FP (red) ";
}
if (overlayTN) {
overlayString += " TN (red) ";
}
if (overlayTP) {
overlayString += " TP (green) ";
}
if (prerecordedNoise != null) {
s = String.format("NTF: Pre-recorded noise from %s with %,d events", prerecordedNoise.file.getName(), prerecordedNoise.recordedNoiseFileNoisePacket.getSize());
} else {
s = String.format("NTF: Synthetic noise: CoV %s dec, Leak %sHz+/-%s jitter, Shot %sHz. %s", eng.format(noiseRateCoVDecades), eng.format(leakNoiseRateHz), eng.format(leakJitterFraction), eng.format(shotNoiseRateHz),
overlayString);
}
glut.glutBitmapString(GLUT.BITMAP_HELVETICA_18, s);
gl.glRasterPos3f(0, getAnnotationRasterYPosition("NTF"), 0);
s = String.format("TPR=%s%% FPR=%s%% TNR=%s%% dT=%.2fus", eng.format(100 * TPR), eng.format(100 * (1 - TNR)), eng.format(100 * TNR), poissonDtUs);
glut.glutBitmapString(GLUT.BITMAP_HELVETICA_18, s);
gl.glRasterPos3f(0, getAnnotationRasterYPosition("NTF") + 10, 0);
s = String.format("In sigRate=%s noiseRate=%s, Out sigRate=%s noiseRate=%s Hz", eng.format(inSignalRateHz), eng.format(inNoiseRateHz), eng.format(outSignalRateHz), eng.format(outNoiseRateHz));
glut.glutBitmapString(GLUT.BITMAP_HELVETICA_18, s);
gl.glPopMatrix();
// nnbHistograms.draw(gl); shows neighbor distributions, not informative
}
private void annotateNoiseFilteringEvents(ArrayList<FilteredEventWithNNb> outSig, ArrayList<FilteredEventWithNNb> outNoise) {
if (renderer == null) {
return;
}
for (FilteredEventWithNNb e : outSig) {
renderer.setAnnotateColorRGBA(e.e.x + LABEL_OFFSET_PIX >= sx ? e.e.x : e.e.x + LABEL_OFFSET_PIX, e.e.y - LABEL_OFFSET_PIX < 0 ? e.e.y : e.e.y - LABEL_OFFSET_PIX, SIG_COLOR);
}
for (FilteredEventWithNNb e : outNoise) {
renderer.setAnnotateColorRGBA(e.e.x + LABEL_OFFSET_PIX >= sx ? e.e.x : e.e.x + LABEL_OFFSET_PIX, e.e.y - LABEL_OFFSET_PIX < 0 ? e.e.y : e.e.y - LABEL_OFFSET_PIX, NOISE_COLOR);
}
}
private void annotateNoiseFilteringEvents(ArrayList<FilteredEventWithNNb> events, float[] color) {
if (renderer == null) {
return;
}
for (FilteredEventWithNNb e : events) {
renderer.setAnnotateColorRGBA(e.e.x + LABEL_OFFSET_PIX >= sx ? e.e.x : e.e.x + LABEL_OFFSET_PIX, e.e.y - LABEL_OFFSET_PIX < 0 ? e.e.y : e.e.y - LABEL_OFFSET_PIX, color);
}
}
private class BackwardsTimestampException extends Exception {
public BackwardsTimestampException(String string) {
super(string);
}
}
private SignalAndNoiseList createEventList(EventPacket<PolarityEvent> p, boolean splitNoiseBySpecialEvents) throws BackwardsTimestampException {
ArrayList<PolarityEvent> signalList = new ArrayList(p.getSize());
ArrayList<PolarityEvent> noiseList = new ArrayList(p.getSize());
SignalAndNoiseList snl = new SignalAndNoiseList(signalList, noiseList);
PolarityEvent previousEvent = null;
for (PolarityEvent e : p) {
if (previousEvent != null && (e.timestamp < previousEvent.timestamp)) {
throw new BackwardsTimestampException(String.format("timestamp %d is earlier than previous %d", e.timestamp, previousEvent.timestamp));
}
if (splitNoiseBySpecialEvents) {
if (e.isSpecial()) {
noiseList.add(e);
} else {
signalList.add(e);
}
} else {
signalList.add(e);
}
previousEvent = e;
}
return snl;
}
private class SignalAndNoiseList { // holds return from createEventList
ArrayList<PolarityEvent> signalList;
ArrayList<PolarityEvent> noiseList;
public SignalAndNoiseList(ArrayList<PolarityEvent> signalList, ArrayList<PolarityEvent> noiseList) {
this.signalList = signalList;
this.noiseList = noiseList;
}
}
private SignalAndNoiseList createEventList(List<PolarityEvent> p) throws BackwardsTimestampException {
ArrayList<PolarityEvent> signalList = new ArrayList(p.size());
SignalAndNoiseList snl = new SignalAndNoiseList(signalList, noiseList);
PolarityEvent pe = null;
for (PolarityEvent e : p) {
if (pe != null && (e.timestamp < pe.timestamp)) {
throw new BackwardsTimestampException(String.format("timestamp %d is earlier than previous %d", e.timestamp, pe.timestamp));
}
if (e.isSpecial()) {
noiseList.add(e);
} else {
signalList.add(e);
}
pe = e;
}
return snl;
}
private final boolean checkStopMe(String where) {
if (stopMe) {
log.severe(where + "\n: Processing took longer than " + MAX_FILTER_PROCESSING_TIME_MS + "ms, disabling filter");
setFilterEnabled(false);
return true;
}
return false;
}
/**
* Finds the intersection of events in a that are in b. Assumes packets are
* non-monotonic in timestamp ordering. Handles duplicates. Each duplicate
* is matched once. The matching is by event .equals() method.
*
* @param a ArrayList<PolarityEvent> of a
* @param b likewise, but is list of events with NNb bits in byte
* @param intersect the target list to fill with intersections, include NNb
* bits
* @return count of intersections
*/
private int countIntersect(ArrayList<PolarityEvent> a, ArrayList<FilteredEventWithNNb> b, ArrayList<FilteredEventWithNNb> intersect) {
intersect.clear();
if (a.isEmpty() || b.isEmpty()) {
return 0;
}
int count = 0;
// TODO test case
// a = new ArrayList();
// b = new ArrayList();
// a.add(new PolarityEvent(4, (short) 0, (short) 0));
// a.add(new PolarityEvent(4, (short) 0, (short) 0));
// a.add(new PolarityEvent(4, (short) 1, (short) 0));
// a.add(new PolarityEvent(4, (short) 2, (short) 0));
//// a.add(new PolarityEvent(2, (short) 0, (short) 0));
//// a.add(new PolarityEvent(10, (short) 0, (short) 0));
//
// b.add(new PolarityEvent(2, (short) 0, (short) 0));
// b.add(new PolarityEvent(2, (short) 0, (short) 0));
// b.add(new PolarityEvent(4, (short) 0, (short) 0));
// b.add(new PolarityEvent(4, (short) 0, (short) 0));
// b.add(new PolarityEvent(4, (short) 1, (short) 0));
// b.add(new PolarityEvent(10, (short) 0, (short) 0));
int i = 0, j = 0;
final int na = a.size(), nb = b.size();
while (i < na && j < nb) {
if (a.get(i).timestamp < b.get(j).e.timestamp) {
i++;
} else if (b.get(j).e.timestamp < a.get(i).timestamp) {
j++;
} else {
// If timestamps equal, it mmight be identical events or maybe not
// and there might be several events with identical timestamps.
// We MUST match all a with all b.
// We don't want to increment both pointers or we can miss matches.
// We do an inner double loop for exhaustive matching as long as the timestamps
// are identical.
int i1 = i, j1 = j;
while (i1 < na && j1 < nb && a.get(i1).timestamp == b.get(j1).e.timestamp) {
boolean match = false;
while (j1 < nb && i1 < na && a.get(i1).timestamp == b.get(j1).e.timestamp) {
if (a.get(i1).equals(b.get(j1).e)) {
count++;
intersect.add(b.get(j1)); // TODO debug
// we have a match, so use up the a element
i1++;
match = true;
}
j1++;
}
if (!match) {
i1++; //
}
j1 = j; // reset j to start of matching ts region
}
i = i1; // when done, timestamps are different or we reached end of either or both arrays
j = j1;
}
}
// System.out.println("%%%%%%%%%%%%%%");
// printarr(a, "a");
// printarr(b, "b");
// printarr(intersect, "intsct");
return count;
}
// TODO test case
private void printarr(ArrayList<PolarityEvent> a, String n) {
final int MAX = 30;
if (a.size() > MAX) {
System.out.printf("--------\n%s[%d]>%d\n", n, a.size(), MAX);
return;
}
System.out.printf("%s[%d] --------\n", n, a.size());
for (int i = 0; i < a.size(); i++) {
PolarityEvent e = a.get(i);
System.out.printf("%s[%d]=[%d %d %d %d]\n", n, i, e.timestamp, e.x, e.y, (e instanceof PolarityEvent) ? ((PolarityEvent) e).getPolaritySignum() : 0);
}
}
@Override
synchronized public EventPacket<? extends BasicEvent> filterPacket(EventPacket<? extends BasicEvent> in) {
totalEventCount = 0; // from super, to measure filtering
filteredOutEventCount = 0;
int TP = 0; // filter take real events as real events. the number of events
int TN = 0; // filter take noise events as noise events
int FP = 0; // filter take noise events as real events
int FN = 0; // filter take real events as noise events
if (in == null || in.isEmpty()) {
// log.warning("empty packet, cannot inject noise");
return in;
}
stopMe = false;
Timer stopper = null;
if (!isDebug) {
stopper = new Timer("NoiseTesterFilter.Stopper", true);
stopper.schedule(new TimerTask() {
@Override
public void run() {
stopMe = true;
}
}, MAX_FILTER_PROCESSING_TIME_MS);
}
BasicEvent firstE = in.getFirstEvent();
if (firstSignalTimestmap == null) {
firstSignalTimestmap = firstE.timestamp;
}
if (resetCalled) {
resetCalled = false;
int ts = in.getLastTimestamp(); // we use getLastTimestamp because getFirstTimestamp contains event from BEFORE the rewind :-( Or at least it used to, fixed now I think (Tobi)
initializeLastTimesMapForNoiseRate(shotNoiseRateHz + leakNoiseRateHz, ts);
// initialize filters with lastTimesMap to Poisson waiting times
log.info("initializing timestamp maps with Poisson process waiting times");
for (AbstractNoiseFilter f : noiseFilters) {
f.initializeLastTimesMapForNoiseRate(shotNoiseRateHz + leakNoiseRateHz, ts); // TODO move to filter so that each filter can initialize its own map
for (int[] i : lastPolMap) {
Arrays.fill(i, 0);
}
}
initializeLeakStates(in.getFirstTimestamp());
}
// copy input events to inList
ArrayList<PolarityEvent> signalList = null, noiseList = null;
try {
SignalAndNoiseList snl = createEventList((EventPacket<PolarityEvent>) in, true); // maybe split sig and noise by labeled special events
signalList = snl.signalList;
noiseList = snl.noiseList;
if (!noiseList.isEmpty()) {
if (!isDisableAddingNoise()) {
setDisableAddingNoise(true);
log.warning(String.format("disabled adding noise because incoming packet has %,d labeled noise events", noiseList.size()));
showWarningDialogInSwingThread("Disabled synthetic noise because incoming packet has labeled noise", "NoiseTesterFilter");
}
}
} catch (BackwardsTimestampException ex) {
log.warning(String.format("%s: skipping nonmonotonic packet [%s]", ex, in));
return in;
}
assert signalList.size() == in.getSizeNotFilteredOut() : String.format("signalList size (%d) != in.getSizeNotFilteredOut() (%d)", signalList.size(), in.getSizeNotFilteredOut());
// add noise into signalList to get the outputPacketWithNoiseAdded, track noise in noiseList
if (isDisableAddingNoise()) {
signalAndNoisePacket=(EventPacket<PolarityEvent>)in; // just make the signal+noise packet be the input packet since there is already labeled noise there
// the noise events are already in noiseList from above
} else {
noiseList.clear();
addNoise((EventPacket<? extends PolarityEvent>) in, signalAndNoisePacket, noiseList, shotNoiseRateHz, leakNoiseRateHz);
}
// we need to copy the augmented event packet to a HashSet for use with Collections
ArrayList<PolarityEvent> signalPlusNoiseList;
try {
SignalAndNoiseList snl = createEventList((EventPacket<PolarityEvent>) signalAndNoisePacket, false); // don't split here
signalPlusNoiseList = snl.signalList;
if (outputTrainingData && csvWriter != null) {
for (PolarityEvent event : signalPlusNoiseList) {
try {
int ts = event.timestamp;
int type = event.getPolarity() == PolarityEvent.Polarity.Off ? -1 : 1;
final int x = (event.x >> subsampleBy), y = (event.y >> subsampleBy);
int patchsize = 25;
int radius = (patchsize - 1) / 2;
if ((x < 0) || (x > sx) || (y < 0) || (y > sy)) {
continue;
}
StringBuilder absTstring = new StringBuilder();
StringBuilder polString = new StringBuilder();
for (int indx = -radius; indx <= radius; indx++) {
for (int indy = -radius; indy <= radius; indy++) {
int absTs = 0;
int pol = 0;
if ((x + indx >= 0) && (x + indx < sx) && (y + indy >= 0) && (y + indy < sy)) {
absTs = timestampImage[x + indx][y + indy];
pol = lastPolMap[x + indx][y + indy];
}
absTstring.append(absTs + ",");
polString.append(pol + ",");
}
}
if (recordPureNoise) { // if pure noise, labels must reversed otherwise the events will be labeled as signal
if (signalList.contains(event)) {
csvWriter.write(String.format("%d,%d,%d,%d,%d,%s%s%d\n",
type, event.x, event.y, event.timestamp, 0, absTstring, polString, firstE.timestamp)); // 1 means signal
} else {
csvWriter.write(String.format("%d,%d,%d,%d,%d,%s%s%d\n",
type, event.x, event.y, event.timestamp, 1, absTstring, polString, firstE.timestamp)); // 0 means noise
csvNoiseCount++;
csvNumEventsWritten++;
}
} else {
if (signalList.contains(event)) {
csvWriter.write(String.format("%d,%d,%d,%d,%d,%s%s%d\n",
type, event.x, event.y, event.timestamp, 1, absTstring, polString, firstE.timestamp)); // 1 means signal
csvSignalCount++;
csvNumEventsWritten++;
} else {
csvWriter.write(String.format("%d,%d,%d,%d,%d,%s%s%d\n",
type, event.x, event.y, event.timestamp, 0, absTstring, polString, firstE.timestamp)); // 0 means noise
csvNoiseCount++;
csvNumEventsWritten++;
}
}
timestampImage[x][y] = ts;
lastPolMap[x][y] = type;
if (csvNumEventsWritten % 100000 == 0) {
log.info(String.format("Wrote %,d events to %s", csvNumEventsWritten, csvFileName));
}
} catch (IOException e) {
doCloseCsvFile();
}
}
}
// filter the augmented packet
// make sure to record events, turned off by default for normal use
for (EventFilter2D f : getEnclosedFilterChain()) {
((AbstractNoiseFilter) f).setRecordFilteredOutEvents(true);
}
EventPacket<PolarityEvent> passedSignalAndNoisePacket = (EventPacket<PolarityEvent>) getEnclosedFilterChain().filterPacket(signalAndNoisePacket);
if (selectedFilter != null) {
ArrayList<FilteredEventWithNNb> negativeList = selectedFilter.getNegativeEvents();
ArrayList<FilteredEventWithNNb> positiveList = selectedFilter.getPositiveEvents();
// make a list of the output packet, which has noise filtered out by selected filter
SignalAndNoiseList snlpassed = createEventList(passedSignalAndNoisePacket, false); // don't split events here
ArrayList<PolarityEvent> passedSignalAndNoiseList = snlpassed.signalList;
assert (signalList.size() + noiseList.size() == signalPlusNoiseList.size());
// now we sort out the mess
TP = countIntersect(signalList, positiveList, tpList); // True positives: Signal that was correctly retained by filtering
if (checkStopMe("after TP")) {
return in;
}
FN = countIntersect(signalList, negativeList, fnList); // False negatives: Signal that was incorrectly removed by filter.
if (checkStopMe("after FN")) {
return in;
}
FP = countIntersect(noiseList, positiveList, fpList); // False positives: Noise that is incorrectly passed by filter
if (checkStopMe("after FP")) {
return in;
}
TN = countIntersect(noiseList, negativeList, tnList); // True negatives: Noise that was correctly removed by filter
if (checkStopMe("after TN")) {
return in;
}
// if (TN + FP != noiseList.size()) {
// System.err.println(String.format("TN (%d) + FP (%d) = %d != noiseList (%d)", TN, FP, TN + FP, noiseList.size()));
// printarr(signalList, "signalList");
// printarr(noiseList, "noiseList");
// printarr(passedSignalAndNoiseList, "passedSignalAndNoiseList");
// printarr(signalAndNoiseList, "signalAndNoiseList");
// }
assert (TN + FP == noiseList.size()) : String.format("TN (%d) + FP (%d) = %d != noiseList (%d)", TN, FP, TN + FP, noiseList.size());
totalEventCount = signalPlusNoiseList.size();
int outputEventCount = passedSignalAndNoiseList.size();
filteredOutEventCount = totalEventCount - outputEventCount;
// if (TP + FP != outputEventCount) {
// System.err.printf("@@@@@@@@@ TP (%d) + FP (%d) = %d != outputEventCount (%d)", TP, FP, TP + FP, outputEventCount);
// printarr(signalList, "signalList");
// printarr(noiseList, "noiseList");
// printarr(passedSignalAndNoiseList, "passedSignalAndNoiseList");
// printarr(signalAndNoiseList, "signalAndNoiseList");
// }
assert TP + FP == outputEventCount : String.format("TP (%d) + FP (%d) = %d != outputEventCount (%d)", TP, FP, TP + FP, outputEventCount);
// if (TP + TN + FP + FN != totalEventCount) {
// System.err.printf("***************** TP (%d) + TN (%d) + FP (%d) + FN (%d) = %d != totalEventCount (%d)", TP, TN, FP, FN, TP + TN + FP + FN, totalEventCount);
// printarr(signalList, "signalList");
// printarr(noiseList, "noiseList");
// printarr(signalAndNoiseList, "signalAndNoiseList");
// printarr(passedSignalAndNoiseList, "passedSignalAndNoiseList");
// }
assert TP + TN + FP + FN == totalEventCount : String.format("TP (%d) + TN (%d) + FP (%d) + FN (%d) = %d != totalEventCount (%d)", TP, TN, FP, FN, TP + TN + FP + FN, totalEventCount);
assert TN + FN == filteredOutEventCount : String.format("TN (%d) + FN (%d) = %d != filteredOutEventCount (%d)", TN, FN, TN + FN, filteredOutEventCount);
// System.out.printf("every packet is: %d %d %d %d %d, %d %d %d: %d %d %d %d\n", inList.size(), newInList.size(), outList.size(), outRealList.size(), outNoiseList.size(), outInitList.size(), outInitRealList.size(), outInitNoiseList.size(), TP, TN, FP, FN);
TPR = TP + FN == 0 ? 0f : (float) (TP * 1.0 / (TP + FN)); // percentage of true positive events. that's output real events out of all real events
TPO = TP + FP == 0 ? 0f : (float) (TP * 1.0 / (TP + FP)); // percentage of real events in the filter's output
TNR = TN + FP == 0 ? 0f : (float) (TN * 1.0 / (TN + FP));
accuracy = (float) ((TP + TN) * 1.0 / (TP + TN + FP + FN));
BR = TPR + TPO == 0 ? 0f : (float) (2 * TPR * TPO / (TPR + TPO)); // wish to norm to 1. if both TPR and TPO is 1. the value is 1
// System.out.printf("shotNoiseRateHz and leakNoiseRateHz is %.2f and %.2f\n", shotNoiseRateHz, leakNoiseRateHz);
}
if (stopper != null) {
stopper.cancel();
}
if (lastTimestampPreviousPacket != null) {
int deltaTime = in.getLastTimestamp() - lastTimestampPreviousPacket;
inSignalRateHz = (1e6f * in.getSize()) / deltaTime;
inNoiseRateHz = (1e6f * noiseList.size()) / deltaTime;
outSignalRateHz = (1e6f * TP) / deltaTime;
outNoiseRateHz = (1e6f * FP) / deltaTime;
}
if (outputFilterStatistic && csvWriter != null) {
try {
csvWriter.write(String.format("%d,%d,%d,%d,%f,%f,%f,%d,%f,%f,%f,%f\n",
TP, TN, FP, FN, TPR, TNR, BR, firstE.timestamp,
inSignalRateHz, inNoiseRateHz, outSignalRateHz, outNoiseRateHz));
} catch (IOException e) {
doCloseCsvFile();
}
}
if (renderer != null) {
renderer.clearAnnotationMap();
}
if (overlayPositives) {
annotateNoiseFilteringEvents(tpList, fpList);
}
if (overlayNegatives) {
annotateNoiseFilteringEvents(fnList, tnList);
}
if (overlayTP) {
annotateNoiseFilteringEvents(tpList, SIG_COLOR);
}
if (overlayTN) {
annotateNoiseFilteringEvents(tnList, NOISE_COLOR);
}
if (overlayFP) {
annotateNoiseFilteringEvents(fpList, NOISE_COLOR);
}
if (overlayFN) {
annotateNoiseFilteringEvents(fnList, SIG_COLOR);
}
rocHistory.addSample(1 - TNR, TPR, getCorrelationTimeS());
lastTimestampPreviousPacket = in.getLastTimestamp();
return passedSignalAndNoisePacket;
} catch (BackwardsTimestampException ex) {
Logger.getLogger(NoiseTesterFilter.class.getName()).log(Level.SEVERE, null, ex);
return in;
}
}
/**
* Adds the recorded or synthetic noise to packet.
*
* @param in the input packet
* @param augmentedPacket the packet with noise added
* @param generatedNoise list of noise events
* @param shotNoiseRateHz noise rate for shot noise, per pixel
* @param leakNoiseRateHz noise rate for leak noise, per pixel
*/
private void addNoise(EventPacket<? extends PolarityEvent> in, EventPacket<? extends PolarityEvent> augmentedPacket, ArrayList<PolarityEvent> generatedNoise, float shotNoiseRateHz, float leakNoiseRateHz) {
// we need at least 1 event to be able to inject noise before it
if ((in.isEmpty())) {
log.warning("no input events in this packet, cannot inject noise because there is no end event");
return;
}
// save input packet
augmentedPacket.clear();
generatedNoise.clear();
// make the itertor to save events with added noise events
OutputEventIterator<ApsDvsEvent> outItr = (OutputEventIterator<ApsDvsEvent>) augmentedPacket.outputIterator();
if (prerecordedNoise == null && leakNoiseRateHz == 0 && shotNoiseRateHz == 0) {
for (PolarityEvent ie : in) {
outItr.nextOutput().copyFrom(ie);
}
return; // no noise, just return which returns the copy from filterPacket
}
int firstTsThisPacket = in.getFirstTimestamp();
// insert noise between last event of last packet and first event of current packet
// but only if there waa a previous packet and we are monotonic
if (lastTimestampPreviousPacket != null) {
if (firstTsThisPacket < lastTimestampPreviousPacket) {
log.warning(String.format("non-monotonic timestamp: Resetting filter. (first event %d is smaller than previous event %d by %d)",
firstTsThisPacket, lastTimestampPreviousPacket, firstTsThisPacket - lastTimestampPreviousPacket));
resetFilter();
return;
}
// we had some previous event
int lastPacketTs = lastTimestampPreviousPacket; // 1us more than timestamp of the last event in the last packet
insertNoiseEvents(lastPacketTs, firstTsThisPacket, outItr, generatedNoise);
checkStopMe(String.format("after insertNoiseEvents at start of packet over interval of %ss",
eng.format(1e-6f * (lastPacketTs - firstTsThisPacket))));
}
// insert noise between events of this packet after the first event, record their timestamp
// if there are no DVS events, then the iteration will not work.
// In this case, we assume there are only IMU or APS events and insert noise events between them, because devices
// typically do not include some special "clock" event to pass time.
int preEts = 0;
int dvsEventCounter = 0;
int lastEventTs = in.getFirstTimestamp();
for (PolarityEvent ie : in) {
dvsEventCounter++;
// if it is the first event or any with first event timestamp then just copy them
if (ie.timestamp == firstTsThisPacket) {
outItr.nextOutput().copyFrom(ie);
continue;
}
// save the previous timestamp and get the next one, and then inject noise between them
preEts = lastEventTs;
lastEventTs = ie.timestamp;
insertNoiseEvents(preEts, lastEventTs, outItr, generatedNoise);
outItr.nextOutput().copyFrom(ie);
}
if (dvsEventCounter == 0 && (in instanceof ApsDvsEventPacket)) {
Iterator itr = ((ApsDvsEventPacket) in).fullIterator();
while (itr.hasNext()) {
PolarityEvent ie = (PolarityEvent) (itr.next());
// if it is the first event or any with first event timestamp then just copy them
if (ie.timestamp == firstTsThisPacket) {
outItr.nextOutput().copyFrom(ie);
continue;
}
// save the previous timestamp and get the next one, and then inject noise between them
preEts = lastEventTs;
lastEventTs = ie.timestamp;
insertNoiseEvents(preEts, lastEventTs, outItr, generatedNoise);
outItr.nextOutput().copyFrom(ie);
}
}
}
private void insertNoiseEvents(int lastPacketTs, int firstTsThisPacket, OutputEventIterator<ApsDvsEvent> outItr, List<PolarityEvent> generatedNoise) {
// check that we don't have too many events, packet will get too large
int tstepUs = (firstTsThisPacket - lastPacketTs);
if (tstepUs > 100_0000) {
stopMe = true;
checkStopMe("timestep longer than 100ms for inserting noise events, disabling filter");
return;
}
final int checkStopInterval = 100000;
int checks = 0;
for (double ts = lastPacketTs; ts < firstTsThisPacket; ts += poissonDtUs) {
// note that poissonDtUs is float but we truncate the actual timestamp to int us value here.
// It's OK if there are events with duplicate timestamps (there are plenty in input already).
int count = sampleNoiseEvent((int) ts, outItr, generatedNoise, shotOffThresholdProb, shotOnThresholdProb, leakOnThresholdProb); // note noise injection updates ts to make sure monotonic
if (checks++ > checkStopInterval) {
if (checkStopMe("sampling noise events")) {
break;
}
}
}
}
/**
* Samples a single noise event
*
* @param ts current timestamp
* @param outItr the output iterator we add event to
* @param noiseList the noise list we add noise event to
* @param shotOffThresholdProb the sampling threshold
* @param shotOnThresholdProb
* @param leakOnThresholdProb
* @return count of number of noise events generated
*/
private int sampleNoiseEvent(int ts, OutputEventIterator<ApsDvsEvent> outItr, List<PolarityEvent> noiseList, float shotOffThresholdProb, float shotOnThresholdProb, float leakOnThresholdProb) {
int count = 0;
if (prerecordedNoise == null) { // sample 'ideal' shot noise
final double randomnum = random.nextDouble();
if (randomnum < shotOffThresholdProb) {
injectShotNoiseEvent(ts, PolarityEvent.Polarity.Off, outItr, noiseList);
count++;
} else if (randomnum > shotOnThresholdProb) {
injectShotNoiseEvent(ts, PolarityEvent.Polarity.On, outItr, noiseList);
count++;
}
if (leakNoiseRateHz > 0) {
PolarityEvent le = leakNoiseQueue.peek();
while (le != null && ts >= le.timestamp) {
le = leakNoiseQueue.poll();
le.timestamp = ts;
ApsDvsEvent eout = (ApsDvsEvent) outItr.nextOutput();
eout.copyFrom(le);
// cryptic next line uses the AEChip's event extractor to compute the 'true' raw AER address for this event assuming word parallel format.
// this raw address is needed for CellStatsProber histograms
// TODO consider using object hash code
eout.address = ((TypedEventExtractor) chip.getEventExtractor()).reconstructDefaultRawAddressFromEvent(eout);
eout.setReadoutType(ApsDvsEvent.ReadoutType.DVS);
noiseList.add(eout);
// generate next leak event for this pixel
int idx = getIdxFromXY(le.x, le.y);
le.timestamp = le.timestamp + (int) (1e6f / (leakNoiseRateHz * noiseRateArray[idx] * (1 - getLeakJitterFraction() * random.nextGaussian())));
leakNoiseQueue.add(le);
le = leakNoiseQueue.peek();
}
}
// if (random.nextDouble() < leakOnThresholdProb) { // TODO replace with periodic leak noise model with log normal rate and jitter
// injectShotNoiseEvent(ts, PolarityEvent.Polarity.On, outItr, noiseList);
// count++;
// }
} else { // inject prerecorded noise event
ArrayList<PolarityEvent> noiseEvents = prerecordedNoise.nextEvents(ts); // these have timestamps of the prerecorded noise
for (PolarityEvent e : noiseEvents) {
count++;
PolarityEvent ecopy = outItr.nextOutput(); // get the next event from output packet
if (ecopy instanceof ApsDvsEvent) {
((ApsDvsEvent) ecopy).setReadoutType(ApsDvsEvent.ReadoutType.DVS);
}
ecopy.copyFrom(e); // copy its fields from the noise event
ecopy.timestamp = ts; // update the timestamp to the current timestamp
noiseList.add(ecopy); // add it to the list of noise events we keep for analysis
}
}
return count;
}
/**
* Initializes the leak noise event states
*
* @param ts The current timestamp, leak event timestamps in future from ts
* are added to queue
*/
private void initializeLeakStates(int ts) {
if (leakNoiseRateHz <= 0) {
return;
}
leakNoiseQueue.clear();
for (int i = 0; i < chip.getNumPixels(); i++) {
XYPt xy = getXYFromIdx(i);
PolarityEvent pe = new PolarityEvent();
pe.x = xy.x;
pe.y = xy.y;
pe.polarity = Polarity.On;
int t = random.nextInt((int) (1e6f / leakNoiseRateHz));
pe.timestamp = ts + t;
leakNoiseQueue.add(pe);
}
}
/**
* Creates array of shot noise rates multipliers drawn from log normal
* distribution. The final linear array of rates are integrated to form a
* line of length 1 where each segment length is proportional to its rate
* multiplier. A random float in range 0 to 1 then selects a pixel with
* frequency according to the length of that segment. Each sample requires
* search with cost log2(N) where N is the number of pixel, i.e.
* log2(90k)=17 steps per sample.
*/
private void maybeCreateOrUpdateNoiseCoVArray() {
if (noiseRateArray == null) {
noiseRateArray = new float[chip.getNumPixels()];
noiseRateIntervals = new float[(sx + 1) * (sy + 1)];
}
// fill float[][] with random normal dist values
int idx = 0;
double summedIntvls = 0;
for (int i = 0; i < noiseRateArray.length; i++) {
float randomVarMult = (float) Math.exp(random.nextGaussian() * noiseRateCoVDecades * Math.log(10));
noiseRateArray[i] = randomVarMult;
noiseRateIntervals[idx++] = randomVarMult;
summedIntvls += randomVarMult;
}
double f = 1 / summedIntvls;
for (int i = 0; i < noiseRateIntervals.length; i++) {
noiseRateIntervals[i] *= f; // store normalized intervals for indiv rates, the higher the pixel's rate, the longer its interval
}
// now compute the integrated intervals
for (int i = 1; i < noiseRateIntervals.length; i++) {
noiseRateIntervals[i] += noiseRateIntervals[i - 1]; // store normalized intervals for indiv rates, the higher the pixel's rate, the longer its interval
}
}
private class XYPt {
short x, y;
}
private XYPt xyPt = new XYPt();
private XYPt getXYFromIdx(int idx) {
xyPt.y = (short) (idx % (sy + 1)); // y changes fastest
xyPt.x = (short) (idx / (sy + 1));
return xyPt;
}