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
//! Processed data structures code
//!
//! This module contains code to process, save and optionally plot the raw data provided
//! by the user.

use std::{
    fs::{File, OpenOptions},
    io::Write,
};

use gnuplot::{
    AutoOption, AxesCommon,
    Coordinate::Graph,
    DashType, Figure,
    LabelOption::{Rotate, TextOffset},
    MarginSide::{MarginLeft, MarginTop},
    PaletteType,
    PlotOption::{Caption, Color, LineStyle, PointSymbol},
    Tick,
    TickOption::{Inward, Mirror},
};

use crate::command_line::ScalingParams;

use super::raw::{
    correlation, TalliedData, TalliesReport, TimerReport, TimerSV, N_TIMERS, TIMERS_ARR,
};

//~~~~~~~~~~~~~~~~~
// Comparison data
//~~~~~~~~~~~~~~~~~

/// Structure used to hold comparison study results.
pub struct ComparisonResults {
    /// Old timer data.
    pub old: TimerReport,
    /// New timer data.
    pub new: TimerReport,
    /// Relative change in percents.
    pub percents: [f64; N_TIMERS],
}

impl ComparisonResults {
    /// Serializing function.
    pub fn save(&self) {
        let mut file = OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .open("comparison.csv")
            .unwrap();
        writeln!(file, "section,old,new,change").unwrap();
        TIMERS_ARR.iter().for_each(|section| {
            writeln!(
                file,
                "{},{},{},{}",
                *section,
                self.old[*section].total,
                self.new[*section].total,
                self.percents[*section as usize]
            )
            .unwrap();
        });
    }

    /// Plotting function.
    pub fn plot(&self) {
        // create figure & adjust characteristics
        let mut fg = Figure::new();
        fg.set_terminal("pngcairo size 800, 800", "comparison.png")
            .set_title("Timers Reports Comparison");
        // prepare data
        let x_coords: [usize; N_TIMERS] = core::array::from_fn(|i| i);
        let x_tics = TIMERS_ARR.map(|section| {
            Tick::Major(
                section as usize,
                AutoOption::Fix(match section {
                    TimerSV::Main => "Main Program",
                    TimerSV::PopulationControl => "Population Control",
                    TimerSV::CycleTracking => "Tracking Phase",
                    TimerSV::CycleTrackingProcess => "Process Phase",
                    TimerSV::CycleTrackingSort => "Sorting Phase",
                    TimerSV::CycleSync => "Sync Phase",
                }),
            )
        });
        let width = 0.25;

        let old_y: [f64; N_TIMERS] = TIMERS_ARR.map(|t| self.old[t].total / 1.0e6);
        let new_y: [f64; N_TIMERS] = TIMERS_ARR.map(|t| self.new[t].total / 1.0e6);
        let new_color = if self.percents[0] > 0.0 {
            Color("#FF0000") // total exec time increase => red
        } else {
            Color("#00BB00") // total exec time decrease => green
        };

        // plot data
        fg.axes2d()
            .set_x_ticks_custom(x_tics, &[Inward(false), Mirror(false)], &[Rotate(-45.0)])
            .set_x_label("Section", &[TextOffset(0.0, 1.5)])
            .set_y_grid(true)
            .set_y_minor_grid(true)
            .set_y_label("Total Time Spent in Section (s)", &[])
            .set_y_log(Some(10.0))
            .boxes_set_width(
                x_coords.iter().map(|x| *x as f64 - width / 2.0),
                old_y,
                [width; N_TIMERS],
                &[Caption("Old times"), Color("#000077")],
            )
            .boxes_set_width(
                x_coords.iter().map(|x| *x as f64 + width / 2.0),
                new_y,
                [width; N_TIMERS],
                &[Caption("New times"), new_color],
            );

        fg.show().unwrap();
    }
}

/// Custom [`From`] implementation used to process the raw data at initialization.
impl From<(TimerReport, TimerReport)> for ComparisonResults {
    fn from((old, new): (TimerReport, TimerReport)) -> Self {
        let relative_change =
            |section: TimerSV| (new[section].mean - old[section].mean) / old[section].mean;

        let percents = [
            TimerSV::Main,
            TimerSV::PopulationControl,
            TimerSV::CycleTracking,
            TimerSV::CycleTrackingProcess,
            TimerSV::CycleTrackingSort,
            TimerSV::CycleSync,
        ]
        .map(|section| relative_change(section) * 100.0);

        Self { old, new, percents }
    }
}

