File size: 178,442 Bytes
16ed9fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
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(reshape2)
library(SnowballC)
library(RColorBrewer)
library(syuzhet)
library(cluster)
library(Rtsne)
library(umap)
library(MASS)
library(koRpus)
library(openxlsx)
library(tools)
library(shinyWidgets)
library(readxl)
library(scales)
library(caret)
library(BBmisc)
library(glmnet)
library(pROC)
library(ROCR)
library(car)
library(ResourceSelection)
library(tree)
library(ggplotify)
library(lmtest)
library(gridExtra)
library(patchwork)
library(caret)
library(randomForest)
library(gbm)
library(earth)
library(broom)
library(rlang)
library(ggdendro)
library(pastecs)
options(width = 150)
options(digits = 4, scipen = 1000000000)
options(shiny.maxRequestSize=30*1024^2)



# Function to process a chunk of lines and update word counts
process_chunk <- function(chunk, word_counts) {
  max_word_length <- 1000  # Set a maximum word length
  
  for (line in chunk) {
    words <- unlist(strsplit(line, "\\s+"))  # Splitting line into words
    for (word in words) {
      word <- as.character(word)  # Ensure 'word' is a character string
      if (nchar(word) == 0 || nchar(word) > max_word_length) {
        next  # Skip empty words or words that are too long
      }
      # Check if word exists and get the current count
      if (!is.null(word_counts[[word]])) {
        current_count <- word_counts[[word]]
      } else {
        current_count <- 0
      }
      word_counts[[word]] <- current_count + 1
    }
  }
  return(word_counts)
}

