-
Notifications
You must be signed in to change notification settings - Fork 0
/
MainPage.xaml.cs
485 lines (367 loc) · 16.8 KB
/
MainPage.xaml.cs
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
/*
The MIT License
Copyright 2018, Dr.-Ing. Markus A. Stulle, München (markus@stulle.zone)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies
or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System; // ArgumentOutOfRangeException
using System.IO; // Stream
using System.Diagnostics; // Stopwatch
using System.Globalization; // CultureInfo
using System.Linq; // ToList
using System.Reflection; // Assembly
using System.Threading; // CancellationTokenSource
using System.Threading.Tasks; // Task
using System.Runtime.InteropServices.WindowsRuntime; // _wb.PixelBuffer
using Windows.UI.Core; // CoreDispatcherPriority
using Windows.UI.Xaml; // RoutedEventArgs
using Windows.UI.Xaml.Controls; // Page
using Windows.UI.Xaml.Media.Imaging; // WriteableBitmap
using WinRTXamlToolkit.Controls.DataVisualization.Charting; // ColumnSeries
using RandomNumbers.Storage; // INumberStorage
namespace RandomNumbers
{
public sealed partial class MainPage : Page
{
#region Public members
public MainPage()
{
this.InitializeComponent();
txtVersion.Text = "Version " + GetAttributeValueFromAssy( "AssemblyFileVersionAttribute" );
// Query bitmap size:
RndBitmapWidth = (int)rndBitmap.Width;
RndBitmapHeight = (int)rndBitmap.Height;
viewModel = new ViewModel( RndBitmapWidth, RndBitmapHeight );
NumOfBins = 50;
// Must adjust output formatting of average and variance if intervall changed:
Dmin = 0.0d;
Dmax = 1.0d;
Delta = (Dmax - Dmin) / NumOfBins;
// Create bins to count frequencies:
binning = new Binning( NumOfBins, Dmin, Dmax );
cs = ColumnChart.Series[ 0 ] as ColumnSeries;
cs.ItemsSource = binning.Bins;
cs.Title = "Frequency";
Rng = new SampleRNG();
int imageSize = RndBitmapWidth * RndBitmapHeight * 4;
imageArray = new byte[ imageSize ];
storage = null;
} // ctor MainPage
public string GetAttributeValueFromAssy( string name )
{
Assembly currentAssembly = typeof( App ).GetTypeInfo().Assembly;
var customAttributes = currentAssembly.CustomAttributes;
var list = customAttributes.ToList();
var result = list.FirstOrDefault( x => x.AttributeType.Name == name );
var value = result.ConstructorArguments[ 0 ].Value;
return (string)value;
} // GetAttributeValueFromAssy
#region Getter/Setter
public int NumOfBins { get => numOfBins; set => numOfBins = value; }
public double Dmin { get => dmin; set => dmin = value; }
public double Dmax { get => dmax; set => dmax = value; }
public double Delta { get => delta; set => delta = value; }
public bool IsRunning { get => isRunning; set => isRunning = value; }
public Task Runner { get => runner; set => runner = value; }
public double AveragePrev { get => averagePrev; set => averagePrev = value; }
public RNG Rng { get => rng; set => rng = value; }
public Stopwatch Watch { get => watch; set => watch = value; }
public int RndBitmapWidth { get => rndBitmapWidth; set => rndBitmapWidth = value; }
public int RndBitmapHeight { get => rndBitmapHeight; set => rndBitmapHeight = value; }
#endregion
#endregion
#region Private members
private Binning binning;
private RNG rng;
private int numOfBins;
private double dmin;
private double dmax;
private double delta;
private double averagePrev;
private int rndBitmapWidth;
private int rndBitmapHeight;
private byte[] imageArray;
private ColumnSeries cs;
private Boolean isRunning;
private Task runner;
private Stopwatch watch;
private const string unit = " [1/s]";
private ViewModel viewModel;
private INumberStorage storage;
private CancellationTokenSource tokenSource;
private CancellationToken token;
private void MinMaxDefaults_Toggled( object sender, RoutedEventArgs e )
{
ToggleSwitch toggleSwitch = sender as ToggleSwitch;
if (toggleSwitch != null)
{
if (toggleSwitch.IsOn == true)
{
// Set default values for random number intervall:
viewModel.Lmin = System.Int32.MinValue + 1;
viewModel.Lmax = System.Int32.MaxValue - 1;
// Disable editing:
minRandomNumber.IsEnabled = false;
maxRandomNumber.IsEnabled = false;
}
else
{
// Enable editing:
minRandomNumber.IsEnabled = true;
maxRandomNumber.IsEnabled = true;
}
} // toggleSwitch != null
} // MinMaxDefaults_Toggled
private void StoreInFile_Toggled( object sender, RoutedEventArgs e )
{
ToggleSwitch toggleSwitch = sender as ToggleSwitch;
if( toggleSwitch != null )
{
storage = null;
fileName.Text = "".PadRight( 14 );
} // toggleSwitch != null
} // StoreInFile_Toggled
private async void Button_Click( object sender, RoutedEventArgs e )
{
if( IsRunning )
{
// Stop random number generation:
tokenSource.Cancel();
}
else
{
// Strategy pattern - set behavior of random number generator:
int idx = rngSelector.SelectedIndex;
switch (idx)
{
case 0:
Rng.Randomness = new PseudoRandomness();
break;
case 1:
Rng.Randomness = new SecureRandomness();
break;
case 2:
Rng.Randomness = new MyRandomness();
break;
case 3:
Rng.Randomness = new NoRandomness();
break;
default:
throw new ArgumentOutOfRangeException( "Invalid randomness index" );
}
viewModel.AssertFieldValues();
// create stop watch to compute number generation rate:
Watch = new Stopwatch();
Boolean isHighRes = Stopwatch.IsHighResolution;
long frequency = Stopwatch.Frequency;
long nanosecPerTick = (1000L * 1000L * 1000L) / frequency;
// Reset image:
viewModel.PixelTested = 0L;
viewModel.PixelSet = 0L;
ClearImage();
WriteImageToBitmap();
// Create token to facilitate task cancellation:
tokenSource = new CancellationTokenSource();
token = tokenSource.Token;
viewModel.PercentageDone = 0;
startStopButton.Content = "Stop Generation";
binning.Clear();
cs.ItemsSource = null;
IsRunning = true;
// write random numbers to file?
if( viewModel.FileStorage )
{
Debug.Assert( storage == null );
storage = new CsvFileStorage();
string path = null;
path = await storage.SelectLocation( "RandomNumbers.csv" );
if( path != null )
{
viewModel.NumbersFileName = Path.GetFileName( path );
bool status = await storage.Open();
Debug.Assert( status == true );
}
else
{
// user aborted file selection:
storage = null;
}
} // viewModel.FileStorage
// Start random number generation:
Watch.Start();
Runner = Task.Run( () => GenerateRandomNumbers( token ), token );
} // isRunning
try {
await Runner;
}
catch (OperationCanceledException x) {
;
}
// wrote random numbers to file?
if( storage != null )
{
bool status = await storage.Close();
Debug.Assert( status == true );
storage = null;
fileName.Text = "saved";
} // storage != null
// Display results:
cs.ItemsSource = binning.Bins;
WriteImageToBitmap();
averageText.Text = viewModel.Average.ToString( "0.########" );
varianceText.Text = viewModel.Variance.ToString( "0.########" );
rndMatches.Text = viewModel.PixelSet.ToString();
startStopButton.Content = "Start Generation";
IsRunning = false;
} // Button_Click
private async Task GenerateRandomNumbers( CancellationToken ct )
{
// Compute 1 percent increment:
long onePercent = viewModel.NumOfRandomNumbers / 100L;
viewModel.Variance = 0.0d;
viewModel.Average = AveragePrev = 0.0d;
int p = -1;
int nextP = 0;
int deltaP = 0;
Boolean randomNumberMatch = false;
// Create random numbers:
for (long k = 0; k < viewModel.NumOfRandomNumbers; k++)
{
int li = Rng.GetRandomNumer( viewModel.Lmin, viewModel.Lmax );
long l = (long)li;
double r = Statistics.Scale( l, viewModel.Lmax, viewModel.Lmin, Dmax, Dmin );
if( !binning.AddNumber( r ) )
{
throw new InvalidOperationException( "Adding number to bin failed (" + r + ")" );
}
// write random numbers to storage?
if( storage != null )
storage.StoreNumbers( li, r );
// Compute offset in bitmap:
nextP = OffsetInBitmap( RndBitmapWidth, RndBitmapHeight, viewModel.NumOfRandomNumbers, k );
deltaP = nextP - p;
// Next pixel reached?
if( deltaP > 0 )
{
int pp;
for( pp = p + 1; pp <= nextP; pp++ )
{
SetPixelNoMatch( pp );
}
randomNumberMatch = false;
p = pp - 1;
} // next pixel reached
Debug.Assert( p == nextP );
if (!randomNumberMatch)
{
if (li == viewModel.RndEquals)
{
#if DEBUG
// compute coordinates (for debugging purposes):
int y = p / RndBitmapWidth;
int x = p - (RndBitmapWidth * y);
#endif
randomNumberMatch = true;
SetPixelMatch( p );
viewModel.PixelSet++;
}
viewModel.PixelTested++;
} // !randomNumberMatch
// Update estimations of expected value and variance:
AveragePrev = viewModel.Average;
viewModel.Average = Statistics.UpdateAverage( k + 1, AveragePrev, r );
viewModel.Variance = Statistics.UpdateVariance( k + 1, viewModel.Variance, AveragePrev, viewModel.Average );
if (ct.IsCancellationRequested)
{
await Dispatcher.RunAsync( CoreDispatcherPriority.Normal, () => {
numberCount.Text = k.ToString();
} );
ct.ThrowIfCancellationRequested();
break;
} // task cancelled
// Update GUI...
if ((k % onePercent) == 0)
{
// ...progress control:
await Dispatcher.RunAsync( CoreDispatcherPriority.Normal, () => {
progressControl.Value++;
} );
// ...average computed so far:
await Dispatcher.RunAsync( CoreDispatcherPriority.Normal, () => {
averageText.Text = viewModel.Average.ToString( "0.########" );
} );
// ...variance computed so far:
await Dispatcher.RunAsync( CoreDispatcherPriority.Normal, () => {
varianceText.Text = viewModel.Variance.ToString( "0.########" );
} );
// ...rate of number generation:
TimeSpan ts = Watch.Elapsed;
double rate = k / ts.TotalSeconds;
await Dispatcher.RunAsync( CoreDispatcherPriority.Normal, () => {
numbersPerSecond.Text = ((int)Math.Floor( rate )).ToString( "N1", CultureInfo.InvariantCulture ) + unit;
} );
// ...random number matches:
await Dispatcher.RunAsync( CoreDispatcherPriority.Normal, () => {
rndMatches.Text = viewModel.PixelSet.ToString();
} );
} // Update GUI
} // for all random numbers
} // GenerateRandomNumbers
private static int OffsetInBitmap( int w, int h, long N, long k )
{
double nom = (w * h - 1.0d);
double denom = (N - 1.0d);
double p = (nom / denom) * k;
int offset = (int)Math.Floor( p );
#if DEBUG
;
#endif
return offset;
} // OffsetInBitmap
private void SetPixelMatch( int offset )
{
int index = 4 * offset;
// Set a white pixel:
imageArray[ index ] = 255; // Blue
imageArray[ index + 1 ] = 255; // Green
imageArray[ index + 2 ] = 255; // Red
imageArray[ index + 3 ] = 255; // Intensity?
} // SetPixelMatch
private void SetPixelNoMatch( int offset )
{
int index = 4 * offset;
// Set a black pixel:
imageArray[ index ] = 0;
imageArray[ index + 1 ] = 0;
imageArray[ index + 2 ] = 0;
imageArray[ index + 3 ] = 255;
} // SetPixelNoMatch
private void ClearImage()
{
Array.Clear( imageArray, 0, imageArray.Length );
} // ClearImage
private async void WriteImageToBitmap()
{
long p = viewModel.PixelTested;
long q = viewModel.PixelSet;
WriteableBitmap _wb = new WriteableBitmap( RndBitmapWidth, RndBitmapHeight );
using (Stream stream = _wb.PixelBuffer.AsStream())
{
await stream.WriteAsync( imageArray, 0, imageArray.Length );
}
rndBitmap.Source = _wb;
} // WriteImageToBitmap
#endregion
} // class MainPage
} // namepsace RandomNumbers
/* [EOF] */