//~~~~~~~~~~~~~~~~~~
// Correlation data
//~~~~~~~~~~~~~~~~~~

/// Columns of the computed correlation matrix.
pub const CORRELATION_COLS: [TalliedData; 11] = [
    TalliedData::Start,
    TalliedData::Rr,
    TalliedData::Split,
    TalliedData::Absorb,
    TalliedData::Scatter,
    TalliedData::Fission,
    TalliedData::Produce,
    TalliedData::Collision,
    TalliedData::Escape,
    TalliedData::Census,
    TalliedData::NumSeg,
];

/// Rows of the computed correlation matrix.
pub const CORRELATION_ROWS: [TalliedData; 4] = [
    TalliedData::CycleSync,
    TalliedData::CycleTracking,
    TalliedData::PopulationControl,
    TalliedData::Cycle,
];

/// Structure used to hold correlation study results.
pub struct CorrelationResults {
    /// Raw data.
    pub corr_data: [f64; 11 * 4],
}

impl CorrelationResults {
    /// Serializing function.
    pub fn save(&self) {
        let mut file = OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .open("correlation.csv")
            .unwrap();
        writeln!(
            file,
            ",Start,Rr,Split,Absorb,Scatter,Fission,Produce,Collision,Escape,Census,NumSeg"
        )
        .unwrap();
        (0..4).for_each(|idx: usize| {
            writeln!(
                file,
                "{},{:.6},{:.6},{:.6},{:.6},{:.6},{:.6},{:.6},{:.6},{:.6},{:.6},{:.6}",
                match idx {
                    0 => "CycleSync",
                    1 => "CycleTracking",
                    2 => "PopulationControl",
                    3 => "Cycle",
                    _ => unreachable!(),
                },
                self.corr_data[11 * idx],
                self.corr_data[1 + 11 * idx],
                self.corr_data[2 + 11 * idx],
                self.corr_data[3 + 11 * idx],
                self.corr_data[4 + 11 * idx],
                self.corr_data[5 + 11 * idx],
                self.corr_data[6 + 11 * idx],
                self.corr_data[7 + 11 * idx],
                self.corr_data[8 + 11 * idx],
                self.corr_data[9 + 11 * idx],
                self.corr_data[10 + 11 * idx],
            )
            .unwrap();
        });
    }

    /// Plotting function.
    pub fn plot(&self) {
        // create figure & adjust characteristics
        let mut fg = Figure::new();
        fg.set_terminal("pngcairo size 1300, 600", "correlation.png")
            .set_title("Event Correlation Matrix");
        // prepare data
        let n_col = CORRELATION_COLS.len();
        let n_row = CORRELATION_ROWS.len();
        let x: [usize; CORRELATION_COLS.len()] = core::array::from_fn(|i| i);
        let y: [usize; CORRELATION_ROWS.len()] = core::array::from_fn(|i| i);
        let x_tics = x.map(|event_idx| {
            Tick::Major(
                event_idx as f64 - 0.5,
                AutoOption::Fix(CORRELATION_COLS[event_idx].to_string()),
            )
        });
        let y_tics = y.map(|event_idx| {
            Tick::Major(
                event_idx as f64 - 0.5,
                AutoOption::Fix(CORRELATION_ROWS[event_idx].to_string()),
            )
        });

        // plot data
        fg.axes2d()
            .set_aspect_ratio(AutoOption::Fix(0.35))
            .set_margins(&[MarginLeft(0.10)])
            .set_x_ticks_custom(
                x_tics,
                &[Inward(false), Mirror(false)],
                &[Rotate(-45.0), TextOffset(4.0, -1.0)],
            )
            .set_y_ticks_custom(
                y_tics,
                &[Inward(false), Mirror(false)],
                &[Rotate(45.0), TextOffset(0.0, 2.0)],
            )
            .set_cb_grid(true)
            .set_grid_options(true, &[LineStyle(DashType::Solid)])
            .set_x_grid(true)
            .set_y_grid(true)
            .set_palette(PaletteType::Custom(&[
                (-5.0, 0.0, 0.0, 1.0),
                (0.0, 1.0, 1.0, 1.0),
                (5.0, 1.0, 0.0, 0.0),
            ]))
            .image(self.corr_data, n_row, n_col, None, &[]);

        fg.show().unwrap();
    }
}

