skillratings 0.29.0

Calculate a player's skill rating using algorithms like Elo, Glicko-2, TrueSkill and many more.
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
//! The Glicko-2 algorithm, an improvement on Glicko and widely used in online games,
//! like Counter Strike: Global Offensive, Team Fortress 2, Splatoon 2 or Lichess.
//!
//! If you are looking for the regular Glicko rating system, please see [`Glicko`](crate::glicko).
//!
//! The main improvement over Glicko is the rating volatility which is the expected fluctuation of a players rating,
//! based on how consistent a player is performing. The lower the volatility, the more consistent a player performs.
//!
//! # Quickstart
//!
//! This is the most basic example on how to use the Glicko-2 Module.\
//! Please take a look at the functions below to see more advanced use cases.
//!
//! ```
//! use skillratings::{
//!     glicko2::{glicko2, Glicko2Config, Glicko2Rating},
//!     Outcomes,
//! };
//!
//! // Initialise a new player rating with a rating of 1500, a deviation of 350 and a volatility of 0.06.
//! let player_one = Glicko2Rating::new();
//!
//! // Or you can initialise it with your own values of course.
//! // Imagine these numbers being pulled from a database.
//! let (some_rating, some_deviation, some_volatility) = (1325.0, 230.0, 0.05932);
//! let player_two = Glicko2Rating {
//!     rating: some_rating,
//!     deviation: some_deviation,
//!     volatility: some_volatility,
//! };
//!
//! // The outcome of the match is from the perspective of player one.
//! let outcome = Outcomes::WIN;
//!
//! // The config allows you to specify certain values in the Glicko-2 calculation.
//! // Here we set the Tau value to 0.9, instead of the default 0.5.
//! // This will increase the change in volatility over time.
//! // According to Mark Glickman, values between 0.3 and 1.2 are reasonable.
//! // For more information on how to customise the config,
//! // please check out the Glicko2Config struct.
//! let config = Glicko2Config {
//!     tau: 0.9,
//!     ..Default::default()
//! };
//!
//! // The glicko2 function will calculate the new ratings for both players and return them.
//! let (new_player_one, new_player_two) = glicko2(&player_one, &player_two, &outcome, &config);
//! ```
//!
//! # More Information
//!
//! - [Wikipedia Article](https://en.wikipedia.org/wiki/Glicko_rating_system)
//! - [Original Paper by Mark Glickman](http://www.glicko.net/glicko/glicko2.pdf)
//! - [Glicko-2 Calculator](https://glicko2-calculator.streamlit.app/)

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

use crate::{
    glicko::GlickoRating, glicko_boost::GlickoBoostRating, sticko::StickoRating, Outcomes, Rating,
    RatingPeriodSystem, RatingSystem,
};
use std::f64::consts::PI;

/// The Glicko-2 rating of a player.
///
/// For the Glicko rating, please see [`GlickoRating`].
///
/// The default rating is 1500.0.\
/// The default deviation is 350.0.\
/// The default volatility is 0.06.
#[derive(Copy, Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Glicko2Rating {
    /// The player's Glicko-2 rating number, by default 1500.0.
    pub rating: f64,
    /// The player's Glicko-2 deviation number, by default 350.0.
    pub deviation: f64,
    /// The player's Glicko-2 volatility number, by default 0.06.
    pub volatility: f64,
}

impl Glicko2Rating {
    /// Initialise a new `Glicko2Rating` with a rating of 1500.0, a deviation of 350.0 and a volatility of 0.06.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            rating: 1500.0,
            deviation: 350.0,
            volatility: 0.06,
        }
    }
}

impl Default for Glicko2Rating {
    fn default() -> Self {
        Self::new()
    }
}

impl Rating for Glicko2Rating {
    fn rating(&self) -> f64 {
        self.rating
    }
    fn uncertainty(&self) -> Option<f64> {
        Some(self.deviation)
    }
    fn new(rating: Option<f64>, uncertainty: Option<f64>) -> Self {
        Self {
            rating: rating.unwrap_or(1500.0),
            deviation: uncertainty.unwrap_or(350.0),
            volatility: 0.06,
        }
    }
}

impl From<(f64, f64, f64)> for Glicko2Rating {
    fn from((r, d, v): (f64, f64, f64)) -> Self {
        Self {
            rating: r,
            deviation: d,
            volatility: v,
        }
    }
}

impl From<GlickoRating> for Glicko2Rating {
    fn from(g: GlickoRating) -> Self {
        Self {
            rating: g.rating,
            deviation: g.deviation,
            ..Default::default()
        }
    }
}

impl From<GlickoBoostRating> for Glicko2Rating {
    fn from(g: GlickoBoostRating) -> Self {
        Self {
            rating: g.rating,
            deviation: g.deviation,
            ..Default::default()
        }
    }
}