# Main function to count word frequencies in the file
count_word_frequencies <- function(file_path) {
  con <- file(file_path, "r")      # Open file connection
  word_counts <- new.env(hash = TRUE, size = 600000)  # Initialize environment for counting
  
  while(TRUE) {
    lines <- readLines(con, n = 5000)  # Adjust 'n' based on system capability
    if (length(lines) == 0) {
      break
    }
    word_counts <- process_chunk(lines, word_counts)
  }
  
  close(con)  # Close file connection
  return(as.list(word_counts))  # Convert environment to list for easy access
}

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 metin analizi başlığı altındaki veri bilimi fonksiyonlarına erişebilirsiniz."),
  #Supervised Learning
        h2("Supervised Learning Section"),
        tabsetPanel(
          tabPanel("Simple Linear Regression",
                   sidebarLayout(
                     sidebarPanel(
                       fileInput("slrinput", "Choose a CSV or XLSX file", accept = c(".csv", ".xlsx")),
                       actionButton("loadslr", "Load Data"),
                       selectInput("targetslr", "Select Target Column", choices = NULL),
                       selectizeInput("independentVar", "Select Independent Variable", choices = NULL, multiple = FALSE),
                       sliderInput("dataSplitslr", 
                                   "Data Split Ratio",
                                   min = 0.1,
                                   max = 0.9,
                                   value = 0.7,  # Default value, for instance, 70% for training and 30% for testing
                                   step = 0.05,
                                   ticks = FALSE,
                                   animate = TRUE),
                       actionButton("slrassumption", "Run Assumption"),
                       actionButton("slrmodel", "Run SLR Model"),
                       HTML("<div>
  <h2>Basit Doğrusal Regresyon Paneli</h2>
  
  <h3>Çıktı Nedir ve Neden Kullanılır?</h3> Bu panel, bir hedef değişken ile bir veya birden fazla bağımsız değişken arasındaki ilişkiyi modellemek için basit doğrusal regresyon (SLR) analizi yapar. SLR, iki değişken arasındaki ilişkinin doğasını ve gücünü anlamak için kullanılır.</p>
  
  <h3>Kullanım Adımları:</h3></p>
  <ol>
    <li><strong>Veri Dosyası Yükleme:</strong> SLR analizi için bir CSV veya XLSX dosyasını <code>fileInput</code> aracılığıyla yükleyin.</li>
    <li><strong>Hedef ve Bağımsız Değişken Seçimi:</strong> Analiz için hedef değişkeni ve bağımsız değişkeni seçin.</li>
    <li><strong>Analizi Çalıştırma:</strong> <code>actionButton</code> butonlarına tıklayarak SLR modelini ve varsayım kontrollerini çalıştırın.</li>
  </ol>
  
  <h3>Kullanıcı Etkileşimi:</h3> Kullanıcılar, dosya yükledikten ve gerekli değişkenleri seçtikten sonra analizi başlatır ve sonuçlar ana panelde görselleştirilir.</p>
  
  <h3>Veri Bilimi Alanındaki Kullanımı:</h3> Basit doğrusal regresyon, özellikle iki değişken arasındaki ilişkiyi keşfetmek ve bu ilişkinin gücünü ve yönünü belirlemek için önemli bir yöntemdir. SLR, tahmin modelleri oluşturma, trend analizi ve değişkenler arasındaki ilişkilerin değerlendirilmesi gibi çeşitli alanlarda kullanılır.</p>
  
  <h3>Desteklenen Dosya Tipleri:</h3> Kullanıcılar, analiz için CSV (.csv) veya Excel (.xlsx) formatında dosyalar yükleyebilirler.</p>
  
  <h3>Sonuçların Yorumlanması:</h3> Elde edilen model özeti, regresyon katsayıları, p-değerleri, R-kare gibi istatistiklerle modelin anlamlılığını ve açıklayıcılığını değerlendirir. Ayrıca, varsayım testleri ve diyagnostik grafikler modelin varsayımlara uygunluğunu kontrol etmek için kullanılır.</p>
  
  <ul>
    <li><strong>Model Özeti:</strong> Modelin istatistiksel anlamlılığını ve açıklayıcılığını değerlendirir.</li>
    <li><strong>Varsayım Testleri:</strong> Modelin normal dağılım, homoskedastisite, bağımsızlık ve doğrusallık gibi temel varsayımlara uygunluğunu test eder.</li>
    <li><strong>Regresyon Çizgisi Grafiği:</strong> Hedef ve bağımsız değişken arasındaki ilişkiyi görsel olarak gösterir.</li>
  </ul>
  
  <p>Bu özellikler, basit doğrusal regresyon analizinin, veri setinden önemli içgörüler elde etmek ve değişkenler arasındaki ilişkileri anlamak için nasıl kullanılabileceğini gösterir.</p>
</div>
")
                     ),
                     mainPanel(
                       tabsetPanel(
                         tabPanel("Data Summary", verbatimTextOutput("slrsummary")),
                         tabPanel("Assumptions for SLR Model", 
                                  tabsetPanel(                                  
                                    tabPanel("Diagnostics",
                                             plotlyOutput("residualsFittedPlot"),
                                             plotlyOutput("qqPlot"),
                                             plotlyOutput("scaleLocationPlot"),
                                             plotlyOutput("residualsLeveragePlot")
                                    ),
                                    tabPanel("Shapiro-Wilk Test", verbatimTextOutput("shapiroTest")),
                                    tabPanel("Breusch-Pagan Test", verbatimTextOutput("ncvTest")),
                                    tabPanel("Linearity Plot", plotlyOutput("linearityPlotOutput", width = "100%", height = "700px")),
                                    tabPanel("Durbin-Watson Test", verbatimTextOutput("durbinWatsonTest"))
                                  )
                         ),
                         tabPanel("SLR Model Evaluation",
                                  tabsetPanel(
                                    tabPanel("Model Summary", verbatimTextOutput("slrmodeleva")),
                                    tabPanel("Correlation Coefficient Between the Variables", verbatimTextOutput("corcoefslr")),
                                    tabPanel("Confidence Interval", verbatimTextOutput("confintslr")),
                                    tabPanel("Regression Line Plot", plotlyOutput("slrregressPlot", width = "100%", height = "625px"))
                                  )
                         )
                       )
                     )
                   )
          ),
          tabPanel("Multiple Linear Regression",
                   sidebarLayout(
                     sidebarPanel(
                       fileInput("mlrinput", "Choose a CSV or XLSX file", accept = c(".csv", ".xslx")),
                       actionButton("loadmlr", "Load Data"),
                       selectInput("targetmlr", "Select Target Column", choices = NULL),
                       selectizeInput("independentVarmlr", "Select Independent Variable", choices = NULL, multiple = TRUE),
                       sliderInput("dataSplitmlr", 
                                   "Data Split Ratio",
                                   min = 0.1,
                                   max = 0.9,
                                   value = 0.7,  # Default value, for instance, 70% for training and 30% for testing
                                   step = 0.05,
                                   ticks = FALSE,
                                   animate = TRUE),
                       actionButton("mlrassumption", "Run Assumption"),
                       actionButton("mlrmodel", "Run MLR Model"),
                       HTML("<div>
  <h2>Çoklu Doğrusal Regresyon Paneli</h2>
  
  <h3>Çıktı Nedir ve Neden Kullanılır?</h3> Bu panel, bir hedef değişken ile birden fazla bağımsız değişken arasındaki ilişkiyi modellemek için çoklu doğrusal regresyon (MLR) analizi yapar. MLR, değişkenler arasındaki ilişkilerin karmaşıklığını anlamak ve birden çok bağımsız değişkenin hedef değişken üzerindeki etkisini keşfetmek için kullanılır.</p>
  
  <h3>Kullanım Adımları:</h3></p>
  <ol>
    <li><strong>Veri Dosyası Yükleme:</strong> MLR analizi için bir CSV veya XLSX dosyasını <code>fileInput</code> aracılığıyla yükleyin.</li>
    <li><strong>Hedef ve Bağımsız Değişkenlerin Seçimi:</strong> Analiz için hedef değişkeni ve birden fazla bağımsız değişkeni seçin.</li>
    <li><strong>Analizi Çalıştırma:</strong> <code>actionButton</code> butonlarına tıklayarak MLR modelini ve varsayım kontrollerini çalıştırın.</li>
  </ol>
  
  <h3>Kullanıcı Etkileşimi:</h3> Kullanıcılar, dosya yükledikten ve gerekli değişkenleri seçtikten sonra analizi başlatır ve sonuçlar ana panelde görselleştirilir.</p>
  
  <h3>Veri Bilimi Alanındaki Kullanımı:</h3> Çoklu doğrusal regresyon, tahmin modelleri oluşturma, çok faktörlü etki analizi ve değişkenler arasındaki ilişkilerin değerlendirilmesi gibi çeşitli alanlarda kullanılır. MLR, birden çok bağımsız değişkenin hedef değişken üzerindeki etkisini ve ilişkilerin yapısını anlamak için tercih edilen bir yöntemdir.</p>
  
  <h3>Desteklenen Dosya Tipleri:</h3> Kullanıcılar, analiz için CSV (.csv) veya Excel (.xlsx) formatında dosyalar yükleyebilirler.</p>
  
  <h3>Sonuçların Yorumlanması:</h3> Elde edilen model özeti, regresyon katsayıları, p-değerleri, R-kare gibi istatistiklerle modelin anlamlılığını ve açıklayıcılığını değerlendirir. Ayrıca, varsayım testleri ve diyagnostik grafikler modelin varsayımlara uygunluğunu kontrol etmek için kullanılır.</p>
  
  <ul>
    <li><strong>Model Özeti:</strong> Modelin istatistiksel anlamlılığını ve açıklayıcılığını değerlendirir.</li>
    <li><strong>Varsayım Testleri:</strong> Modelin normal dağılım, homoskedastisite, bağımsızlık, doğrusallık ve çoklu bağlantı gibi temel varsayımlara uygunluğunu test eder.</li>
    <li><strong>Regresyon Çizgisi Grafiği:</strong> Hedef ve bağımsız değişkenler arasındaki ilişkiyi görsel olarak gösterir.</li>
  </ul>
  
  <p>Bu özellikler, çoklu doğrusal regresyon analizinin, veri setinden derinlemesine içgörüler elde etmek ve değişkenler arasındaki ilişkileri anlamak için nasıl kullanılabileceğini gösterir.</p>
</div>
")
                     ),
                     mainPanel(
                       tabsetPanel(
                         tabPanel("Data Summary", verbatimTextOutput("mlrsummary")),
                         tabPanel("Assumptions for MLR Model", 
                                  tabsetPanel(                                  
                                    tabPanel("Diagnostics",
                                             plotlyOutput("resFitmlrPlot"),
                                             plotlyOutput("qqPlotmlr"),
                                             plotlyOutput("scaleLocmlrPlot"),
                                             plotlyOutput("resLevmlrPlot")
                                    ),
                                    tabPanel("Shapiro-Wilk Test", verbatimTextOutput("shapTestmlr")),
                                    tabPanel("Breusch-Pagan Test", verbatimTextOutput("ncvTestmlr")),
                                    tabPanel("Linearity Plot", plotlyOutput("linPlotmlr", width = "100%", height = "725px")),
                                    tabPanel("Durbin-Watson Test", verbatimTextOutput("dWTestmlr")),
                                    tabPanel("Variance Inflation Factor", verbatimTextOutput("vifmlr"))
                                  )
                         ),
                         tabPanel("MLR Model Evaluation",
                                  tabsetPanel(
                                    tabPanel("Model Summary", verbatimTextOutput("mlrmodeleva")),
                                    tabPanel("Correlation Coefficient Between the Variables", verbatimTextOutput("corcoefmlr")),
                                    tabPanel("Confidence Interval", verbatimTextOutput("confintmlr")),
                                    tabPanel("Model Evaluation Metrics", verbatimTextOutput("modelevamet")),
                                    tabPanel("Regression Line Plot", plotlyOutput("mlrregressPlot", width = "100%", height = "625px"))
                                  )
                         ),
                         
                       ),
                     )
                   )
          ),
          tabPanel("Logistic Regression",
                   sidebarLayout(
                     sidebarPanel(
                       fileInput("glmfile", "Choose a CSV or XLSX file", accept = c(".csv", ".xlsx")),
                       actionButton("loadData", "Load Data"),
                       selectInput("targetglm", "Select Target Column", choices = NULL),
                       selectizeInput("independentVars", "Select Independent Variables", choices = NULL, multiple = TRUE),
                       sliderInput("dataSplit", 
                                   "Data Split Ratio",
                                   min = 0.1,
                                   max = 0.9,
                                   value = 0.7,  # Default value, for instance, 70% for training and 30% for testing
                                   step = 0.05,
                                   ticks = FALSE,
                                   animate = TRUE),
                       actionButton("glmassumption", "Run Assumption"),
                       actionButton("runLogisticRegression", "Run Logistic Regression"),
                       HTML("<div>
  <h2>Lojistik Regresyon Paneli</h2>
  
  <h3>Çıktı Nedir ve Neden Kullanılır?</h3> Bu panel, bir veya birden fazla bağımsız değişken ile kategorik bir hedef değişken arasındaki ilişkiyi modellemek için lojistik regresyon analizi yapar. Lojistik regresyon, özellikle ikili (binary) sonuçlar için tercih edilen bir yöntemdir ve olasılıkların tahmin edilmesinde kullanılır.</p>
  
  <h3>Kullanım Adımları:</h3></p>
  <ol>
    <li><strong>Veri Dosyası Yükleme:</strong> Lojistik regresyon analizi için bir CSV veya XLSX dosyasını <code>fileInput</code> aracılığıyla yükleyin.</li>
    <li><strong>Hedef ve Bağımsız Değişkenlerin Seçimi:</strong> Analiz için kategorik hedef değişkeni ve bir veya birden fazla bağımsız değişkeni seçin.</li>
    <li><strong>Analizi Çalıştırma:</strong> <code>actionButton</code> butonlarına tıklayarak lojistik regresyon modelini ve varsayım kontrollerini çalıştırın.</li>
  </ol>
  
  <h3>Kullanıcı Etkileşimi:</h3> Kullanıcılar, dosya yükledikten ve gerekli değişkenleri seçtikten sonra analizi başlatır ve sonuçlar ana panelde görselleştirilir.</p>
  
  <h3>Veri Bilimi Alanındaki Kullanımı:</h3> Lojistik regresyon, sınıflandırma, olasılık tahmini ve risk faktörlerinin incelenmesi gibi çeşitli alanlarda kullanılır. Özellikle, kategorik sonuçların (örneğin, evet/hayır, başarılı/başarısız) olasılıklarının tahmin edilmesinde tercih edilen bir yöntemdir.</p>
  
  <h3>Desteklenen Dosya Tipleri:</h3> Kullanıcılar, analiz için CSV (.csv) veya Excel (.xlsx) formatında dosyalar yükleyebilirler.</p>
  
  <h3>Sonuçların Yorumlanması:</h3> Elde edilen model özeti, regresyon katsayıları, p-değerleri, ROC eğrisi gibi istatistiklerle modelin anlamlılığını ve performansını değerlendirir. Ayrıca, varsayım testleri modelin varsayımlara uygunluğunu kontrol etmek için kullanılır.</p>
  
  <ul>
    <li><strong>Model Özeti:</strong> Modelin istatistiksel anlamlılığını ve performansını değerlendirir.</li>
    <li><strong>Varsayım Testleri:</strong> Modelin normal dağılım, homoskedastisite, bağımsızlık gibi temel varsayımlara uygunluğunu test eder.</li>
    <li><strong>ROC Eğrisi:</strong> Modelin sınıflandırma performansını değerlendirir ve AUC (Alan Altında Kalan Alan) değeri ile modelin ayırt edici gücünü gösterir.</li>
  </ul>
  
  <p>Bu özellikler, lojistik regresyon analizinin, veri setinden derinlemesine içgörüler elde etmek ve kategorik sonuçların olasılıklarını tahmin etmek için nasıl kullanılabileceğini gösterir.</p>
</div>
")
                     ),
                     
                     mainPanel(
                       tabsetPanel(
                         tabPanel("Data Summary", verbatimTextOutput("dataSummary")),
                         tabPanel("Assumptions for Model", verbatimTextOutput("glmassumption")),
                         tabPanel("Logistic Regression Output", verbatimTextOutput("logisticOutput")),
                         tabPanel("Cross Validation GLM Output", plotlyOutput("glmcvplot")),
                         tabPanel("Area Under the Curve Plot", plotlyOutput("glmaucplot"))
                       )
                     )
                   )
          ),
          tabPanel("Decision Tree",
                   sidebarLayout(
                     sidebarPanel(
                       fileInput("treedecfile", "Choose a CSV or XLSX file", accept = c(".csv", ".xlsx")),
                       selectInput("targetdectree", "Select Target Column", choices = NULL),
                       sliderInput("dataSplittree", 
                                   "Data Split Ratio",
                                   min = 0.1,
                                   max = 0.9,
                                   value = 0.7,  # Default value, for instance, 70% for training and 30% for testing
                                   step = 0.05,
                                   ticks = FALSE,
                                   animate = TRUE),
                       actionButton("rundectree", "Run Prior Steps"),
                       HTML("<div>
  <h2>Karar Ağacı Paneli</h2>
  
  <h3>Çıktı Nedir ve Neden Kullanılır?</h3> Bu panel, sınıflandırma ve regresyon problemleri için karar ağacı modellemesi yapar. Karar ağacı, veri setindeki özelliklerin farklı kombinasyonlarını kullanarak sonuçları tahmin eder ve bu tahminlerin nasıl yapıldığını açıklayabilir bir şekilde görselleştirir.</p>
  
  <h3>Kullanım Adımları:</h3></p>
  <ol>
    <li><strong>Veri Dosyası Yükleme:</strong> Karar ağacı modellemesi için bir CSV veya XLSX dosyasını <code>fileInput</code> aracılığıyla yükleyin.</li>
    <li><strong>Hedef Değişken Seçimi:</strong> Modelde tahmin edilecek hedef değişkeni seçin.</li>
    <li><strong>Modellemeyi Çalıştırma:</strong> <code>actionButton</code> butonuna tıklayarak karar ağacı modellemesini ve ilgili ön adımları çalıştırın.</li>
  </ol>
  
  <h3>Kullanıcı Etkileşimi:</h3> Kullanıcılar, dosya yükledikten ve hedef değişkeni seçtikten sonra modellemeyi başlatır ve sonuçlar ana panelde görselleştirilir.</p>
  
  <h3>Veri Bilimi Alanındaki Kullanımı:</h3> Karar ağacı, sınıflandırma ve regresyon problemlerinde yaygın olarak kullanılan bir yöntemdir. Ağaç yapısı, modelin kararlarını ve tahminlerini açıklayıcı bir şekilde sunar, bu da modelin yorumlanabilirliğini artırır.</p>
  
  <h3>Desteklenen Dosya Tipleri:</h3> Kullanıcılar, analiz için CSV (.csv) veya Excel (.xlsx) formatında dosyalar yükleyebilirler.</p>
  
  <h3>Sonuçların Yorumlanması:</h3> Elde edilen karar ağacı modeli, veri setindeki özelliklerin nasıl birleştirildiğini ve sonuçların nasıl tahmin edildiğini gösterir. Model özeti, karar ağacının performansını ve doğruluğunu değerlendirir. Ayrıca, ağacın budanması ve çapraz doğrulama gibi tekniklerle modelin genelleştirilmesi incelenir.</p>
  
  <ul>
    <li><strong>Model Özeti:</strong> Modelin performansını ve doğruluğunu değerlendirir.</li>
    <li><strong>Karar Ağacı Görselleştirme:</strong> Karar ağacının nasıl yapılandırıldığını ve tahminlerin nasıl yapıldığını görsel olarak sunar.</li>
    <li><strong>Çapraz Doğrulama:</strong> Modelin farklı veri setleri üzerindeki performansını test eder ve genelleştirme yeteneğini değerlendirir.</li>
    <li><strong>Karışıklık Matrisi:</strong> Modelin sınıflandırma performansını detaylı bir şekilde gösterir.</li>
  </ul>
  
  <p>Bu özellikler, karar ağacı modellemesinin, veri setinden derinlemesine içgörüler elde etmek ve tahminler yapmak için nasıl kullanılabileceğini gösterir.</p>
</div>
")
                     ),
                     
                     mainPanel(
                       tabsetPanel(
                         tabPanel("Finding Right Model",
                                  tabsetPanel(
                                    tabPanel("Data Summary", verbatimTextOutput("dataSummarydt")),
                                    tabPanel("Run First Model", verbatimTextOutput("rundectree")),
                                    tabPanel("Before Pruning Model's Plot", plotOutput("dectreeplot", width = "100%", height = "750px")),
                                    tabPanel("Cross-validation Plot", plotOutput("cvplot", width = "100%", height = "750px")),
                                    tabPanel("Confusion Matrix", verbatimTextOutput("confMatrix")),
                                    tabPanel("Pruned Tree", plotOutput("pruneddtree", width = "100%", height = "725px")),
                                  )
                         ),
                         tabPanel("Decision Tree Model Evaluation",
                                  tabsetPanel(
                                    tabPanel("Model Evaluation", verbatimTextOutput("cfdtpteva")),
                                  ))
                       )
                     ),
                   )
          ),
          tabPanel("Random Forest",
                   sidebarLayout(
                     sidebarPanel(
                       fileInput("rfinput", "Choose a CSV or XLSX file", accept = c(".csv", ".xlsx")),
                       actionButton("loadrf", "Load Data"),
                       selectInput("targetrf", "Select Target Column", choices = NULL),
                       selectizeInput("independentVarrf", "Select Independent Variables", choices = NULL, multiple = TRUE),
                       sliderInput("dataSplitrf", 
                                   "Data Split Ratio",
                                   min = 0.1,
                                   max = 0.9,
                                   value = 0.7,  # Default value, for instance, 70% for training and 30% for testing
                                   step = 0.05,
                                   ticks = FALSE,
                                   animate = TRUE),
                       numericInput("mtryInput", "Mtry Value", value = 3, min = 1),
                       numericInput("ntreeInput", "Ntree Value", value = 14, min = 1),
                       actionButton("runrf", "Run Prior Steps"),
                       actionButton("predictBtn", "Predict"),
                       HTML("<div>
  <h2>Rastgele Orman Paneli</h2>
  
  <h3>Çıktı Nedir ve Neden Kullanılır?</h3> Bu panel, sınıflandırma ve regresyon problemleri için rastgele orman modellemesi yapar. Rastgele orman, birden fazla karar ağacını birleştirerek oluşturulan bir topluluk öğrenme yöntemidir. Bu yöntem, modelin genel hatası üzerindeki varyansı azaltır ve aşırı uyuma karşı dirençli olmasını sağlar.</p>
  
  <h3>Kullanım Adımları:</h3></p>
  <ol>
    <li><strong>Veri Dosyası Yükleme:</strong> Rastgele orman modellemesi için bir CSV veya XLSX dosyasını <code>fileInput</code> aracılığıyla yükleyin.</li>
    <li><strong>Hedef Değişken ve Bağımsız Değişkenler Seçimi:</strong> Modelde tahmin edilecek hedef değişkeni ve kullanılacak bağımsız değişkenleri seçin.</li>
    <li><strong>Model Parametreleri Ayarlama:</strong> Modelin <code>mtry</code> ve <code>ntree</code> değerlerini ayarlayın.</li>
    <li><strong>Modellemeyi Çalıştırma:</strong> <code>actionButton</code> butonlarına tıklayarak rastgele orman modellemesini ve tahmin işlemini çalıştırın.</li>
  </ol>
  
  <h3>Kullanıcı Etkileşimi:</h3> Kullanıcılar, dosya yükledikten, değişkenleri seçtikten ve model parametrelerini ayarladıktan sonra modellemeyi başlatır ve sonuçlar ana panelde görselleştirilir.</p>
  
  <h3>Veri Bilimi Alanındaki Kullanımı:</h3> Rastgele orman, sınıflandırma ve regresyon gibi çeşitli makine öğrenmesi problemlerinde kullanılır. Modelin oluşturduğu birden fazla karar ağacının sonuçlarını birleştirerek daha doğru tahminler yapılmasını sağlar.</p>
  
  <h3>Desteklenen Dosya Tipleri:</h3> Kullanıcılar, analiz için CSV (.csv) veya Excel (.xlsx) formatında dosyalar yükleyebilirler.</p>
  
  <h3>Sonuçların Yorumlanması:</h3> Elde edilen rastgele orman modeli, bağımsız değişkenlerin hedef değişken üzerindeki etkilerini ve önem derecelerini gösterir. Model özeti, rastgele ormanın performansını ve doğruluğunu değerlendirir. Ayrıca, modelin tahminlerini ve bu tahminlerin gerçek değerlerle karşılaştırılmasını içeren görselleştirmeler sunar.</p>
  
  <ul>
    <li><strong>Model Özeti:</strong> Modelin performansını ve doğruluğunu değerlendirir.</li>
    <li><strong>Özellik Önemi:</strong> Bağımsız değişkenlerin model üzerindeki etkisinin ve öneminin değerlendirilmesi.</li>
    <li><strong>Model Tahminleri:</strong> Modelin tahmin ettiği sonuçlar ve bu tahminlerin gerçek değerlerle karşılaştırılması.</li>
  </ul>
  
  <p>Bu özellikler, rastgele orman modellemesinin, veri setinden derinlemesine içgörüler elde etmek ve tahminler yapmak için nasıl kullanılabileceğini gösterir.</p>
</div>
")
                     ),
                     mainPanel(
                       tabsetPanel(
                         tabPanel("Data Summary", verbatimTextOutput("dataSummaryrf")),
                         tabPanel("Run First Model", verbatimTextOutput("runrf")),
                         tabPanel("Feature Importance Plot", plotlyOutput("importancePlot", width = "100%", height = "625px")),
                         tabPanel("Model Prediction",
                                  tabsetPanel(
                                    tabPanel("Predicted Result", verbatimTextOutput("predictionOutput")),
                                    tabPanel("Predicted Plot", plotlyOutput("performancePlot", width = "100%", height = "625px"))
                                  )
                         )
                       )
                       
                     )
                   )
          ),
          tabPanel("Bagging",
                   sidebarLayout(
                     sidebarPanel(
                       fileInput("bginput", "Choose a CSV or XLSX file", accept = c(".csv", ".xlsx")),
                       actionButton("loadbg", "Load Data"),
                       selectInput("targetbg", "Select Target Column", choices = NULL),
                       selectizeInput("independentVarbg", "Select Independent Variables", choices = NULL, multiple = TRUE),
                       sliderInput("dataSplitbg", 
                                   "Data Split Ratio",
                                   min = 0.1,
                                   max = 0.9,
                                   value = 0.7,  # Default value, for instance, 70% for training and 30% for testing
                                   step = 0.05,
                                   ticks = FALSE,
                                   animate = TRUE),
                       numericInput("nbaggInput", "Nbagg Value", value = 14, min = 1),
                       actionButton("runbg", "Run Prior Steps"),
                       actionButton("baggingBtn", "Predict"),
                       HTML("<div>
  <h2>Çanta (Bagging) Paneli</h2>
  
  <h3>Çıktı Nedir ve Neden Kullanılır?</h3>
  <p>Bu panel, çok sayıda karar ağacı modelini birleştirerek güçlü bir makine öğrenimi modeli oluşturan çanta (bagging) yöntemini kullanır. Çanta yöntemi, modelin genel hatasını azaltarak ve aşırı uyum (overfitting) riskini minimize ederek tahminlerin doğruluğunu artırır.</p>
  
  <h3>Kullanım Adımları:</h3>
  <ol>
    <li><strong>Veri Dosyası Yükleme:</strong> CSV veya XLSX formatında bir dosya yükleyerek analize başlayın.</li>
    <li><strong>Hedef ve Bağımsız Değişkenlerin Seçilmesi:</strong> Modelde kullanılacak hedef ve bağımsız değişkenleri seçin.</li>
    <li><strong>Model Parametrelerinin Ayarlanması:</strong> Modelin performansını etkileyen parametreleri (örneğin, çanta iterasyon sayısı) ayarlayın.</li>
    <li><strong>Modelin Eğitilmesi ve Tahmin Yapılması:</strong> Modeli eğitin ve test veri seti üzerinde tahminlerde bulunun.</li>
  </ol>
  
  <h3>Kullanıcı Etkileşimi:</h3>
  <p>Kullanıcılar, veri setini yükledikten ve gerekli seçimleri yaptıktan sonra, modeli eğitmek ve tahminler yapmak için belirtilen butonlara tıklar. Sonuçlar, ana panelde görselleştirilir ve detaylı analizler sunulur.</p>
  
  <h3>Veri Bilimi ve Makine Öğrenmesindeki Uygulamaları:</h3>
  <p>Çanta yöntemi, hem sınıflandırma hem de regresyon problemleri için yaygın olarak kullanılan bir topluluk öğrenme yöntemidir. Bu yöntem, veri setlerinden elde edilen bilgiyi maksimize eder ve modelin genel performansını iyileştirir.</p>
  
  <h3>Desteklenen Dosya Tipleri ve Seçenekler:</h3>
  <p>Panel, kullanıcıların CSV (.csv) veya Excel (.xlsx) formatındaki dosyaları yüklemesine izin verir. Bu, veri bilimcilerin ve analistlerin çeşitli veri setleri üzerinde çalışabilmesi için esneklik sağlar.</p>
  
  <h3>Sonuçların Yorumlanması:</h3>
  <p>Modelin performansı, çeşitli metrikler kullanılarak değerlendirilir. Özellik önem dereceleri, hangi değişkenlerin model tahminlerini en çok etkilediğini gösterir. Ayrıca, tahmin edilen sonuçlar ve modelin genel doğruluğu hakkında bilgiler sunulur.</p>
  
  <ul>
    <li><strong>Model Özeti:</strong> Modelin performans metrikleri ve ayarlanan parametreler hakkında bilgi verir.</li>
    <li><strong>Özellik Önemi:</strong> Model tahminlerinde hangi bağımsız değişkenlerin önemli olduğunu gösterir.</li>
    <li><strong>Tahmin Sonuçları:</strong> Modelin test veri seti üzerinde yaptığı tahminler ve bu tahminlerin gerçek değerlerle karşılaştırılması.</li>
  </ul>
  
  <p>Bu özellikler, çanta yönteminin veri setlerinden maksimum bilgiyi çıkararak tahminlerin doğruluğunu artırma potansiyelini gösterir.</p>
</div>")
                     ),
                     mainPanel(
                       tabsetPanel(
                         tabPanel("Data Summary", verbatimTextOutput("dataSummarybg")),
                         tabPanel("Run First Model", verbatimTextOutput("runbg")),
                         tabPanel("Feature Importance Plot", plotlyOutput("importancePlotbg", width = "100%", height = "625px")),
                         tabPanel("Model Prediction",
                                  tabsetPanel(
                                    tabPanel("Predicted Result", verbatimTextOutput("predictionOutputbg")),
                                    tabPanel("Predicted Plot", plotlyOutput("performancePlotbg", width = "100%", height = "625px"))
                                  )
                         )
                       )
                       
                     )
                   )
          ),
          tabPanel("Boosting",
                   sidebarLayout(
                     sidebarPanel(
                       fileInput("bsinput", "Choose a CSV or XLSX file", accept = c(".csv", ".xlsx")),
                       actionButton("loadbs", "Load Data"),
                       selectInput("targetbs", "Select Target Column", choices = NULL),
                       selectizeInput("independentVarbs", "Select Independent Variables", choices = NULL, multiple = TRUE),
                       sliderInput("dataSplitbs", 
                                   "Data Split Ratio",
                                   min = 0.1,
                                   max = 0.9,
                                   value = 0.7,  # Default value, for instance, 70% for training and 30% for testing
                                   step = 0.05,
                                   ticks = FALSE,
                                   animate = TRUE),
                       numericInput("nbsInput", "N Trees Value", value = 14, min = 1),
                       numericInput("nbsdepth", "Interaction Depth", value = 4, min = 1),
                       numericInput("nbshr", "Shrinkage", value = 0.03, min = 0.0001),
                       actionButton("runbs", "Run Prior Steps"),
                       actionButton("boostingBtn", "Predict"),
                       HTML("<div>
  <h2>Artırma (Boosting) Paneli</h2>
  
  <h3>Çıktı Nedir ve Neden Kullanılır?</h3>
  <p>Bu panel, zayıf öğrenicileri güçlü bir model oluşturmak üzere birleştiren artırma (boosting) yöntemini kullanır. Artırma, bir dizi zayıf modeli sıralı olarak eğitir ve her birini öncekinin hatalarını düzeltmeye odaklanır, böylece modelin genel performansı artar.</p>
  
  <h3>Kullanım Adımları:</h3>
  <ol>
    <li><strong>Veri Dosyası Yükleme:</strong> CSV veya XLSX formatında bir dosya yükleyerek analize başlayın.</li>
    <li><strong>Hedef ve Bağımsız Değişkenlerin Seçilmesi:</strong> Modelde kullanılacak hedef ve bağımsız değişkenleri seçin.</li>
    <li><strong>Model Parametrelerinin Ayarlanması:</strong> Modelin performansını etkileyen parametreleri (örneğin, ağaç sayısı, etkileşim derinliği, küçültme) ayarlayın.</li>
    <li><strong>Modelin Eğitilmesi ve Tahmin Yapılması:</strong> Modeli eğitin ve test veri seti üzerinde tahminlerde bulunun.</li>
  </ol>
  
  <h3>Kullanıcı Etkileşimi:</h3>
  <p>Kullanıcılar, veri setini yükledikten ve gerekli seçimleri yaptıktan sonra, modeli eğitmek ve tahminler yapmak için belirtilen butonlara tıklar. Sonuçlar, ana panelde görselleştirilir ve detaylı analizler sunulur.</p>
  
  <h3>Veri Bilimi ve Makine Öğrenmesindeki Uygulamaları:</h3>
  <p>Artırma yöntemi, genellikle sınıflandırma ve regresyon problemlerinde kullanılır ve modelin aşırı uyuma (overfitting) eğilimini azaltırken tahmin doğruluğunu artırır.</p>
  
  <h3>Desteklenen Dosya Tipleri ve Seçenekler:</h3>
  <p>Panel, kullanıcıların CSV (.csv) veya Excel (.xlsx) formatındaki dosyaları yüklemesine izin verir. Bu, veri bilimcilerin ve analistlerin çeşitli veri setleri üzerinde çalışabilmesi için esneklik sağlar.</p>
  
  <h3>Sonuçların Yorumlanması:</h3>
  <p>Modelin performansı, çeşitli metrikler kullanılarak değerlendirilir. Özellik önem dereceleri, hangi değişkenlerin model tahminlerini en çok etkilediğini gösterir. Ayrıca, tahmin edilen sonuçlar ve modelin genel doğruluğu hakkında bilgiler sunulur.</p>
  
  <ul>
    <li><strong>Model Özeti:</strong> Modelin performans metrikleri ve ayarlanan parametreler hakkında bilgi verir.</li>
    <li><strong>Özellik Önemi:</strong> Model tahminlerinde hangi bağımsız değişkenlerin önemli olduğunu gösterir.</li>
    <li><strong>Tahmin Sonuçları:</strong> Modelin test veri seti üzerinde yaptığı tahminler ve bu tahminlerin gerçek değerlerle karşılaştırılması.</li>
  </ul>
  
  <p>Bu özellikler, artırma yönteminin veri setlerinden maksimum bilgiyi çıkararak tahminlerin doğruluğunu artırma potansiyelini gösterir.</p>
</div>")
                     ),
                     mainPanel(
                       tabsetPanel(
                         tabPanel("Data Summary", verbatimTextOutput("dataSummarybs")),
                         tabPanel("Run First Model", verbatimTextOutput("runbs")),
                         tabPanel("Feature Importance Plot", plotlyOutput("importancePlotbs", width = "100%", height = "625px")),
                         tabPanel("Model Prediction",
                                  tabsetPanel(
                                    tabPanel("Predicted Result", verbatimTextOutput("predictionOutputbs")),
                                    tabPanel("Predicted Plot", plotlyOutput("performancePlotbs", width = "100%", height = "625px"))
                                  )
                         )
                       )
                       
                     )
                   )
          ),
          tabPanel("MARS",
                   sidebarLayout(
                     sidebarPanel(
                       fileInput("msinput", "Choose a CSV or XLSX file", accept = c(".csv", ".xlsx")),
                       actionButton("loadms", "Load Data"),
                       selectInput("targetms", "Select Target Column", choices = NULL),
                       selectizeInput("independentVarms", "Select Independent Variables", choices = NULL, multiple = TRUE),
                       sliderInput("dataSplitms", 
                                   "Data Split Ratio",
                                   min = 0.1,
                                   max = 0.9,
                                   value = 0.7,  # Default value, for instance, 70% for training and 30% for testing
                                   step = 0.05,
                                   ticks = FALSE,
                                   animate = TRUE),
                       actionButton("runms", "Run Prior Steps"),
                       actionButton("marsBtn", "Predict"),
                       HTML("<div>
  <h2>MARS Paneli</h2>
  
  <h3>Çıktı Nedir ve Neden Kullanılır?</h3>
  <p>Bu panel, Çoklu Adaptif Regresyon Spline'ları (MARS) kullanarak veri setinden karmaşık ilişkileri ve etkileşimleri yakalayabilen bir model oluşturur. MARS, lineer olmayan ilişkileri ve değişkenler arasındaki etkileşimleri otomatik olarak tanımlayabilen esnek bir yöntemdir.</p>
  
  <h3>Kullanım Adımları:</h3>
  <ol>
    <li><strong>Veri Dosyası Yükleme:</strong> Analize başlamak için CSV veya XLSX formatında bir dosya yükleyin.</li>
    <li><strong>Hedef ve Bağımsız Değişkenlerin Seçilmesi:</strong> Modelde kullanılacak hedef ve bağımsız değişkenleri belirleyin.</li>
    <li><strong>Veri Bölme Oranının Ayarlanması:</strong> Modelin eğitim ve test veri setlerine bölünme oranını ayarlayın.</li>
    <li><strong>Modelin Eğitilmesi ve Değerlendirilmesi:</strong> Modeli eğitip performansını değerlendirin. Modelin doğruluğunu ve bağımsız değişkenlerin önemini inceleyin.</li>
  </ol>
  
  <h3>Kullanıcı Etkileşimi:</h3>
  <p>Kullanıcılar, analiz için gerekli veri ve parametreleri girer ve modeli eğitmek için belirtilen adımları takip eder. Sonuçlar, kullanıcıya modelin performansı ve değişkenlerin önemi hakkında detaylı bilgiler sunar.</p>
  
  <h3>Veri Bilimi ve Makine Öğrenmesindeki Uygulamaları:</h3>
  <p>MARS yöntemi, özellikle karmaşık ilişkilerin ve değişken etkileşimlerinin olduğu durumlarda tercih edilen bir modelleme tekniğidir. Hem sınıflandırma hem de regresyon problemleri için uygundur.</p>
  
  <h3>Desteklenen Dosya Tipleri ve Seçenekler:</h3>
  <p>Panel, kullanıcıların analiz için CSV (.csv) veya Excel (.xlsx) formatlarında veri dosyaları yüklemesine olanak tanır, bu da farklı veri setleri üzerinde çalışmayı kolaylaştırır.</p>
  
  <h3>Sonuçların Yorumlanması:</h3>
  <p>Modelin performansı, çeşitli metrikler kullanılarak değerlendirilir. Bağımsız değişkenlerin model üzerindeki etkisi, özellik önem dereceleriyle gösterilir. Ayrıca, modelin genel doğruluğu ve tahmin edilen sonuçlar hakkında bilgiler sağlanır.</p>
  
  <ul>
    <li><strong>Model Özeti:</strong> Modelin performans metrikleri ve ayarlanan parametreler hakkında bilgi sağlar.</li>
    <li><strong>Özellik Önemi:</strong> Hangi bağımsız değişkenlerin model tahminlerini en çok etkilediğini gösterir.</li>
    <li><strong>Tahmin Sonuçları:</strong> Modelin test veri seti üzerinde yaptığı tahminler ve bu tahminlerin gerçek değerlerle karşılaştırılması.</li>
  </ul>
  
  <p>Bu panel, MARS modelinin veri setlerinden karmaşık ilişkileri çıkararak tahminlerin doğruluğunu artırma potansiyeline sahip olduğunu gösterir.</p>
</div>")
                     ),
                     mainPanel(
                       tabsetPanel(
                         tabPanel("Data Summary", verbatimTextOutput("dataSummaryms")),
                         tabPanel("Run First Model", verbatimTextOutput("runms")),
                         tabPanel("Feature Importance Plot", plotlyOutput("importancePlotms", width = "100%", height = "625px")),
                         tabPanel("Model Prediction",
                                  tabsetPanel(
                                    tabPanel("Predicted Result", verbatimTextOutput("predictionOutputms")),
                                    tabPanel("Predicted Plot", plotlyOutput("performancePlotms", width = "100%", height = "625px"))
                                  )
                         )
                       )
                       
                     )
                   )
          ),
          tabPanel("Ridge Regression",
                   sidebarLayout(
                     sidebarPanel(
                       fileInput("rrinput", "Choose a CSV or XLSX file", accept = c(".csv", ".xlsx")),
                       actionButton("loadrr", "Load Data"),
                       selectInput("targetrr", "Select Target Column", choices = NULL),
                       selectizeInput("independentVarrr", "Select Independent Variables", choices = NULL, multiple = TRUE),
                       sliderInput("dataSplitrr", 
                                   "Data Split Ratio",
                                   min = 0.1,
                                   max = 0.9,
                                   value = 0.7,  # Default value, for instance, 70% for training and 30% for testing
                                   step = 0.05,
                                   ticks = FALSE,
                                   animate = TRUE),
                       actionButton("runrr", "Run Prior Steps"),
                       actionButton("RidgeBtn", "Predict"),
                       HTML("<div>
  <h2>Ridge Regresyon Paneli</h2>
  
  <h3>Çıktı Nedir ve Neden Kullanılır?</h3>
  <p>Ridge Regresyonu, çoklu doğrusal regresyon modellerinde aşırı uyumun önlenmesine yardımcı olan bir düzenlileştirme tekniğidir. Bu panel, yüksek boyutlu veri setlerinde bile değişkenler arası ilişkileri daha iyi anlamak için Ridge Regresyon modelini kullanır.</p>
  
  <h3>Kullanım Adımları:</h3>
  <ol>
    <li><strong>Veri Dosyası Yükleme:</strong> Analize başlamak için uygun bir CSV veya XLSX dosyası yükleyin.</li>
    <li><strong>Hedef ve Bağımsız Değişkenlerin Seçimi:</strong> Modelde hedef değişken olarak neyin tahmin edileceğini ve hangi bağımsız değişkenlerin kullanılacağını seçin.</li>
    <li><strong>Veri Bölme Oranı Ayarlama:</strong> Veri setinin eğitim ve test seti olarak nasıl bölüneceğini belirleyin.</li>
    <li><strong>Model Eğitimi ve Değerlendirme:</strong> Modeli eğitin ve performansını değerlendirin. Modelin nasıl performans gösterdiğini ve hangi değişkenlerin önemli olduğunu öğrenin.</li>
  </ol>
  
  <h3>Kullanıcı Etkileşimi:</h3>
  <p>Kullanıcılar, panel aracılığıyla veri setlerini yükleyebilir, model parametrelerini ayarlayabilir ve modelin performansını değerlendirme sonuçlarını görüntüleyebilir. Bu süreç, veri bilimi projelerinde kritik öneme sahip olan modelleme ve analiz işlemlerini kolaylaştırır.</p>
  
  <h3>Veri Bilimi ve Makine Öğrenmesindeki Uygulamaları:</h3>
  <p>Ridge Regresyonu, özellikle çok sayıda özellik içeren veri setlerinde ve değişkenler arasında yüksek korelasyon olduğunda kullanışlıdır. Model karmaşıklığını kontrol ederek aşırı uyumu azaltır ve modelin genelleştirme yeteneğini artırır.</p>
  
  <h3>Desteklenen Dosya Tipleri ve Seçenekler:</h3>
  <p>Panel, CSV (.csv) ve Excel (.xlsx) formatlarındaki veri dosyalarını destekler, bu da kullanıcıların çeşitli veri kaynaklarından kolayca veri yüklemesine olanak tanır.</p>
  
  <h3>Sonuçların Yorumlanması:</h3>
  <p>Modelin başarısı, RMSE, R-kare gibi metriklerle değerlendirilir. Ayrıca, değişkenlerin model üzerindeki etkisi ve önemi hakkında bilgiler sunulur, bu da hangi özelliklerin hedef değişkeni en çok etkilediğini anlamaya yardımcı olur.</p>
  
  <ul>
    <li><strong>Model Özeti:</strong> Modelin ayar parametreleri, performans metrikleri ve doğrulama sonuçları hakkında ayrıntılı bilgi sağlar.</li>
    <li><strong>Özellik Önemi:</strong> Model tahminlerinde hangi bağımsız değişkenlerin daha etkili olduğunu gösterir.</li>
    <li><strong>Tahmin Sonuçları:</strong> Modelin test veri seti üzerindeki tahminleri ve bu tahminlerin gerçek değerlerle olan karşılaştırması.</li>
  </ul>
  
  <p>Ridge Regresyon paneli, modelin veri setindeki özellikler arasındaki karmaşık ilişkileri nasıl yakaladığını ve tahminlerin doğ

ruluğunu nasıl artırdığını gösterir.</p>
</div>")
                     ),
                     mainPanel(
                       tabsetPanel(
                         tabPanel("Data Summary", verbatimTextOutput("dataSummaryrr")),
                         tabPanel("Run First Model", verbatimTextOutput("runrr")),
                         tabPanel("Feature Importance Plot", plotlyOutput("importancePlotrr", width = "100%", height = "625px")),
                         tabPanel("Model Prediction",
                                  tabsetPanel(
                                    tabPanel("Predicted Result", verbatimTextOutput("predictionOutputrr")),
                                    tabPanel("Predicted Plot", plotlyOutput("performancePlotrr", width = "100%", height = "625px"))
                                  )
                         )
                       )
                       
                     )
                   )
          ),
          tabPanel("LASSO Regression",
                   sidebarLayout(
                     sidebarPanel(
                       fileInput("lsinput", "Choose a CSV or XLSX file", accept = c(".csv", ".xlsx")),
                       actionButton("loadls", "Load Data"),
                       selectInput("targetls", "Select Target Column", choices = NULL),
                       selectizeInput("independentVarls", "Select Independent Variables", choices = NULL, multiple = TRUE),
                       sliderInput("dataSplitls", 
                                   "Data Split Ratio",
                                   min = 0.1,
                                   max = 0.9,
                                   value = 0.7,  # Default value, for instance, 70% for training and 30% for testing
                                   step = 0.05,
                                   ticks = FALSE,
                                   animate = TRUE),
                       actionButton("runls", "Run Prior Steps"),
                       actionButton("LassoBtn", "Predict"),
                       HTML("<div>
  <h2>LASSO Regresyon Paneli</h2>
  
  <h3>Çıktı Nedir ve Neden Kullanılır?</h3>
  <p>LASSO Regresyonu, özellik seçimi ve düzenlileştirme sağlayarak modelin karmaşıklığını azaltır ve genelleştirme kabiliyetini artırır. Bu panel, veri setlerindeki değişkenler arasındaki ilişkileri anlamak ve önemli özellikleri belirlemek için LASSO Regresyon modelini kullanır.</p>
  
  <h3>Kullanım Adımları:</h3>
  <ol>
    <li><strong>Veri Dosyası Yükleme:</strong> Analize başlamak için bir CSV veya XLSX dosyası yükleyin.</li>
    <li><strong>Hedef ve Bağımsız Değişkenlerin Seçimi:</strong> Modelin neyi tahmin edeceğini ve hangi bağımsız değişkenlerin kullanılacağını seçin.</li>
    <li><strong>Veri Bölme Oranı Ayarlama:</strong> Eğitim ve test setlerinin nasıl bölüneceğini belirleyin.</li>
    <li><strong>Model Eğitimi ve Değerlendirme:</strong> Modeli eğitin, performansını değerlendirin ve önemli özellikleri keşfedin.</li>
  </ol>
  
  <h3>Kullanıcı Etkileşimi:</h3>
  <p>Kullanıcılar, veri setlerini yükleyebilir, model parametrelerini ayarlayabilir ve modelin nasıl performans gösterdiğini anlayabilir. Panel, modelleme ve analiz işlemlerini kolaylaştırarak veri bilimi projelerinde değerli bir araç sunar.</p>
  
  <h3>Veri Bilimi ve Makine Öğrenmesindeki Uygulamaları:</h3>
  <p>LASSO Regresyonu, özellikle çok sayıda özelliği olan ve değişkenler arasında yüksek korelasyon bulunan veri setlerinde kullanışlıdır. Model, önemsiz özellikleri sıfıra yaklaştırarak özellik seçimi yapar ve daha anlamlı tahminler sağlar.</p>
  
  <h3>Desteklenen Dosya Tipleri ve Seçenekler:</h3>
  <p>Panel, CSV (.csv) ve Excel (.xlsx) formatlarını destekler, bu da kullanıcıların farklı veri kaynaklarından kolaylıkla veri yüklemesine olanak tanır.</p>
  
  <h3>Sonuçların Yorumlanması:</h3>
  <p>Modelin başarısı, RMSE, R-kare gibi metriklerle değerlendirilir. Ayrıca, modelin hangi değişkenleri önemli bulduğu ve tahminlerin doğruluğu hakkında bilgi sunulur.</p>
  
  <ul>
    <li><strong>Model Özeti:</strong> Modelin performans metrikleri, ayar parametreleri ve doğrulama sonuçları hakkında detaylı bilgiler sağlar.</li>
    <li><strong>Özellik Önemi:</strong> Model tahminlerinde hangi bağımsız değişkenlerin daha etkili olduğunu belirler.</li>
    <li><strong>Tahmin Sonuçları:</strong> Modelin test veri seti üzerindeki tahmin sonuçları ve bu tahminlerin gerçek değerlerle karşılaştırılması.</li>
  </ul>
  
  <p>LASSO Regresyon paneli, modelin veri setindeki özellikler arasındaki ilişkileri nasıl çözümlendiğini ve tahminlerin doğruluğunu nasıl artırdığını gösterir.</p>
</div>")
                     ),
                     mainPanel(
                       tabsetPanel(
                         tabPanel("Data Summary", verbatimTextOutput("dataSummaryls")),
                         tabPanel("Run First Model", verbatimTextOutput("runls")),
                         tabPanel("Feature Importance Plot", plotlyOutput("importancePlotls", width = "100%", height = "625px")),
                         tabPanel("Model Prediction",
                                  tabsetPanel(
                                    tabPanel("Predicted Result", verbatimTextOutput("predictionOutputls")),
                                    tabPanel("Predicted Plot", plotlyOutput("performancePlotls", width = "100%", height = "625px"))
                                  )
                         )
                       )
                       
                     )
                   )
          )
          
        )

)

server <- function(input, output, session) {

  ##Supervised Learning
  ###Simple Linear Regression
  # Define reactive values for each assumption test
  shapiroTestResult <- reactiveVal()
  ncvTestResult <- reactiveVal()
  linearityPlot <- reactiveVal()
  durbinWatsonTestResult <- reactiveVal()
  modelslr <- reactiveVal()
  dataslr <- reactiveVal(NULL)
  modelslreva <- reactiveVal(NULL)
  dataslreva <- reactiveVal(NULL)
  # Fix the data loading and cleaning part
  observeEvent(input$loadslr, {
    file <- input$slrinput
    if (!is.null(file)) {
      data_slr <- read_data(file$datapath)
      data_slr <- clean_column_names(data_slr)
      dataslr(data_slr)  # Update the reactive value correctly
      updateSelectInput(session, "targetslr", choices = colnames(data_slr))
      updateSelectizeInput(session, "independentVar", choices = setdiff(colnames(data_slr), input$targetslr))
    }
  })
  
  output$slrsummary <- renderPrint({
    req(dataslr())
    summary(dataslr())
  })
  
  # Observe the action button for triggering assumption tests
  observeEvent(input$slrassumption, {
    req(dataslr(), input$targetslr, input$independentVar)
    data_slr <- dataslr()
    target_col <- input$targetslr
    independent_var <- input$independentVar
    
    # Ensure the target and independent variables are available
    if (is.null(data_slr[[target_col]]) || is.null(data_slr[[independent_var]])) {
      return("Target or independent variable not found in the data.")
    }
    
    # Filter out rows where any character column is an empty string
    data_slr <- data_slr %>% dplyr::select(all_of(target_col), all_of(independent_var)) %>%
      na.omit()
    
    # Split the data into training and testing sets
    set.seed(123)
    split_ratio <- input$dataSplitslr
    training.samples <- createDataPartition(data_slr[[target_col]], p = split_ratio, list = FALSE)
    train_data <- data_slr[training.samples, ]
    test_data <- data_slr[-training.samples, ]
    
    # Fit the linear regression model
    fitted_model <- lm(reformulate(independent_var, target_col), data = train_data)
    modelslr(fitted_model)  # Update the reactive value
    
    # Print the summary of the model
    summary(fitted_model)
  })
  
  output$shapiroTest <- renderPrint({
    req(dataslr(), input$targetslr, input$independentVar)
    data_slr <- dataslr()
    target_col <- input$targetslr
    independent_var <- input$independentVar
    # Ensure the target and independent variables are available
    if (is.null(data_slr[[target_col]]) || is.null(data_slr[[independent_var]])) {
      return("Target or independent variable not found in the data.")
    }
    
    # Filter out rows where any character column is an empty string
    data_slr <- data_slr %>% dplyr::select(all_of(target_col), all_of(independent_var)) %>%
      na.omit()
    
    # Split the data into training and testing sets
    set.seed(123)
    split_ratio <- input$dataSplitslr
    training.samples <- createDataPartition(data_slr[[target_col]], p = split_ratio, list = FALSE)
    train_data <- data_slr[training.samples, ]
    test_data <- data_slr[-training.samples, ]
    
    # Fit the linear regression model
    fitted_model <- lm(reformulate(independent_var, target_col), data = train_data)
    modelslr(fitted_model)  # Update the reactive value
    
    # Print the summary of the model
    summary(fitted_model)
    # Shapiro-Wilk Test for Normality
    cat("\nShapiro-Wilk Test for Normality of Residuals:\n")
    shap_Test <- shapiro.test(fitted_model$residuals)
    print(shap_Test)
    if (shap_Test$p.value > 0.05) {
      cat("Result: Residuals appear to be normally distributed.\n")
    } else {
      cat("Result: Residuals may not be normally distributed.\n")
    }
  })
  
  
  output$ncvTest <- renderPrint({
    req(modelslr())  # Ensure modelslr is available
    fitted_model <- modelslr()  # Access the model
    
    # Perform Breusch-Pagan Test for Heteroscedasticity
    cat("\nBreusch-Pagan Test for Heteroscedasticity:\n")
    bp_test_result <- tryCatch({
      bptest(fitted_model)
    }, error = function(e) {
      cat("Error in conducting Breusch-Pagan test: ", e$message, "\n")
      NULL  # Return NULL in case of error
    })
    
    if (!is.null(bp_test_result) && !is.na(bp_test_result$p.value)) {
      print(bp_test_result)
      if (bp_test_result$p.value > 0.05) {
        cat("Result: No evidence of heteroscedasticity.\n")
      } else {
        cat("Result: There may be heteroscedasticity.\n")
      }
    } else {
      cat("Result: Breusch-Pagan test could not be conducted.\n")
    }
  })
  
  output$linearityPlotOutput <- renderPlotly({
    req(dataslr(), input$targetslr, input$independentVar)
    data_slr <- dataslr()
    target_col <- input$targetslr
    independent_var <- input$independentVar
    # Ensure the target and independent variables are available
    if (is.null(data_slr[[target_col]]) || is.null(data_slr[[independent_var]])) {
      return("Target or independent variable not found in the data.")
    }
    
    # Filter out rows where any character column is an empty string
    data_slr <- data_slr %>% dplyr::select(all_of(target_col), all_of(independent_var)) %>%
      na.omit()
    
    # Split the data into training and testing sets
    set.seed(123)
    split_ratio <- input$dataSplitslr
    training.samples <- createDataPartition(data_slr[[target_col]], p = split_ratio, list = FALSE)
    train_data <- data_slr[training.samples, ]
    test_data <- data_slr[-training.samples, ]
    
    # Fit the linear regression model
    fitted_model <- lm(reformulate(independent_var, target_col), data = train_data)
    # Create the ggplot object for the linearity plot
    ggplot_object <- ggplot(train_data, aes_string(x = independent_var, y = target_col)) +
      geom_point(color = "darkorange") +
      geom_smooth(method = "lm", se = FALSE, color = "dodgerblue") +
      ggtitle("Linearity") +
      scale_x_continuous(name = independent_var) +
      scale_y_continuous(name = target_col)
    
    # Convert ggplot object to plotly and render
    ggplotly(ggplot_object)
  })
  
  output$durbinWatsonTest <- renderPrint({
    req(modelslr())  # Ensure modelslr is available
    fitted_model <- modelslr()  # Access the model
    
    # Perform Durbin-Watson Test for Autocorrelation
    dw_test_result <- tryCatch({
      lmtest::dwtest(fitted_model)
    }, error = function(e) {
      cat("Error in conducting Durbin-Watson test: ", e$message, "\n")
      NULL  # Return NULL in case of error
    })
    
    if (!is.null(dw_test_result) && !is.na(dw_test_result$p.value)) {
      cat("\nDurbin-Watson Test for Autocorrelation:\n")
      print(dw_test_result)
      if (dw_test_result$p.value > 0.05) {
        cat("Result: No evidence of autocorrelation.\n")
      } else {
        cat("Result: There may be autocorrelation in the residuals.\n")
      }
    } else {
      cat("Result: Durbin-Watson test could not be conducted.\n")
    }
  })
  
  # Server function to create diagnostic plots
  output$residualsFittedPlot <- renderPlotly({
    req(modelslr())
    fitted_model <- modelslr()
    
    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)
  })
  
  output$qqPlot <- renderPlotly({
    req(modelslr())
    fitted_model <- modelslr()
    
    p <- ggplot(fitted_model, aes(sample = .stdresid)) +
      stat_qq(color = "darkorange") +
      stat_qq_line(color = "dodgerblue") +
      labs(title = "Normal Q-Q")
    
    ggplotly(p)
  })
  
  output$scaleLocationPlot <- renderPlotly({
    req(modelslr())
    fitted_model <- modelslr()
    
    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)
  })
  
  output$residualsLeveragePlot <- renderPlotly({
    req(modelslr())
    fitted_model <- modelslr()
    
    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)
  })
  
  
  # Define the reactive value for the data and model at the top of the server function
  dataslreva <- reactiveVal(NULL)
  modelslreva <- reactiveVal(NULL)
  test_data_slr <- reactiveVal(NULL)  
  
  # Load and clean data
  observeEvent(input$loadslr, {
    req(input$slrinput)
    file <- input$slrinput
    if (!is.null(file)) {
      data_slreva <- read_data(file$datapath)
      data_slreva <- clean_column_names(data_slreva)
      dataslreva(data_slreva)  # Update the reactive value correctly
      updateSelectInput(session, "targetslr", choices = colnames(data_slreva))
      updateSelectizeInput(session, "independentVar", choices = setdiff(colnames(data_slreva), input$targetslr))
    }
  })
  
  observeEvent(input$slrmodel, {
    req(dataslreva(), input$targetslr, input$independentVar)
    data_slreva <- dataslreva()
    target_col <- input$targetslr
    independent_var <- input$independentVar
    
    # Ensure the target and independent variables are available
    if (is.null(data_slreva[[target_col]]) || is.null(data_slreva[[independent_var]])) {
      return("Target or independent variable not found in the data.")
    }
    
    # Filter out rows with NAs and split the data
    data_slreva <- na.omit(data_slreva[, c(target_col, independent_var)])
    set.seed(123)
    split_ratio <- input$dataSplitslr
    training.samples <- createDataPartition(data_slreva[[target_col]], p = split_ratio, list = FALSE)
    train_data <- data_slreva[training.samples, ]
    test_data <- data_slreva[-training.samples, ]
    
    # Fit the linear regression model and update the reactive value
    fitted_modelslr <- lm(reformulate(independent_var, target_col), data = train_data)
    modelslreva(fitted_modelslr)
    
    # After fitting the model, update test_data_slr reactive value
    test_data_slr(test_data)  # Store test_data in the reactive value
  })
  
  output$slrmodeleva <- renderPrint({
    req(modelslreva())
    fitted_modelslr <- modelslreva()
    
    if (inherits(fitted_modelslr, "lm")) {
      # Model Summary
      cat("Model Summary:\n")
      print(summary(fitted_modelslr))
      
      # Interpretation of the key components
      cat("\nInterpretation:\n")
      cat("1. Coefficients: Estimates of the model parameters.\n")
      cat("   - Intercept: Represents the predicted value of the dependent variable when all independent variables are zero.\n")
      cat("   - Slope: Represents the change in the dependent variable for a one-unit change in the independent variable.\n")
      cat("2. Residual standard error: Measures the quality of the linear regression fit.\n")
      cat("   - Lower values indicate a better fit.\n")
      cat("3. Multiple R-squared: Indicates the proportion of variance in the dependent variable explained by the model.\n")
      cat("   - Values closer to 1 suggest a better explanatory power of the model.\n")
      cat("4. F-statistic and p-value: Test the overall significance of the model.\n")
      cat("   - A low p-value (< 0.05) indicates that the model is statistically significant.\n")
      
      # Additional specific interpretations can be added here
    } else {
      "Model has not been run or is not a linear model."
    }
  })
  
  # Render print for correlation coefficient
  output$corcoefslr <- renderPrint({
    req(modelslreva(), test_data_slr())  # Ensure model and test data are available
    fitted_modelslr <- modelslreva()
    test_data <- test_data_slr()  # Access the test data
    target_col <- input$targetslr
    independent_var <- input$independentVar
    
    # Prediction and calculation of correlation coefficient
    lm_predict <- predict(fitted_modelslr, newdata = test_data)
    actual_pred <- data.frame(actuals = test_data[[target_col]], predicted = lm_predict)
    cor_accuracy <- cor(actual_pred$actuals, actual_pred$predicted)
    
    # Output with interpretation
    cat("Correlation Coefficient between Actual and Predicted Values:\n")
    cat(cor_accuracy, "\n\n")
    
    # Interpretation of the correlation coefficient
    cat("Interpretation:\n")
    if(cor_accuracy > 0.75) {
      cat("The model has a strong positive correlation between actual and predicted values.\n")
    } else if(cor_accuracy > 0.5) {
      cat("The model has a moderate positive correlation between actual and predicted values.\n")
    } else if(cor_accuracy > 0.25) {
      cat("The model has a weak positive correlation between actual and predicted values.\n")
    } else {
      cat("The model shows little to no correlation between actual and predicted values.\n")
    }
    cat("Note: A correlation coefficient close to 1 indicates a strong positive relationship, while values closer to 0 indicate weaker relationships.\n")
  })
  
  
  output$confintslr <- renderPrint({
    req(modelslreva(), test_data_slr())  # Ensure model and test data are available
    fitted_modelslr <- modelslreva()
    test_data <- test_data_slr()  # Access the test data
    target_col <- input$targetslr
    independent_var <- input$independentVar
    
    # Model Confidence Intervals
    cat("Model Confidence Intervals (95% Level):\n")
    conf_intervals <- confint(fitted_modelslr, level=0.95)
    print(conf_intervals)
    
    cat("\nInterpretation of Model Confidence Intervals:\n")
    cat("The intervals represent the range within which the true model coefficients are likely to fall with 95% confidence.\n")
    cat("For each coefficient, the lower and upper bounds indicate the plausible range of values.\n")
    
    # Predicted Confidence Intervals for Test Data
    cat("\nPredicted Confidence Intervals for Test Data (First 10 Observations):\n")
    conf_int_predictions <- predict(fitted_modelslr, newdata = test_data, interval = 'confidence')
    print(head(conf_int_predictions, n=10))
    
    cat("\nInterpretation of Predicted Confidence Intervals:\n")
    cat("These intervals provide a range within which the true value of the dependent variable is expected to fall for each observation, with 95% confidence.\n")
    cat("The 'fit' column represents the predicted value, while 'lwr' and 'upr' represent the lower and upper bounds of the confidence interval, respectively.\n")
  })
  
  output$slrregressPlot <- renderPlotly({
    req(modelslreva(), dataslreva())
    fitted_model <- modelslreva()
    data_for_plot <- dataslreva()
    
    # Ensure the target and independent variables are provided
    target_col <- input$targetslr
    independent_var <- input$independentVar
    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)
  })
  
  ###Multiple Linear Regression
  # Define reactive values for each assumption test
  shapTestmlr <- reactiveVal()
  ncvTestmlrmlr <- reactiveVal()
  linPlotmlr <- reactiveVal()
  dWTestmlr <- reactiveVal()
  vifmlr <- reactiveVal()
  modelmlr <- reactiveVal()
  datamlr <- reactiveVal(NULL)
  modelmlreva <- reactiveVal(NULL)
  datamlreva <- reactiveVal(NULL)
  # Fix the data loading and cleaning part
  observeEvent(input$loadmlr, {
    file <- input$mlrinput
    if (!is.null(file)) {
      data_mlr <- read_data(file$datapath)
      data_mlr <- clean_column_names(data_mlr)
      datamlr(data_mlr)  # Update the reactive value correctly
      updateSelectInput(session, "targetmlr", choices = colnames(data_mlr))
      updateSelectizeInput(session, "independentVarmlr", choices = setdiff(colnames(data_mlr), input$targetmlr))
    }
  })
  
  output$mlrsummary <- renderPrint({
    req(datamlr())
    summary(datamlr())
  })
  
  # Observe the action button for triggering model fitting and assumption tests
  observeEvent(input$mlrassumption, {
    req(datamlr(), input$targetmlr, input$independentVarmlr)
    data_mlr <- datamlr()
    target_col <- input$targetmlr
    independent_vars <- input$independentVarmlr
    
    # Check if independent variables are selected
    if (length(independent_vars) == 0) {
      return("Please select independent variables.")
    }
    
    # Check for NAs and remove rows with NAs in relevant columns
    data_mlr <- na.omit(data_mlr[, c(target_col, independent_vars)])
    
    # Check if the dataset is large enough
    if (nrow(data_mlr) < 10) {
      return("Dataset is too small after removing NA values.")
    }
    
    # Ensure split ratio is valid
    split_ratio <- input$dataSplitmlr
    if (split_ratio <= 0 || split_ratio >= 1) {
      return("Invalid split ratio. Please choose a value between 0 and 1.")
    }
    
    # Partition the data
    set.seed(123)
    training.samples <- createDataPartition(data_mlr[[target_col]], p = split_ratio, list = FALSE)
    train_data <- data_mlr[training.samples, ]
    test_data <- data_mlr[-training.samples, ]
    
    # Fit the MLR model
    formula_mlr <- as.formula(paste(target_col, "~", paste(independent_vars, collapse = "+")))
    fitted_model_mlr <- lm(formula_mlr, data = train_data)
    modelmlr(fitted_model_mlr)
  })
  
  
  
  output$shapTestmlr <- renderPrint({
    req(datamlr(), input$targetmlr, input$independentVarmlr)
    data_mlr <- datamlr()
    target_col <- input$targetmlr
    independent_vars <- input$independentVarmlr
    
    # Ensure that independent variables are selected
    if (length(independent_vars) == 0) {
      return("Please select independent variables.")
    }
    
    # Concatenate independent variables into a formula string
    independent_vars_str <- paste(independent_vars, collapse = "+")
    
    # Filter out rows with NAs in relevant columns
    data_mlr_filtered <- na.omit(data_mlr[, c(target_col, independent_vars)])
    
    # Check if the dataset is sufficient after NA removal
    if (nrow(data_mlr_filtered) < 10) {
      return("Dataset is too small after removing NA values.")
    }
    
    # Split the data
    set.seed(123)
    split_ratio <- input$dataSplitmlr
    training.samples <- createDataPartition(data_mlr_filtered[[target_col]], p = split_ratio, list = FALSE)
    train_data <- data_mlr_filtered[training.samples, ]
    test_data <- data_mlr_filtered[-training.samples, ]
    
    # Fit the multiple linear regression model
    formula_mlr <- as.formula(paste(target_col, "~", independent_vars_str))
    fitted_model_mlr <- lm(formula_mlr, data = train_data)
    modelmlr(fitted_model_mlr) # Update the reactive value with the fitted model
    
    # Perform Shapiro-Wilk Test for Normality
    cat("\nShapiro-Wilk Test for Normality of Residuals:\n")
    shap_Test <- shapiro.test(residuals(fitted_model_mlr))  # Perform the test on the model's residuals
    print(shap_Test)
    
    # Interpret the test results for the user
    if (shap_Test$p.value > 0.05) {
      cat("Interpretation: With a p-value greater than 0.05, there is no statistical evidence to reject the null hypothesis that the residuals are normally distributed. 
        This suggests that the residuals of the model do not deviate significantly from a normal distribution, meeting one of the key assumptions of linear regression.\n")
    } else {
      cat("Interpretation: A p-value less than or equal to 0.05 suggests that the residuals are not normally distributed. 
        This could potentially violate the normality assumption of linear regression. In such cases, consider transforming the dependent variable, 
        adding polynomial terms or interaction effects, or using a non-linear modeling approach.\n")
    }
  })
  
  
  
  output$ncvTestmlr <- renderPrint({
    req(modelmlr())  # Ensure the MLR model is available for the test
    fitted_model <- modelmlr()  # Retrieve the fitted model
    
    # Execute the Breusch-Pagan Test for Heteroscedasticity
    cat("\nBreusch-Pagan Test for Heteroscedasticity:\n")
    bp_test_result <- tryCatch({
      bptest(fitted_model)  # bptest() function from the lmtest package
    }, error = function(e) {
      cat("Error in conducting Breusch-Pagan test: ", e$message, "\n")
      NULL  # Return NULL if there's an error to handle it gracefully
    })
    
    # Interpret the test results for the user
    if (!is.null(bp_test_result) && !is.na(bp_test_result$p.value)) {
      print(bp_test_result)
      if (bp_test_result$p.value > 0.05) {
        cat("Interpretation: With a p-value greater than 0.05, there is no statistical evidence of heteroscedasticity. 
          This suggests that the variance of residuals is constant across the levels of the independent variables, 
          which is a desirable property in regression models.\n")
      } else {
        cat("Interpretation: A p-value less than or equal to 0.05 indicates the presence of heteroscedasticity. 
          It suggests that the variance of residuals varies across levels of the independent variables. 
          This can impact the reliability of the regression coefficients' standard errors and the model's predictions. 
          Consider using weighted least squares or other forms of heteroscedasticity-consistent standard errors.\n")
      }
    } else {
      cat("Result: The Breusch-Pagan test could not be conducted. Check if the model is correctly specified, or consider other diagnostic tests for heteroscedasticity.\n")
    }
  })
  
  # Render plot for each independent variable
  output$linPlotmlr <- renderPlotly({
    req(datamlr(), modelmlr(), input$targetmlr, input$independentVarmlr)
    data_mlr <- datamlr()
    fitted_model_mlr <- modelmlr()
    independent_vars <- input$independentVarmlr
    target_col <- input$targetmlr
    
    # Generate plots for each independent variable
    plots <- lapply(independent_vars, function(var) {
      ggplot_object <- ggplot(data_mlr, aes_string(x = var, y = target_col)) +
        geom_point() +
        geom_smooth(method = "lm", se = FALSE, color = "dodgerblue") +
        labs(title = paste("Linearity with", var), x = var, y = target_col) +
        theme(
          plot.title = element_text(size = 12, hjust = 0.5),
          plot.margin = margin(5, 5, 5, 5)
        ) +
        geom_text(aes(label = var), hjust = 0, vjust = 1, size = 2.35, color = "darkorange")
      
      ggplotly(ggplot_object) %>% layout(title = paste("Linearity with", var))
    })
    
    # Combine plots (if multiple) or return single plot
    if (length(plots) > 1) {
      combined_plot <- subplot(
        plots,
        nrows = length(plots),
        shareX = TRUE,
        titleX = FALSE,
        margin = 0.05
      ) %>% layout(title = "Linearity Plots", margin = list(t = 40, b = 80, l = 40, r = 40))
      return(combined_plot)
    } else {
      return(plots[[1]])
    }
  })
  
  
  output$dWTestmlr <- renderPrint({
    req(modelmlr())  # Ensure modelmlr is available
    fitted_model <- modelmlr()  # Access the model
    
    # Perform Durbin-Watson Test for Autocorrelation
    cat("\nDurbin-Watson Test for Autocorrelation:\n")
    dw_test_result <- tryCatch({
      lmtest::dwtest(fitted_model)
    }, error = function(e) {
      cat("Error in conducting Durbin-Watson test: ", e$message, "\n")
      NULL  # Return NULL in case of error
    })
    
    # Check the test results and provide interpretation
    if (!is.null(dw_test_result) && !is.na(dw_test_result$p.value)) {
      print(dw_test_result)
      if (dw_test_result$p.value > 0.05) {
        cat("Interpretation: With a p-value greater than 0.05, there is no statistical evidence of autocorrelation in the residuals. 
          This suggests that the residuals are independent of each other, which is an assumption of the linear regression model.\n")
      } else {
        cat("Interpretation: A p-value less than or equal to 0.05 suggests that there is statistical evidence of autocorrelation in the residuals. 
          This could mean that the model is missing important predictors, there is a time series structure not accounted for, or the data is not being captured by the model adequately. 
          Consider investigating time series models, adding lagged variables, or exploring other model specifications.\n")
      }
    } else {
      cat("Result: The Durbin-Watson test could not be conducted. This could be due to computational issues or other data-related problems.\n")
    }
  })
  
  
  output$vifmlr <- renderPrint({
    # VIF - to check for multicollinearity
    # Hosmer-Lemeshow test - to check goodness of fit
    req(modelmlr())  # Ensure modelmlr is available
    fitted_model <- modelmlr()  # Access the model
    
    cat("Variance Inflation Factor (VIF) Results:\n")
    vif_results <- vif(fitted_model)
    print(vif_results)
    
    # Interpretation for the user
    if(any(vif_results > 10)) {
      cat("Note: High VIF values (greater than 10) indicate potential multicollinearity issues among predictors.\n")
      cat("This can affect the reliability of the regression coefficients. Consider removing or combining variables, or using dimensionality reduction techniques like PCA.\n")
    } else {
      cat("VIF values less than 10 are generally considered acceptable, indicating no severe multicollinearity between the predictors.\n")
    }
  })
  
  
  # Server function to create diagnostic plots
  output$resFitmlrPlot <- renderPlotly({
    req(modelmlr())
    fitted_model <- modelmlr()
    
    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)
  })
  
  ####Diagnostic Plots
  output$qqPlotmlr <- renderPlotly({
    req(modelmlr())
    fitted_model <- modelmlr()
    
    p <- ggplot(fitted_model, aes(sample = .stdresid)) +
      stat_qq(color = "darkorange") +
      stat_qq_line(color = "dodgerblue") +
      labs(title = "Normal Q-Q")
    
    ggplotly(p)
  })
  
  output$scaleLocmlrPlot <- renderPlotly({
    req(modelmlr())
    fitted_model <- modelmlr()
    
    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)
  })
  
  output$resLevmlrPlot <- renderPlotly({
    req(modelmlr())
    fitted_model <- modelmlr()
    
    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)
  })
  
  # Define the reactive value for the data and model at the top of the server function
  datamlreva <- reactiveVal(NULL)
  mlrmodeleva <- reactiveVal(NULL)
  test_data_mlr <- reactiveVal(NULL)  
  
  # Load and clean data
  observeEvent(input$loadmlr, {
    req(input$mlrinput)
    file <- input$mlrinput
    if (!is.null(file)) {
      data_mlreva <- read_data(file$datapath)
      data_mlreva <- clean_column_names(data_mlreva)
      datamlreva(data_mlreva)  # Update the reactive value correctly
      updateSelectInput(session, "targetmlr", choices = colnames(data_mlreva))
      updateSelectizeInput(session, "independentVarmlr", choices = setdiff(colnames(data_mlreva), input$targetmlr))
    }
  })
  
  observeEvent(input$mlrmodel, {
    req(datamlreva(), input$targetmlr, input$independentVarmlr)
    data_mlreva <- datamlreva()
    target_col <- input$targetmlr
    independent_vars <- input$independentVarmlr
    
    # Check if independent variables are selected
    if (length(independent_vars) == 0) {
      return("Please select independent variables.")
    }
    
    # Concatenate independent variables into one string
    independent_vars_str <- paste(independent_vars, collapse = "+")
    
    # Filter out rows with NAs and split the data
    data_mlreva <- na.omit(data_mlreva[, c(target_col, independent_vars)])
    set.seed(123)
    split_ratio <- input$dataSplitmlr
    training.samples <- createDataPartition(data_mlreva[[target_col]], p = split_ratio, list = FALSE)
    train_data <- data_mlreva[training.samples, ]
    test_data <- data_mlreva[-training.samples, ]
    
    # Fit the linear regression model
    formula_str <- paste(target_col, "~", independent_vars_str)
    fitted_modelmlr <- lm(as.formula(formula_str), data = train_data)
    modelmlreva(fitted_modelmlr)
    
    # Store test_data in the reactive value
    test_data_mlr(test_data)
  })
  
  output$mlrmodeleva <- renderPrint({
    req(modelmlreva())
    fitted_modelmlr <- modelmlreva()
    
    if (inherits(fitted_modelmlr, "lm")) {
      # Model Summary
      cat("Model Summary:\n")
      print(summary(fitted_modelmlr))
      
      # Interpretation of the key components
      cat("\nInterpretation:\n")
      cat("1. Coefficients: Estimates of the model parameters.\n")
      cat("   - Intercept: Represents the predicted value of the dependent variable when all independent variables are zero.\n")
      cat("   - Slope: Represents the change in the dependent variable for a one-unit change in the independent variable.\n")
      cat("2. Residual standard error: Measures the quality of the linear regression fit.\n")
      cat("   - Lower values indicate a better fit.\n")
      cat("3. Multiple R-squared: Indicates the proportion of variance in the dependent variable explained by the model.\n")
      cat("   - Values closer to 1 suggest a better explanatory power of the model.\n")
      cat("4. F-statistic and p-value: Test the overall significance of the model.\n")
      cat("   - A low p-value (< 0.05) indicates that the model is statistically significant.\n")
      
      # Additional specific interpretations can be added here
    } else {
      "Model has not been run or is not a linear model."
    }
  })
  
  
  # Render print for correlation coefficient
  output$corcoefmlr <- renderPrint({
    req(modelmlreva(), test_data_mlr())  # Ensure model and test data are available
    fitted_modelmlr <- modelmlreva()
    test_data <- test_data_mlr()  # Access the test data
    target_col <- input$targetmlr
    independent_vars <- input$independentVar
    
    # Prediction and calculation of correlation coefficient
    lm_predict <- predict(fitted_modelmlr, newdata = test_data)
    actual_pred <- data.frame(actuals = test_data[[target_col]], predicted = lm_predict)
    cor_accuracy <- cor(actual_pred$actuals, actual_pred$predicted)
    
    # Output with interpretation
    cat("Correlation Coefficient between Actual and Predicted Values:\n")
    cat(cor_accuracy, "\n\n")
    
    # Interpretation of the correlation coefficient
    cat("Interpretation:\n")
    if(cor_accuracy > 0.75) {
      cat("The model has a strong positive correlation between actual and predicted values.\n")
    } else if(cor_accuracy > 0.5) {
      cat("The model has a moderate positive correlation between actual and predicted values.\n")
    } else if(cor_accuracy > 0.25) {
      cat("The model has a weak positive correlation between actual and predicted values.\n")
    } else {
      cat("The model shows little to no correlation between actual and predicted values.\n")
    }
    cat("Note: A correlation coefficient close to 1 indicates a strong positive relationship, while values closer to 0 indicate weaker relationships.\n")
  })
  
  output$confintmlr <- renderPrint({
    req(modelmlreva(), test_data_mlr())  # Ensure model and test data are available
    fitted_modelmlr <- modelmlreva()
    test_data <- test_data_mlr()  # Access the test data
    target_col <- input$targetmlr
    independent_vars <- input$independentVarmlr
    
    # Model Confidence Intervals
    cat("Model Confidence Intervals (95% Level):\n")
    conf_intervals <- confint(fitted_modelmlr, level=0.95)
    print(conf_intervals)
    
    cat("\nInterpretation of Model Confidence Intervals:\n")
    cat("The intervals represent the range within which the true model coefficients are likely to fall with 95% confidence.\n")
    cat("For each coefficient, the lower and upper bounds indicate the plausible range of values.\n")
    
    # Predicted Confidence Intervals for Test Data
    cat("\nPredicted Confidence Intervals for Test Data (First 10 Observations):\n")
    conf_int_predictions <- predict(fitted_modelmlr, newdata = test_data, interval = 'confidence')
    print(head(conf_int_predictions, n=10))
    
    cat("\nInterpretation of Predicted Confidence Intervals:\n")
    cat("These intervals provide a range within which the true value of the dependent variable is expected to fall for each observation, with 95% confidence.\n")
    cat("The 'fit' column represents the predicted value, while 'lwr' and 'upr' represent the lower and upper bounds of the confidence interval, respectively.\n")
  })
  
  output$modelevamet <- renderPrint({
    req(modelmlreva(), test_data_mlr())  # Ensure model and test data are available
    fitted_modelmlr <- modelmlreva()
    test_data <- test_data_mlr()  # Access the test data
    target_col_name <- input$targetmlr
    
    # Check if the target column exists in test_data
    if (!target_col_name %in% names(test_data)) {
      cat("Target column not found in test data.\n")
      return()
    }
    
    # Predictions
    predictions <- predict(fitted_modelmlr, newdata = test_data)
    
    # Check for NA values in predictions
    if (any(is.na(predictions))) {
      cat("NA values found in predictions.\n")
      return()
    }
    
    # Calculate metrics
    R2_adj <- summary(fitted_modelmlr)$adj.r.squared  # Adjusted R-squared
    MSE <- mean((test_data[[target_col_name]] - predictions)^2, na.rm = TRUE)  # Mean Squared Error
    RMSE <- sqrt(MSE)  # Root Mean Squared Error
    MAE <- mean(abs(test_data[[target_col_name]] - predictions), na.rm = TRUE)  # Mean Absolute Error
    
    # MAPE function with check for zero values
    mape <- function(actual, predicted){
      if (any(actual == 0)) {
        cat("MAPE calculation: Actual values contain zero.\n")
        return(NA)
      }
      mean(abs((actual - predicted) / actual), na.rm = TRUE) * 100
    }
    MAPE <- mape(test_data[[target_col_name]], predictions)  # Mean Absolute Percentage Error
    
    # Output with interpretation
    cat("Multiple Linear Regression Evaluation Metrics:\n\n")
    
    cat("Adjusted R-squared:\n")
    cat("Value: ", R2_adj, "\n")
    cat("Interpretation: Adjusted R-squared accounts for the number of predictors in the model. A higher value closer to 1 indicates a strong explanatory power of the model.\n\n")
    
    cat("Mean Squared Error (MSE):\n")
    cat("Value: ", MSE, "\n")
    cat("Interpretation: MSE represents the average of the squares of the errors. Lower values indicate that the model's predictions are more accurate.\n\n")
    
    cat("Root Mean Squared Error (RMSE):\n")
    cat("Value: ", RMSE, "\n")
    cat("Interpretation: RMSE is the square root of MSE and gives an estimate of the error magnitude in the same units as the response variable. Lower values suggest a closer fit of the model to the data.\n\n")
    
    cat("Mean Absolute Error (MAE):\n")
    cat("Value: ", MAE, "\n")
    cat("Interpretation: MAE measures the average magnitude of the errors in the predictions. A lower MAE value suggests a better fit of the model to the observed data.\n\n")
    
    cat("Mean Absolute Percentage Error (MAPE):\n")
    cat("Value: ", MAPE, "\n")
    cat("Interpretation: MAPE indicates the prediction accuracy as a percentage. Lower values close to 0% indicate high predictive accuracy of the model.\n")
    
    cat("\nNote: While evaluating these metrics, it's crucial to contextualize them within the specific domain and objectives of your model. Statistical significance may not always equate to practical significance.")
    
  })
  
  output$mlrregressPlot <- renderPlotly({
    req(modelmlreva(), datamlreva(), input$targetmlr, input$independentVarmlr)
    data_for_plot <- datamlreva()
    target_col <- input$targetmlr
    independent_vars <- input$independentVarmlr
    
    # Check if variables are selected and dataset is valid
    if (is.null(data_for_plot) || is.null(data_for_plot[[target_col]]) || length(independent_vars) == 0) {
      return("Please ensure target and independent variables are selected and the dataset is valid.")
    }
    
    # Create a list of plots, one for each independent variable
    plots_list <- lapply(independent_vars, function(var) {
      p <- ggplot(data_for_plot, aes_string(x = var, y = target_col)) +
        geom_point(color = "darkorange") +
        geom_smooth(method = "lm", se = FALSE, color = "dodgerblue") +
        ggtitle(paste("Regression Line with", var)) +
        xlab(var) +
        ylab(target_col) +
        theme_minimal() +
        theme(legend.position = "none")
      ggplotly(p)
    })
    
    # Combine plots if there are multiple independent variables
    if (length(plots_list) > 1) {
      combined_plot <- subplot(plots_list, nrows = length(plots_list), shareX = TRUE, titleX = FALSE)
      return(combined_plot)
    } else {
      return(plots_list[[1]])
    }
  })
  
  
  
  
  ### Logistic Regression 
  data <- reactiveVal(NULL)
  
  observeEvent(input$loadData, {
    file <- input$glmfile
    if (!is.null(file)) {
      data_df <- read_data(file$datapath)
      data_df <- clean_column_names(data_df)
      data(data_df)
      updateSelectInput(session, "targetglm", choices = colnames(data_df))
      updateSelectizeInput(session, "independentVars", choices = setdiff(colnames(data_df), input$targetglm))
    }
  })
  
  clean_column_names <- function(dataframe) {
    colnames(dataframe) <- gsub("[^[:alnum:]_]", "", make.names(colnames(dataframe), unique = TRUE))
    return(dataframe)
  }
  
  output$dataSummary <- renderPrint({
    req(data())
    summary(data())
  })
  
  output$glmassumption <- renderPrint({
    req(data())
    target_col <- input$targetglm
    independent_vars <- input$independentVars
    data_df <- data()  # Original data
    
    # Check if the target column is numeric and mutate it
    if (is.numeric(data_df[[target_col]])) {
      median_val <- median(data_df[[target_col]], na.rm = TRUE)
      data_df[[target_col]] <- as.factor(ifelse(data_df[[target_col]] < median_val, "No", "Yes"))
    }
    
    # Filter out rows where any character column is an empty string
    data_df <- data_df %>% dplyr::select(all_of(target_col), all_of(independent_vars)) %>%
      na.omit()
    
    # Example: Splitting the data, normalizing, and running glm
    set.seed(123)
    split_ratio <- input$dataSplit
    training.samples <- createDataPartition(data_df[[target_col]], p = split_ratio, list = FALSE)
    train_data <- data_df[training.samples, ]
    test_data <- data_df[-training.samples, ]
    
    train_data <- normalize(train_data, method = "standardize", range = c(0, 1), margin = 1L, on.constant = "quiet")
    test_data <- normalize(test_data, method = "standardize", range = c(0, 1), margin = 1L, on.constant = "quiet")
    
    formula <- as.formula(paste(target_col, "~", paste(independent_vars, collapse = "+")))
    x <- as.matrix(train_data[, setdiff(names(train_data), target_col)]) 
    y <- train_data[[target_col]]
    # Fit a standard logistic regression model with increased max iterations
    glm_model <- glm(formula, data = train_data, family = binomial(), 
                     control = glm.control(maxit = 50))  # Increase max iterations
    
    # Check if the model has converged
    if(!glm_model$converged) {
      cat("Warning: The logistic regression model did not converge.\n")
    }
    
    # VIF - to check for multicollinearity
    # Hosmer-Lemeshow test - to check goodness of fit
    cat("Variance Inflation Factor (VIF) Results:\n")
    vif_results <- vif(glm_model)
    print(vif_results)
    if(any(vif_results > 10)) {
      cat("Note: High VIF values indicate potential multicollinearity issues among predictors.\n")
    }
    
    cat("\nHosmer-Lemeshow Goodness of Fit Test:\n")
    tryCatch({
      hl_test <- hoslem.test(glm_model$y, fitted(glm_model), g = 5)  # Adjusted g value
      print(hl_test)
    }, error = function(e) {
      cat("Note: Hosmer-Lemeshow test could not be conducted. This may indicate issues with model fit or data.\n")
    })
  })
  
  observeEvent(input$runLogisticRegression, {
    req(data())
    target_col <- input$targetglm
    independent_vars <- input$independentVars
    data_df <- data()  # Original data
    
    
    # Check if the target column is numeric and mutate it
    if (is.numeric(data_df[[target_col]])) {
      median_val <- median(data_df[[target_col]], na.rm = TRUE)
      data_df[[target_col]] <- as.factor(ifelse(data_df[[target_col]] < median_val, "No", "Yes"))
    }
    
    # Rest of your code...
    
    # Filter out rows where any character column is an empty string
    data_df <- data_df %>% dplyr::select(all_of(target_col), all_of(independent_vars)) %>%
      na.omit()
    
    # Example: Splitting the data, normalizing, and running glm
    set.seed(123)
    split_ratio <- input$dataSplit
    training.samples <- createDataPartition(data_df[[target_col]], p = split_ratio, list = FALSE)
    train_data <- data_df[training.samples, ]
    test_data <- data_df[-training.samples, ]
    
    train_data <- normalize(train_data, method = "standardize", range = c(0, 1), margin = 1L, on.constant = "quiet")
    test_data <- normalize(test_data, method = "standardize", range = c(0, 1), margin = 1L, on.constant = "quiet")
    
    formula <- as.formula(paste(target_col, "~", paste(independent_vars, collapse = "+")))
    x <- as.matrix(train_data[, setdiff(names(train_data), target_col)]) 
    y <- train_data[[target_col]]
    # Perform cross-validation to find the optimal lambda
    cv_model <- cv.glmnet(x, y, family = "binomial", alpha = 1)
    
    # Extract the coefficients at the optimal lambda
    optimal_lambda <- cv_model$lambda.min
    
    # Extract coefficients at the optimal lambda
    coefficients <- coef(cv_model, s = optimal_lambda)
    
    # Convert the sparse matrix to a regular matrix and then to a dataframe
    coef_matrix <- as.matrix(coefficients)
    coef_df <- as.data.frame(coef_matrix)
    
    # Give meaningful names to the dataframe columns
    names(coef_df) <- c("Coefficients")
    rownames(coef_df) <- names(coefficients)
    
    # Assuming 'model' is your trained glmnet model, and 'test_data' is your test dataset
    # Prepare test data for prediction
    x_test <- as.matrix(test_data[, independent_vars])  # independent variables
    y_test <- as.factor(test_data[[target_col]])        # actual outcomes
    
    # Predict using the model
    predictions <- predict(cv_model, newx = x_test, type = "response", s = optimal_lambda)
    
    # Convert predictions to a binary factor based on a threshold (e.g., 0.5)
    predicted_class <- ifelse(predictions > 0.5, "Yes", "No")
    
    # Calculate accuracy
    accuracy <- mean(predicted_class == y_test)
    # Get predicted probabilities (make sure to use 'type = "response"')
    predicted_probs <- predict(cv_model, newx = x_test, type = "response", s = optimal_lambda)
    
    # Calculate AUC
    roc_curve <- roc(response = y_test, predictor = as.numeric(predicted_probs))
    auc_value <- auc(roc_curve)
    
    # Convert predicted classes and actual outcomes to factor if they are not already
    predicted_class <- factor(predicted_class, levels = c("No", "Yes"))
    y_test <- factor(y_test, levels = c("No", "Yes"))
    
    # Calculate the confusion matrix
    conf_matrix <- confusionMatrix(predicted_class, y_test)
    
    # Creating a prediction object for ROC analysis
    pred <- ROCR::prediction(predicted_probs, y_test)
    
    # Creating a performance object for ROC curve
    perf <- ROCR::performance(pred, "tpr", "fpr")
    
    # Calculating AUC
    auc_value <- ROCR::performance(pred, "auc")@y.values[[1]]
    
    # Output coefficients and optimal lambda
    output$logisticOutput <- renderPrint({
      cat("Optimal Lambda Value:", optimal_lambda, "\n")
      cat("This is the value of the regularization parameter lambda that minimizes the cross-validated error.\n\n")
      
      cat("Coefficients:\n")
      print(coef_df)
      cat("Each coefficient represents the change in the log odds of the outcome for a one-unit change in the predictor variable.\n\n")
      
      cat("Accuracy:", accuracy, "\n")
      cat("This is the proportion of correctly predicted instances out of the total instances in the dataset.\n\n")
      
      cat("AUC (Area Under the Curve):", auc_value, "\n")
      cat("AUC ranges from 0 to 1 with higher values indicating better model performance. A model with an AUC close to 0.5 has no discriminative ability.\n\n")
      
      cat("Confusion Matrix:\n")
      print(conf_matrix$table)
      cat("The confusion matrix shows the number of correct and incorrect predictions compared with the actual outcomes.\n")
      cat("- True Positives (TP): Actual Yes predicted as Yes\n")
      cat("- False Positives (FP): Actual No predicted as Yes\n")
      cat("- True Negatives (TN): Actual No predicted as No\n")
      cat("- False Negatives (FN): Actual Yes predicted as No\n\n")
      
      cat("Additional Metrics:\n")
      cat("- Sensitivity (True Positive Rate): ", conf_matrix$byClass['Sensitivity'], "\n")
      cat("  The proportion of actual positives that were correctly identified.\n")
      cat("- Specificity (True Negative Rate): ", conf_matrix$byClass['Specificity'], "\n")
      cat("  The proportion of actual negatives that were correctly identified.\n")
      cat("- Positive Predictive Value (Precision): ", conf_matrix$byClass['Positive Predictive Value'], "\n")
      cat("  The proportion of positive identifications that were actually correct.\n")
      cat("- Negative Predictive Value: ", conf_matrix$byClass['Negative Predictive Value'], "\n")
      cat("  The proportion of negative identifications that were actually correct.\n")
      cat("- F1 Score: ", conf_matrix$byClass['F1'], "\n")
      cat("  The harmonic mean of Precision and Sensitivity, useful for unbalanced classes.\n")
    })
    
    
    output$glmcvplot <- renderPlotly({
      req(cv_model)  # Ensure cv_model is available
      
      # Extract necessary data from cv_model
      lambda <- cv_model$lambda
      cvm <- cv_model$cvm
      cvsd <- cv_model$cvsd
      
      # Create a plotly plot
      plot_ly(x = lambda, y = cvm, type = 'scatter', mode = 'lines') %>%
        add_trace(y = cvm + cvsd, name = 'Upper CI', mode = 'lines', line = list(dash = 'dash')) %>%
        add_trace(y = cvm - cvsd, name = 'Lower CI', mode = 'lines', line = list(dash = 'dash')) %>%
        layout(
          xaxis = list(type = 'log', title = 'Lambda'),
          yaxis = list(title = 'Cross-Validated Error'),
          title = 'Cross-Validation Plot for GLMNET Model'
        )
    })
    
    # Render AUC plot in Shiny
    output$glmaucplot <- renderPlotly({
      # Ensure the performance object is available
      req(perf, auc_value)
      
      # Prepare the data for the plot
      data <- data.frame(
        FPR = perf@x.values[[1]],
        TPR = perf@y.values[[1]]
      )
      
      # Create the ROC curve plot with Plotly
      p <- plot_ly(data, x = ~FPR, y = ~TPR, type = 'scatter', mode = 'lines', 
                   line = list(color = 'blue'), name = 'ROC Curve') %>%
        add_trace(x = 0:1, y = 0:1, type = 'scatter', mode = 'lines', 
                  line = list(color = 'red', dash = 'dash'), name = 'Chance') %>%
        layout(title = paste("ROC Curve (AUC =", round(auc_value, 2), ")"),
               xaxis = list(title = "False Positive Rate"),
               yaxis = list(title = "True Positive Rate"))
      
      return(p)
    })
  })
  
  read_data <- function(filepath) {
    ext <- tools::file_ext(filepath)
    if (ext %in% c("csv", "xlsx")) {
      if (ext == "csv") {
        read.csv(filepath, stringsAsFactors = FALSE)
      } else if (ext == "xlsx") {
        read_excel(filepath)
      }
    } else {
      stop("Invalid file format. Please select a CSV or XLSX file.")
    }
  }
  
  ###Decision Tree
  # Reactive values for the decision tree model and training data
  treedecision <- reactiveVal(NULL)
  train_data_rv <- reactiveVal(NULL)
  train_data_reactive <- reactiveVal(NULL)
  target_col_rv <- reactiveVal(NULL)
  test_data_reactive <- reactiveVal(NULL)
  
  # Define the function to clean column names
  cl_column_names <- function(dataframe) {
    colnames(dataframe) <- gsub("[^[:alnum:]_]", "", make.names(colnames(dataframe), unique = TRUE))
    return(dataframe)
  }
  
  # Reactive expression to read and process the data
  datadectree <- reactive({
    req(input$treedecfile)
    inFile <- input$treedecfile
    ext <- tools::file_ext(inFile$name)
    if (ext == "csv") {
      df <- read.csv(inFile$datapath, stringsAsFactors = FALSE, na.strings = c("", "NA", "na"))
    } else if (ext == "xlsx") {
      df <- readxl::read_xlsx(inFile$datapath, na = c("", "NA", "na"))
    }
    cl_column_names(df)
  })
  
  # Observer to update the select inputs
  observe({
    req(datadectree())
    updateSelectInput(session, "targetdectree", choices = names(datadectree()))
  })
  
  observe({
    req(input$targetdectree)
    target_col_rv(input$targetdectree)
  })
  
  output$dataSummarydt <- renderPrint({
    req(datadectree())
    summary(datadectree())
  })
  
  # Define the reactive expression for train data
  train_data_reactive <- reactive({
    req(datadectree())
    data_df <- datadectree()
    target_col <- target_col_rv()  # Use the reactive value
    
    # Numeric to factor conversion (if necessary)
    if (is.numeric(data_df[[target_col]])) {
      median_val <- median(data_df[[target_col]], na.rm = TRUE)
      data_df[[target_col]] <- as.factor(ifelse(data_df[[target_col]] < median_val, "No", "Yes"))
    }
    
    # Filter out rows with NA and split the data
    data_df <- data_df %>% filter(!is.na(.[[target_col]]))
    set.seed(123)
    split_ratio <- input$dataSplittree
    training.samples <- createDataPartition(data_df[[target_col]], p = split_ratio, list = FALSE)
    train_data <- data_df[training.samples, ]
    train_data_rv(train_data)  # This line was missing
    return(train_data)
  })
  
  
  # Trigger to fit the decision tree model
  observeEvent(input$rundectree, {
    req(train_data_reactive())
    local_train_data <- train_data_rv()  # Now it will have the updated data
    
    # Fit the decision tree model
    tree_formula <- as.formula(paste(target_col_rv(), "~ ."))
    treedecision(tree(tree_formula, data = local_train_data))  # Ensure local_train_data is correctly passed
  })
  
  # Summarize the decision tree model
  output$rundectree <- renderPrint({
    req(treedecision())
    decision_tree_model <- treedecision()  # Retrieve the decision tree model
    
    # Check if the decision tree model is correctly retrieved
    if(is.null(decision_tree_model)) {
      cat("Decision tree model is not available.\n")
      return()
    }
    
    # Print model summary
    cat("Decision Tree Model Summary:\n\n")
    tryCatch({
      print(summary(decision_tree_model))
    }, error = function(e) {
      cat("Error in printing model summary: ", e$message, "\n")
    })
    
    cat("\nInterpretation:\n")
    cat("1. Node Number: Each number represents a node in the tree.\n")
    cat("2. Split Variable: The variable used to split the node. If 'leaf', it indicates the node is a terminal node (leaf).\n")
    cat("3. Split Point: The value of the split variable that divides the node.\n")
    cat("4. n: The number of observations in the node.\n")
    cat("5. Deviance: Measures the variability of the response variable within the node. Lower values indicate better model fit.\n")
    cat("6. Prediction: The predicted class (or value for regression trees) for each node.\n")
    
    cat("\nHow to Read the Tree:\n")
    cat("- Start at the top node (Root Node) and make decisions based on the split variables and points.\n")
    cat("- Follow the branches to reach the leaf nodes, which contain the final predictions.\n")
    cat("- Each path from the root to a leaf represents a decision rule.\n")
    
    cat("\nNote:\n")
    cat("- A simpler tree (fewer nodes) with good predictive accuracy is generally preferable to avoid overfitting.\n")
    cat("- Decision trees are intuitive but can become complex with many splits (consider pruning if needed).\n")
  })
  
  # Tree Plot
  output$dectreeplot <- renderPlot({
    req(treedecision())
    plot(treedecision())
    text(treedecision(), pretty = 0)
  })
  
  # Cross-validation Plot
  # Define cv_errors as a reactive expression
  cv_errors <- reactive({
    local_train_data <- train_data_rv()  # Your dataset
    req(local_train_data)
    
    target_column <- target_col_rv()  # Your target column
    req(target_column)
    
    folds <- createFolds(local_train_data[[target_column]], k = 10, list = TRUE)
    errors <- numeric(length(folds))
    
    for(i in seq_along(folds)) {
      training_set <- local_train_data[-folds[[i]], ]
      testing_set <- local_train_data[folds[[i]], ]
      
      # Assuming that your model formula is correct and uses the target column
      tree_model <- tree(paste(target_column, "~ ."), data = training_set)
      
      predictions <- predict(tree_model, testing_set, type = "class")
      errors[i] <- mean(predictions != testing_set[[target_column]])
    }
    
    return(errors)  # Return the vector of errors
  })
  
  # Plot for cross-validation errors
  output$cvplot <- renderPlot({
    errors <- cv_errors()  # Retrieve the vector of CV errors
    req(errors)  # Make sure errors are available before proceeding
    
    # Plot the errors against fold numbers
    plot(seq_along(errors), errors, type = "b",
         xlab = "Fold Number", ylab = "Misclassification Error",
         main = "Cross-Validation Error by Fold")
  })
  
  #Pruned Tree
  # Define pruned_dtree as a reactive expression
  pruned_dtree <- reactive({
    decision_tree_model <- treedecision()
    req(decision_tree_model)
    req(cv_errors())  # Access cv_errors as a reactive expression
    
    optimal_size <- which.min(cv_errors())
    prune.tree(decision_tree_model, best = optimal_size)
  })
  
  # Pruned Tree Plot
  output$pruneddtree <- renderPlot({
    req(pruned_dtree())
    plot(pruned_dtree())
    text(pruned_dtree(), pretty = 0)
  })
  
  
  # Confusion Matrix
  output$confMatrix <- renderPrint({
    req(treedecision(), train_data_rv())
    local_train_data <- train_data_rv()
    
    # Prediction
    tree_pred <- tryCatch({
      predict(treedecision(), local_train_data, type = "class")
    }, error = function(e) {
      cat("Error in prediction:", e$message, "\n")
      return(NULL)
    })
    
    # Ensure tree_pred and the target column have the same length
    if (length(tree_pred) != nrow(local_train_data)) {
      cat("Error: Prediction length does not match the number of rows in training data.\n")
      return()
    }
    
    # Compute the confusion matrix
    cm <- table(tree_pred, local_train_data[[target_col_rv()]])
    
    # Print the confusion matrix
    cat("Confusion Matrix:\n")
    print(cm)
    
    cat("The confusion matrix shows the number of correct and incorrect predictions compared with the actual outcomes.\n")
    cat("- True Positives (TP): Actual Yes predicted as Yes\n")
    cat("- False Positives (FP): Actual No predicted as Yes\n")
    cat("- True Negatives (TN): Actual No predicted as No\n")
    cat("- False Negatives (FN): Actual Yes predicted as No\n\n")
    
    cat("Additional Metrics:\n")
    cat("- Sensitivity (True Positive Rate): ", "\n")
    cat("  The proportion of actual positives that were correctly identified.\n")
    cat("- Specificity (True Negative Rate): ", "\n")
    cat("  The proportion of actual negatives that were correctly identified.\n")
    cat("- Positive Predictive Value (Precision): ", "\n")
    cat("  The proportion of positive identifications that were actually correct.\n")
    cat("- Negative Predictive Value: ",  "\n")
    cat("  The proportion of negative identifications that were actually correct.\n")
    cat("- F1 Score: ", "\n")
    cat("  The harmonic mean of Precision and Sensitivity, useful for unbalanced classes.\n")
    
    # Interpretation of the confusion matrix
    cat("\nInterpretation:\n")
    cat("- Each row of the matrix represents the instances in a predicted class.\n")
    cat("- Each column represents the instances in an actual class.\n")
    cat("- The diagonal elements (top left to bottom right) represent the number of correct classifications.\n")
    cat("- Off-diagonal elements are those that were misclassified by the model.\n")
    cat("- Higher values on the diagonal indicate better performance.\n")
    
    # Additional specific interpretations can be added here based on the context and the data
  })
  
  
  # Define the reactive expression for train data
  test_data_reactive <- reactive({
    req(datadectree(), input$targetdectree, input$dataSplittree)
    data_df <- datadectree()
    target_col <- target_col_rv()  # Use the reactive value
    
    # Numeric to factor conversion (if necessary)
    if (is.numeric(data_df[[target_col]])) {
      median_val <- median(data_df[[target_col]], na.rm = TRUE)
      data_df[[target_col]] <- as.factor(ifelse(data_df[[target_col]] < median_val, "No", "Yes"))
    }
    
    data_df <- data_df %>% filter(!is.na(.[[target_col]]))
    # Split the data into training and testing sets
    set.seed(123)  # It's good you're setting a seed for reproducibility
    split_ratio <- input$dataSplittree  # The ratio for splitting, e.g., 0.7 for 70% training data
    training.samples <- createDataPartition(data_df[[target_col]], p = split_ratio, list = FALSE)
    
    # Assuming that training.samples is a vector of indices for the training set
    test_data <- data_df[-training.samples, ]  # Use negative indexing to get the test set
    return(test_data)
  })
  
  
  
  # Assuming 'predictions' and 'local_eval_data' are available as they were in the previous step
  output$cfdtpteva <- renderPrint({
    # Retrieve the pruned decision tree model
    pruned_model <- pruned_dtree()
    req(pruned_model)
    
    # Retrieve the evaluation dataset from the reactive expression
    local_eval_data <- test_data_reactive()  # Using test_data_reactive
    req(local_eval_data)
    
    # Make predictions using the pruned tree model
    predictions <- predict(pruned_model, local_eval_data, type = "class")
    
    # Generate the confusion matrix
    cm <- table(True = local_eval_data[[target_col_rv()]], Predicted = predictions)
    
    # Calculate metrics
    accuracy <- sum(diag(cm)) / sum(cm)
    precision <- cm[2, 2] / sum(cm[2, ])
    recall <- cm[2, 2] / sum(cm[, 2])
    F1_score <- 2 * precision * recall / (precision + recall)
    
    # Print the evaluation metrics
    cat("Confusion Matrix:\n")
    print(cm)
    cat("\n")
    cat("Accuracy:", accuracy, "\n")
    cat("Precision:", precision, "\n")
    cat("Recall:", recall, "\n")
    cat("F1 Score:", F1_score, "\n")
    
    # Enhanced interpretation
    cat("\nDetailed Interpretation and Decision Insights:\n")
    cat("1. Accuracy reflects the overall correctness of the model and is a good initial indicator of performance. However, it may not fully capture the nuances in imbalanced datasets.\n")
    cat("2. Precision measures the reliability of the model's positive predictions. High precision indicates that when the model predicts a positive outcome, it is likely correct. This is critical in scenarios where false positives carry a high cost.\n")
    cat("3. Recall assesses the model's ability to detect all relevant cases. High recall means the model is effective at capturing the majority of positive instances, which is crucial in situations where missing a positive case is detrimental.\n")
    cat("4. F1 Score provides a balance between precision and recall. A high F1 score suggests the model effectively balances the trade-off between not missing positive cases and maintaining high accuracy in its positive predictions.\n")
    cat("\n")
    
    cat("Decision-Making Insights:\n")
    cat("- The model's performance should be considered in the context of your specific application. For instance, if missing a positive case has serious consequences, prioritize improving recall.\n")
    cat("- If your focus is on the accuracy of the positive predictions (to avoid false alarms or unnecessary actions), aim to improve precision.\n")
    cat("- The F1 Score is particularly informative when you need a single metric to assess the model's balance between precision and recall, especially in cases of class imbalance.\n")
    cat("- Consider the model's limitations and strengths in the context of your dataset, and use these insights to guide your decision-making process or further model refinement.\n")
    cat("\n")
    cat("Remember, no model is perfect. It's crucial to continuously evaluate the model's performance in real-world scenarios and update it as new data becomes available to ensure its ongoing effectiveness.\n")
  })
  
  ###Random Forest
  datarf <- reactiveVal(NULL)
  rf_model_reactive <- reactiveVal()
  pred_rf_reactive <- reactiveVal()
  results_reactive <- reactiveVal()
  # Load and clean data
  observeEvent(input$loadrf, {
    req(input$rfinput)
    file <- input$rfinput
    if (!is.null(file)) {
      # Reading and cleaning data
      data_df <- read_data(file$datapath)
      data_df <- clean_column_names(data_df)
      
      # Setting the reactive value
      datarf(data_df)
      
      # Updating UI elements
      updateSelectInput(session, "targetrf", choices = colnames(data_df))
      updateSelectizeInput(session, "independentVarrf", choices = setdiff(colnames(data_df), input$targetrf))
    }
  })
  
  
  output$dataSummaryrf <- renderPrint({
    req(datarf())
    summary(datarf())
  })
  
  
  observeEvent(input$runrf, {
    req(datarf(), input$targetrf, input$independentVarrf)
    
    data_rf <- datarf() %>%
      dplyr::select(all_of(c(input$targetrf, input$independentVarrf))) %>%
      na.omit()
    withProgress(message = 'Model is being trained...', value = 0, {
      # Increment progress
      incProgress(0.1)  # Initial progress
      # Early return if conditions are not met
      if (length(input$independentVarrf) == 0) {
        output$modelOutputrf <- renderPrint({ "Please select independent variables." })
        return()
      }
      
      if (nrow(data_rf) < 10) {
        output$modelOutputrf <- renderPrint({ "Dataset is too small after removing NA values." })
        return()
      }
      
      split_ratio <- input$dataSplitrf
      if (split_ratio <= 0 || split_ratio >= 1) {
        output$modelOutputrf <- renderPrint({ "Invalid split ratio. Please choose a value between 0 and 1." })
        return()
      }
      incProgress(0.3)  # Increment progress
      # Partition the data
      set.seed(123)
      train <- data_rf %>% sample_frac(split_ratio)
      test <- data_rf %>% setdiff(train)
      incProgress(0.6)  # Increment progress
      formula_rf <- as.formula(paste(input$targetrf, "~", paste(input$independentVarrf, collapse = "+")))
      # Fit the Random Forest model
      rf_model <- randomForest(formula_rf,
                               data = train, 
                               mtry = input$mtryInput, 
                               ntree = input$ntreeInput)
      
      rf_model_reactive(rf_model)
      
      # Model summary
      output$runrf <- renderPrint({
        print(rf_model)
        
        # Feature Importance
        cat("Feature Importance:\n")
        importance_vals <- importance(rf_model)
        print(importance_vals)
        
      })
      # Finalize progress
      incProgress(1.0)  # Complete the progress
    })
  })
  
  output$importancePlot <- renderPlotly({
    req(datarf(), input$targetrf, input$independentVarrf)
    
    # Access the model from the reactive value
    rf_model <- rf_model_reactive()
    req(rf_model)  # Ensure the model is available
    
    # Extracting feature importance
    importance_vals <- importance(rf_model)
    
    # Converting to a data frame for plotting
    importance_df <- as.data.frame(importance_vals)
    importance_df$Feature <- rownames(importance_df)
    
    # For example, if the correct column name is "Importance"
    ggplot(importance_df, aes(x = reorder(Feature, IncNodePurity), y = IncNodePurity)) +
      geom_bar(stat = "identity", fill = "dodgerblue") +
      theme_minimal() +
      coord_flip() +  # Flipping coordinates for horizontal bars
      labs(title = "Feature Importance", x = "Features", y = "Importance")
  })
  
  # Define the Mean Squared Error function
  mse <- function(actual, predicted) {
    mean((actual - predicted) ^ 2)
  }
  
  # Define the Mean Absolute Error function
  mae <- function(actual, predicted) {
    mean(abs(actual - predicted))
  }
  
  observeEvent(input$predictBtn, {
    req(datarf(), input$targetrf, input$independentVarrf)
    data_rf <- datarf() %>%
      dplyr::select(all_of(c(input$targetrf, input$independentVarrf))) %>%
      na.omit()
    
    withProgress(message = 'Model is being trained...', value = 0, {
      # Increment progress
      incProgress(0.1)  # Initial progress
      # Early return if conditions are not met
      if (length(input$independentVarrf) == 0) {
        output$modelOutputrf <- renderPrint({ "Please select independent variables." })
        return()
      }
      
      if (nrow(data_rf) < 10) {
        output$modelOutputrf <- renderPrint({ "Dataset is too small after removing NA values." })
        return()
      }
      
      split_ratio <- input$dataSplitrf
      if (split_ratio <= 0 || split_ratio >= 1) {
        output$modelOutputrf <- renderPrint({ "Invalid split ratio. Please choose a value between 0 and 1." })
        return()
      }
      incProgress(0.3)  # Increment progress
      # Partition the data
      set.seed(123)
      train <- data_rf %>% sample_frac(split_ratio)
      test <- data_rf %>% setdiff(train)
      
      # Assuming train dataset is already prepared
      control <- trainControl(method="cv", number=10)
      tunegrid <- expand.grid(.mtry = input$mtryInput)
      set.seed(2)
      formula_rf <- as.formula(paste(input$targetrf, "~", paste(input$independentVarrf, collapse = "+")))
      rf_model <- randomForest(formula_rf, 
                               data=train,
                               metric="RMSE", 
                               tuneGrid=tunegrid, 
                               ntree = input$ntreeInput,
                               trControl=control,
                               importance = TRUE)
      
      # Make predictions for the entire dataset
      pred_rf <- predict(rf_model, newdata = train)
      
      # Calculate metrics
      MSE_rf <- mse(actual = train[[input$targetrf]], predicted = pred_rf)
      
      # For R_square_rf, ensure you have a function or package that provides R2
      R_square_rf <- R2(pred_rf, train[[input$targetrf]])
      
      # For MAE_rf, ensure you have a function or package that provides mae
      MAE_rf <- mae(actual = train[[input$targetrf]], predicted = pred_rf)
      
      output$predictionOutput <- renderPrint({
        cat("Mean Squared Error (MSE):\n\n", MSE_rf, "\n\n", "Interpretation: MSE measures the average squared difference between actual and predicted values. 
          Lower values indicate better model performance. 
          A value of 0 means perfect predictions.")
        cat("\n\nR-squared (R²):\n\n", R_square_rf, "\n\n", "Interpretation: R² represents the proportion of variance in the dependent variable that's predictable from the independent variables. 
          It ranges from 0 to 1, with higher values indicating better model fit.")
        cat("\n\nMean Absolute Error (MAE):\n\n", MAE_rf, "\n\n", "Interpretation: MAE measures the average absolute difference between actual and predicted values. 
          Like MSE, lower MAE values indicate better model performance.")
      })
      # Finalize progress
      incProgress(1.0)  # Complete the progress
      # Store results in a reactive value
      results_reactive(list(actual = train[[input$targetrf]], predicted = pred_rf))
    })
  })
  
  output$performancePlot <- renderPlotly({
    # Access the stored results
    results <- results_reactive()
    req(results)  # Ensure results are available
    
    # Creating the plot
    plot_data <- data.frame(Actual = results$actual, Predicted = results$predicted)
    p <- ggplot(plot_data, aes(x = Actual, y = Predicted)) +
      geom_point(alpha = 0.5) +
      geom_abline(intercept = 0, slope = 1, color = "red", linetype = "dashed") +
      labs(x = "Actual Values", y = "Predicted Values", title = "Actual vs. Predicted Values") +
      theme_minimal()
    
    ggplotly(p)
  })
  
  datarf <- reactiveVal(NULL)
  rf_model_reactive <- reactiveVal()
  pred_rf_reactive <- reactiveVal()
  results_reactive <- reactiveVal()
  # Load and clean data
  observeEvent(input$loadrf, {
    req(input$rfinput)
    file <- input$rfinput
    if (!is.null(file)) {
      # Reading and cleaning data
      data_df <- read_data(file$datapath)
      data_df <- clean_column_names(data_df)
      
      # Setting the reactive value
      datarf(data_df)
      
      # Updating UI elements
      updateSelectInput(session, "targetrf", choices = colnames(data_df))
      updateSelectizeInput(session, "independentVarrf", choices = setdiff(colnames(data_df), input$targetrf))
    }
  })
  
  
  output$dataSummaryrf <- renderPrint({
    req(datarf())
    summary(datarf())
  })
  
  
  observeEvent(input$runrf, {
    req(datarf(), input$targetrf, input$independentVarrf)
    
    data_rf <- datarf() %>%
      dplyr::select(all_of(c(input$targetrf, input$independentVarrf))) %>%
      na.omit()
    withProgress(message = 'Model is being trained...', value = 0, {
      # Increment progress
      incProgress(0.1)  # Initial progress
      # Early return if conditions are not met
      if (length(input$independentVarrf) == 0) {
        output$modelOutputrf <- renderPrint({ "Please select independent variables." })
        return()
      }
      
      if (nrow(data_rf) < 10) {
        output$modelOutputrf <- renderPrint({ "Dataset is too small after removing NA values." })
        return()
      }
      incProgress(0.3)  # Increment progress
      split_ratio <- input$dataSplitrf
      if (split_ratio <= 0 || split_ratio >= 1) {
        output$modelOutputrf <- renderPrint({ "Invalid split ratio. Please choose a value between 0 and 1." })
        return()
      }
      
      # Partition the data
      set.seed(123)
      train <- data_rf %>% sample_frac(split_ratio)
      test <- data_rf %>% setdiff(train)
      
      # Fit the Random Forest model
      formula_rf <- as.formula(paste(input$targetrf, "~", paste(input$independentVarrf, collapse = "+")))
      incProgress(0.6)  # Increment progress
      # Fit the Random Forest model
      rf_model <- randomForest(formula_rf, 
                               data = train, 
                               mtry = input$mtryInput, 
                               ntree = input$ntreeInput)
      
      rf_model_reactive(rf_model)
      
      # Model summary
      output$runrf <- renderPrint({
        print(rf_model)
        
        # Feature Importance
        cat("Feature Importance:\n")
        importance_vals <- importance(rf_model)
        print(importance_vals)
        
      })
      # Finalize progress
      incProgress(1.0)  # Complete the progress
    })
  })
  
  output$importancePlot <- renderPlotly({
    req(datarf(), input$targetrf, input$independentVarrf)
    
    # Access the model from the reactive value
    rf_model <- rf_model_reactive()
    req(rf_model)  # Ensure the model is available
    
    # Extracting feature importance
    importance_vals <- importance(rf_model)
    
    # Converting to a data frame for plotting
    importance_df <- as.data.frame(importance_vals)
    importance_df$Feature <- rownames(importance_df)
    
    # For example, if the correct column name is "Importance"
    ggplot(importance_df, aes(x = reorder(Feature, IncNodePurity), y = IncNodePurity)) +
      geom_bar(stat = "identity", fill = "dodgerblue") +
      theme_minimal() +
      coord_flip() +  # Flipping coordinates for horizontal bars
      labs(title = "Feature Importance", x = "Features", y = "Importance")
  })
  
  # Define the Mean Squared Error function
  mse <- function(actual, predicted) {
    mean((actual - predicted) ^ 2)
  }
  
  # Define the Mean Absolute Error function
  mae <- function(actual, predicted) {
    mean(abs(actual - predicted))
  }
  
  observeEvent(input$predictBtn, {
    req(datarf(), input$targetrf, input$independentVarrf)
    data_rf <- datarf() %>%
      dplyr::select(all_of(c(input$targetrf, input$independentVarrf))) %>%
      na.omit()
    withProgress(message = 'Model is being trained...', value = 0, {
      # Increment progress
      incProgress(0.1)  # Initial progress
      
      # Early return if conditions are not met
      if (length(input$independentVarrf) == 0) {
        output$modelOutputrf <- renderPrint({ "Please select independent variables." })
        return()
      }
      incProgress(0.3)  # Increment progress
      if (nrow(data_rf) < 10) {
        output$modelOutputrf <- renderPrint({ "Dataset is too small after removing NA values." })
        return()
      }
      
      split_ratio <- input$dataSplitrf
      if (split_ratio <= 0 || split_ratio >= 1) {
        output$modelOutputrf <- renderPrint({ "Invalid split ratio. Please choose a value between 0 and 1." })
        return()
      }
      
      # Assuming train dataset is already prepared
      control <- trainControl(method="cv", number=10)
      tunegrid <- expand.grid(.mtry = input$mtryInput)
      # Partition the data
      set.seed(2)
      train <- data_rf %>% sample_frac(split_ratio)
      test <- data_rf %>% setdiff(train)
      incProgress(0.6)  # Increment progress
      formula_rf <- as.formula(paste(input$targetrf, "~", paste(input$independentVarrf, collapse = "+")))
      # Fit the Random Forest model
      rf_model <- train(formula_rf, 
                        data=train, method="rf", 
                        metric="RMSE", 
                        tuneGrid=tunegrid, 
                        ntree = input$ntreeInput,
                        trControl=control,
                        importance = TRUE)
      
      # Make predictions for the entire dataset
      pred_rf <- predict(rf_model, newdata = train)
      
      # Calculate metrics
      MSE_rf <- mse(actual = train[[input$targetrf]], predicted = pred_rf)
      
      # For R_square_rf, ensure you have a function or package that provides R2
      R_square_rf <- R2(pred_rf, train[[input$targetrf]])
      
      # For MAE_rf, ensure you have a function or package that provides mae
      MAE_rf <- mae(actual = train[[input$targetrf]], predicted = pred_rf)
      
      output$predictionOutput <- renderPrint({
        cat("Mean Squared Error (MSE):\n\n", MSE_rf, "\n\n", "Interpretation: MSE measures the average squared difference between actual and predicted values. 
          Lower values indicate better model performance. 
          A value of 0 means perfect predictions.")
        cat("\n\nR-squared (R²):\n\n", R_square_rf, "\n\n", "Interpretation: R² represents the proportion of variance in the dependent variable that's predictable from the independent variables. 
          It ranges from 0 to 1, with higher values indicating better model fit.")
        cat("\n\nMean Absolute Error (MAE):\n\n", MAE_rf, "\n\n", "Interpretation: MAE measures the average absolute difference between actual and predicted values. 
          Like MSE, lower MAE values indicate better model performance.")
      })
      # Finalize progress
      incProgress(1.0)  # Complete the progress
      # Store results in a reactive value
      results_reactive(list(actual = train[[input$targetrf]], predicted = pred_rf))
    })
  })
  
  output$performancePlot <- renderPlotly({
    # Access the stored results
    results <- results_reactive()
    req(results)  # Ensure results are available
    
    # Creating the plot
    plot_data <- data.frame(Actual = results$actual, Predicted = results$predicted)
    p <- ggplot(plot_data, aes(x = Actual, y = Predicted)) +
      geom_point(alpha = 0.5) +
      geom_abline(intercept = 0, slope = 1, color = "red", linetype = "dashed") +
      labs(x = "Actual Values", y = "Predicted Values", title = "Actual vs. Predicted Values") +
      theme_minimal()
    
    ggplotly(p)
  })
  
  ###Bagging
  databg <- reactiveVal(NULL)
  bg_model_reactive <- reactiveVal()
  pred_bg_reactive <- reactiveVal()
  results_reactive_bg <- reactiveVal()
  # Load and clean data
  observeEvent(input$loadbg, {
    req(input$bginput)
    file <- input$bginput
    if (!is.null(file)) {
      # Reading and cleaning data
      data_df <- read_data(file$datapath)
      data_df <- clean_column_names(data_df)
      
      # Setting the reactive value
      databg(data_df)
      
      # Updating UI elements
      updateSelectInput(session, "targetbg", choices = colnames(data_df))
      updateSelectizeInput(session, "independentVarbg", choices = setdiff(colnames(data_df), input$targetbg))
    }
  })
  
  output$dataSummarybg <- renderPrint({
    req(databg())
    summary(databg())
  })
  
  
  observeEvent(input$runbg, {
    req(databg(), input$targetbg, input$independentVarbg)
    
    data_bg <- databg() %>%
      dplyr::select(all_of(c(input$targetbg, input$independentVarbg))) %>%
      na.omit()
    
    # Early return if conditions are not met
    if (length(input$independentVarbg) == 0) {
      output$modelOutputbg <- renderPrint({ "Please select independent variables." })
      return()
    }
    
    if (nrow(data_bg) < 10) {
      output$modelOutputbg <- renderPrint({ "Dataset is too small after removing NA values." })
      return()
    }
    
    split_ratio <- input$dataSplitbg
    if (split_ratio <= 0 || split_ratio >= 1) {
      output$modelOutputbg <- renderPrint({ "Invalid split ratio. Please choose a value between 0 and 1." })
      return()
    }
    
    # Partition the data
    set.seed(123)
    train <- data_bg %>% sample_frac(split_ratio)
    test <- data_bg %>% setdiff(train)
    
    # Fit the Bagging model
    formula_bg <- as.formula(paste(input$targetbg, "~", paste(input$independentVarbg, collapse = "+")))
    # Fit the Random Forest model
    ctrl <- trainControl(method = "cv",  number = 10)
    bg_model <- caret::train(formula_bg, 
                             data = train, 
                             method = "treebag",  
                             nbagg = input$nbaggInput,
                             trControl = ctrl,
                             importance = TRUE)
    
    bg_model_reactive(bg_model)
    
    # Model summary
    output$runbg <- renderPrint({
      print(bg_model)
      # Add interpretations
      cat("\nModel Interpretation:\n")
      cat("1. Best-Tuned Parameters: These parameters, such as the number of bagging iterations (nbagg), were found to be most effective during the training process.\n")
      cat("2. Performance Metrics: These numbers indicate how well the model predicts the target variable. For a regression model, metrics like RMSE or MAE are common, where lower values are better. For a classification model, metrics like Accuracy or AUC are used, where higher values indicate better performance.\n")
      cat("3. Resampling Results: The cross-validation results show how the model's performance varied across different subsets of the training data. Consistent performance across folds suggests a robust model.\n")
      
      # If the model includes variable importance
      if ("importance" %in% names(bg_model)) {
        cat("4. Variable Importance: This shows which predictors are most influential in the model. Higher values indicate more important predictors.\n")
      }
    })
  })
  
  output$importancePlotbg <- renderPlotly({
    req(bg_model_reactive)  # Ensure the model is available
    
    # Access the model from the reactive value
    bg_model <- bg_model_reactive()
    
    # Extracting feature importance using varImp from caret
    importance_vals <- varImp(bg_model, scale = FALSE)
    
    # Converting to a data frame for plotting
    importance_df <- as.data.frame(importance_vals$importance)
    importance_df$Feature <- rownames(importance_df)
    
    # Plot using ggplot
    p <- ggplot(importance_df, aes(x = reorder(Feature, Overall), y = Overall)) +
      geom_bar(stat = "identity", fill = "dodgerblue") +
      theme_minimal() +
      coord_flip() +  # Flipping coordinates for horizontal bars
      labs(title = "Feature Importance", x = "Features", y = "Importance")
    
    # Convert to Plotly for an interactive plot
    ggplotly(p)
  })
  
  observeEvent(input$baggingBtn, {
    req(databg(), input$targetbg, input$independentVarbg)
    data_bg <- databg() %>%
      dplyr::select(all_of(c(input$targetbg, input$independentVarbg))) %>%
      na.omit()
    withProgress(message = 'Model is being trained...', value = 0, {
      # Increment progress
      incProgress(0.1)  # Initial progress
      # Early return if conditions are not met
      if (length(input$independentVarbg) == 0) {
        output$modelOutputbg <- renderPrint({ "Please select independent variables." })
        return()
      }
      incProgress(0.3)  # Increment progress
      if (nrow(data_bg) < 10) {
        output$modelOutputbg <- renderPrint({ "Dataset is too small after removing NA values." })
        return()
      }
      
      split_ratio <- input$dataSplitbg
      if (split_ratio <= 0 || split_ratio >= 1) {
        output$modelOutputbg <- renderPrint({ "Invalid split ratio. Please choose a value between 0 and 1." })
        return()
      }
      
      # Assuming train dataset is already prepared
      control <- trainControl(method="cv", number=10)
      
      set.seed(2)
      
      train <- data_bg %>% sample_frac(split_ratio)
      test <- data_bg %>% setdiff(train)
      formula_bg <- as.formula(paste(input$targetbg, "~", paste(input$independentVarbg, collapse = "+")))
      bg_model <- caret::train(formula_bg, 
                               data=train,  
                               method="treebag", 
                               ntree = input$nbaggInput,
                               trControl=control,
                               importance = TRUE)
      incProgress(0.6)  # Increment progress
      # Make predictions for the entire dataset
      pred_bg <- predict(bg_model, newdata = train)
      
      # Calculate metrics
      MSE_bg <- mse(actual = train[[input$targetbg]], predicted = pred_bg)
      
      # For R_square_bg, ensure you have a function or package that provides R2
      R_square_bg <- R2(pred_bg, train[[input$targetbg]])
      
      # For MAE_bg, ensure you have a function or package that provides mae
      MAE_bg <- mae(actual = train[[input$targetbg]], predicted = pred_bg)
      
      output$predictionOutputbg <- renderPrint({
        cat("Mean Squared Error (MSE):\n\n", MSE_bg, "\n\n", "Interpretation: MSE measures the average squared difference between actual and predicted values. 
          Lower values indicate better model performance. 
          A value of 0 means perfect predictions.")
        cat("\n\nR-squared (R²):\n\n", R_square_bg, "\n\n", "Interpretation: R² represents the proportion of variance in the dependent variable that's predictable from the independent variables. 
          It ranges from 0 to 1, with higher values indicating better model fit.")
        cat("\n\nMean Absolute Error (MAE):\n\n", MAE_bg, "\n\n", "Interpretation: MAE measures the average absolute difference between actual and predicted values. 
          Like MSE, lower MAE values indicate better model performance.")
      })
      # Finalize progress
      incProgress(1.0)  # Complete the progress
      # Store results in a reactive value
      results_reactive_bg(list(actual = train[[input$targetbg]], predicted = pred_bg))
    })
  })
  
  output$performancePlotbg <- renderPlotly({
    # Access the stored results
    results <- results_reactive_bg()
    req(results)  # Ensure results are available
    
    # Creating the plot
    plot_data <- data.frame(Actual = results$actual, Predicted = results$predicted)
    p <- ggplot(plot_data, aes(x = Actual, y = Predicted)) +
      geom_point(alpha = 0.5) +
      geom_abline(intercept = 0, slope = 1, color = "red", linetype = "dashed") +
      labs(x = "Actual Values", y = "Predicted Values", title = "Actual vs. Predicted Values") +
      theme_minimal()
    
    ggplotly(p)
  })
  
  ###Boosting
  databs <- reactiveVal(NULL)
  bs_model_reactive <- reactiveVal()
  pred_bs_reactive <- reactiveVal()
  results_reactive_bs <- reactiveVal()
  # Load and clean data
  observeEvent(input$loadbs, {
    req(input$bsinput)
    file <- input$bsinput
    if (!is.null(file)) {
      # Reading and cleaning data
      data_df <- read_data(file$datapath)
      data_df <- clean_column_names(data_df)
      
      # Setting the reactive value
      databs(data_df)
      
      # Updating UI elements
      updateSelectInput(session, "targetbs", choices = colnames(data_df))
      updateSelectizeInput(session, "independentVarbs", choices = setdiff(colnames(data_df), input$targetbs))
    }
  })
  
  output$dataSummarybs <- renderPrint({
    req(databs())
    summary(databs())
  })
  
  observeEvent(input$runbs, {
    req(databs(), input$targetbs, input$independentVarbs)
    
    # Start the progress bar
    withProgress(message = 'Model is being trained...', value = 0, {
      # Increment progress
      incProgress(0.1)  # Initial progress
      
      data_bs <- databs() %>%
        dplyr::select(all_of(c(input$targetbs, input$independentVarbs))) %>%
        na.omit()
      
      # Early return if conditions are not met
      if (length(input$independentVarbs) == 0) {
        output$modelOutputbs <- renderPrint({ "Please select independent variables." })
        return()
      }
      
      incProgress(0.3)  # Increment progress
      
      if (nrow(data_bs) < 10) {
        output$modelOutputbs <- renderPrint({ "Dataset is too small after removing NA values." })
        return()
      }
      
      split_ratio <- input$dataSplitbs
      if (split_ratio <= 0 || split_ratio >= 1) {
        output$modelOutputbs <- renderPrint({ "Invalid split ratio. Please choose a value between 0 and 1." })
        return()
      }
      
      # Partition the data
      set.seed(123)
      train <- data_bs %>% sample_frac(split_ratio)
      test <- data_bs %>% setdiff(train)
      
      incProgress(0.5)  # Increment progress
      
      # Fit the Boosting model
      formula_bs <- as.formula(paste(input$targetbs, "~", paste(input$independentVarbs, collapse = "+")))
      # Fit the Boosting model
      ctrl <- trainControl(method = "cv",  number = 10)
      bs_model <- gbm(formula_bs, 
                      data = train, 
                      distribution = "gaussian", 
                      n.trees = input$nbsInput, 
                      interaction.depth = input$nbsdepth,
                      cv.folds = 10,
                      shrinkage = input$nbshr,
                      verbose = F)
      
      bs_model_reactive(bs_model)
      
      # Model summary
      output$runbs <- renderPrint({
        summary <- summary(bs_model)
        print(summary)
        # Add interpretations
        cat("\nModel Interpretation:\n")
        cat("1. Variable Importance: The summary shows the relative influence of each predictor variable in the model. 
          Variables with higher values have more influence on the model's predictions.\n")
      })
      # Finalize progress
      incProgress(1.0)  # Complete the progress
    })
  })
  
  output$importancePlotbs <- renderPlotly({
    req(bs_model_reactive)  # Ensure the model is available
    
    # Access the model from the reactive value
    bs_model <- bs_model_reactive()
    
    # Extracting feature importance
    # Note: The 'n.trees' argument should be set to the number of trees used in the model
    importance_vals <- summary(bs_model, n.trees = input$nbsInput, plot = FALSE)
    
    # Preparing the data frame for ggplot
    importance_df <- data.frame(
      Feature = rownames(importance_vals),
      Overall = importance_vals$rel.inf
    )
    
    # Plot using ggplot
    p <- ggplot(importance_df, aes(x = reorder(Feature, Overall), y = Overall)) +
      geom_bar(stat = "identity", fill = "dodgerblue") +
      theme_minimal() +
      coord_flip() +  # Flipping coordinates for horizontal bars
      labs(title = "Feature Importance", x = "Features", y = "Relative Influence")
    
    # Convert to Plotly for an interactive plot
    ggplotly(p)
  })
  
  observeEvent(input$boostingBtn, {
    req(databs(), input$targetbs, input$independentVarbs)
    # Start the progress bar
    withProgress(message = 'Model is being trained...', value = 0, {
      # Increment progress
      incProgress(0.1)  # Initial progress
      
      df <- databs() %>%
        dplyr::select(all_of(c(input$targetbs, input$independentVarbs))) %>%
        na.omit()
      
      # Early return if conditions are not met
      if (length(input$independentVarbs) == 0) {
        output$modelOutputbs <- renderPrint({ "Please select independent variables." })
        return()
      }
      
      if (nrow(df) < 10) {
        output$modelOutputbs <- renderPrint({ "Dataset is too small after removing NA values." })
        return()
      }
      
      split_ratio <- input$dataSplitbs
      if (split_ratio <= 0 || split_ratio >= 1) {
        output$modelOutputbs <- renderPrint({ "Invalid split ratio. Please choose a value between 0 and 1." })
        return()
      }
      
      
      incProgress(0.3)  # Increment progress
      # Partition the data
      set.seed(123)  # For reproducibility
      train <- df %>% sample_frac(split_ratio)
      test <- df %>% setdiff(train)
      
      # Fit the Boosting model
      formula_bs <- as.formula(paste(input$targetbs, "~", paste(input$independentVarbs, collapse = "+")))
      bs_model <- gbm(formula_bs, 
                      data = train, 
                      distribution = "gaussian", 
                      n.trees = input$nbsInput, 
                      interaction.depth = input$nbsdepth,
                      cv.folds = 10,
                      shrinkage = input$nbshr,
                      verbose = F)
      
      incProgress(0.7)  # Increment progress
      
      # Make predictions for the entire dataset
      pred_bs <- predict(bs_model, newdata = train)
      
      # Calculate metrics
      MSE_bs <- mse(actual = train[[input$targetbs]], predicted = pred_bs)
      
      # For R_square_bs, ensure you have a function or package that provides R2
      R_square_bs <- R2(pred_bs, train[[input$targetbs]])
      
      # For MAE_bs, ensure you have a function or package that provides mae
      MAE_bs <- mae(actual = train[[input$targetbs]], predicted = pred_bs)
      
      # Finalize progress
      incProgress(1.0)  # Complete the progress
      
      output$predictionOutputbs <- renderPrint({
        cat("Mean Squared Error (MSE):\n\n", MSE_bs, "\n\n", "Interpretation: MSE measures the average squared difference between actual and predicted values. 
          Lower values indicate better model performance. 
          A value of 0 means perfect predictions.")
        cat("\n\nR-squared (R²):\n\n", R_square_bs, "\n\n", "Interpretation: R² represents the proportion of variance in the dependent variable that's predictable from the independent variables. 
          It ranges from 0 to 1, with higher values indicating better model fit.")
        cat("\n\nMean Absolute Error (MAE):\n\n", MAE_bs, "\n\n", "Interpretation: MAE measures the average absolute difference between actual and predicted values. 
          Like MSE, lower MAE values indicate better model performance.")
      })
      
      # Store results in a reactive value
      results_reactive_bs(list(actual = train[[input$targetbs]], predicted = pred_bs))
    })
  })
  
  output$performancePlotbs <- renderPlotly({
    # Access the stored results
    results <- results_reactive_bs()
    req(results)  # Ensure results are available
    
    # Creating the plot
    plot_data <- data.frame(Actual = results$actual, Predicted = results$predicted)
    p <- ggplot(plot_data, aes(x = Actual, y = Predicted)) +
      geom_point(alpha = 0.5) +
      geom_abline(intercept = 0, slope = 1, color = "red", linetype = "dashed") +
      labs(x = "Actual Values", y = "Predicted Values", title = "Actual vs. Predicted Values") +
      theme_minimal()
    
    ggplotly(p)
  })
  
  ###MARS
  datams <- reactiveVal(NULL)
  ms_model_reactive <- reactiveVal()
  pred_ms_reactive <- reactiveVal()
  results_reactive_ms <- reactiveVal()
  # Load and clean data
  observeEvent(input$loadms, {
    req(input$msinput)
    file <- input$msinput
    if (!is.null(file)) {
      # Reading and cleaning data
      data_df <- read_data(file$datapath)
      data_df <- clean_column_names(data_df)
      
      # Setting the reactive value
      datams(data_df)
      
      # Updating UI elements
      updateSelectInput(session, "targetms", choices = colnames(data_df))
      updateSelectizeInput(session, "independentVarms", choices = setdiff(colnames(data_df), input$targetms))
    }
  })
  
  
  output$dataSummaryms <- renderPrint({
    req(datams())
    summary(datams())
  })
  
  observeEvent(input$runms, {
    req(datams(), input$targetms, input$independentVarms)
    
    withProgress(message = 'Model is being trained...', value = 0, {
      # Increment progress
      incProgress(0.1)  # Initial progress
      data_ms <- datams() %>%
        dplyr::select(all_of(c(input$targetms, input$independentVarms))) %>%
        na.omit()
      
      # Early return if conditions are not met
      if (length(input$independentVarms) == 0) {
        output$modelOutputms <- renderPrint({ "Please select independent variables." })
        return()
      }
      incProgress(0.3)  # Increment progress
      if (nrow(data_ms) < 10) {
        output$modelOutputms <- renderPrint({ "Dataset is too small after removing NA values." })
        return()
      }
      
      split_ratio <- input$dataSplitms
      if (split_ratio <= 0 || split_ratio >= 1) {
        output$modelOutputms <- renderPrint({ "Invalid split ratio. Please choose a value between 0 and 1." })
        return()
      }
      incProgress(0.6)  # Increment progress
      # Partition the data
      set.seed(123)
      train <- data_ms %>% sample_frac(split_ratio)
      test <- data_ms %>% setdiff(train)
      
      # Fit the Random Forest model
      formula_ms <- as.formula(paste(input$targetms, "~", paste(input$independentVarms, collapse = "+")))
      # Fit the Random Forest model
      
      # Define the range of values for .nk and other parameters
      marsGrid <- expand.grid(.degree = 1:2, .nprune = 2:20)
      ms_model <- train(formula_ms, data = train, method = "earth", tuneGrid = marsGrid,
                        trControl = trainControl(method = "cv", verboseIter = T))
      
      
      
      ms_model_reactive(ms_model)
      
      # Model summary
      output$runms <- renderPrint({
        print(ms_model)
        cat("\nModel Summary Interpretation:\n")
        cat("\n1. Tuned Parameters: This section shows the best parameters found during the training process, 
            such as the degree of interactions and the number of terms/pruning in the MARS model. 
            These parameters are crucial for the model's ability to capture complex relationships in the data.\n")
        cat("\n2. Model Performance: The summary will also include performance metrics. 
            For regression tasks, look for metrics like RMSE or R-squared, where a lower RMSE or a higher R-squared indicates better performance. 
            For classification, metrics like Accuracy or AUC are common.\n")
        cat("\n3. Cross-Validation Results: If cross-validation was used, 
            the summary may show how the model performed across different subsets of the data, which can be an indicator of the model's robustness.\n")
        # Feature Importance
        cat("Feature Importance:\n")
        importance_vals <- varImp(ms_model, scale = FALSE)
        print(importance_vals)
        cat("\nFeature Importance Interpretation:\n")
        cat("\nThis table shows the importance of each predictor variable in the model. 
            Variables with higher values have more influence on the model's predictions. 
            In the context of MARS, this importance can be seen as how much each variable contributes to the model's ability to fit the data and make accurate predictions. 
            High-importance variables are key drivers of the target variable, while low-importance variables have less impact.\n")
        
      })
      # Finalize progress
      incProgress(1.0)  # Complete the progress
    })
  })
  
  output$importancePlotms <- renderPlotly({
    req(ms_model_reactive)  # Ensure the model is available
    
    # Access the model from the reactive value
    ms_model <- ms_model_reactive()
    
    # Extracting feature importance using caret's varImp function
    importance_vals <- varImp(ms_model, scale = FALSE)
    
    # Preparing the data frame for ggplot
    importance_df <- as.data.frame(importance_vals$importance)
    importance_df$Feature <- rownames(importance_df)
    
    # Plot using ggplot
    p <- ggplot(importance_df, aes(x = reorder(Feature, Overall), y = Overall)) +
      geom_bar(stat = "identity", fill = "dodgerblue") +
      theme_minimal() +
      coord_flip() +  # Flipping coordinates for horizontal bars
      labs(title = "Feature Importance", x = "Features", y = "Relative Importance")
    
    # Convert to Plotly for an interactive plot
    ggplotly(p)
  })
  
  # Define the Mean Squared Error function
  mse <- function(actual, predicted) {
    mean((actual - predicted) ^ 2)
  }
  
  # Define the Mean Absolute Error function
  mae <- function(actual, predicted) {
    mean(abs(actual - predicted))
  }
  
  observeEvent(input$marsBtn, {
    req(datams(), input$targetms, input$independentVarms)
    
    data_ms <- datams() %>%
      dplyr::select(all_of(c(input$targetms, input$independentVarms))) %>%
      na.omit()
    
    withProgress(message = 'Model is being trained...', value = 0, {
      # Increment progress
      incProgress(0.1)  # Initial progress
      
      # Early return if conditions are not met
      if (length(input$independentVarms) == 0) {
        output$modelOutputms <- renderPrint({ "Please select independent variables." })
        return()
      }
      
      if (nrow(data_ms) < 10) {
        output$modelOutputms <- renderPrint({ "Dataset is too small after removing NA values." })
        return()
      }
      
      incProgress(0.3)  # Increment progress  
      split_ratio <- input$dataSplitms
      if (split_ratio <= 0 || split_ratio >= 1) {
        output$modelOutputms <- renderPrint({ "Invalid split ratio. Please choose a value between 0 and 1." })
        return()
      }
      
      # Partition the data
      set.seed(123)
      train <- data_ms %>% sample_frac(split_ratio)
      test <- data_ms %>% setdiff(train)
      
      # Fit the Random Forest model
      formula_ms <- as.formula(paste(input$targetms, "~", paste(input$independentVarms, collapse = "+")))
      # Fit the Random Forest model
      
      # Define the range of values for .nk and other parameters
      set.seed(2)
      marsGrid <- expand.grid(.degree = 1:2, .nprune = 2:20)
      ms_model <- train(formula_ms, data = train, method = "earth", tuneGrid = marsGrid,
                        trControl = trainControl(method = "cv", verboseIter = T))
      incProgress(0.7)  # Increment progress
      # Make predictions for the entire dataset
      pred_ms <- predict(ms_model, newdata = train)
      
      # Calculate metrics
      MSE_ms <- mse(actual = train[[input$targetms]], predicted = pred_ms)
      
      # For R_square_rf, ensure you have a function or package that provides R2
      R_square_ms <- R2(pred_ms, train[[input$targetms]])
      
      # For MAE_rf, ensure you have a function or package that provides mae
      MAE_ms <- mae(actual = train[[input$targetms]], predicted = pred_ms)
      
      # Finalize progress
      incProgress(1.0)  # Complete the progress
      
      output$predictionOutputms <- renderPrint({
        cat("Mean Squared Error (MSE):\n\n", MSE_ms, "\n\n", "Interpretation: MSE measures the average squared difference between actual and predicted values. 
          Lower values indicate better model performance. 
          A value of 0 means perfect predictions.")
        cat("\n\nR-squared (R²):\n\n", R_square_ms, "\n\n", "Interpretation: R² represents the proportion of variance in the dependent variable that's predictable from the independent variables. 
          It ranges from 0 to 1, with higher values indicating better model fit.")
        cat("\n\nMean Absolute Error (MAE):\n\n", MAE_ms, "\n\n", "Interpretation: MAE measures the average absolute difference between actual and predicted values. 
          Like MSE, lower MAE values indicate better model performance.")
      })
      
      # Store results in a reactive value
      results_reactive_ms(list(actual = train[[input$targetms]], predicted = pred_ms))
    })
  })
  
  
  output$performancePlotms <- renderPlotly({
    # Access the stored results
    results <- results_reactive_ms()
    req(results)  # Ensure results are available
    
    # Extract the 'y' column from the 'predicted' matrix and rename it to 'Predicted'
    predicted_vector <- results$predicted[, "y"]
    
    # Creating the plot data frame with 'Actual' and 'Predicted'
    plot_data <- data.frame(Actual = results$actual, Predicted = predicted_vector)
    
    p <- ggplot(plot_data, aes(x = Actual, y = Predicted)) +
      geom_point(alpha = 0.5) +
      geom_abline(intercept = 0, slope = 1, color = "red", linetype = "dashed") +
      labs(x = "Actual Values", y = "Predicted Values", title = "Actual vs. Predicted Values") +
      theme_minimal()
    
    ggplotly(p)
  })
  
  ###Ridge Regression
  datarr <- reactiveVal(NULL)
  rr_model_reactive <- reactiveVal()
  pred_rr_reactive <- reactiveVal()
  results_reactive_rr <- reactiveVal()
  # Load and clean data
  observeEvent(input$loadrr, {
    req(input$rrinput)
    file <- input$rrinput
    if (!is.null(file)) {
      # Reading and cleaning data
      data_df <- read_data(file$datapath)
      data_df <- clean_column_names(data_df)
      
      # Setting the reactive value
      datarr(data_df)
      
      # Updating UI elements
      updateSelectInput(session, "targetrr", choices = colnames(data_df))
      updateSelectizeInput(session, "independentVarrr", choices = setdiff(colnames(data_df), input$targetrr))
    }
  })
  
  output$dataSummaryrr <- renderPrint({
    req(datarr())
    summary(datarr())
  })
  
  observeEvent(input$runrr, {
    req(datarr(), input$targetrr, input$independentVarrr)
    
    withProgress(message = 'Model is being trained...', value = 0, {
      # Increment progress
      incProgress(0.1)  # Initial progress
      data_rr <- datarr() %>%
        dplyr::select(all_of(c(input$targetrr, input$independentVarrr))) %>%
        na.omit()
      
      # Early return if conditions are not met
      if (length(input$independentVarrr) == 0) {
        output$modelOutputrr <- renderPrint({ "Please select independent variables." })
        return()
      }
      incProgress(0.3)  # Increment progress
      if (nrow(data_rr) < 10) {
        output$modelOutputrr <- renderPrint({ "Dataset is too small after removing NA values." })
        return()
      }
      
      split_ratio <- input$dataSplitrr
      if (split_ratio <= 0 || split_ratio >= 1) {
        output$modelOutputrr <- renderPrint({ "Invalid split ratio. Please choose a value between 0 and 1." })
        return()
      }
      incProgress(0.6)  # Increment progress
      # Partition the data
      set.seed(123)
      train <- data_rr %>% sample_frac(split_ratio)
      test <- data_rr %>% setdiff(train)
      
      # Define the tuning grid for Ridge Regression
      ridgeGrid <- expand.grid(.lambda = 10^seq(-3, 3, length = 100),
                               .alpha = 0)  # alpha = 0 for Ridge
      formula_rr <- as.formula(paste(input$targetrr, "~", paste(input$independentVarrr, collapse = "+")))
      # Fit the Random Forest model
      rr_model <- train(
        formula_rr, 
        data = train, 
        method = "glmnet", 
        tuneGrid = ridgeGrid,
        trControl = trainControl(method = "cv", number = 10, verboseIter = TRUE)
      )
      
      rr_model_reactive(rr_model)
      
      # Model summary
      output$runrr <- renderPrint({
        print(rr_model)
        cat("\nModel Summary Interpretation:\n")
        cat("\n1. Tuned Parameters: This section shows the best parameters found during the training process, 
            such as the degree of interactions and the number of terms/pruning in the MARS model. 
            These parameters are crucial for the model's ability to capture complex relationships in the data.\n")
        cat("\n2. Model Performance: The summary will also include performance metrics. 
            For regression tasks, look for metrics like RMSE or R-squared, where a lower RMSE or a higher R-squared indicates better performance. 
            For classification, metrics like Accuracy or AUC are common.\n")
        cat("\n3. Cross-Validation Results: If cross-validation was used, 
            the summary may show how the model performed across different subsets of the data, which can be an indicator of the model's robustness.\n")
        # Feature Importance
        cat("Feature Importance:\n")
        importance_vals <- varImp(rr_model, scale = FALSE)
        print(importance_vals)
        cat("\nFeature Importance Interpretation:\n")
        cat("\nThis table shows the importance of each predictor variable in the model. 
            Variables with higher values have more influence on the model's predictions. 
            In the context of MARS, this importance can be seen as how much each variable contributes to the model's ability to fit the data and make accurate predictions. 
            High-importance variables are key drivers of the target variable, while low-importance variables have less impact.\n")
        
      })
      # Finalize progress
      incProgress(1.0)  # Complete the progress
    })
  }) 
  
  output$importancePlotrr <- renderPlotly({
    req(rr_model_reactive)  # Ensure the model is available
    
    # Access the model from the reactive value
    rr_model <- rr_model_reactive()
    
    # Extracting feature importance using caret's varImp function
    importance_vals <- varImp(rr_model, scale = FALSE)
    
    # Preparing the data frame for ggplot
    importance_df <- as.data.frame(importance_vals$importance)
    importance_df$Feature <- rownames(importance_df)
    
    # Plot using ggplot
    p <- ggplot(importance_df, aes(x = reorder(Feature, Overall), y = Overall)) +
      geom_bar(stat = "identity", fill = "dodgerblue") +
      theme_minimal() +
      coord_flip() +  # Flipping coordinates for horizontal bars
      labs(title = "Feature Importance", x = "Features", y = "Relative Importance")
    
    # Convert to Plotly for an interactive plot
    ggplotly(p)
  })
  
  # Define the Mean Squared Error function
  mse <- function(actual, predicted) {
    mean((actual - predicted) ^ 2)
  }
  
  # Define the Mean Absolute Error function
  mae <- function(actual, predicted) {
    mean(abs(actual - predicted))
  }
  
  observeEvent(input$RidgeBtn, {
    req(datarr(), input$targetrr, input$independentVarrr)
    
    data_rr <- datarr() %>%
      dplyr::select(all_of(c(input$targetrr, input$independentVarrr))) %>%
      na.omit()
    
    withProgress(message = 'Model is being trained...', value = 0, {
      # Increment progress
      incProgress(0.1)  # Initial progress
      
      # Early return if conditions are not met
      if (length(input$independentVarrr) == 0) {
        output$modelOutputrr <- renderPrint({ "Please select independent variables." })
        return()
      }
      
      if (nrow(data_rr) < 10) {
        output$modelOutputrr <- renderPrint({ "Dataset is too small after removing NA values." })
        return()
      }
      
      incProgress(0.3)  # Increment progress  
      split_ratio <- input$dataSplitrr
      if (split_ratio <= 0 || split_ratio >= 1) {
        output$modelOutputrr <- renderPrint({ "Invalid split ratio. Please choose a value between 0 and 1." })
        return()
      }
      
      # Partition the data
      set.seed(123)
      train <- data_rr %>% sample_frac(split_ratio)
      test <- data_rr %>% setdiff(train)
      
      # Define the tuning grid for Ridge Regression
      ridgeGrid <- expand.grid(.lambda = 10^seq(-3, 3, length = 100),
                               .alpha = 0)  # alpha = 0 for Ridge
      formula_rr <- as.formula(paste(input$targetrr, "~", paste(input$independentVarrr, collapse = "+")))
      # Fit the Random Forest model
      rr_model <- train(
        formula_rr, 
        data = train, 
        method = "glmnet", 
        tuneGrid = ridgeGrid,
        trControl = trainControl(method = "cv", number = 10, verboseIter = TRUE)
      )
      incProgress(0.7)  # Increment progress
      # Make predictions for the entire dataset
      pred_rr <- predict(rr_model, newdata = train)
      
      # Calculate metrics
      MSE_rr <- mse(actual = train[[input$targetrr]], predicted = pred_rr)
      
      # For R_square_rf, ensure you have a function or package that provides R2
      R_square_rr <- R2(pred_rr, train[[input$targetrr]])
      
      # For MAE_rf, ensure you have a function or package that provides mae
      MAE_rr <- mae(actual = train[[input$targetrr]], predicted = pred_rr)
      
      # Finalize progress
      incProgress(1.0)  # Complete the progress
      
      output$predictionOutputrr <- renderPrint({
        cat("Mean Squared Error (MSE):\n\n", MSE_rr, "\n\n", "Interpretation: MSE measures the average squared difference between actual and predicted values. 
          Lower values indicate better model performance. 
          A value of 0 means perfect predictions.")
        cat("\n\nR-squared (R²):\n\n", R_square_rr, "\n\n", "Interpretation: R² represents the proportion of variance in the dependent variable that's predictable from the independent variables. 
          It ranges from 0 to 1, with higher values indicating better model fit.")
        cat("\n\nMean Absolute Error (MAE):\n\n", MAE_rr, "\n\n", "Interpretation: MAE measures the average absolute difference between actual and predicted values. 
          Like MSE, lower MAE values indicate better model performance.")
      })
      
      # Store results in a reactive value
      results_reactive_rr(list(actual = train[[input$targetrr]], predicted = pred_rr))
    })
  })
  
  output$performancePlotrr <- renderPlotly({
    # Access the stored results
    results <- results_reactive_rr()
    req(results)  # Ensure results are available
    
    # Since results$predicted is a vector, use it directly
    plot_data <- data.frame(Actual = results$actual, Predicted = results$predicted)
    
    p <- ggplot(plot_data, aes(x = Actual, y = Predicted)) +
      geom_point(alpha = 0.5) +
      geom_abline(intercept = 0, slope = 1, color = "red", linetype = "dashed") +
      labs(x = "Actual Values", y = "Predicted Values", title = "Actual vs. Predicted Values") +
      theme_minimal()
    
    ggplotly(p)
  })
  
  ###LASSO Regression    
  datals <- reactiveVal(NULL)
  ls_model_reactive <- reactiveVal()
  pred_ls_reactive <- reactiveVal()
  results_reactive_ls <- reactiveVal()
  # Load and clean data
  observeEvent(input$loadls, {
    req(input$lsinput)
    file <- input$lsinput
    if (!is.null(file)) {
      # Reading and cleaning data
      data_df <- read_data(file$datapath)
      data_df <- clean_column_names(data_df)
      
      # Setting the reactive value
      datals(data_df)
      
      # Updating UI elements
      updateSelectInput(session, "targetls", choices = colnames(data_df))
      updateSelectizeInput(session, "independentVarls", choices = setdiff(colnames(data_df), input$targetls))
    }
  })
  
  output$dataSummaryls <- renderPrint({
    req(datals())
    summary(datals())
  })  
  
  observeEvent(input$runls, {
    req(datals(), input$targetls, input$independentVarls)
    
    withProgress(message = 'Model is being trained...', value = 0, {
      # Increment progress
      incProgress(0.1)  # Initial progress
      data_ls <- datals() %>%
        dplyr::select(all_of(c(input$targetls, input$independentVarls))) %>%
        na.omit()
      
      # Early return if conditions are not met
      if (length(input$independentVarls) == 0) {
        output$modelOutputls <- renderPrint({ "Please select independent variables." })
        return()
      }
      incProgress(0.3)  # Increment progress
      if (nrow(data_ls) < 10) {
        output$modelOutputls <- renderPrint({ "Dataset is too small after removing NA values." })
        return()
      }
      
      split_ratio <- input$dataSplitls
      if (split_ratio <= 0 || split_ratio >= 1) {
        output$modelOutputls <- renderPrint({ "Invalid split ratio. Please choose a value between 0 and 1." })
        return()
      }
      incProgress(0.6)  # Increment progress
      # Partition the data
      set.seed(123)
      train <- data_ls %>% sample_frac(split_ratio)
      test <- data_ls %>% setdiff(train)
      
      # Define the tuning grid for Ridge Regression
      ridgeGrid <- expand.grid(.lambda = 10^seq(-3, 3, length = 100),
                               .alpha = 1)  # alpha = 0 for Ridge
      formula_ls <- as.formula(paste(input$targetls, "~", paste(input$independentVarls, collapse = "+")))
      # Fit the Random Forest model
      ls_model <- train(
        formula_ls, 
        data = train, 
        method = "glmnet", 
        tuneGrid = ridgeGrid,
        trControl = trainControl(method = "cv", number = 10, verboseIter = TRUE)
      )
      
      ls_model_reactive(ls_model)
      
      # Model summary
      output$runls <- renderPrint({
        print(ls_model)
        cat("\nModel Summary Interpretation:\n")
        cat("\n1. Tuned Parameters: This section shows the best parameters found during the training process, 
            such as the degree of interactions and the number of terms/pruning in the MARS model. 
            These parameters are crucial for the model's ability to capture complex relationships in the data.\n")
        cat("\n2. Model Performance: The summary will also include performance metrics. 
            For regression tasks, look for metrics like RMSE or R-squared, where a lower RMSE or a higher R-squared indicates better performance. 
            For classification, metrics like Accuracy or AUC are common.\n")
        cat("\n3. Cross-Validation Results: If cross-validation was used, 
            the summary may show how the model performed across different subsets of the data, which can be an indicator of the model's robustness.\n")
        # Feature Importance
        cat("Feature Importance:\n")
        importance_vals <- varImp(ls_model, scale = FALSE)
        print(importance_vals)
        cat("\nFeature Importance Interpretation:\n")
        cat("\nThis table shows the importance of each predictor variable in the model. 
            Variables with higher values have more influence on the model's predictions. 
            In the context of MARS, this importance can be seen as how much each variable contributes to the model's ability to fit the data and make accurate predictions. 
            High-importance variables are key drivers of the target variable, while low-importance variables have less impact.\n")
        
      })
      # Finalize progress
      incProgress(1.0)  # Complete the progress
    })
  }) 
  
  output$importancePlotls <- renderPlotly({
    req(ls_model_reactive)  # Ensure the model is available
    
    # Access the model from the reactive value
    ls_model <- ls_model_reactive()
    
    # Extracting feature importance using caret's varImp function
    importance_vals <- varImp(ls_model, scale = FALSE)
    
    # Preparing the data frame for ggplot
    importance_df <- as.data.frame(importance_vals$importance)
    importance_df$Feature <- rownames(importance_df)
    
    # Plot using ggplot
    p <- ggplot(importance_df, aes(x = reorder(Feature, Overall), y = Overall)) +
      geom_bar(stat = "identity", fill = "dodgerblue") +
      theme_minimal() +
      coord_flip() +  # Flipping coordinates for horizontal bars
      labs(title = "Feature Importance", x = "Features", y = "Relative Importance")
    
    # Convert to Plotly for an interactive plot
    ggplotly(p)
  })
  
  # Define the Mean Squared Error function
  mse <- function(actual, predicted) {
    mean((actual - predicted) ^ 2)
  }
  
  # Define the Mean Absolute Error function
  mae <- function(actual, predicted) {
    mean(abs(actual - predicted))
  }
  
  observeEvent(input$LassoBtn, {
    req(datals(), input$targetls, input$independentVarls)
    
    data_ls <- datals() %>%
      dplyr::select(all_of(c(input$targetls, input$independentVarls))) %>%
      na.omit()
    
    withProgress(message = 'Model is being trained...', value = 0, {
      # Increment progress
      incProgress(0.1)  # Initial progress
      
      # Early return if conditions are not met
      if (length(input$independentVarls) == 0) {
        output$modelOutputls <- renderPrint({ "Please select independent variables." })
        return()
      }
      
      if (nrow(data_ls) < 10) {
        output$modelOutputls <- renderPrint({ "Dataset is too small after removing NA values." })
        return()
      }
      
      incProgress(0.3)  # Increment progress  
      split_ratio <- input$dataSplitls
      if (split_ratio <= 0 || split_ratio >= 1) {
        output$modelOutputls <- renderPrint({ "Invalid split ratio. Please choose a value between 0 and 1." })
        return()
      }
      
      # Partition the data
      set.seed(123)
      train <- data_ls %>% sample_frac(split_ratio)
      test <- data_ls %>% setdiff(train)
      
      # Define the tuning grid for Ridge Regression
      ridgeGrid <- expand.grid(.lambda = 10^seq(-3, 3, length = 100),
                               .alpha = 1)  # alpha = 0 for Ridge
      formula_ls <- as.formula(paste(input$targetls, "~", paste(input$independentVarls, collapse = "+")))
      # Fit the Random Forest model
      ls_model <- train(
        formula_ls, 
        data = train, 
        method = "glmnet", 
        tuneGrid = ridgeGrid,
        trControl = trainControl(method = "cv", number = 10, verboseIter = TRUE)
      )
      incProgress(0.7)  # Increment progress
      # Make predictions for the entire dataset
      pred_ls <- predict(ls_model, newdata = train)
      
      # Calculate metrics
      MSE_ls <- mse(actual = train[[input$targetls]], predicted = pred_ls)
      
      # For R_square_rf, ensure you have a function or package that provides R2
      R_square_ls <- R2(pred_ls, train[[input$targetls]])
      
      # For MAE_rf, ensure you have a function or package that provides mae
      MAE_ls <- mae(actual = train[[input$targetls]], predicted = pred_ls)
      
      # Finalize progress
      incProgress(1.0)  # Complete the progress
      
      output$predictionOutputls <- renderPrint({
        cat("Mean Squared Error (MSE):\n\n", MSE_ls, "\n\n", "Interpretation: MSE measures the average squared difference between actual and predicted values. 
          Lower values indicate better model performance. 
          A value of 0 means perfect predictions.")
        cat("\n\nR-squared (R²):\n\n", R_square_ls, "\n\n", "Interpretation: R² represents the proportion of variance in the dependent variable that's predictable from the independent variables. 
          It ranges from 0 to 1, with higher values indicating better model fit.")
        cat("\n\nMean Absolute Error (MAE):\n\n", MAE_ls, "\n\n", "Interpretation: MAE measures the average absolute difference between actual and predicted values. 
          Like MSE, lower MAE values indicate better model performance.")
      })
      
      # Store results in a reactive value
      results_reactive_ls(list(actual = train[[input$targetls]], predicted = pred_ls))
    })
  })
  
  output$performancePlotls <- renderPlotly({
    # Access the stored results
    results <- results_reactive_ls()
    req(results)  # Ensure results are available
    
    # Since results$predicted is a vector, use it directly
    plot_data <- data.frame(Actual = results$actual, Predicted = results$predicted)
    
    p <- ggplot(plot_data, aes(x = Actual, y = Predicted)) +
      geom_point(alpha = 0.5) +
      geom_abline(intercept = 0, slope = 1, color = "red", linetype = "dashed") +
      labs(x = "Actual Values", y = "Predicted Values", title = "Actual vs. Predicted Values") +
      theme_minimal()
    
    ggplotly(p)
  })
}

shinyApp(ui, server)