/// Custom [`From`] implementation used to process the raw data at initialization.
impl From<TalliesReport> for CorrelationResults {
    fn from(report: TalliesReport) -> Self {
        // compute correlations
        let table: [[f64; 11]; 4] = CORRELATION_ROWS.map(|tallied_data| {
            CORRELATION_COLS
                .map(|tallied_event| correlation(&report[tallied_data], &report[tallied_event]))
        });

        // a little black magic to flatten the array
        let flat_table: &[f64; 11 * 4] = unsafe { std::mem::transmute(&table) };

        Self {
            corr_data: *flat_table,
        }
    }
}

//~~~~~~~~~~~~~~
// Scaling data
//~~~~~~~~~~~~~~

/// Enum used to represent the type of scaling study.
pub enum ScalingType {
    /// Weak scaling, i.e. the size of the problem grows with the number of threads.
    Weak,
    /// Strong scaling, i.e. the size of the problem does not grow with the number of threads.
    Strong(usize),
}

/// Structure used to hold scaling study results.
pub struct ScalingResults {
    /// Number of threads used for each simulation run.
    pub n_threads: Vec<usize>,
    /// Total execution time of each simulation run.
    pub total_exec_times: Vec<f64>,
    /// Average population control time of each simulation run.
    pub population_control_avgs: Vec<f64>,
    /// Average tracking time of each simulation run.
    pub tracking_avgs: Vec<f64>,
    /// Average processing time of each simulation run.
    pub tracking_process_avgs: Vec<f64>,
    /// Average sorting time of each simulation run.
    pub tracking_sort_avgs: Vec<f64>,
    /// Average synchronization time of each simulation run.
    pub sync_avgs: Vec<f64>,
    /// Scaling type.
    pub scaling_type: ScalingType,
}

impl ScalingResults {
    /// Serializing function.
    pub fn save_tracking(&self) {
        let mut file = OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .open(match self.scaling_type {
                ScalingType::Weak => "weak_scaling_tracking.csv",
                ScalingType::Strong(_) => "strong_scaling_tracking.csv",
            })
            .unwrap();
        writeln!(
            file,
            "n_threads,TrackingAvg,TrackingAvgIdeal,TrackingProcessAvg,TrackingSortAvg"
        )
        .unwrap();
        let avg_ref = self.tracking_avgs[0];
        let n_elem = self.n_threads.len();
        assert_eq!(self.tracking_avgs.len(), n_elem);
        assert_eq!(self.tracking_process_avgs.len(), n_elem);
        assert_eq!(self.tracking_sort_avgs.len(), n_elem);
        for idx in 0..n_elem {
            let ideal = match self.scaling_type {
                ScalingType::Weak => avg_ref,
                ScalingType::Strong(factor) => avg_ref / (factor.pow(idx as u32) as f64),
            };
            writeln!(
                file,
                "{},{},{},{},{}",
                self.n_threads[idx],
                self.tracking_avgs[idx],
                ideal,
                self.tracking_process_avgs[idx],
                self.tracking_sort_avgs[idx]
            )
            .unwrap();
        }
    }

    /// Serializing function.
    pub fn save_others(&self) {
        let mut file = OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .open(match self.scaling_type {
                ScalingType::Weak => "weak_scaling_others.csv",
                ScalingType::Strong(_) => "strong_scaling_others.csv",
            })
            .unwrap();
        writeln!(file, "n_threads,TotalExecTime,PopulationControlAvg,SyncAvg").unwrap();
        let n_elem = self.n_threads.len();
        assert_eq!(self.total_exec_times.len(), n_elem);
        assert_eq!(self.population_control_avgs.len(), n_elem);
        assert_eq!(self.sync_avgs.len(), n_elem);
        for idx in 0..n_elem {
            writeln!(
                file,
                "{},{},{},{}",
                self.n_threads[idx],
                self.total_exec_times[idx],
                self.population_control_avgs[idx],
                self.sync_avgs[idx]
            )
            .unwrap();
        }
    }