impl From<StickoRating> for Glicko2Rating {
    fn from(s: StickoRating) -> Self {
        Self {
            rating: s.rating,
            deviation: s.deviation,
            ..Default::default()
        }
    }
}

#[derive(Clone, Copy, Debug)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
/// Constants used in the Glicko-2 calculations.
pub struct Glicko2Config {
    /// The tau constant constrains the change in volatility over time.
    /// To cite Mark Glickman himself: "Reasonable choices are between 0.3 and 1.2".
    /// Smaller values mean less change in volatility and vice versa.\
    /// The default value here is `0.5`.
    pub tau: f64,
    /// The convergence tolerance value, the smaller the value the more accurate the volatility calculations.\
    /// The default value is `0.000_001`, as suggested in [the paper (page 3)](http://www.glicko.net/glicko/glicko2.pdf).\
    /// Do not set this to a negative value.
    pub convergence_tolerance: f64,
}

impl Glicko2Config {
    #[must_use]
    /// Initialise a new `Glicko2Config` with a tau value of `0.5` and a convergence tolerance of `0.000_001`.
    pub const fn new() -> Self {
        Self {
            tau: 0.5,
            convergence_tolerance: 0.000_001,
        }
    }
}

impl Default for Glicko2Config {
    fn default() -> Self {
        Self::new()
    }
}

/// Struct to calculate ratings and expected score for [`Glicko2Rating`]
pub struct Glicko2 {
    config: Glicko2Config,
}

impl RatingSystem for Glicko2 {
    type RATING = Glicko2Rating;
    type CONFIG = Glicko2Config;

    fn new(config: Self::CONFIG) -> Self {
        Self { config }
    }

    fn rate(
        &self,
        player_one: &Glicko2Rating,
        player_two: &Glicko2Rating,
        outcome: &Outcomes,
    ) -> (Glicko2Rating, Glicko2Rating) {
        glicko2(player_one, player_two, outcome, &self.config)
    }

    fn expected_score(&self, player_one: &Glicko2Rating, player_two: &Glicko2Rating) -> (f64, f64) {
        expected_score(player_one, player_two)
    }
}

impl RatingPeriodSystem for Glicko2 {
    type RATING = Glicko2Rating;
    type CONFIG = Glicko2Config;

    fn new(config: Self::CONFIG) -> Self {
        Self { config }
    }

    fn rate(&self, player: &Glicko2Rating, results: &[(Glicko2Rating, Outcomes)]) -> Glicko2Rating {
        glicko2_rating_period(player, results, &self.config)
    }

    fn expected_score(&self, player: &Self::RATING, opponents: &[Self::RATING]) -> Vec<f64> {
        expected_score_rating_period(player, opponents)
    }
}

