File size: 37,115 Bytes
f734497
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10ddc22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f734497
 
 
 
 
 
 
 
 
 
 
 
 
 
10ddc22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f734497
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10ddc22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f734497
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10ddc22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f734497
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
library(shiny)
library(shinyjs)
library(bslib)
library(dplyr)
library(ggplot2)
library(tm)
library(SnowballC)
library(plotly)
library(text2vec)
library(tokenizers)
library(dplyr)
library(tidyr)
library(igraph)
library(ggraph)
library(topicmodels)
library(wordcloud)
library(wordcloud2)
library(reshape2)
library(SnowballC)
library(RColorBrewer)
library(syuzhet)
library(cluster)
library(tidytext)
library(word2vec)
library(Rtsne)
library(umap)
library(MASS)
library(koRpus)
library(openxlsx)
library(tools)
library(shinyWidgets)
library(reticulate)
library(keras)
library(tensorflow)
library(neuralnet)
library(rsample)
library(tfdatasets)
library(statnet)
library(UserNetR)
library(visNetwork)
library(networkD3)
library(ergm)
library(ergm.count)
library(network)
library(tidyverse)
options(width = 150)
options(digits = 4, scipen = 1000000000)
options(shiny.maxRequestSize=30*1024^2)



ui <- fluidPage(
  theme = bs_theme(version = 5, bootswatch = "spacelab"),
  useShinyjs(),  # Initialize shinyjs
  titlePanel("PtteM Data Science"),
  tags$head(tags$link(rel = "stylesheet", href="https://fonts.googleapis.com/css?family=Montserrat:100,300,400,700&display=swap"),
            tags$style(HTML("
        body, h1, h2, h3, h4, h5, h6, .nav, p, a, .shiny-input-container {
        font-family: 'Montserrat'; /* Font type for the title attribute */
        font-weight: 385;
        color: #007c9e !important;
      }
        * {
        font-family: 'Montserrat', sans-serif;
        font-weight: 385; 
        color: #195576; /* Blue color */
      }
        body { 
        background-color: #f7f7f7; /* Light gray background */
        }
      .icon-btn {
        border: 1px solid #0d6efd; /* Example border: solid, 2 pixels, #555 color */
        border-radius: 15%; /* Circular border */
        color: #00969e; /* Icon color */
        font-family: 'Montserrat'; /* Font type for the title attribute */
        font-weight: 385;
        background-color: #f7f7f7;
        padding: 125px; /* Space around the icon */
        margin: 25px; /* Space around the button */
        font-size: 24px; /* Icon size */
        box-shadow: 0 2px 4px rgba(0,0,0,0.2);
      }
      .icon-btn:hover {
        color: #00969e; /* Icon color on hover */
        border-color: #007c9e;
        background-color: #ebfbfd;/* Border color on hover */
      }
           /* Add custom styles here */
      .shiny-input-container {
        margin-bottom: 15px;
      }
      .box {
        border: 1px solid #ddd;
        padding: 20px;
        border-radius: 50px;
        margin-bottom: 200px;
        gap: 200px;
        align-items: center;
      }
    #statsTable_wrapper {
      margin: 0 auto;
    }
    .shiny-output-error {
    border: 1px solid #FF0000; /* Red border on error */
    }
      /* If you want to change the font size of the tooltip, you can add custom CSS for the 'title' attribute's default styling. */
    "))),
  tags$head(
    # Include JavaScript to reload the page
    tags$script(HTML("
    document.addEventListener('DOMContentLoaded', function() {
    document.getElementById('myElement').style.color = '#0d6efd'; // Change to your desired color
  });
"))
  ),
  tags$head(
    tags$script(HTML("
      function reloadPage() {
        window.location.reload();
      }
    "))
  ),
  # Refresh button that calls the JavaScript function
  actionButton("refresh", "Refresh Analysis", onclick = "reloadPage();"),
  # Help Text or Information for the user
  helpText("Bu uygulama ile pekiştirmeli öğrenme başlığı altındaki veri bilimi fonksiyonlarına erişebilirsiniz."),
        #Reinforcement Learning
        h2("Reinforcement Learning Section"),
        tabsetPanel(
          tabPanel("Multi-Armed Bandit (MAB) Algorithms",
                   tabsetPanel(
                     tabPanel("Epsilon-Greedy",
                              sidebarLayout(
                                sidebarPanel(
                                  fileInput('epsgreefile', 'Upload Data File', accept = c(".csv", ".xlsx", ".xls")),
                                  uiOutput('selectActionColumn'),
                                  uiOutput('selectRewardColumn'),
                                  numericInput("epsilon", "Epsilon (Exploration Rate)", value = 0.1, min = 0, max = 1, step = 0.01),
                                  actionButton("runMAB", "Run MAB Decision"),
                                  HTML("<div>
  <h2>Epsilon-Greedy Modeli</h2>
  <p>Bu model, çok kollu haydut problemi (multi-armed bandit, MAB) gibi karar verme sorunlarında, keşif (exploration) ile sömürü (exploitation) arasındaki dengeyi yönetmek için kullanılır. Epsilon-Greedy algoritması, belirli bir olasılıkla rastgele bir aksiyon seçerek keşif yapmayı ve geri kalan zamanlarda en iyi performans gösteren aksiyonu seçerek sömürü yapmayı dengeler.</p>

  <h3>Kullanım Adımları:</h3>
  <ol>
    <li><strong>Veri Dosyası Yükleme:</strong> <code>fileInput</code> ile CSV, XLSX veya XLS formatında bir veri dosyası yükleyin.</li>
    <li><strong>Aksiyon ve Ödül Sütunlarının Seçilmesi:</strong> Dinamik UI aracılığıyla aksiyon ve ödül sütunlarını seçin.</li>
    <li><strong>Epsilon Değerinin Belirlenmesi:</strong> <code>numericInput</code> ile keşif oranını belirleyin (0 ile 1 arasında bir değer).</li>
    <li><strong>MAB Kararının Çalıştırılması:</strong> <code>Run MAB Decision</code> butonuna basarak algoritmayı çalıştırın ve seçilen aksiyonu gözlemleyin.</li>
  </ol>

  <h3>Epsilon-Greedy Modelinin Anlamı ve Kullanımı:</h3>
  <p>Model, belirli bir epsilon değeri ile rastgele aksiyonlar seçerek yeni fırsatları keşfederken, en yüksek ödülü veren aksiyonları tekrar seçerek mevcut bilgiden yararlanır. Bu yaklaşım, belirsizlik altında optimal karar verme stratejileri geliştirmek için kullanılır.</p>

  <h3>Uygulama Alanları:</h3>
  <p>Reklam yerleştirme, stok yönetimi, web sayfası optimizasyonu gibi birçok farklı alanda kullanılabilir.</p>

  <h3>Sonuçların Yorumlanması:</h3>
  <p>Algoritma, seçilen aksiyonları ve her bir aksiyonun toplam ödülünü gösterir. Bu bilgi, hangi stratejilerin en etkili olduğunu anlamak için kullanılabilir.</p>
</div>")
                                  
                                ),
                                mainPanel(
                                  tableOutput("actionResults"),
                                  textOutput("selectedAction"),
                                )
                              )
                     ),
                     tabPanel("Upper Confidence Bound (UCB)",
                              sidebarLayout(
                                sidebarPanel(
                                  fileInput("ucbfile", "Upload Data File", accept = c(".csv", ".xlsx", ".xls")),
                                  uiOutput("selectStrategyColucb"),
                                  uiOutput("selectRewardColucb"),
                                  numericInput("epsilon", "Epsilon (Exploration Rate)", value = 0.1, min = 0, max = 1, step = 0.01),
                                  actionButton("runMABucb", "Run MAB Decision"),
                                  HTML("<div>
  <h2>Üst Güven Sınırı (UCB) Modeli</h2>
  <p>Üst Güven Sınırı (UCB) modeli, çok kollu haydut problemlerinde bir stratejinin hem ödülünü hem de bu ödülün güvenilirliğini dikkate alarak karar verme sürecini optimize eder. Keşif ve sömürü arasındaki dengeyi dinamik bir şekilde yönetir.</p>

  <h3>Kullanım Adımları:</h3>
  <ol>
    <li><strong>Veri Dosyası Yükleme:</strong> <code>fileInput</code> aracılığıyla CSV, XLSX veya XLS formatında veri dosyası yükleyin.</li>
    <li><strong>Strateji ve Ödül Sütunlarının Seçilmesi:</strong> Dinamik UI üzerinden strateji ve ödül sütunlarını seçin.</li>
    <li><strong>Epsilon Değerinin Belirlenmesi:</strong> Keşif oranını belirlemek için <code>numericInput</code> aracını kullanın (0 ile 1 arasında bir değer).</li>
    <li><strong>MAB Kararının Çalıştırılması:</strong> <code>Run MAB Decision</code> butonu ile modeli çalıştırın ve sonuçları gözlemleyin.</li>
  </ol>

  <h3>UCB Modelinin Anlamı ve Kullanımı:</h3>
  <p>Model, her bir stratejinin ödülünün ortalama değerini ve bu ortalamanın güven aralığını hesaplar. Yüksek bir güven aralığına sahip stratejiler, potansiyel olarak keşfedilmemiş yüksek ödüllere işaret eder ve model, bu stratejileri denemeye yatkın hale gelir.</p>

  <h3>Uygulama Alanları:</h3>
  <p>Online reklamcılık, stok optimizasyonu ve web sitesi düzeni testleri gibi alanlarda etkili karar verme mekanizmaları geliştirmek için kullanılabilir.</p>

  <h3>Sonuçların Yorumlanması:</h3>
  <p>Model, her bir stratejinin kaç kez denendiğini, elde edilen toplam ödülü ve zamanla ödülün nasıl değiştiğini gösterir. Bu bilgiler, hangi stratejilerin uzun vadede en etkili olduğunu belirlemek için kullanılabilir.</p>
</div>")
                                  
                                ),
                                mainPanel(
                                  tabsetPanel(
                                    tabPanel("Results", tableOutput("actionResultsucb")),
                                    tabPanel("Reward History", plotlyOutput("rewardHistoryucb", width = "100%", height = "750px"))
                                  )
                                )
                              )
                     ),
                     tabPanel("Thompson Sampling",
                              sidebarLayout(
                                sidebarPanel(
                                  fileInput("tsfile", "Upload Data File", accept = c(".csv", ".xlsx", ".xls")),
                                  uiOutput("selectStrategyColumnTS"),  # This should be in the UI part
                                  uiOutput("selectRewardColumnTS"),
                                  textInput("successConditionsTS", "Enter success conditions (comma separated)"),
                                  actionButton("runMABTS", "Run MAB Thompson Sampling"),
                                  HTML("<div>
  <h2>Thompson Örnekleme Modeli</h2>
  <p>Thompson Örnekleme, belirsizliği yönetmek ve en iyi sonucu veren stratejiyi dinamik olarak belirlemek için olasılık modellerini kullanır. Çok kollu haydut problemlerinde kullanılır ve hem keşif hem de sömürü eylemlerini dengeler.</p>

  <h3>Kullanım Adımları:</h3>
  <ol>
    <li><strong>Veri Dosyası Yükleme:</strong> <code>fileInput</code> aracılığıyla uygun formatta (CSV, XLSX, XLS) veri dosyası yükleyin.</li>
    <li><strong>Strateji ve Ödül Sütunlarının Seçimi:</strong> Yüklenen veri setinden strateji ve ödül sütunlarını seçmek için dinamik UI araçlarını kullanın.</li>
    <li><strong>Başarı Koşullarının Girilmesi:</strong> Başarılı sonuçları belirlemek için <code>textInput</code> aracı ile virgülle ayrılmış başarı koşullarını girin.</li>
    <li><strong>MAB Thompson Örnekleme Çalıştırma:</strong> <code>Run MAB Thompson Sampling</code> butonu ile modeli çalıştırın ve stratejilerin performansını değerlendirin.</li>
  </ol>

  <h3>Modelin Anlamı ve Kullanımı:</h3>
  <p>Thompson Örnekleme modeli, her bir stratejinin başarı olasılığını güncelleyerek en iyi stratejiyi seçer. Model, zamanla elde edilen öğrenmeleri dikkate alarak dinamik bir şekilde strateji seçimi yapar.</p>

  <h3>Uygulama Alanları:</h3>
  <p>Dijital pazarlama kampanyalarının optimizasyonu, stok seçimi ve finansal yatırım stratejileri gibi çeşitli alanlarda karar verme süreçlerini iyileştirmek için kullanılabilir.</p>

  <h3>Sonuçların Yorumlanması:</h3>
  <p>Model, her stratejinin başarı oranını ve zaman içindeki performansını gösterir. Bu sonuçlar, uzun vadeli karar verme süreçlerinde stratejik yön belirlemede kullanılabilir.</p>
</div>")
                                  
                                ),
                                mainPanel(
                                  tabsetPanel(
                                    tabPanel("Best Display", verbatimTextOutput("bestStrategyDisplayTS")),
                                    tabPanel("Reward History TS", plotlyOutput("rewardHistoryTS", width = "100%", height = "750px")),
                                    tabPanel("Strategy Frequency", plotlyOutput("strFrePlotTS", width = "100%", height = "750px"))
                                  )
                                )
                              )
                     ),
                     
                     
                   )
          ),
          tabPanel("Contextual Bandits",
                   tabsetPanel(
                     tabPanel("Linear Regression UCB",
                              sidebarLayout(
                                sidebarPanel(
                                  fileInput("lrucbfile", "Upload your dataset", accept = c(".csv", ".xlsx", ".xls")),
                                  actionButton("loadlrucb", "Load Data"),
                                  selectInput("targetlrucb", "Select Target Column", choices = NULL),
                                  selectizeInput("independentVarlrucb", "Select Independent Variable", choices = NULL, multiple = FALSE),
                                  actionButton("runModellrucb", "Run Linear Regression UCB"),
                                  HTML("<div>
  <h2>Doğrusal Regresyon UCB</h2>
  <p>Doğrusal Regresyon UCB, belirsizlik altında en iyi kararları vermek için üst güven sınırını kullanır. Özellikle, çok değişkenli verilerde, hangi bağımsız değişkenlerin hedef değişken üzerinde önemli etkiye sahip olduğunu belirlemek için kullanılır.</p>
  
  <h3>Kullanım Adımları:</h3>
  <ol>
    <li><strong>Veri Dosyası Yükleme:</strong> <code>fileInput</code> ile CSV, XLSX veya XLS formatında veri dosyası yükleyin.</li>
    <li><strong>Veri Yükleme:</strong> <code>Load Data</code> butonu ile yüklenen veri dosyasını sisteme yükleyin.</li>
    <li><strong>Hedef ve Bağımsız Değişken Seçimi:</strong> Analiz için hedef ve bağımsız değişkenleri seçin.</li>
    <li><strong>Modeli Çalıştır:</strong> <code>Run Linear Regression UCB</code> butonu ile doğrusal regresyon modelini çalıştırın.</li>
  </ol>

  <h3>Modelin Anlamı ve Kullanımı:</h3>
  <p>Doğrusal Regresyon UCB, belirsizliği yönetmek ve veriler arasındaki ilişkileri anlamak için kullanılır. UCB, bir değişkenin model üzerindeki etkisini değerlendirirken belirsizliği dikkate alır.</p>

  <h3>Uygulama Alanları:</h3>
  <p>Finansal tahminler, ürün fiyatlandırma stratejileri ve pazar araştırması gibi çeşitli alanlarda karar verme süreçlerinde kullanılabilir.</p>

  <h3>Sonuçların Yorumlanması:</h3>
  <p>Model, seçilen bağımsız değişkenin hedef değişken üzerindeki etkisini ve bu etkinin güven aralığını gösterir. Sonuçlar, stratejik planlama ve karar verme süreçlerinde kullanılabilir.</p>
</div>")
                                  
                                ),
                                mainPanel(
                                  tabsetPanel(
                                    tabPanel("Model Summary", verbatimTextOutput("modelSummarylrucb")),
                                    tabPanel("Diagnostics",
                                             plotlyOutput("resFitlrucbPlot"),
                                             plotlyOutput("qqPlotlrucb"),
                                             plotlyOutput("scaleLoclrucbPlot"),
                                             plotlyOutput("resLevlrucbPlot")
                                    ),
                                    tabPanel("Regression Plot", plotlyOutput("regressionPlot", width = "100%", height = "750px"))
                                  )
                                )
                              )
                     )
                     
                     
                   )
          )
        )
        


)

server <- function(input, output, session) {
  ##Reinforcement Learning
  ###Multi-Armed Bandit (MAB) Algorithms
  ####Epsilon-Greedy
  # Reactive to store uploaded data
  uploadedepsgree <- reactive({
    req(input$epsgreefile)
    ext <- tools::file_ext(input$epsgreefile$name)
    switch(ext,
           csv = read.csv(input$epsgreefile$datapath, stringsAsFactors = FALSE),
           xlsx = readxl::read_excel(input$epsgreefile$datapath),
           stop("Unsupported file type"))
  })
  
  # Dynamic UI to select the action and reward columns
  output$selectActionColumn <- renderUI({
    df <- uploadedepsgree()
    req(df)
    selectInput("actionColumn", "Select Action Column", choices = names(df))
  })
  
  output$selectRewardColumn <- renderUI({
    df <- uploadedepsgree()
    req(df)
    selectInput("rewardColumn", "Select Reward Column", choices = names(df))
  })
  
  # Reactive values to store actions and performance metrics
  actionRewards <- reactiveValues(actions = NULL, rewards = NULL, counts = NULL)
  
  observeEvent(input$runMAB, {
    req(input$epsilon, input$actionColumn, input$rewardColumn)
    df <- uploadedepsgree()
    df <- df %>% dplyr::select(all_of(input$actionColumn), all_of(input$rewardColumn)) %>% na.omit() 
    uniqueActions <- unique(df[[input$actionColumn]])
    summedRewards <- tapply(df[[input$rewardColumn]], df[[input$actionColumn]], sum, na.rm = TRUE)
    
    # Store processed data in actionRewards
    actionRewards$actions <- uniqueActions
    actionRewards$rewards <- summedRewards
    actionRewards$counts <- rep(10, length(uniqueActions)) # Initialize with some counts
    
    # Run epsilon-greedy algorithm
    if (runif(1) < input$epsilon) {
      # Exploration
      selectedActionIndex <- sample(length(uniqueActions), 1)
    } else {
      # Exploitation
      averages <- summedRewards / actionRewards$counts
      selectedActionIndex <- which.max(averages)
    }
    
    selectedAction <- uniqueActions[selectedActionIndex]
    simulatedReward <- runif(1, min = 0, max = max(summedRewards)) # Simulate a reward
    actionRewards$rewards[selectedActionIndex] <- actionRewards$rewards[selectedActionIndex] + simulatedReward
    actionRewards$counts[selectedActionIndex] <- actionRewards$counts[selectedActionIndex] + 1
    
    # Update UI
    output$selectedAction <- renderText({ selectedAction })
    output$actionResults <- renderTable({
      data.frame(Action = actionRewards$actions, Reward = actionRewards$rewards, Count = actionRewards$counts)
    })
  })
  
  ####Upper Confidence Bound (UCB)
  # Reactive values to store actions and performance metrics
  actionData <- reactiveValues(
    actions = NULL,
    counts = NULL,
    rewards = NULL,
    history = list() # Initialize the history list here
  )
  
  uploadeducb <- reactive({
    req(input$ucbfile)
    ext <- tools::file_ext(input$ucbfile$name)
    switch(ext,
           csv = read.csv(input$ucbfile$datapath, stringsAsFactors = FALSE),
           xlsx = readxl::read_excel(input$ucbfile$datapath),
           xls = readxl::read_excel(input$ucbfile$datapath),
           stop("Unsupported file type")
    )
  })
  
  output$selectStrategyColucb <- renderUI({
    req(input$ucbfile)
    data <- uploadeducb()
    selectInput("strategyColumn", "Select Strategy Column",
                choices = names(data), selected = names(data)[1])
  })
  
  output$selectRewardColucb <- renderUI({
    req(input$ucbfile)
    data <- uploadeducb()
    selectInput("rewardColumn", "Select Reward Column",
                choices = names(data), selected = names(data)[2])
  })
  
  
  
  observeEvent(input$runMABucb, {
    
    data <- uploadeducb()
    strategyColumn <- input$strategyColumn
    rewardColumn <- input$rewardColumn
    
    # Ensure numerical data for computation
    data[[rewardColumn]] <- as.numeric(as.character(data[[rewardColumn]]))
    
    # Unique strategies
    strategies <- unique(data[[strategyColumn]])
    n <- nrow(data) # Total number of events
    
    if (is.null(actionData$actions)) {
      actionData$actions <- strategies
      actionData$counts <- rep(0, length(strategies))
      actionData$rewards <- rep(0, length(strategies))
      # Initialize history for each strategy
      actionData$history <- setNames(vector("list", length(strategies)), strategies)
      for(strategy in strategies) {
        actionData$history[[strategy]] <- data.frame(Time = integer(), Reward = numeric())
      }
    }
    
    # Loop over strategies to compute UCB and update history
    for (strategy in strategies) {
      strategy_data <- data[data[[strategyColumn]] == strategy, ]
      ni <- nrow(strategy_data) # Number of times this strategy was tried
      avg_reward <- mean(strategy_data[[rewardColumn]], na.rm = TRUE)
      
      if (ni > 0) {
        ucb_value <- avg_reward + sqrt((2 * log(n)) / ni)
      } else {
        ucb_value <- Inf # Encourage exploration of untried strategies
      }
      # Define strategy_index here, inside the loop, before you use it
      strategy_index <- which(actionData$actions == strategy)
      
      actionData$counts[strategy_index] <- actionData$counts[strategy_index] + ni
      actionData$rewards[strategy_index] <- ucb_value
      actionData$history[[strategy]] <- rbind(
        actionData$history[[strategy]],
        data.frame(Time = as.integer(actionData$counts[strategy_index]), Reward = ucb_value)
      )
    }
    # After the loop, the history should be updated
  })
  
  output$actionResultsucb <- renderTable({
    req(actionData$actions) # Ensure the action data is not NULL
    data.frame(
      Strategy = actionData$actions, 
      Counts = actionData$counts, 
      Rewards = actionData$rewards
    )
  })
  
  
  
  # Create the plot in a separate reactive context, responding to changes in actionData
  output$rewardHistoryucb <- renderPlotly({
    req(actionData$history) # Ensure that the history is not NULL or empty
    
    # Create plot_data for plotting
    plot_data <- do.call(rbind, Filter(Negate(is.null), lapply(names(actionData$history), function(strategy) {
      history_data <- actionData$history[[strategy]]
      if(nrow(history_data) > 0) {
        return(data.frame(Strategy = strategy, Time = history_data$Time, Reward = history_data$Reward))
      }
    })))
    
    # Only attempt to create a plot if plot_data is a data frame and not NULL
    if(!is.null(plot_data) && is.data.frame(plot_data)) {
      # Create a custom color palette with as many colors as there are strategies
      colors <- grDevices::colorRampPalette(RColorBrewer::brewer.pal(8, "Set2"))(length(unique(plot_data$Strategy)))
      
      plot_ly(plot_data, x = ~Time, y = ~Reward, color = ~Strategy, colors = colors, type = 'scatter', mode = 'lines+markers') %>%
        layout(title = "Reward History Over Time",
               xaxis = list(title = "Time"),
               yaxis = list(title = "Reward"))
    } else {
      plot_ly() %>% 
        add_annotations(text = "No data available for plot", x = 0.5, y = 0.5, showarrow = FALSE, xref = "paper", yref = "paper")
    }
  })
  
  ####Thompson Sampling
  uploadedTS <- reactive({
    req(input$tsfile)
    ext <- tools::file_ext(input$tsfile$name)
    switch(ext,
           csv = read.csv(input$tsfile$datapath, stringsAsFactors = FALSE),
           xlsx = readxl::read_excel(input$tsfile$datapath),
           xls = readxl::read_excel(input$tsfile$datapath),
           stop("Unsupported file type: ", ext)
    )
  })
  
  # Initialize actionDataTS similar to actionData for UCB
  actionDataTS <- reactiveValues(
    actions = NULL,
    successes = NULL,
    failures = NULL,
    theta = NULL
  )
  
  
  output$selectStrategyColumnTS <- renderUI({
    req(input$tsfile)
    data <- uploadedTS()
    selectInput("selectStrategyColumnTS", "Select Strategy Column",
                choices = names(data), selected = names(data)[1])
  })
  
  output$selectRewardColumnTS <- renderUI({
    req(input$tsfile)
    data <- uploadedTS()
    selectInput("selectRewardColumnTS", "Select Reward Column",
                choices = names(data), selected = names(data)[2])
  })
  
  
  observeEvent(input$runMABTS, {
    req(input$tsfile)
    data <- uploadedTS()  
    
    strategyColumn <- input$selectStrategyColumnTS
    rewardColumn <- input$selectRewardColumnTS
    success_conditions <- unlist(strsplit(input$successConditionsTS, ",")) # split the input string into a vector
    
    if (is.null(actionDataTS$actions)) {
      actionDataTS$actions <- unique(data[[strategyColumn]])
      actionDataTS$successes <- rep(1, length(actionDataTS$actions)) # Start with 1 success for beta distribution
      actionDataTS$failures <- rep(1, length(actionDataTS$actions)) # Start with 1 failure for beta distribution
      actionDataTS$theta <- rep(0, length(actionDataTS$actions))
      actionDataTS$history <- list() # Initialize history for plotting
      actionDataTS$selectionCount <- rep(0, length(actionDataTS$actions)) # Initialize with zeros
    }
    
    for (strategy in actionDataTS$actions) {
      strategy_index <- which(actionDataTS$actions == strategy)
      
      # Define strategy_data and num_successes/num_failures after defining strategy_index
      strategy_data <- data[data[[strategyColumn]] == strategy, ]
      strategy_data[[rewardColumn]] <- as.numeric(strategy_data[[rewardColumn]] %in% success_conditions) # Convert to binary
      
      num_successes <- sum(strategy_data[[rewardColumn]], na.rm = TRUE)
      num_failures <- nrow(strategy_data) - num_successes
      
      actionDataTS$successes[strategy_index] <- actionDataTS$successes[strategy_index] + num_successes
      actionDataTS$failures[strategy_index] <- actionDataTS$failures[strategy_index] + num_failures
      actionDataTS$theta[strategy_index] <- rbeta(1, actionDataTS$successes[strategy_index], actionDataTS$failures[strategy_index])
      actionDataTS$selectionCount[strategy_index] <- actionDataTS$selectionCount[strategy_index] + 1
      
      # Update the history with the new data for plotting
      if (is.null(actionDataTS$history[[strategy]])) {
        actionDataTS$history[[strategy]] <- data.frame(Time = seq_along(strategy_data[[rewardColumn]]), Reward = strategy_data[[rewardColumn]])
      } else {
        actionDataTS$history[[strategy]] <- rbind(actionDataTS$history[[strategy]], data.frame(Time = seq_along(strategy_data[[rewardColumn]]) + nrow(actionDataTS$history[[strategy]]), Reward = strategy_data[[rewardColumn]]))
      }
    }
  })
  
  output$bestStrategyDisplayTS <- renderPrint({
    req(actionDataTS$theta)  # Ensure theta values have been calculated
    best_strategy_index <- which.max(actionDataTS$theta)
    best_strategy <- actionDataTS$actions[best_strategy_index] # Ensure this variable matches throughout your code
    theta_value <- actionDataTS$theta[best_strategy_index]
    
    cat("The best strategy is:", best_strategy, "\n",
        "Estimated success probability (theta):", theta_value)
  })
  
  
  createPlotData <- function(history) {
    if (is.list(history) && length(history) > 0 && all(sapply(history, is.data.frame))) {
      # Combine all strategy data frames into one, adding a 'Strategy' column
      plot_data <- do.call(rbind, lapply(names(history), function(strategy) {
        strategy_data <- history[[strategy]]
        if ("Time" %in% names(strategy_data) && "Reward" %in% names(strategy_data)) {
          strategy_data$Strategy <- strategy  # Add the 'Strategy' column
          return(strategy_data)
        } else {
          # Return a data frame with missing values if required columns are not present
          return(data.frame(Time = NA, Reward = NA, Strategy = strategy))
        }
      }))
      # Remove rows with missing values
      plot_data <- na.omit(plot_data)
      return(plot_data)
    } else {
      # If history is not as expected, return an empty data frame with the correct columns
      return(data.frame(Time = integer(0), Reward = numeric(0), Strategy = factor()))
    }
  }
  
  
  output$rewardHistoryTS <- renderPlotly({
    req(actionDataTS$history)  # Ensure that the history is not NULL or empty
    
    # Create the required plot_data using the createPlotData function
    plot_data <- createPlotData(actionDataTS$history)
    
    # Check if the plot_data has rows to plot
    if (!is.null(plot_data) && nrow(plot_data) > 0) {
      # Create the plot with plotly
      plot_ly(
        data = plot_data,
        x = ~Time,
        y = ~Reward,
        color = ~Strategy,
        type = 'scatter',  # Use 'scatter' for line and point plots
        mode = 'markers',  # Combine line and marker styles
        marker = list(color = 'rgba(74, 93, 191, 0.7))', line = list(color = 'rgba(55, 128, 191, 1.0)', width = 2))  # Optionally, adjust marker size
      ) %>%
        layout(
          title = "Reward History Over Time",
          xaxis = list(title = "Time"),
          yaxis = list(title = "Reward"),
          hovermode = 'closest'  # Improves tooltip behavior
        )
    } else {
      # Provide a message or an empty plot if plot_data is empty
      return(plotly_empty())
    }
  })
  output$strFrePlotTS <- renderPlotly({
    req(input$tsfile) # Make sure a file is uploaded
    data <- uploadedTS() # Get the uploaded data
    
    # Calculate the frequency of each strategy
    strategy_freq <- table(data[[input$selectStrategyColumnTS]])
    
    # Convert to a data frame for plotting
    strategy_freq_df <- as.data.frame(strategy_freq)
    
    # Create the plot with plotly
    plot_ly(
      data = strategy_freq_df,
      x = ~Var1, # The strategy names
      y = ~Freq, # The frequency counts
      type = 'scatter', # Use a scatter chart
      mode = 'markers',
      marker = list(color = 'rgba(74, 93, 191, 0.7)', line = list(color = 'rgba(55, 128, 191, 1.0)', width = 2))
    ) %>%
      layout(
        title = "Strategy Frequency",
        xaxis = list(title = "Strategy"),
        yaxis = list(title = "Frequency"),
        hovermode = 'closest'
      )
  })
  
  ####Linear Regression UCB
  # Reactive value to store preprocessed data
  datalrucb <- reactiveVal(NULL)
  modelsList <- reactiveVal(list())
  # Function to read and clean data
  read_data <- function(filepath) {
    ext <- tools::file_ext(filepath)
    if (ext == "csv") {
      read.csv(filepath, stringsAsFactors = FALSE)
    } else if (ext == "xlsx") {
      readxl::read_excel(filepath)
    } else {
      stop("Invalid file format. Please select a CSV or XLSX file.")
    }
  }
  
  clean_column_names <- function(dataframe) {
    colnames(dataframe) <- gsub("[^[:alnum:]_]", "", make.names(colnames(dataframe), unique = TRUE))
    return(dataframe)
  }
  
  # Observe load data button click
  observeEvent(input$loadlrucb, {
    file <- input$lrucbfile
    req(file)
    data_lrucb <- read_data(file$datapath)
    data_lrucb <- clean_column_names(data_lrucb)
    datalrucb(data_lrucb)  # Store the data
    updateSelectInput(session, "targetlrucb", choices = colnames(data_lrucb))
    updateSelectizeInput(session, "independentVarlrucb", choices = setdiff(colnames(data_lrucb), input$targetlrucb))
  })
  
  # Function to perform safe regression
  safe_regression <- function(data, responseVar, var) {
    tryCatch({
      # Print types to debug
      #print(paste("Type of response variable:", class(data[[responseVar]])))
      #print(paste("Type of independent variable:", class(data[[var]])))
      
      #if(!is.numeric(data[[var]])) {
      #stop(paste(var, "is not numeric and will be skipped."))
      #}
      #if(!is.numeric(data[[responseVar]])) {
      #stop(paste(responseVar, "is not numeric and will be skipped."))
      #}
      
      # Check for missing or infinite values
      #if(any(!is.finite(data[[var]])) || any(!is.finite(data[[responseVar]]))) {
      #stop("Non-finite values detected in variables.")
      #}
      # Assuming 'data' is your data frame and 'responseVar' and 'var' are column names
      data <- na.omit(data[c(responseVar, var)])
      formula <- as.formula(paste(responseVar, "~", var))
      model <- lm(formula, data = data)
      summary_model <- summary(model)
      ucb_estimate <- summary_model$coefficients[var, "Estimate"]
      # Store the entire model object along with variable names
      return(list(variable = var, model = model, ucb_estimate = ucb_estimate))
    }, error = function(e) {
      message("Error in regression with variable: ", var, "; Error: ", e$message)
      return(NULL)  # Skip this variable
    })
  }
  
  
  # Perform regression on Run Model button click
  observeEvent(input$runModellrucb, {
    data <- req(datalrucb())
    responseVar <- req(input$targetlrucb)
    var <- req(input$independentVarlrucb)
    
    if(!responseVar %in% names(data)) {
      stop("Selected response variable is not in the dataset.")
    }
    
    results <- safe_regression(data, responseVar, var)
    modelsList(list(results))  # Append new result to the list
    output$modelSummarylrucb <- renderPrint({
      req(results)
      if (is.null(results$ucb_estimate)) {
        paste("Regression could not be performed for variable:", var)
      } else {
        paste("UCB estimate for variable", var, "is", results$ucb_estimate)
      }
    })
  })
  
  # Server function to create diagnostic plots
  output$resFitlrucbPlot <- renderPlotly({
    req(modelsList(), datalrucb())
    models <- req(modelsList())
    
    # Use the first model for the plot as an example
    if (length(models) >= 1 && !is.null(models[[1]]$model)) {
      fitted_model <- models[[1]]$model
      p <- ggplot(fitted_model, aes(.fitted, .resid)) +
        geom_point(color = "darkorange") +
        geom_smooth(method = "lm", se = FALSE, color = "dodgerblue") +
        labs(title = "Residuals vs Fitted", x = "Fitted Values", y = "Residuals")
      
      ggplotly(p)
    } else {
      return(NULL)  # No models to plot
    }
  })
  
  
  output$qqPlotlrucb <- renderPlotly({
    req(modelsList(), datalrucb())
    models <- req(modelsList())
    
    # Use the first model for the plot as an example
    if (length(models) >= 1 && !is.null(models[[1]]$model)) {
      fitted_model <- models[[1]]$model
      p <- ggplot(fitted_model, aes(sample = .stdresid)) +
        stat_qq(color = "darkorange") +
        stat_qq_line(color = "dodgerblue") +
        labs(title = "Normal Q-Q")
      
      ggplotly(p)
    } else {
      return(NULL)  # No models to plot
    }
  })
  
  output$scaleLoclrucbPlot <- renderPlotly({
    req(modelsList(), datalrucb())
    models <- req(modelsList())
    
    # Use the first model for the plot as an example
    if (length(models) >= 1 && !is.null(models[[1]]$model)) {
      fitted_model <- models[[1]]$model
      p <- ggplot(fitted_model, aes(.fitted, sqrt(abs(.resid)))) +
        geom_point(color = "darkorange") +
        geom_smooth(method = "lm", se = FALSE, color = "dodgerblue") +
        labs(title = "Scale-Location", x = "Fitted Values", y = "Sqrt(|Residuals|)")
      
      ggplotly(p)
    } else {
      return(NULL)  # No models to plot
    }
  })
  
  output$resLevlrucbPlot <- renderPlotly({
    req(modelsList(), datalrucb())
    models <- req(modelsList())
    
    # Use the first model for the plot as an example
    if (length(models) >= 1 && !is.null(models[[1]]$model)) {
      fitted_model <- models[[1]]$model
      p <- ggplot(fitted_model, aes(.hat, .stdresid)) +
        geom_point(aes(size = .cooksd), shape = 1, color = "darkorange") +
        geom_smooth(method = "lm", se = FALSE, color = "dodgerblue") +
        labs(title = "Residuals vs Leverage", x = "Leverage", y = "Standardized Residuals")
      
      ggplotly(p)
    } else {
      return(NULL)  # No models to plot
    }
  })
  
  output$regressionPlot <- renderPlotly({
    req(modelsList(), datalrucb())
    fitted_model <- modelsList()
    data_for_plot <- datalrucb()
    
    # Ensure the target and independent variables are provided
    target_col <- input$targetlrucb
    independent_var <- input$independentVarlrucb
    if (is.null(data_for_plot[[target_col]]) || is.null(data_for_plot[[independent_var]])) {
      return("Target or independent variable not found in the data.")
    }
    
    # Creating the plot with added color
    p <- ggplot(data_for_plot, aes_string(x = independent_var, y = target_col)) +
      geom_point(color = "darkorange") +  # Change color of points
      geom_smooth(method = "lm", se = FALSE, color = "dodgerblue") +  # Change color of regression line
      ggtitle("Regression Line Plot") +
      xlab(independent_var) +
      ylab(target_col) +
      theme_minimal() +  # Adding a minimal theme for a cleaner look
      theme(legend.position = "none")  # Remove legend if not needed
    
    # Convert ggplot object to Plotly for an interactive plot
    ggplotly(p)
  }) 

}

shinyApp(ui, server)