    /// Computes & plot the speedup / efficiency (depending on the scaling type).
    pub fn plot_se(&self) {
        let mut fg = Figure::new();
        let (out, title) = match self.scaling_type {
            ScalingType::Weak => ("efficiency.png", "Ideal vs Real Efficiency"),
            ScalingType::Strong(_) => ("speedup.png", "Ideal vs Real Speedup"),
        };
        fg.set_terminal("pngcairo", out).set_title(title);

        let y_ideal: Vec<f64> = self
            .n_threads
            .iter()
            .map(|n_thread| match self.scaling_type {
                ScalingType::Weak => 1.0,
                ScalingType::Strong(_) => *n_thread as f64,
            })
            .collect();

        let y_real: Vec<f64> = self
            .n_threads
            .iter()
            .enumerate()
            .map(|(idx, _)| self.tracking_avgs[0] / self.tracking_avgs[idx])
            .collect();

        fg.axes2d()
            .set_x_log(Some(self.n_threads[1] as f64 / self.n_threads[0] as f64))
            .set_x_label("Number of Threads Used for Execution", &[])
            .set_x_ticks(Some((AutoOption::Auto, 0)), &[Inward(false)], &[])
            .set_y_log(match self.scaling_type {
                ScalingType::Weak => None,
                ScalingType::Strong(factor) => Some(factor as f64),
            })
            .set_y_label(
                match self.scaling_type {
                    ScalingType::Weak => "Efficiency",
                    ScalingType::Strong(_) => "Speedup",
                },
                &[],
            )
            .set_y_grid(true)
            .lines_points(
                &self.n_threads,
                &y_ideal,
                &[Caption("Ideal"), Color("#00FF00"), PointSymbol('x')],
            )
            .lines_points(
                &self.n_threads,
                &y_real,
                &[Caption("Real"), Color("#008800"), PointSymbol('x')],
            );

        fg.show().unwrap();
    }

    /// Plotting function.
    pub fn plot_tracking(&self) {
        // create figure & adjust characteristics
        let mut fg = Figure::new();
        let (out, title) = match self.scaling_type {
            ScalingType::Weak => ("weak_scaling_tracking.png", "Weak Scaling Characteristics"),
            ScalingType::Strong(_) => (
                "strong_scaling_tracking.png",
                "Strong Scaling Characteristics",
            ),
        };
        fg.set_terminal("pngcairo", out).set_title(title);
        // prepare data
        // let x = self.n_threads.clone();
        let y_ideal: Vec<f64> = self
            .n_threads
            .iter()
            .enumerate()
            .map(|(idx, _)| match self.scaling_type {
                ScalingType::Weak => self.tracking_avgs[0],
                ScalingType::Strong(factor) => {
                    self.tracking_avgs[0] / (factor.pow(idx as u32) as f64)
                }
            })
            .collect();

        // plot data
        fg.axes2d()
            .set_x_log(Some(self.n_threads[1] as f64 / self.n_threads[0] as f64))
            .set_x_label("Number of Threads Used for Execution", &[])
            .set_x_ticks(Some((AutoOption::Auto, 0)), &[Inward(false)], &[])
            .set_y_log(match self.scaling_type {
                ScalingType::Weak => None,
                ScalingType::Strong(_) => Some(self.n_threads[1] as f64 / self.n_threads[0] as f64),
            })
            .set_y_label("Time (µs)", &[])
            .set_y_grid(true)
            .lines_points(
                &self.n_threads,
                &y_ideal,
                &[
                    Caption("Ideal Average Tracking time"),
                    Color("#00FF00"),
                    PointSymbol('x'),
                ],
            )
            .lines_points(
                &self.n_threads,
                &self.tracking_avgs,
                &[
                    Caption("Average Tracking time"),
                    Color("#008800"),
                    PointSymbol('x'),
                ],
            )
            .lines_points(
                &self.n_threads,
                &self.tracking_process_avgs,
                &[
                    Caption("Average Processing time"),
                    Color("#CCCC00"),
                    PointSymbol('x'),
                ],
            )
            .lines_points(
                &self.n_threads,
                &self.tracking_sort_avgs,
                &[
                    Caption("Average Sorting time"),
                    Color("#999900"),
                    PointSymbol('x'),
                ],
            );

        fg.show().unwrap();
    }