/// Calculates the [`Glicko2Rating`]s of two players based on their old ratings, deviations, volatilities, and the outcome of the game.
///
/// For the original version, please see [`Glicko`](crate::glicko).
///
/// Takes in two players as [`Glicko2Rating`]s, an [`Outcome`](Outcomes), and a [`Glicko2Config`].
///
/// Instead of the traditional way of calculating the Glicko-2 for only one player only using a list of results,
/// we are calculating the Glicko-2 rating for two players at once, like in the Elo calculation,
/// to make it easier to see instant results.
///
/// For the traditional way of calculating a Glicko-2 rating please see [`glicko2_rating_period`].
///
/// The outcome of the match is in the perspective of `player_one`.
/// This means [`Outcomes::WIN`] is a win for `player_one` and [`Outcomes::LOSS`] is a win for `player_two`.
///
/// # Examples
/// ```
/// use skillratings::{
///     glicko2::{glicko2, Glicko2Config, Glicko2Rating},
///     Outcomes,
/// };
///
/// let player_one = Glicko2Rating {
///     rating: 1500.0,
///     deviation: 350.0,
///     volatility: 0.06,
/// };
/// let player_two = Glicko2Rating {
///     rating: 1500.0,
///     deviation: 350.0,
///     volatility: 0.06,
/// };
///
/// let outcome = Outcomes::WIN;
///
/// let config = Glicko2Config::new();
///
/// let (new_one, new_two) = glicko2(&player_one, &player_two, &outcome, &config);
///
/// assert!((new_one.rating.round() - 1662.0).abs() < f64::EPSILON);
/// assert!((new_one.deviation.round() - 290.0).abs() < f64::EPSILON);
/// assert!((new_one.volatility - 0.05999967537233814).abs() < f64::EPSILON);
///
/// assert!((new_two.rating.round() - 1338.0).abs() < f64::EPSILON);
/// assert!((new_two.deviation.round() - 290.0).abs() < f64::EPSILON);
/// assert!((new_two.volatility - 0.05999967537233814).abs() < f64::EPSILON);
/// ```
#[must_use]
pub fn glicko2(
    player_one: &Glicko2Rating,
    player_two: &Glicko2Rating,
    outcome: &Outcomes,
    config: &Glicko2Config,
) -> (Glicko2Rating, Glicko2Rating) {
    // First we need to convert the ratings into the glicko-2 scale.
    let player_one_rating = (player_one.rating - 1500.0) / 173.7178;
    let player_two_rating = (player_two.rating - 1500.0) / 173.7178;

    // Same with the deviation.
    let player_one_deviation = player_one.deviation / 173.7178;
    let player_two_deviation = player_two.deviation / 173.7178;

    let outcome1 = outcome.to_chess_points();
    let outcome2 = 1.0 - outcome1;

    // We always need the deviation of the opponent in the g function.
    let g1 = g_value(player_two_deviation);
    let g2 = g_value(player_one_deviation);

    let e1 = e_value(player_one_rating, player_two_rating, g1);
    let e2 = e_value(player_two_rating, player_one_rating, g2);

    let v1 = v_value(g1, e1);
    let v2 = v_value(g2, e2);

    let player_one_new_volatility = new_volatility(
        player_one.volatility,
        delta_value(outcome1, v1, g1, e1).powi(2),
        player_one_deviation.powi(2),
        v1,
        config.tau,
        config.convergence_tolerance,
    );
    let player_two_new_volatility = new_volatility(
        player_two.volatility,
        delta_value(outcome2, v2, g2, e2).powi(2),
        player_two_deviation.powi(2),
        v2,
        config.tau,
        config.convergence_tolerance,
    );

    let new_deviation1 = new_deviation(player_one_deviation, player_one_new_volatility, v1);
    let new_deviation2 = new_deviation(player_two_deviation, player_two_new_volatility, v2);

    let new_rating1 = new_rating(player_one_rating, new_deviation1, outcome1, g1, e1);
    let new_rating2 = new_rating(player_two_rating, new_deviation2, outcome2, g2, e2);

    // We return the new values, converted back to the original scale.
    let player_one_new = Glicko2Rating {
        rating: new_rating1.mul_add(173.7178, 1500.0),
        deviation: new_deviation1 * 173.7178,
        volatility: player_one_new_volatility,
    };
    let player_two_new = Glicko2Rating {
        rating: new_rating2.mul_add(173.7178, 1500.0),
        deviation: new_deviation2 * 173.7178,
        volatility: player_two_new_volatility,
    };

    (player_one_new, player_two_new)
}

#[must_use]
/// The "traditional" way of calculating a [`Glicko2Rating`] of a player in a rating period.
///
/// Note that in this case, all of the matches are considered to be played at once.\
/// This means that the player will not get updated in-between matches, as you might expect.\
/// This will result in *slightly* different results than if you were to use the [`glicko2`] function in a loop.
///
/// Takes in a player as an [`Glicko2Rating`] and their results as a Slice of tuples containing the opponent as an [`Glicko2Rating`],
/// the outcome of the game as an [`Outcome`](Outcomes) and a [`Glicko2Config`].
///
/// The outcome of the match is in the perspective of the player.
/// This means [`Outcomes::WIN`] is a win for the player and [`Outcomes::LOSS`] is a win for the opponent.
///
/// If the player's results are empty, the player's rating deviation will automatically be decayed using [`decay_deviation`].
///
/// # Examples
/// ```
/// use skillratings::{
///     glicko2::{glicko2_rating_period, Glicko2Config, Glicko2Rating},
///     Outcomes,
/// };
///
/// let player = Glicko2Rating {
///     rating: 1500.0,
///     deviation: 200.0,
///     volatility: 0.06,
/// };
///
/// let opponent1 = Glicko2Rating {
///     rating: 1400.0,
///     deviation: 30.0,
///     volatility: 0.06,
/// };
///
/// let opponent2 = Glicko2Rating {
///     rating: 1550.0,
///     deviation: 100.0,
///     volatility: 0.06,
/// };
///
/// let opponent3 = Glicko2Rating {
///     rating: 1700.0,
///     deviation: 300.0,
///     volatility: 0.06,
/// };
///
/// let results = vec![
///     (opponent1, Outcomes::WIN),
///     (opponent2, Outcomes::LOSS),
///     (opponent3, Outcomes::LOSS),
/// ];
///
/// let new_player = glicko2_rating_period(&player, &results, &Glicko2Config::new());
///
/// assert!((new_player.rating.round() - 1464.0).abs() < f64::EPSILON);
/// assert!((new_player.deviation.round() - 152.0).abs() < f64::EPSILON);
/// assert!((new_player.volatility - 0.059995984286488495).abs() < f64::EPSILON);
/// ```
pub fn glicko2_rating_period(
    player: &Glicko2Rating,
    results: &[(Glicko2Rating, Outcomes)],
    config: &Glicko2Config,
) -> Glicko2Rating {
    if results.is_empty() {
        return decay_deviation(player);
    }

    let player_rating = (player.rating - 1500.0) / 173.7178;
    let player_deviation = player.deviation / 173.7178;

    let v = results
        .iter()
        .map(|r| {
            let g = g_value(r.0.deviation / 173.7178);

            let e = e_value(player_rating, (r.0.rating - 1500.0) / 173.7178, g);

            g.powi(2) * e * (1.0 - e)
        })
        .sum::<f64>()
        .recip();

    let scores: f64 = (results.iter().map(|r| {
        let g = g_value(r.0.deviation / 173.7178);

        let e = e_value(player_rating, (r.0.rating - 1500.0) / 173.7178, g);

        let s = r.1.to_chess_points();

        g * (s - e)
    }))
    .sum();

    let delta = v * scores;

    let new_volatility = new_volatility(
        player.volatility,
        delta.powi(2),
        player_deviation.powi(2),
        v,
        config.tau,
        config.convergence_tolerance,
    );

    let new_deviation = new_deviation(player_deviation, new_volatility, v);

    let new_rating = new_deviation.powi(2).mul_add(scores, player_rating);

    Glicko2Rating {
        rating: new_rating.mul_add(173.7178, 1500.0),
        deviation: new_deviation * 173.7178,
        volatility: new_volatility,
    }
}

