-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIDS702_Final_Tennis_Official.html
974 lines (937 loc) · 50.6 KB
/
IDS702_Final_Tennis_Official.html
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
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"><head>
<meta charset="utf-8">
<meta name="generator" content="quarto-1.5.57">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
<meta name="author" content="Alejandro Paredes La Torre, Liangcheng (Jay) Liu">
<meta name="author" content="Nzarama Michaella Desire Kouadio, Jahnavi Maddhuri">
<title>Study of tennis performance on different surfaces and factors that affect wins</title>
<style>
code{white-space: pre-wrap;}
span.smallcaps{font-variant: small-caps;}
div.columns{display: flex; gap: min(4vw, 1.5em);}
div.column{flex: auto; overflow-x: auto;}
div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
ul.task-list{list-style: none;}
ul.task-list li input[type="checkbox"] {
width: 0.8em;
margin: 0 0.8em 0.2em -1em; /* quarto-specific, see https://github.com/quarto-dev/quarto-cli/issues/4556 */
vertical-align: middle;
}
</style>
<script src="IDS702_Final_Tennis_Official_files/libs/clipboard/clipboard.min.js"></script>
<script src="IDS702_Final_Tennis_Official_files/libs/quarto-html/quarto.js"></script>
<script src="IDS702_Final_Tennis_Official_files/libs/quarto-html/popper.min.js"></script>
<script src="IDS702_Final_Tennis_Official_files/libs/quarto-html/tippy.umd.min.js"></script>
<script src="IDS702_Final_Tennis_Official_files/libs/quarto-html/anchor.min.js"></script>
<link href="IDS702_Final_Tennis_Official_files/libs/quarto-html/tippy.css" rel="stylesheet">
<link href="IDS702_Final_Tennis_Official_files/libs/quarto-html/quarto-syntax-highlighting.css" rel="stylesheet" id="quarto-text-highlighting-styles">
<script src="IDS702_Final_Tennis_Official_files/libs/bootstrap/bootstrap.min.js"></script>
<link href="IDS702_Final_Tennis_Official_files/libs/bootstrap/bootstrap-icons.css" rel="stylesheet">
<link href="IDS702_Final_Tennis_Official_files/libs/bootstrap/bootstrap.min.css" rel="stylesheet" id="quarto-bootstrap" data-mode="light">
</head><body>\usepackage{float}
\usepackage{authblk}
\floatplacement{table}{H}
<script src="https://cdnjs.cloudflare.com/polyfill/v3/polyfill.min.js?features=es6"></script>
<script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml-full.js" type="text/javascript"></script>
<script type="text/javascript">
const typesetMath = (el) => {
if (window.MathJax) {
// MathJax Typeset
window.MathJax.typeset([el]);
} else if (window.katex) {
// KaTeX Render
var mathElements = el.getElementsByClassName("math");
var macros = [];
for (var i = 0; i < mathElements.length; i++) {
var texText = mathElements[i].firstChild;
if (mathElements[i].tagName == "SPAN") {
window.katex.render(texText.data, mathElements[i], {
displayMode: mathElements[i].classList.contains('display'),
throwOnError: false,
macros: macros,
fleqn: false
});
}
}
}
}
window.Quarto = {
typesetMath
};
</script>
<div id="quarto-content" class="page-columns page-rows-contents page-layout-article">
<div id="quarto-margin-sidebar" class="sidebar margin-sidebar">
<div class="quarto-alternate-formats"><h2>Other Formats</h2><ul><li><a href="IDS702_Final_Tennis_Official.pdf"><i class="bi bi-file-pdf"></i>PDF</a></li></ul></div></div>
<main class="content" id="quarto-document-content">
<header id="title-block-header" class="quarto-title-block default">
<div class="quarto-title">
<h1 class="title">Study of tennis performance on different surfaces and factors that affect wins</h1>
<p class="subtitle lead">2024-12-15</p>
</div>
<div class="quarto-title-meta">
<div>
<div class="quarto-title-meta-heading">Authors</div>
<div class="quarto-title-meta-contents">
<p>Alejandro Paredes La Torre, Liangcheng (Jay) Liu </p>
<p>Nzarama Michaella Desire Kouadio, Jahnavi Maddhuri </p>
</div>
</div>
</div>
</header>
<section id="abstract" class="level2">
<h2 class="anchored" data-anchor-id="abstract">Abstract</h2>
<p>This study explores how player rankings and aces affect tennis match outcomes using the Association of Tennis Professionals (ATP) data. The first research topic examines the impact of ranking differences on match duration. The research then evolves to investigate the relationship between the number of aces by a tennis player and that player’s odds of winning.</p>
<p>Methodology to the study includes exploratory data analysis combined with linear and logistic regression models, supported by visualizations. These findings highlight the connection between player rankings, aces, and match outcomes, while emphasizing the interactive impact of surface type.</p>
<p>Results show that larger ranking gaps lead to shorter matches, though surface type and match conditions also influence duration. Additionally, the findings indicate that hitting more aces improves the odds of winning, with surface types like clay and hard courts playing a significant role in this relationship.</p>
</section>
<section id="introduction" class="level2">
<h2 class="anchored" data-anchor-id="introduction">Introduction</h2>
<p>A substantial body of research has explored the prediction of tennis match outcomes using statistical models, highlighting the importance of player attributes and match statistics. Early studies, such as those by Newton and Keller (2005)[2], O’Malley (2008)[3], and Riddle (1988)[4], demonstrate that under the assumption of independent and identically distributed (iid) point outcomes on a player’s serve, the probability of winning a match can be derived from the probabilities of winning points on serve.</p>
<p>Kovalchik (2016) [5] conducted a comparison of 11 published tennis prediction models, categorizing them into three classes: point-based models relying on the iid assumption, regression-based models, and paired comparison models. The study found that while point-based models had lower accuracy and higher log loss, regression and paired comparison models generally outperformed them.</p>
</section>
<section id="methods" class="level2">
<h2 class="anchored" data-anchor-id="methods">Methods</h2>
<section id="data-and-preprocessing" class="level3">
<h3 class="anchored" data-anchor-id="data-and-preprocessing">Data and preprocessing</h3>
<p>The dataset utilized in this study is the Tennis ATP Dataset curated by Jeff Sackmann (Sackmann, 2021) [1]. This dataset serves as a comprehensive repository of professional tennis data, encompassing a wide range of player information, historical rankings, match outcomes, and statistical metrics. Specifically, it includes a player file containing detailed biographical data, such as unique player identifiers, names, handedness, birth dates, nationalities, and physical attributes like height. Additionally, ranking files provide a historical record of ATP rankings over time, while the results file covers match outcomes across tour-level, challenger, and futures events. This dataset forms a robust foundation for exploring various aspects of professional tennis performance and trends.</p>
<p>The dataset selected includes ATP match data from 2014-2024, the subset chosen are challenger matches and professional and tournament class A such as Davis Cup, Roland Garros and others. The records from this period consist in 116,103 matches where each match has 49 variables.</p>
<p>The initial collection of data contains features at the match level, therefore it has information from the winner player and the loser player. In order to analyze the effect of match win this structured has been modified to portray the results at the player level, including both win and loss outcomes.</p>
<p>In order to improve the quality of the data, those players that do not have a rank and rank points have been set to zero as the data dictionary explains that unranked players are new to these tournaments. To handle missing values in height, an imputation technique is used where player height is estimated using the average of the country of birth of the player.</p>
<p>Furthermore, rows where the number of aces played is missing have been removed as this is key information in our research questionanalyzing that matches whose number of aces for the winner nor the loser are missing lack all the statistical information from the the other aspects of the match therefore those records have been filtered. The same rationale applies to the serving games as it signals records that have missing information overall therefore those records have been filtered out from the analysis data.</p>
<p>Lastly, for highly correlated information, ratios have been computed to continue to capture granularity in information, but also reduce the number of variables needed in any model, minimizing multicollinearity.</p>
<p>On the other hand to assess the effect of factors on the match length, missing values in the dataset were adrressed to prepare for further analysis. Group-wise imputation was performed based on the surface type: missing player heights were replaced with the average height for that surface, and missing match durations were replaced with the median duration for that surface. This approach ensured that missing data was filled in a way that preserved context and prepared the dataset for modeling.</p>
<p>Moreover, the difference in the number of aces, rankings, and ranking points between the winner and loser was calculated. These perfomance metrics aim to provide more tangible and interpretable predictors for the model by focusing on measurable aspects of the players performance. Grouping variables into performance metrics also helps to frame the analysis in a way that aligns with the context of the sport and makes the regressors more meaningful and insightful.</p>
<p>Finally, rows with missing values for match duration (our target variable) were removed since only 8% of the data was affected. This approach is acceptable because the missing proportion is relatively small, and our target variable needs to be complete for modeling purposes.</p>
</section>
<section id="variable-selection" class="level3">
<h3 class="anchored" data-anchor-id="variable-selection">Variable selection</h3>
<p>Taking as reference previous research regarding the most relevant features involved in the outcome of a tennis match (Newton et al., 2005[1]; O’Malley 2008[2]; Kovalchik, 2016) a pre selection was made observing the limitation of the available data. In order to further refine the process of feature selection exploratory data analysis was conducted using correlation plots, box plots and scatterplots.</p>
</section>
<section id="modeling-and-evaluation" class="level3">
<h3 class="anchored" data-anchor-id="modeling-and-evaluation">Modeling and evaluation</h3>
<p>The present study focuses on the effects of the duration of a match using linear regression to evaluate inference capabilities and determining the principal factors for a match win using logistic regression to evaluate the probability of a win. Variance Inflation Factor (VIF) was used to test multi-colinearity. For the linear regression task the assumptions for the model are tested via residual vs fitted plots and normal q-q plots, furthermore, the performance of the model is evaluated using the adjusted r squared metric. In terms of logistic regression, accuracy, recall sensitivity and specificity are used to evaluate the model. Lasso Regularization is implemented to prevent overfitting of the model due to too many variables. The AIC score is also used to evaluate the model, incorporating the number of predictors into the overall score.</p>
</section>
</section>
<section id="results" class="level2">
<h2 class="anchored" data-anchor-id="results">Results</h2>
<section id="overview-of-key-variables-of-interest" class="level3">
<h3 class="anchored" data-anchor-id="overview-of-key-variables-of-interest">Overview of key variables of interest</h3>
<p>The dataset has a fairly even distribution of players that Win (101746) and Lose (111621), implying that there would not be more information gain in one outcome over the other. The surface types do not have as balanced of a distribution. Majority of the matches are played on a Hard or Clay surface, accounting for 53.5% and 41.1% of the matches. About 5% of the matches are played on Grass and only 0.2% on Carpet. Below we consider the distribution of the key continuous variables:</p>
<div class="cell">
<div class="cell-output-display">
<table class="caption-top table table-sm table-striped small">
<caption>Summary Statistics for Variables</caption>
<colgroup>
<col style="width: 13%">
<col style="width: 12%">
<col style="width: 16%">
<col style="width: 16%">
<col style="width: 10%">
<col style="width: 16%">
<col style="width: 12%">
</colgroup>
<thead>
<tr class="header">
<th style="text-align: left;">Variable</th>
<th style="text-align: right;">Minimum</th>
<th style="text-align: right;">Quantile.1</th>
<th style="text-align: right;">Mean</th>
<th style="text-align: right;">Median</th>
<th style="text-align: right;">Quantile.3</th>
<th style="text-align: right;">Maximum</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td style="text-align: left;">minutes</td>
<td style="text-align: right;">0</td>
<td style="text-align: right;">74</td>
<td style="text-align: right;">100.490937</td>
<td style="text-align: right;">94</td>
<td style="text-align: right;">123</td>
<td style="text-align: right;">4756</td>
</tr>
<tr class="even">
<td style="text-align: left;">rank</td>
<td style="text-align: right;">0</td>
<td style="text-align: right;">98</td>
<td style="text-align: right;">268.974804</td>
<td style="text-align: right;">200</td>
<td style="text-align: right;">343</td>
<td style="text-align: right;">2257</td>
</tr>
<tr class="odd">
<td style="text-align: left;">aces</td>
<td style="text-align: right;">0</td>
<td style="text-align: right;">2</td>
<td style="text-align: right;">4.745965</td>
<td style="text-align: right;">4</td>
<td style="text-align: right;">7</td>
<td style="text-align: right;">75</td>
</tr>
</tbody>
</table>
</div>
</div>
</section>
<section id="research-question-1-effects-of-the-difference-in-ranking-over-the-length-in-minutes-for-a-tennis-match" class="level3">
<h3 class="anchored" data-anchor-id="research-question-1-effects-of-the-difference-in-ranking-over-the-length-in-minutes-for-a-tennis-match"><strong>Research question 1: Effects of the difference in ranking over the length in minutes for a tennis match</strong></h3>
<blockquote class="blockquote">
<p>Below is the linear regression analyzing the relationshiop between minutes, surface and ranking differences amongst players</p>
</blockquote>
<p><span class="math display">\[
minutes = β0 +β1⋅(difference) + β2⋅surface + β3(difference*surface) + ϵ
\]</span></p>
<div class="cell">
<div class="cell-output cell-output-stdout">
<pre><code>
Call:
lm(formula = minutes ~ diff_rank * surface, data = tennis)
Residuals:
Min 1Q Median 3Q Max
-113.273 -23.769 -6.455 19.352 224.685
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 93.164377 2.108913 44.176 < 2e-16 ***
diff_rank -0.012734 0.005621 -2.265 0.02349 *
surfaceClay 11.007736 2.115392 5.204 1.96e-07 ***
surfaceGrass 11.625079 2.158509 5.386 7.23e-08 ***
surfaceHard 6.708298 2.113904 3.173 0.00151 **
diff_rank:surfaceClay -0.003546 0.005649 -0.628 0.53012
diff_rank:surfaceGrass -0.006105 0.005993 -1.019 0.30839
diff_rank:surfaceHard -0.002185 0.005642 -0.387 0.69853
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Residual standard error: 34.13 on 111528 degrees of freedom
(4514 observations deleted due to missingness)
Multiple R-squared: 0.02066, Adjusted R-squared: 0.0206
F-statistic: 336.1 on 7 and 111528 DF, p-value: < 2.2e-16</code></pre>
</div>
</div>
<p>Initially, the goal was to explore the relationship between match duration (minutes) and a limited set of predictors, specifically the difference in rankings and the interaction with surface type. However, the adjusted R² of the initial model was quite low (R² = 0.02), indicating that the predictors explained only a small fraction of the variation in match duration. This suggests that there are likely other important factors influencing the outcome that were not accounted for in the model.</p>
<p>To address this limitation, a second approach was taken to include additional variables in the model, particularly player performance metrics and other contextual factors. The rationale was that these additional predictors might capture more of the complexity and variability inherent in match durations, thereby improving the model’s explanatory power and increasing the adjusted R². This step aims to make the model more robust and reflective of the factors that influence match duration.</p>
<blockquote class="blockquote">
<p>Below is the diagnostic plot for the first linear model.</p>
</blockquote>
<div class="cell">
<div class="cell-output-display">
<div>
<figure class="figure">
<p><img src="IDS702_Final_Tennis_Official_files/figure-html/unnamed-chunk-6-1.png" class="img-fluid figure-img" width="864"></p>
</figure>
</div>
</div>
</div>
<p>The residual diagnostics reveal some violations of the linear regression assumptions, albeit less severe compared to the second model. The “Residuals vs Fitted” plot still shows signs of non-linearity, indicating the model may not adequately capture all patterns in the data. The “Q-Q Residuals” plot suggests moderate deviations from normality, particularly in the tails, which could affect hypothesis testing but to a lesser extent than the expanded model. The “Scale-Location” plot exhibits slight heteroscedasticity, where the variance of residuals increases with fitted values, suggesting the model’s predictions may not be equally reliable across all ranges. These issues indicate that while the model may be simpler, its assumptions are not entirely satisfied, and its reliability could still be questioned despite fewer violations (compared to the 2nd model, see below).</p>
<blockquote class="blockquote">
<p>Below is the linear regression analyzing the relationshiop between minutes and a multitude of regressors</p>
</blockquote>
<p>The second regression model was designed to address the low explanatory power of the initial model, which had a low adjusted R². By incorporating additional predictors such as player performance metrics, tournament levels, and specific match characteristics, the aim was to better capture the complexity of factors affecting match duration (minutes). This approach improved the adjusted R² = 0.57, suggesting that these added variables account for more of the variance in the response variable. The model also includes an interaction term and accounts for more detailed match-level attributes, providing a more comprehensive view of the factors influencing match length.</p>
<p>Some variables that significantly impact match duration (minutes) include the difference in rank between players, which shows a strong negative association, indicating that matches with greater rank disparity are shorter. The number of breakpoints saved by the winner has a significant positive effect, suggesting that matches where the winner saves more breakpoints tend to last longer. Lastly, the difference in aces between players negatively affects match duration, with matches showing a greater disparity in aces being resolved more quickly. These variables emphasize the importance of player performance and competitive dynamics in determining match length.</p>
<div class="cell">
<div class="cell-output cell-output-stdout">
<pre><code>
Call:
lm(formula = minutes ~ diff_rank + diff_aces + winner_ht + loser_ht +
surface + tourney_level + winner_age + loser_age + w_df +
l_df + w_bpSaved + l_bpSaved + w_bpFaced + l_bpFaced, data = train)
Residuals:
Min 1Q Median 3Q Max
-157.382 -13.363 -2.301 11.097 222.503
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 29.6525579 3.8812136 7.640 2.19e-14 ***
diff_rank -0.0031624 0.0002866 -11.033 < 2e-16 ***
diff_aces -0.1439204 0.0169901 -8.471 < 2e-16 ***
winner_ht 0.1437769 0.0136255 10.552 < 2e-16 ***
loser_ht 0.0741766 0.0137634 5.389 7.09e-08 ***
surfaceClay 3.0187494 1.4862371 2.031 0.042244 *
surfaceGrass -1.6028739 1.5282455 -1.049 0.294258
surfaceHard 0.2177494 1.4839764 0.147 0.883343
tourney_levelC -2.5735801 0.2064400 -12.466 < 2e-16 ***
tourney_levelD 16.0622104 0.8087540 19.860 < 2e-16 ***
tourney_levelF 5.9992554 1.8205561 3.295 0.000984 ***
tourney_levelG 25.7579945 0.3466462 74.306 < 2e-16 ***
tourney_levelM 2.2330977 0.3395012 6.578 4.81e-11 ***
winner_age 0.2600481 0.0182872 14.220 < 2e-16 ***
loser_age 0.1046355 0.0182651 5.729 1.02e-08 ***
w_df 1.4493410 0.0398569 36.364 < 2e-16 ***
l_df 0.7683978 0.0342925 22.407 < 2e-16 ***
w_bpSaved -9.7522118 0.0867795 -112.379 < 2e-16 ***
l_bpSaved 9.2642637 0.0732964 126.394 < 2e-16 ***
w_bpFaced 12.3729588 0.0725784 170.477 < 2e-16 ***
l_bpFaced -6.8579122 0.0657674 -104.275 < 2e-16 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Residual standard error: 22.75 on 85957 degrees of freedom
(6862 observations deleted due to missingness)
Multiple R-squared: 0.5723, Adjusted R-squared: 0.5722
F-statistic: 5752 on 20 and 85957 DF, p-value: < 2.2e-16</code></pre>
</div>
</div>
<blockquote class="blockquote">
<p>Below is the diagnostic plot for the second linear model.</p>
</blockquote>
<div class="cell">
<div class="cell-output-display">
<div>
<figure class="figure">
<p><img src="IDS702_Final_Tennis_Official_files/figure-html/unnamed-chunk-8-1.png" class="img-fluid figure-img" width="864"></p>
</figure>
</div>
</div>
</div>
<p>Despite achieving a higher adjusted R² compared to the first model, several key assumptions of the linear regression model appear to be violated. The “Residuals vs Fitted” plot indicates potential non-linearity in the relationships between predictors and the response variable, suggesting the model may not be capturing all relevant patterns. The “Q-Q Residuals” plot shows significant deviations from normality, particularly in the tails, which could compromise the reliability of hypothesis tests and confidence intervals. Additionally, the “Scale-Location” plot reveals heteroscedasticity, with residuals showing increasing variance as fitted values grow. While the larger R²suggests the model explains more variance in match duration, these assumption violations indicate that the results may not be entirely valid or interpretable under the linear regression framework, reducing the model’s overall reliability. These violations suggest that the model might require transformations, interaction terms, or alternative regression methods to better satisfy these assumptions.</p>
</section>
<section id="research-question-2-aces-and-court-surface-type-influence-in-match-outcome" class="level3">
<h3 class="anchored" data-anchor-id="research-question-2-aces-and-court-surface-type-influence-in-match-outcome"><strong>Research question 2: Aces and court surface type influence in match outcome</strong></h3>
<p>The results for the final fitted model for win prediction are in the Anex I since the table is large. The selected variables along with the interaction term of the type of surface was included. Multiple iterations to find the best model were performed and multicolinearity evaluations were used to assess the model. To evaluate multicollinearity, the VIF score was used on a logistic regression model. The raw variables representing a player’s total serve points, number of first serve points made, number of first serve points won, number of second serve points won, number of break points faced, number of break points saved, total draw size in the tournament and the tournament level were all highly correlated. To address the multicollinearity in serve variables, ratios of successful serves for the first and second attempt were generated. Similarly, the break points saved ratio is used in place of the overall counts. Lastly, between draw size and tournament level, draw size is only used as there is more granular information derived from draw size than tournament level.</p>
<p>Apart from the VIF scores, Lasso Regularization is also performed to prevent the model from overfitting as the number of variables used is large. Using the optimal lambda value in the cross validation process, extraneous variables are identified. However, this approach did not result in the removal of any variables, rather specific binary variables representing a category like whether or not the surface is grass were deemed insignificant. Hence, Lasso Regularization is not used in the final model. The model function is:</p>
<p><span class="math display">\[
\begin{aligned}
\log \left( \frac{P(\text{win})}{1 - P(\text{win})} \right) = \beta_0 \\
&+\beta_1 \cdot \text{draw size} \\
&+\beta_2 \cdot \text{left-handed player} \\
&+\beta_3 \cdot \text{right-handed player} \\
&+\beta_4 \cdot \text{undefined-handed player} \\
&+\beta_5 \cdot \text{player height} \\
&+\beta_6 \cdot \text{player age} \\
&+\beta_7 \cdot \text{rank} \\
&+\beta_8 \cdot \text{rank points} \\
&+\beta_9 \cdot \text{aces} \\
&+\beta_{10} \cdot \text{clay surface} \\
&+\beta_{11} \cdot \text{grass surface} \\
&+\beta_{12} \cdot \text{hard surface} \\
&+\beta_{13} \cdot \text{double faults} \\
&+\beta_{14} \cdot \text{first serve win ratio} \\
&+\beta_{15} \cdot \text{second serve win ratio} \\
&+\beta_{16} \cdot \text{break points saved ratio} \\
&+\beta_{17} \cdot (\text{aces} \cdot \text{clay surface}) \\
&+\beta_{18} \cdot (\text{aces} \cdot \text{grass surface}) \\
&+\beta_{19} \cdot (\text{aces} \cdot \text{hard surface}) \\
\end{aligned}
\]</span></p>
<p><strong>Below is a summary of the final logistic regression model:</strong></p>
<div class="cell">
<div class="cell-output-display">
<table class="caption-top table table-sm table-striped small">
<caption>Logistic Regression Coefficients, Odds Ratios, and P-values</caption>
<thead>
<tr class="header">
<th style="text-align: left;">Variable</th>
<th style="text-align: right;">Coefficient</th>
<th style="text-align: right;">Odds Ratio</th>
<th style="text-align: right;">P-value</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td style="text-align: left;">(Intercept)</td>
<td style="text-align: right;">-0.3636746</td>
<td style="text-align: right;">0.6951173</td>
<td style="text-align: right;">0.5729598</td>
</tr>
<tr class="even">
<td style="text-align: left;">draw_size</td>
<td style="text-align: right;">-0.0024621</td>
<td style="text-align: right;">0.9975409</td>
<td style="text-align: right;">0.0000000</td>
</tr>
<tr class="odd">
<td style="text-align: left;">player_handL</td>
<td style="text-align: right;">2.2698780</td>
<td style="text-align: right;">9.6782204</td>
<td style="text-align: right;">0.0001411</td>
</tr>
<tr class="even">
<td style="text-align: left;">player_handR</td>
<td style="text-align: right;">2.2755000</td>
<td style="text-align: right;">9.7327838</td>
<td style="text-align: right;">0.0001354</td>
</tr>
<tr class="odd">
<td style="text-align: left;">player_handU</td>
<td style="text-align: right;">2.0070022</td>
<td style="text-align: right;">7.4409776</td>
<td style="text-align: right;">0.0007650</td>
</tr>
<tr class="even">
<td style="text-align: left;">player_height</td>
<td style="text-align: right;">-0.0191927</td>
<td style="text-align: right;">0.9809903</td>
<td style="text-align: right;">0.0000000</td>
</tr>
<tr class="odd">
<td style="text-align: left;">player_age</td>
<td style="text-align: right;">-0.0154771</td>
<td style="text-align: right;">0.9846421</td>
<td style="text-align: right;">0.0000000</td>
</tr>
<tr class="even">
<td style="text-align: left;">rank</td>
<td style="text-align: right;">-0.0005144</td>
<td style="text-align: right;">0.9994858</td>
<td style="text-align: right;">0.0000000</td>
</tr>
<tr class="odd">
<td style="text-align: left;">rank_points</td>
<td style="text-align: right;">0.0001543</td>
<td style="text-align: right;">1.0001543</td>
<td style="text-align: right;">0.0000000</td>
</tr>
<tr class="even">
<td style="text-align: left;">aces</td>
<td style="text-align: right;">0.0966552</td>
<td style="text-align: right;">1.1014805</td>
<td style="text-align: right;">0.0000005</td>
</tr>
<tr class="odd">
<td style="text-align: left;">surfaceClay</td>
<td style="text-align: right;">0.7382147</td>
<td style="text-align: right;">2.0921969</td>
<td style="text-align: right;">0.0001173</td>
</tr>
<tr class="even">
<td style="text-align: left;">surfaceGrass</td>
<td style="text-align: right;">0.3250532</td>
<td style="text-align: right;">1.3841042</td>
<td style="text-align: right;">0.0956714</td>
</tr>
<tr class="odd">
<td style="text-align: left;">surfaceHard</td>
<td style="text-align: right;">0.5582932</td>
<td style="text-align: right;">1.7476870</td>
<td style="text-align: right;">0.0035779</td>
</tr>
<tr class="even">
<td style="text-align: left;">double_faults</td>
<td style="text-align: right;">-0.1403072</td>
<td style="text-align: right;">0.8690912</td>
<td style="text-align: right;">0.0000000</td>
</tr>
<tr class="odd">
<td style="text-align: left;">break_pt_save_ratio</td>
<td style="text-align: right;">2.5465202</td>
<td style="text-align: right;">12.7626151</td>
<td style="text-align: right;">0.0000000</td>
</tr>
<tr class="even">
<td style="text-align: left;">aces:surfaceClay</td>
<td style="text-align: right;">0.0048078</td>
<td style="text-align: right;">1.0048194</td>
<td style="text-align: right;">0.8041908</td>
</tr>
<tr class="odd">
<td style="text-align: left;">aces:surfaceGrass</td>
<td style="text-align: right;">-0.0242897</td>
<td style="text-align: right;">0.9760029</td>
<td style="text-align: right;">0.2163763</td>
</tr>
<tr class="even">
<td style="text-align: left;">aces:surfaceHard</td>
<td style="text-align: right;">-0.0169552</td>
<td style="text-align: right;">0.9831877</td>
<td style="text-align: right;">0.3794067</td>
</tr>
</tbody>
</table>
</div>
</div>
<p>Analyzing the variables of interest aces and surface, holding every other variable constant, applying exponential we have an effect of 1.1 times increase in odds of winning for every extra ace point. Similarly matches on Clay and Hard surfaces increase the odds of winning in comparison to playing on a Carpet by 2.1 and 1.7 times respectively. Surprisingly, the impact of every extra ace point is not statistically significant between the different surface types. Another statistically significant variable impacting the odds of winning is the right vs left-handed stature of the player. Specifically being Right or Left Handed (as opposed to undefined) is associated with approximately 9.7 times increase in odds of winning.</p>
<div class="cell">
<div class="cell-output-display">
<table class="caption-top table table-sm table-striped small">
<thead>
<tr class="header">
<th style="text-align: left;">Metric</th>
<th style="text-align: right;">Value</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td style="text-align: left;">Accuracy</td>
<td style="text-align: right;">0.6838672</td>
</tr>
<tr class="even">
<td style="text-align: left;">Precision</td>
<td style="text-align: right;">0.6899683</td>
</tr>
<tr class="odd">
<td style="text-align: left;">Recall</td>
<td style="text-align: right;">0.7648834</td>
</tr>
<tr class="even">
<td style="text-align: left;">F1 Score</td>
<td style="text-align: right;">0.7254970</td>
</tr>
<tr class="odd">
<td style="text-align: left;">Specificity</td>
<td style="text-align: right;">0.5863642</td>
</tr>
<tr class="even">
<td style="text-align: left;">Sensitivity</td>
<td style="text-align: right;">0.7648834</td>
</tr>
<tr class="odd">
<td style="text-align: left;">Positive Predictive Value</td>
<td style="text-align: right;">0.6899683</td>
</tr>
<tr class="even">
<td style="text-align: left;">Negative Predictive Value</td>
<td style="text-align: right;">0.6745036</td>
</tr>
</tbody>
</table>
</div>
</div>
<p>The performance of the logistic regression model was evaluated using standard classification metrics, including accuracy, precision, recall, and F1 score. The model achieved an accuracy of 0.8117, indicating that approximately 81.17% of predictions matched the true outcomes. The precision of the model was 0.8230, reflecting its ability to correctly identify positive cases while minimizing false positives. The recall was measured at 0.8155, demonstrating the model’s capability to correctly identify a high proportion of actual positive cases. Finally, the F1 score, a harmonic mean of precision and recall, was calculated to be 0.8192, indicating a balanced performance between these two metrics. Together, these results suggest the model performs reliably in predicting match outcomes based on the given features.</p>
<div class="cell">
<div class="cell-output-display">
<div>
<figure class="figure">
<p><img src="IDS702_Final_Tennis_Official_files/figure-html/unnamed-chunk-13-1.png" class="img-fluid figure-img" width="672"></p>
</figure>
</div>
</div>
</div>
<p>The distribution of aces played by Winners is slightly higher valued than the distribution of aces by Losers. This supports the model estimates and the slight increase in odds of winning (by 1.1 times) for every additional ace played.</p>
</section>
</section>
<section id="conclusion" class="level2">
<h2 class="anchored" data-anchor-id="conclusion">Conclusion</h2>
<p>In conclusion, our analysis for identifying key factors significantly influencing match duration, including rank differences, aces, player heights, the type of surface of the field, age, breakpoints and tournament-level details. By expanding the model to include these variables, we improved the explanatory power (adjusted R²), highlighting their importance in predicting match length. However, residual diagnostics revealed violations of assumptions, indicating limitations in the linear regression approach for capturing complex relationships in the data. These findings emphasize the value of significant predictors while suggesting the need for alternative models to better address the data’s complexity</p>
<p>Overall, while every additional ace does improve the probability of a player winning, this factor does not have a heavy impact. Further, some surfaces like clay, significantly improve the chances of winning; however, these two variables are not highly interactive. More realistically, in a match both players will be on the same surface level, so this factor does not help one player over another. Since the model only reached an F-score of 72.5, it appears as though there may be other more indicitave factors of which player will win.</p>
</section>
<section id="references" class="level2">
<h2 class="anchored" data-anchor-id="references">References</h2>
<p>[1] Sackmann, J. (n.d.). Tennis databases, files, and algorithms [Data set]. Tennis Abstract. Licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. Based on a work at https://github.com/JeffSackmann.</p>
<p>[2] Newton, P. K., & Keller, J. B. (2005). Probability of winning at tennis I. Theory and data. Studies in applied Mathematics, 114(3), 241-269.</p>
<p>[3] O’Malley, A. J. (2008). Probability formulas and statistical analysis in tennis. Journal of Quantitative Analysis in Sports, 4(2).</p>
<p>[4] Riddle, L. H. (1988). Probability models for tennis scoring systems. Journal of the Royal Statistical Society Series C: Applied Statistics, 37(1), 63-75.</p>
<p>[5] Kovalchik, S. A. (2016). Searching for the GOAT of tennis win prediction. Journal of Quantitative Analysis in Sports, 12(3), 127-138.</p>
</section>
</main>
<!-- /main column -->
<script id="quarto-html-after-body" type="application/javascript">
window.document.addEventListener("DOMContentLoaded", function (event) {
const toggleBodyColorMode = (bsSheetEl) => {
const mode = bsSheetEl.getAttribute("data-mode");
const bodyEl = window.document.querySelector("body");
if (mode === "dark") {
bodyEl.classList.add("quarto-dark");
bodyEl.classList.remove("quarto-light");
} else {
bodyEl.classList.add("quarto-light");
bodyEl.classList.remove("quarto-dark");
}
}
const toggleBodyColorPrimary = () => {
const bsSheetEl = window.document.querySelector("link#quarto-bootstrap");
if (bsSheetEl) {
toggleBodyColorMode(bsSheetEl);
}
}
toggleBodyColorPrimary();
const icon = "";
const anchorJS = new window.AnchorJS();
anchorJS.options = {
placement: 'right',
icon: icon
};
anchorJS.add('.anchored');
const isCodeAnnotation = (el) => {
for (const clz of el.classList) {
if (clz.startsWith('code-annotation-')) {
return true;
}
}
return false;
}
const onCopySuccess = function(e) {
// button target
const button = e.trigger;
// don't keep focus
button.blur();
// flash "checked"
button.classList.add('code-copy-button-checked');
var currentTitle = button.getAttribute("title");
button.setAttribute("title", "Copied!");
let tooltip;
if (window.bootstrap) {
button.setAttribute("data-bs-toggle", "tooltip");
button.setAttribute("data-bs-placement", "left");
button.setAttribute("data-bs-title", "Copied!");
tooltip = new bootstrap.Tooltip(button,
{ trigger: "manual",
customClass: "code-copy-button-tooltip",
offset: [0, -8]});
tooltip.show();
}
setTimeout(function() {
if (tooltip) {
tooltip.hide();
button.removeAttribute("data-bs-title");
button.removeAttribute("data-bs-toggle");
button.removeAttribute("data-bs-placement");
}
button.setAttribute("title", currentTitle);
button.classList.remove('code-copy-button-checked');
}, 1000);
// clear code selection
e.clearSelection();
}
const getTextToCopy = function(trigger) {
const codeEl = trigger.previousElementSibling.cloneNode(true);
for (const childEl of codeEl.children) {
if (isCodeAnnotation(childEl)) {
childEl.remove();
}
}
return codeEl.innerText;
}
const clipboard = new window.ClipboardJS('.code-copy-button:not([data-in-quarto-modal])', {
text: getTextToCopy
});
clipboard.on('success', onCopySuccess);
if (window.document.getElementById('quarto-embedded-source-code-modal')) {
// For code content inside modals, clipBoardJS needs to be initialized with a container option
// TODO: Check when it could be a function (https://github.com/zenorocha/clipboard.js/issues/860)
const clipboardModal = new window.ClipboardJS('.code-copy-button[data-in-quarto-modal]', {
text: getTextToCopy,
container: window.document.getElementById('quarto-embedded-source-code-modal')
});
clipboardModal.on('success', onCopySuccess);
}
var localhostRegex = new RegExp(/^(?:http|https):\/\/localhost\:?[0-9]*\//);
var mailtoRegex = new RegExp(/^mailto:/);
var filterRegex = new RegExp('/' + window.location.host + '/');
var isInternal = (href) => {
return filterRegex.test(href) || localhostRegex.test(href) || mailtoRegex.test(href);
}
// Inspect non-navigation links and adorn them if external
var links = window.document.querySelectorAll('a[href]:not(.nav-link):not(.navbar-brand):not(.toc-action):not(.sidebar-link):not(.sidebar-item-toggle):not(.pagination-link):not(.no-external):not([aria-hidden]):not(.dropdown-item):not(.quarto-navigation-tool):not(.about-link)');
for (var i=0; i<links.length; i++) {
const link = links[i];
if (!isInternal(link.href)) {
// undo the damage that might have been done by quarto-nav.js in the case of
// links that we want to consider external
if (link.dataset.originalHref !== undefined) {
link.href = link.dataset.originalHref;
}
}
}
function tippyHover(el, contentFn, onTriggerFn, onUntriggerFn) {
const config = {
allowHTML: true,
maxWidth: 500,
delay: 100,
arrow: false,
appendTo: function(el) {
return el.parentElement;
},
interactive: true,
interactiveBorder: 10,
theme: 'quarto',
placement: 'bottom-start',
};
if (contentFn) {
config.content = contentFn;
}
if (onTriggerFn) {
config.onTrigger = onTriggerFn;
}
if (onUntriggerFn) {
config.onUntrigger = onUntriggerFn;
}
window.tippy(el, config);
}
const noterefs = window.document.querySelectorAll('a[role="doc-noteref"]');
for (var i=0; i<noterefs.length; i++) {
const ref = noterefs[i];
tippyHover(ref, function() {
// use id or data attribute instead here
let href = ref.getAttribute('data-footnote-href') || ref.getAttribute('href');
try { href = new URL(href).hash; } catch {}
const id = href.replace(/^#\/?/, "");
const note = window.document.getElementById(id);
if (note) {
return note.innerHTML;
} else {
return "";
}
});
}
const xrefs = window.document.querySelectorAll('a.quarto-xref');
const processXRef = (id, note) => {
// Strip column container classes
const stripColumnClz = (el) => {
el.classList.remove("page-full", "page-columns");
if (el.children) {
for (const child of el.children) {
stripColumnClz(child);
}
}
}
stripColumnClz(note)
if (id === null || id.startsWith('sec-')) {
// Special case sections, only their first couple elements
const container = document.createElement("div");
if (note.children && note.children.length > 2) {
container.appendChild(note.children[0].cloneNode(true));
for (let i = 1; i < note.children.length; i++) {
const child = note.children[i];
if (child.tagName === "P" && child.innerText === "") {
continue;
} else {
container.appendChild(child.cloneNode(true));
break;
}
}
if (window.Quarto?.typesetMath) {
window.Quarto.typesetMath(container);
}
return container.innerHTML
} else {
if (window.Quarto?.typesetMath) {
window.Quarto.typesetMath(note);
}
return note.innerHTML;
}
} else {
// Remove any anchor links if they are present
const anchorLink = note.querySelector('a.anchorjs-link');
if (anchorLink) {
anchorLink.remove();
}
if (window.Quarto?.typesetMath) {
window.Quarto.typesetMath(note);
}
// TODO in 1.5, we should make sure this works without a callout special case
if (note.classList.contains("callout")) {
return note.outerHTML;
} else {
return note.innerHTML;
}
}
}
for (var i=0; i<xrefs.length; i++) {
const xref = xrefs[i];
tippyHover(xref, undefined, function(instance) {
instance.disable();
let url = xref.getAttribute('href');
let hash = undefined;
if (url.startsWith('#')) {
hash = url;
} else {
try { hash = new URL(url).hash; } catch {}
}
if (hash) {
const id = hash.replace(/^#\/?/, "");
const note = window.document.getElementById(id);
if (note !== null) {
try {
const html = processXRef(id, note.cloneNode(true));
instance.setContent(html);
} finally {
instance.enable();
instance.show();
}
} else {
// See if we can fetch this
fetch(url.split('#')[0])
.then(res => res.text())
.then(html => {
const parser = new DOMParser();
const htmlDoc = parser.parseFromString(html, "text/html");
const note = htmlDoc.getElementById(id);
if (note !== null) {
const html = processXRef(id, note);
instance.setContent(html);
}
}).finally(() => {
instance.enable();
instance.show();
});
}
} else {
// See if we can fetch a full url (with no hash to target)
// This is a special case and we should probably do some content thinning / targeting
fetch(url)
.then(res => res.text())
.then(html => {
const parser = new DOMParser();
const htmlDoc = parser.parseFromString(html, "text/html");
const note = htmlDoc.querySelector('main.content');
if (note !== null) {
// This should only happen for chapter cross references
// (since there is no id in the URL)
// remove the first header
if (note.children.length > 0 && note.children[0].tagName === "HEADER") {
note.children[0].remove();
}
const html = processXRef(null, note);
instance.setContent(html);
}
}).finally(() => {
instance.enable();
instance.show();
});
}
}, function(instance) {
});
}
let selectedAnnoteEl;
const selectorForAnnotation = ( cell, annotation) => {
let cellAttr = 'data-code-cell="' + cell + '"';
let lineAttr = 'data-code-annotation="' + annotation + '"';
const selector = 'span[' + cellAttr + '][' + lineAttr + ']';
return selector;
}
const selectCodeLines = (annoteEl) => {
const doc = window.document;
const targetCell = annoteEl.getAttribute("data-target-cell");
const targetAnnotation = annoteEl.getAttribute("data-target-annotation");
const annoteSpan = window.document.querySelector(selectorForAnnotation(targetCell, targetAnnotation));
const lines = annoteSpan.getAttribute("data-code-lines").split(",");
const lineIds = lines.map((line) => {
return targetCell + "-" + line;
})
let top = null;
let height = null;
let parent = null;
if (lineIds.length > 0) {
//compute the position of the single el (top and bottom and make a div)
const el = window.document.getElementById(lineIds[0]);
top = el.offsetTop;
height = el.offsetHeight;
parent = el.parentElement.parentElement;
if (lineIds.length > 1) {
const lastEl = window.document.getElementById(lineIds[lineIds.length - 1]);
const bottom = lastEl.offsetTop + lastEl.offsetHeight;
height = bottom - top;
}
if (top !== null && height !== null && parent !== null) {
// cook up a div (if necessary) and position it
let div = window.document.getElementById("code-annotation-line-highlight");
if (div === null) {
div = window.document.createElement("div");
div.setAttribute("id", "code-annotation-line-highlight");
div.style.position = 'absolute';
parent.appendChild(div);
}
div.style.top = top - 2 + "px";
div.style.height = height + 4 + "px";
div.style.left = 0;
let gutterDiv = window.document.getElementById("code-annotation-line-highlight-gutter");
if (gutterDiv === null) {
gutterDiv = window.document.createElement("div");
gutterDiv.setAttribute("id", "code-annotation-line-highlight-gutter");
gutterDiv.style.position = 'absolute';
const codeCell = window.document.getElementById(targetCell);
const gutter = codeCell.querySelector('.code-annotation-gutter');
gutter.appendChild(gutterDiv);
}
gutterDiv.style.top = top - 2 + "px";
gutterDiv.style.height = height + 4 + "px";
}
selectedAnnoteEl = annoteEl;
}
};
const unselectCodeLines = () => {
const elementsIds = ["code-annotation-line-highlight", "code-annotation-line-highlight-gutter"];
elementsIds.forEach((elId) => {
const div = window.document.getElementById(elId);
if (div) {
div.remove();
}
});
selectedAnnoteEl = undefined;
};
// Handle positioning of the toggle
window.addEventListener(
"resize",
throttle(() => {
elRect = undefined;
if (selectedAnnoteEl) {
selectCodeLines(selectedAnnoteEl);
}
}, 10)
);
function throttle(fn, ms) {
let throttle = false;
let timer;
return (...args) => {
if(!throttle) { // first call gets through
fn.apply(this, args);
throttle = true;
} else { // all the others get throttled
if(timer) clearTimeout(timer); // cancel #2
timer = setTimeout(() => {
fn.apply(this, args);
timer = throttle = false;
}, ms);
}
};
}
// Attach click handler to the DT
const annoteDls = window.document.querySelectorAll('dt[data-target-cell]');
for (const annoteDlNode of annoteDls) {
annoteDlNode.addEventListener('click', (event) => {
const clickedEl = event.target;
if (clickedEl !== selectedAnnoteEl) {
unselectCodeLines();
const activeEl = window.document.querySelector('dt[data-target-cell].code-annotation-active');
if (activeEl) {
activeEl.classList.remove('code-annotation-active');
}
selectCodeLines(clickedEl);
clickedEl.classList.add('code-annotation-active');
} else {
// Unselect the line
unselectCodeLines();
clickedEl.classList.remove('code-annotation-active');
}
});
}
const findCites = (el) => {
const parentEl = el.parentElement;
if (parentEl) {
const cites = parentEl.dataset.cites;
if (cites) {
return {
el,
cites: cites.split(' ')
};
} else {
return findCites(el.parentElement)
}
} else {
return undefined;
}
};
var bibliorefs = window.document.querySelectorAll('a[role="doc-biblioref"]');
for (var i=0; i<bibliorefs.length; i++) {
const ref = bibliorefs[i];
const citeInfo = findCites(ref);
if (citeInfo) {
tippyHover(citeInfo.el, function() {
var popup = window.document.createElement('div');
citeInfo.cites.forEach(function(cite) {
var citeDiv = window.document.createElement('div');
citeDiv.classList.add('hanging-indent');
citeDiv.classList.add('csl-entry');
var biblioDiv = window.document.getElementById('ref-' + cite);
if (biblioDiv) {
citeDiv.innerHTML = biblioDiv.innerHTML;
}
popup.appendChild(citeDiv);
});
return popup.innerHTML;
});
}
}
});
</script>
</div> <!-- /content -->
</body></html>