    /// Plotting function.
    pub fn plot_others(&self) {
        // create figure & adjust characteristics
        let mut fg = Figure::new();
        let (out, title) = match self.scaling_type {
            ScalingType::Weak => ("weak_scaling_others.png", "Weak Scaling Characteristics"),
            ScalingType::Strong(_) => (
                "strong_scaling_others.png",
                "Strong Scaling Characteristics",
            ),
        };
        fg.set_terminal("pngcairo", out).set_title(title);

        // plot data
        fg.axes2d()
            .set_x_log(Some(self.n_threads[1] as f64 / self.n_threads[0] as f64))
            .set_x_label("Number of Threads Used for Execution", &[])
            .set_x_ticks(
                Some((AutoOption::Auto, 0)),
                &[Inward(false), Mirror(false)],
                &[],
            )
            .set_y_range(AutoOption::Auto, AutoOption::Auto)
            .set_y_label("Time (µs)", &[])
            .set_y_grid(true)
            .set_margins(&[MarginTop(0.8)])
            .set_legend(Graph(1.0), Graph(1.15), &[], &[])
            .lines_points(
                &self.n_threads,
                &self.population_control_avgs,
                &[
                    Caption("Average Pop. Control Time"),
                    Color("#00AA00"),
                    PointSymbol('x'),
                ],
            )
            .lines_points(
                &self.n_threads,
                &self.sync_avgs,
                &[
                    Caption("Average Synchronization Time"),
                    Color("#AAAA00"),
                    PointSymbol('x'),
                ],
            );

        fg.show().unwrap();
    }
}

/// Custom [`From`] implementation used to process the raw data at initialization.
impl From<(&str, &ScalingParams, ScalingType)> for ScalingResults {
    fn from((root_path, params, scaling_type): (&str, &ScalingParams, ScalingType)) -> Self {
        // fetch data from files
        let n_threads: Vec<usize> = (0..params.t_iter.unwrap())
            .map(|idx| params.t_init.unwrap() * params.t_factor.unwrap().pow(idx as u32))
            .collect();
        let reports: Vec<TimerReport> = n_threads
            .iter()
            .map(|n_thread| {
                let filename = format!("{}{}.csv", root_path, n_thread);
                TimerReport::from(File::open(filename).unwrap())
            })
            .collect();

        // use data to init structure
        let mut total_exec_times: Vec<f64> = Vec::with_capacity(n_threads.len());
        let mut population_control_avgs: Vec<f64> = Vec::with_capacity(n_threads.len());
        let mut tracking_avgs: Vec<f64> = Vec::with_capacity(n_threads.len());
        let mut tracking_process_avgs: Vec<f64> = Vec::with_capacity(n_threads.len());
        let mut tracking_sort_avgs: Vec<f64> = Vec::with_capacity(n_threads.len());
        let mut sync_avgs: Vec<f64> = Vec::with_capacity(n_threads.len());

        reports.iter().for_each(|report| {
            total_exec_times.push(report[TimerSV::Main].mean);
            population_control_avgs.push(report[TimerSV::PopulationControl].mean);
            tracking_avgs.push(report[TimerSV::CycleTracking].mean);
            tracking_process_avgs.push(report[TimerSV::CycleTrackingProcess].mean);
            tracking_sort_avgs.push(report[TimerSV::CycleTrackingSort].mean);
            sync_avgs.push(report[TimerSV::CycleSync].mean);
        });

        Self {
            n_threads,
            total_exec_times,
            population_control_avgs,
            tracking_avgs,
            tracking_process_avgs,
            tracking_sort_avgs,
            sync_avgs,
            scaling_type,
        }
    }
}