/// Calculates the expected outcome of two players based on glicko-2.
///
/// Takes in two players as [`Glicko2Rating`]s and returns the probability of victory for each player as an [`f64`] between 1.0 and 0.0.\
/// 1.0 means a certain victory for the player, 0.0 means certain loss.
/// Values near 0.5 mean a draw is likely to occur.
///
/// # Examples
/// ```
/// use skillratings::glicko2::{expected_score, Glicko2Rating};
///
/// let player_one = Glicko2Rating {
///     rating: 2500.0,
///     deviation: 41.0,
///     volatility: 0.06,
/// };
/// let player_two = Glicko2Rating {
///     rating: 1950.0,
///     deviation: 320.0,
///     volatility: 0.06,
/// };
/// let (exp_one, exp_two) = expected_score(&player_one, &player_two);
/// assert!(((exp_one * 100.0).round() - 90.0).abs() < f64::EPSILON);
/// assert!(((exp_two * 100.0).round() - 10.0).abs() < f64::EPSILON);
/// ```
#[must_use]
pub fn expected_score(player_one: &Glicko2Rating, player_two: &Glicko2Rating) -> (f64, f64) {
    // First we need to convert the ratings into the glicko-2 scale.
    let player_one_rating = (player_one.rating - 1500.0) / 173.7178;
    let player_two_rating = (player_two.rating - 1500.0) / 173.7178;

    // Same with the deviation.
    let player_one_deviation = player_one.deviation / 173.7178;
    let player_two_deviation = player_two.deviation / 173.7178;

    // The win probability of player_one is E(μ, μj, √(φj^2 + φ^2)) instead of E(μ, μj, φj).
    let exp_one = e_value(
        player_one_rating,
        player_two_rating,
        g_value(player_two_deviation.hypot(player_one_deviation)),
    );
    let exp_two = 1.0 - exp_one;

    (exp_one, exp_two)
}

#[must_use]
/// Calculates the expected outcome of a player in a rating period or tournament.
///
/// Takes in a players as [`Glicko2Rating`] and a list of opponents as a slice of [`Glicko2Rating`]
/// and returns the probability of victory for each match as an Vec of [`f64`] between 1.0 and 0.0 from the perspective of the player.\
/// 1.0 means a certain victory for the player, 0.0 means certain loss.
/// Values near 0.5 mean a draw is likely to occur.
///
/// # Examples
/// ```
/// use skillratings::glicko2::{expected_score_rating_period, Glicko2Rating};
///
/// let player = Glicko2Rating {
///     rating: 1900.0,
///     deviation: 120.0,
///     volatility: 0.00583,
/// };
///
/// let opponent1 = Glicko2Rating {
///     rating: 1930.0,
///     deviation: 120.0,
///     volatility: 0.00583,
/// };
///
/// let opponent2 = Glicko2Rating {
///     rating: 1730.0,
///     deviation: 120.0,
///     volatility: 0.00583,
/// };
///
/// let exp = expected_score_rating_period(&player, &[opponent1, opponent2]);
///
/// assert_eq!((exp[0] * 100.0).round(), 46.0);
/// assert_eq!((exp[1] * 100.0).round(), 70.0);
/// ```
pub fn expected_score_rating_period(
    player: &Glicko2Rating,
    opponents: &[Glicko2Rating],
) -> Vec<f64> {
    opponents
        .iter()
        .map(|o| {
            let player_one_rating = (player.rating - 1500.0) / 173.7178;
            let player_two_rating = (o.rating - 1500.0) / 173.7178;

            let player_one_deviation = player.deviation / 173.7178;
            let player_two_deviation = o.deviation / 173.7178;

            let a1 = g_value(player_two_deviation.hypot(player_one_deviation))
                * (player_one_rating - player_two_rating);

            (1.0 + (-a1).exp()).recip()
        })
        .collect()
}

/// Decays a Rating Deviation Value for a player, if they missed playing in a certain rating period.
///
/// The length of the rating period and thus the number of missed periods per player is something to decide and track yourself.
///
/// Takes in a player as a [`Glicko2Rating`] and returns the decayed [`Glicko2Rating`].
///
/// # Examples
/// ```
/// use skillratings::glicko2::{decay_deviation, Glicko2Rating};
///
/// let player_one = Glicko2Rating {
///     rating: 2720.0,
///     deviation: 41.3,
///     volatility: 0.06,
/// };
///
/// let player_one_decay = decay_deviation(&player_one);
///
/// assert!((player_one_decay.deviation.round() - 43.0).abs() < f64::EPSILON);
/// ```
#[must_use]
pub fn decay_deviation(player: &Glicko2Rating) -> Glicko2Rating {
    let player_deviation = player.deviation / 173.7178;
    let new_player_deviation = player_deviation.hypot(player.volatility);

    Glicko2Rating {
        rating: player.rating,
        deviation: (new_player_deviation * 173.7178).min(350.0),
        volatility: player.volatility,
    }
}

#[must_use]
/// The 95% confidence interval of the lowest to highest rating.
///
/// The system is 95% sure that the "true skill" of the player is in-between these values.
///
/// Takes in a player as a [`Glicko2Rating`] and returns two [`f64`]s that describe the lowest and highest rating.
///
/// # Examples
/// ```
/// use skillratings::glicko2::{confidence_interval, Glicko2Rating};
///
/// let player = Glicko2Rating {
///     rating: 2250.0,
///     deviation: 79.0,
///     volatility: 0.0598,
/// };
///
/// let (interval_low, interval_high) = confidence_interval(&player);
///
/// assert!(interval_low.round() - 2095.0 < f64::EPSILON);
/// assert!(interval_high.round() - 2405.0 < f64::EPSILON);
/// ```
pub fn confidence_interval(player: &Glicko2Rating) -> (f64, f64) {
    (
        1.96f64.mul_add(-player.deviation, player.rating),
        1.96f64.mul_add(player.deviation, player.rating),
    )
}

fn g_value(deviation: f64) -> f64 {
    (1.0 + ((3.0 * deviation.powi(2)) / (PI.powi(2))))
        .sqrt()
        .recip()
}

fn e_value(rating: f64, opponent_rating: f64, g: f64) -> f64 {
    (1.0 + (-g * (rating - opponent_rating)).exp()).recip()
}

fn v_value(g: f64, e: f64) -> f64 {
    (g.powi(2) * e * (1.0 - e)).recip()
}

fn delta_value(outcome: f64, v: f64, g: f64, e: f64) -> f64 {
    v * (g * (outcome - e))
}

fn f_value(
    x: f64,
    delta_square: f64,
    deviation_square: f64,
    v: f64,
    volatility: f64,
    tau: f64,
) -> f64 {
    let i = (x.exp() * (delta_square - deviation_square - v - x.exp()))
        / (2.0 * (deviation_square + v + x.exp()).powi(2));

    let j = (x - volatility.powi(2).ln()) / tau.powi(2);

    i - j
}

fn new_volatility(
    old_volatility: f64,
    delta_squared: f64,
    deviation_squared: f64,
    v: f64,
    tau: f64,
    convergence_tolerance: f64,
) -> f64 {
    let mut a = old_volatility.powi(2).ln();
    let mut b = if delta_squared > deviation_squared + v {
        (delta_squared - deviation_squared - v).ln()
    } else {
        let mut k: f64 = 1.0;
        #[allow(clippy::while_float)]
        while f_value(
            k.mul_add(-tau, a),
            delta_squared,
            deviation_squared,
            v,
            old_volatility,
            tau,
        ) < 0.0
        {
            k += 1.0;
        }
        k.mul_add(-tau, a)
    };

    let mut fa = f_value(a, delta_squared, deviation_squared, v, old_volatility, tau);
    let mut fb = f_value(b, delta_squared, deviation_squared, v, old_volatility, tau);

    // 0.000001 is the convergence tolerance suggested by Mark Glickman.
    #[allow(clippy::while_float)]
    while (b - a).abs() > convergence_tolerance {
        let c = a + ((a - b) * fa / (fb - fa));
        let fc = f_value(c, delta_squared, deviation_squared, v, old_volatility, tau);

        if fc * fb <= 0.0 {
            a = b;
            fa = fb;
        } else {
            fa /= 2.0;
        }

        b = c;
        fb = fc;
    }

    (a / 2.0).exp()
}

fn new_deviation(deviation: f64, new_volatility: f64, v: f64) -> f64 {
    let pre_deviation = deviation.hypot(new_volatility);

    ((pre_deviation.powi(2).recip()) + (v.recip()))
        .sqrt()
        .recip()
}

fn new_rating(rating: f64, new_deviation: f64, outcome: f64, g_value: f64, e_value: f64) -> f64 {
    (new_deviation.powi(2) * g_value).mul_add(outcome - e_value, rating)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_equal_glicko2() {
        let player1 = Glicko2Rating {
            rating: 1520.0,
            deviation: 350.0,
            volatility: 0.06,
        };

        let player2 = Glicko2Rating {
            rating: 1420.0,
            deviation: 350.0,
            volatility: 0.06,
        };

        let config = Glicko2Config::default();

        let (player1new, player2new) = glicko2(&player1, &player2, &Outcomes::WIN, &config);

        assert!((player1new.rating.round() - 1653.0).abs() < f64::EPSILON);
        assert!((player1new.deviation.round() - 292.0).abs() < f64::EPSILON);

        assert!((player2new.rating.round() - 1287.0).abs() < f64::EPSILON);
        assert!((player2new.deviation.round() - 292.0).abs() < f64::EPSILON);
    }

    #[test]
    fn not_equal_deviation_draw() {
        let player1 = Glicko2Rating {
            rating: 1600.0,
            deviation: 350.0,
            volatility: 0.06,
        };

        let player2 = Glicko2Rating {
            rating: 1500.0,
            deviation: 50.0,
            volatility: 0.06,
        };

        let (player1new, player2new) = glicko2(
            &player1,
            &player2,
            &Outcomes::DRAW,
            &Glicko2Config::default(),
        );

        assert!((player1new.rating.round() - 1550.0).abs() < f64::EPSILON);
        assert!((player1new.deviation.round() - 253.0).abs() < f64::EPSILON);

        assert!((player2new.rating.round() - 1501.0).abs() < f64::EPSILON);
        assert!((player2new.deviation.round() - 51.0).abs() < f64::EPSILON);
    }

    #[test]
    /// This test is taken directly from the official glicko2 example.
    /// <http://www.glicko.net/glicko/glicko2.pdf>
    fn test_glicko2() {
        let player = Glicko2Rating {
            rating: 1500.0,
            deviation: 200.0,
            volatility: 0.06,
        };

        let opponent_one = Glicko2Rating {
            rating: 1400.0,
            deviation: 30.0,
            volatility: 0.06,
        };

        let (player, opponent_one) = glicko2(
            &player,
            &opponent_one,
            &Outcomes::WIN,
            &Glicko2Config::new(),
        );

        assert!((player.rating.round() - 1564.0).abs() < f64::EPSILON);
        assert!((player.deviation.round() - 175.0).abs() < f64::EPSILON);

        assert!((opponent_one.rating.round() - 1398.0).abs() < f64::EPSILON);
        assert!((opponent_one.deviation.round() - 32.0).abs() < f64::EPSILON);

        let opponent_two = Glicko2Rating {
            rating: 1550.0,
            deviation: 100.0,
            volatility: 0.06,
        };

        let (player, _) = glicko2(
            &player,
            &opponent_two,
            &Outcomes::LOSS,
            &Glicko2Config::new(),
        );

        let opponent_three = Glicko2Rating {
            rating: 1700.0,
            deviation: 300.0,
            volatility: 0.06,
        };

        let (player, _) = glicko2(
            &player,
            &opponent_three,
            &Outcomes::LOSS,
            &Glicko2Config::new(),
        );

        assert!((player.rating.round() - 1464.0).abs() < f64::EPSILON);
        assert!((player.deviation.round() - 152.0).abs() < f64::EPSILON);
        assert!((player.volatility - 0.059_997_514_049_860_735).abs() < f64::EPSILON);
    }

    #[test]
    fn test_glicko2_rating_period() {
        let player = Glicko2Rating {
            rating: 1500.0,
            deviation: 200.0,
            volatility: 0.06,
        };

        let opponent_one = Glicko2Rating {
            rating: 1400.0,
            deviation: 30.0,
            volatility: 0.06,
        };

        let opponent_two = Glicko2Rating {
            rating: 1550.0,
            deviation: 100.0,
            volatility: 0.06,
        };

        let opponent_three = Glicko2Rating {
            rating: 1700.0,
            deviation: 300.0,
            volatility: 0.06,
        };

        let results = vec![
            (opponent_one, Outcomes::WIN),
            (opponent_two, Outcomes::LOSS),
            (opponent_three, Outcomes::LOSS),
        ];

        let new_player = glicko2_rating_period(&player, &results, &Glicko2Config::new());

        assert!((new_player.rating.round() - 1464.0).abs() < f64::EPSILON);
        assert!(((new_player.deviation * 100.0).round() - 15152.0).abs() < f64::EPSILON);
        assert!((new_player.volatility - 0.059_995_984_286_488_495).abs() < f64::EPSILON);

        let player = Glicko2Rating {
            rating: 1250.0,
            deviation: 95.0,
            volatility: 0.06,
        };

        let results: Vec<(Glicko2Rating, Outcomes)> = Vec::new();

        let new_player = glicko2_rating_period(&player, &results, &Glicko2Config::new());

        assert!((new_player.deviation.round() - 96.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_expected_score() {
        let player_one = Glicko2Rating {
            rating: 1500.0,
            deviation: 350.0,
            volatility: 0.06,
        };

        let player_two = Glicko2Rating {
            rating: 1500.0,
            deviation: 350.0,
            volatility: 0.06,
        };

        let (exp_one, exp_two) = expected_score(&player_one, &player_two);

        assert!(exp_one.mul_add(100.0, -50.0).abs() < f64::EPSILON);
        assert!(exp_two.mul_add(100.0, -50.0).abs() < f64::EPSILON);

        let player_three = Glicko2Rating {
            rating: 2000.0,
            deviation: 50.0,
            volatility: 0.06,
        };

        let player_four = Glicko2Rating {
            rating: 1780.0,
            deviation: 150.0,
            volatility: 0.06,
        };

        let (exp_three, exp_four) = expected_score(&player_three, &player_four);

        assert!(((exp_three * 100.0).round() - 76.0).abs() < f64::EPSILON);
        assert!(((exp_four * 100.0).round() - 24.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_decay() {
        let player_one = Glicko2Rating {
            rating: 1500.0,
            deviation: 350.0,
            volatility: 0.06,
        };

        let player_two = Glicko2Rating {
            rating: 1250.0,
            deviation: 95.0,
            volatility: 0.06,
        };

        let player_three = Glicko2Rating {
            rating: 2250.0,
            deviation: 35.0,
            volatility: 0.059_998,
        };

        let player_one_decayed = decay_deviation(&player_one);
        let player_one_decayed_2 = decay_deviation(&player_one_decayed);

        let player_two_decayed = decay_deviation(&player_two);

        let player_three_decayed = decay_deviation(&player_three);
        let player_three_decayed_2 = decay_deviation(&player_three_decayed);

        assert!((player_one_decayed.deviation.round() - 350.0).abs() < f64::EPSILON);
        assert!((player_one_decayed_2.deviation.round() - 350.0).abs() < f64::EPSILON);
        assert!((player_two_decayed.deviation.round() - 96.0).abs() < f64::EPSILON);
        assert!((player_three_decayed.deviation.round() - 37.0).abs() < f64::EPSILON);
        assert!((player_three_decayed_2.deviation.round() - 38.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_single_rp() {
        let player = Glicko2Rating {
            rating: 1200.0,
            deviation: 25.0,
            volatility: 0.05999,
        };
        let opponent = Glicko2Rating {
            rating: 1500.0,
            deviation: 34.0,
            volatility: 0.05923,
        };

        let config = Glicko2Config::new();

        let (np, _) = glicko2(&player, &opponent, &Outcomes::WIN, &config);

        let rp = glicko2_rating_period(&player, &[(opponent, Outcomes::WIN)], &config);

        assert_eq!(rp, np);
    }

    #[test]
    fn test_confidence_interval() {
        let player = Glicko2Rating {
            rating: 1500.0,
            deviation: 30.0,
            volatility: 0.06,
        };

        let ci = confidence_interval(&player);

        assert!((ci.0.round() - 1441.0).abs() < f64::EPSILON);
        assert!((ci.1.round() - 1559.0).abs() < f64::EPSILON);
    }

    #[test]
    fn negative_tau() {
        let mut player = Glicko2Rating {
            rating: 2250.0,
            deviation: 3100.0,
            volatility: 0.07,
        };

        let mut opponent = Glicko2Rating {
            rating: 2250.0,
            deviation: 41.0,
            volatility: 0.1,
        };

        let config = Glicko2Config {
            tau: -10.0,
            convergence_tolerance: 0.000_001,
        };

        (player, opponent) = glicko2(&player, &opponent, &Outcomes::WIN, &config);

        assert!((player.rating.round() - 2596.0).abs() < f64::EPSILON);
        assert!((opponent.rating.round() - 2249.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_lose_streak() {
        let mut player = Glicko2Rating::new();

        let mut opponent = Glicko2Rating::default();

        for _ in 0..6 {
            (player, opponent) =
                glicko2(&player, &opponent, &Outcomes::LOSS, &Glicko2Config::new());
        }

        (player, opponent) = glicko2(&player, &opponent, &Outcomes::WIN, &Glicko2Config::new());

        assert!((player.rating.round() - 1397.0).abs() < f64::EPSILON);
        assert!((player.deviation.round() - 212.0).abs() < f64::EPSILON);
        assert!(((player.volatility * 1_000_000.0).round() - 60_004.0).abs() < f64::EPSILON);

        assert!((opponent.rating.round() - 1603.0).abs() < f64::EPSILON);
        assert!((opponent.deviation.round() - 212.0).abs() < f64::EPSILON);
        assert!(((opponent.volatility * 1_000_000.0).round() - 60_004.0).abs() < f64::EPSILON);

        let mut player = Glicko2Rating::new();

        let mut opponent = Glicko2Rating::new();

        for _ in 0..25 {
            (player, opponent) =
                glicko2(&player, &opponent, &Outcomes::LOSS, &Glicko2Config::new());
        }

        (player, opponent) = glicko2(&player, &opponent, &Outcomes::WIN, &Glicko2Config::new());

        assert!((player.rating.round() - 1248.0).abs() < f64::EPSILON);
        assert!((player.deviation.round() - 176.0).abs() < f64::EPSILON);
        assert!(((player.volatility * 1_000_000.0).round() - 60_001.0).abs() < f64::EPSILON);

        assert!((opponent.rating.round() - 1752.0).abs() < f64::EPSILON);
        assert!((opponent.deviation.round() - 176.0).abs() < f64::EPSILON);
        assert!(((opponent.volatility * 1_000_000.0).round() - 60_001.0).abs() < f64::EPSILON);
    }

    #[test]
    fn glicko_conversion() {
        let glicko2_player = Glicko2Rating::new();

        let glicko1_player = GlickoRating::from(glicko2_player);

        assert_eq!(glicko1_player, GlickoRating::new());

        let other_glicko2_player = Glicko2Rating::from(GlickoRating {
            rating: 350.0,
            deviation: 40.0,
        });

        assert!((other_glicko2_player.rating - 350.0).abs() < f64::EPSILON);
        assert!((other_glicko2_player.volatility - 0.06).abs() < f64::EPSILON);
    }

    #[test]
    #[allow(clippy::clone_on_copy)]
    fn test_misc_stuff() {
        let player_one = Glicko2Rating::new();
        let config = Glicko2Config::new();

        assert_eq!(player_one, player_one.clone());
        assert!((config.tau - config.clone().tau).abs() < f64::EPSILON);

        assert!(!format!("{player_one:?}").is_empty());
        assert!(!format!("{config:?}").is_empty());

        assert_eq!(player_one, Glicko2Rating::from((1500.0, 350.0, 0.06)));
    }

    #[test]
    fn test_traits() {
        let player_one: Glicko2Rating = Rating::new(Some(240.0), Some(90.0));
        let player_two: Glicko2Rating = Rating::new(Some(240.0), Some(90.0));

        let rating_system: Glicko2 = RatingSystem::new(Glicko2Config::new());

        assert!((player_one.rating() - 240.0).abs() < f64::EPSILON);
        assert_eq!(player_one.uncertainty(), Some(90.0));

        let (new_player_one, new_player_two) =
            RatingSystem::rate(&rating_system, &player_one, &player_two, &Outcomes::WIN);

        let (exp1, exp2) = RatingSystem::expected_score(&rating_system, &player_one, &player_two);

        assert!((new_player_one.rating - 261.373_963_260_869_7).abs() < f64::EPSILON);
        assert!((new_player_two.rating - 218.626_036_739_130_34).abs() < f64::EPSILON);
        assert!((exp1 - 0.5).abs() < f64::EPSILON);
        assert!((exp2 - 0.5).abs() < f64::EPSILON);

        let rating_period_system: Glicko2 = RatingPeriodSystem::new(Glicko2Config::new());
        let exp_rp =
            RatingPeriodSystem::expected_score(&rating_period_system, &player_one, &[player_two]);
        assert!((exp1 - exp_rp[0]).abs() < f64::EPSILON);

        let player_one: Glicko2Rating = Rating::new(Some(240.0), Some(90.0));
        let player_two: Glicko2Rating = Rating::new(Some(240.0), Some(90.0));

        let rating_period: Glicko2 = RatingPeriodSystem::new(Glicko2Config::new());

        let new_player_one =
            RatingPeriodSystem::rate(&rating_period, &player_one, &[(player_two, Outcomes::WIN)]);

        assert!((new_player_one.rating - 261.373_963_260_869_7).abs() < f64::EPSILON);
    }
}