-
Notifications
You must be signed in to change notification settings - Fork 0
/
cytometry_app.R
1914 lines (1609 loc) · 123 KB
/
cytometry_app.R
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
##Una web en shiny tiene 3 elementos, UI, server interface y función shiny
### Cargamos los paquetes que sean necesarios ###
#Instalación de paquetes:
# List of packages for session
.packages = c("shiny", "shinythemes", "RColorBrewer", "lattice", "reshape2", "googleVis", "flowCore", "bit", "CytoTree", "ggplot2", "ggthemes", "plotly", "devtools", "DynTxRegime", "modelObj", "shinydashboard", "shinydashboardPlus", "reticulate", "this.path", "rMIDAS", "BiocManager", "LSD", "tcltk", "gplots", "graphics", "e1071", "lle", "vegan", "tabplot", "shinybusy")
#this.path->localizar scripts
#reticulate-> uso de python dentro de R
#rMIDAS -> para poder fijar el env de python
# Install CRAN packages (if not already installed)
.inst <- .packages %in% installed.packages()
if(length(.packages[!.inst]) > 0) install.packages(.packages[!.inst])
# Load packages into session -> #ALICIA: entiendo que con esta línea podría eliminar todas las de library()
lapply(.packages, require, character.only=TRUE)
#library(shiny)
#library(shinythemes)
#library(RColorBrewer)
#library(lattice)
#library(reshape2)
#library(googleVis)
#library(flowCore)
#library(bit)
#library(CytoTree)
#library(ggplot2)
#library(ggthemes)
#library(plotly)
#library(DynTxRegime)
#library(modelObj)
#ALICIA: este paquete teniendo en cuenta que da problemas lo pongo de forma independiente
if("tabplot" %in% rownames(installed.packages()) == FALSE) {install_github("mtennekes/tabplot")}
if("reticulate" %in% rownames(installed.packages()) == FALSE){devtools::install_github("rstudio/reticulate")} #necesario instalarlo así, sino da errores luego cuando usamos reticulate
if("CytoTree" %in% rownames(installed.packages()) == FALSE){devtools::install_github("JhuangLab/CytoTree")}
if("flowAI" %in% rownames(installed.packages()) == FALSE){BiocManager::install("flowAI")}
###cargamos las funciones auxiliares
source("global.R") ##este es el script auxiliar que contiene funciones del módulo FlowiQC y de cytotree, son funciones que pueden ser llamadas por iu o server
##GENPATTERN -PYTHON
#Para evitar problemas de inconpatibilidades de versiones de python, trabajaremos desde un entorno específico para esta app
if("r-reticulate" %in% virtualenv_list() == FALSE) {virtualenv_create("r-reticulate")}
use_virtualenv("r-reticulate") #indicamos que use este entorno
#system("sudo apt install python3.8-venv") #Desmarcar si es necesario, yo tuve que hacerlo para que me dejase tener pip en el entorno virtual
#system(" .virtualenvs/r-reticulate/bin/python -m ensurepip")
#instalamos el módulo de genepattern de python
#if (import("gp")== FALSE) {virtualenv_install("r-reticulate", packages = "genepattern-python")}
virtualenv_install("r-reticulate", packages = "genepattern-python") #opto por esta opción ya que da menos problemas de instalación
gp <-import("gp") #cargamos genepattern
###### INVOCAR PYTHON Y GENEPATTERM
current_dir <-this.dir() #marco el directorio actual
path_python_scripts <-paste(current_dir, "/python/", sep = "") #busco la carpeta python donde guardo mis scripts de python
##para el previewfcs
script_preprocessing<-paste(path_python_scripts, "FCS_preprocessing.py", sep="") #busco el script de FCS_preprocessing.py
source_python(script_preprocessing) #lo cargo en r con esta función de reticulate
### Creo la UI (User interface) ####
#este apartado es el que corresponde a la apariencia gráfica de la web.
ui<- fluidPage(theme=shinytheme("cerulean"),
add_busy_spinner(spin="fulfilling-bouncing-circle"), ###COMENTARIO ALICIA, dependiendo del tipo de spinner que se use me da errores una parte u otra; si uso double-bounce o fading-spin, la parte de quality va bien, pero gating no. Si uso "radar" gating va bien, pero quality no
#van bien con gating:flower, pixel, spring,fulfilling-bouncing-circle, semipolar,
#van bien con quality:circle
#funciona con ambas cosas:fulfilling-square,
titlePanel("FLOW CYTOMETRY ANALYSIS SERVER"), #título de la web
navbarPage( "",
collapsible = TRUE, #para que cambie la vista en pantallas más pequeñas
windowTitle = "Cytometry Biotechvana",
tabPanel("Home", icon=icon("home"), #esto corresponde a la página principal o de inicio
fluidRow(
h3("Welcome to Biotechvana Flow Cytometry Server!"),
p("Here you you can find several tools to asses your journey of flow cytometry Data analysis:"),
column(
br(), br(), br(),
tags$img(src="fcs-files.png", width="110px", height="110px"),
width=2),
column(
br(), br(), br(),br(),br(),
tags$img(src="flecha.png", width="30px", height="30px"),
width = 1),
column(
br(),
h4("Data PreProcesing"),
p("Includes modules to evaluate initial data and conversion between formats"),
width = 2),
column(
br(), br(), br(),br(),br(),
tags$img(src="flecha.png", width="30px", height="30px"),
width = 1),
column(
br(),
h4("Quality Assessment"),
p("It includes several tools to assess the quality of the FCS data"),
width = 2),
column(
br(), br(), br(),br(),br(),
tags$img(src="flecha.png", width="30px", height="30px"),
width = 1),
column(
br(),
h4("Clustering"),
p("Here you can find tools for manual gating as well as several clustering algorithms"),
width = 2),
column(
width = 1)
)
),
navbarMenu("Data preprocessing",
tabPanel("FCS Preview",
h3("Module for PreviewFCS"),
br(),
h5(strong("Description:")),
p("Allows viewing of structural metadata, parameters, and descriptive statistics from a Flow Cytometry Standard (FCS) data file"),
hr(),
fluidRow(
column(3, #lado izquierdo con todos los botones interactivos
h5("Parameters:"),
fileInput('previewFCSfile', strong('Choose fcs file:'), multiple = FALSE, #de momento que el archivo sea único, en una mejora se podría mirar para meter varios
accept = c('text/fcs', '.fcs')),
br(),
actionButton("go_fcspreview", "Submit!"),
hr(),
div(style = "margin-top: 30px; width: 200px; ", HTML("Based on an implementation of GenePattern 2.0 Nature Genetics 38 no. 5 (2006): pp500-501 Google Scholar | Endnote | RIS")),
div(style = "margin-top: 10px; ",
tags$a(href="https://cloud.genepattern.org/gp/module/doc/urn:lsid:broad.mit.edu:cancer.software.genepattern.module.analysis:00185:2", "PreviewFCS")),
),
column(9,
p("Once submitted and processed, click on the download button to get your results"),
p(em("Be patient, this process can take some time")),
uiOutput("fcspreviewresult")
))),
tabPanel("FCS Data Conversions",
h3("Module for Data format conversions"),
br(),
h5(strong("Description:")),
p("Allows CSV-FCS format conversions of Flow Cytometry Data."),
hr(),
fluidRow(
#pongo un conditionalPanel para que según que Tabpanel esté seleccionada, aparezcan unos parámetros u otros al lado izquierdo con todos los botones interactivos
conditionalPanel(
condition = "input.conversion=='CsvToFCS'",
column(3, #lado izquierdo
h5("Parameters:"),
fileInput('csvfile_input', strong('Choose csv file:'), multiple = FALSE,
accept = c('text/csv', '.csv')),
br(),
actionButton("go_CSVtoFCS", "Convert!"),
br(),
br(),
p("You can download a sample CSV file:", tags$a(href="Prueba.csv", "Here", download=NA, target="_blank") ),
hr(),
div(style = "margin-top: 30px; width: 200px; ", HTML("Based on an implementation of GenePattern 2.0 Nature Genetics 38 no. 5 (2006): pp500-501 Google Scholar | Endnote | RIS")),
div(style = "margin-top: 10px; ",
tags$a(href="https://www.genepattern.org/flow-cytometry-data-preprocessing", "Genepattern Suite"))
)
),
conditionalPanel(
condition = "input.conversion=='FCStoCsv'",
column(3, #lado izquierdo
h5("Parameters:"),
fileInput('FCSfile_input_2convrt', strong('Choose fcs file:'), multiple = FALSE,
accept = c('text/fcs', '.fcs')),
br(),
actionButton("go_FCStoCSV", "Convert!"),
hr(),
div(style = "margin-top: 30px; width: 200px; ", HTML("Based on an implementation of GenePattern 2.0 Nature Genetics 38 no. 5 (2006): pp500-501 Google Scholar | Endnote | RIS")),
div(style = "margin-top: 10px; ",
tags$a(href="https://www.genepattern.org/flow-cytometry-data-preprocessing", "Genepattern Suite"))
)),
column(9,
tabsetPanel(type = "pills", id="conversion",
tabPanel("CsvToFCS",
h3("Module for CsvToFcs"),
br(),
h5(strong("Description: ")),
p("Converts Flow Cytometry data in a comma-separated values (CSV) file to a Flow Cytometry Standard (FCS) file."),
br(),
p("Once submitted and processed, click on the download button to get your results"),
p(em("Be patient, this process can take some time")),
#uiOutput("CSVtoFCSresult")
downloadButton("CSVtoFCSresult", "Download your file")
),
tabPanel("FCStoCsv",
h3("Module for FCStoCsv"),
br(),
h5(strong("Description: ")),
p("Converts a Flow Cytometry Standard (FCS) file to a comma-separated values (CSV) file."),
br(),
p("Once submitted and processed, click on the download button to get your results"),
p(em("Be patient, this process can take some time")),
uiOutput("FCStoCSVresult")
))
)))
#######Toda esta parte comentada iría enfocada a un desarrollo futuro del apartado de preprocesado metiendo más módulos de genepattern
#Dejo aquí la estructura hecha
# tabPanel("FCS keywords manipulation",
# h3("Module for FCS keywords manipulation"),
# br(),
# h5(strong("Description:")),
# p("Includes several modules for FCS keywords manipulation "),
# hr(),
# fluidRow(
#
#
# column(3, #lado izquierdo con todos los botones interactivos
# #style = "background-color:#F6f6fb;",
# h5("Parameters:"),
# fileInput('previewFCSfile', strong('Choose fcs file:'), multiple = FALSE, #de momento que el archivo sea único, en una mejora se podría mirar para meter varios
# accept = c('text/fcs', '.fcs')),
# hr(),
#
# hr(),
# div(style = "margin-top: 30px; width: 200px; ", HTML("Based on an implementation of GenePattern 2.0 Nature Genetics 38 no. 5 (2006): pp500-501 Google Scholar | Endnote | RIS")),
# div(style = "margin-top: 10px; ",
# tags$a(href="https://cloud.genepattern.org/gp/module/doc/urn:lsid:broad.mit.edu:cancer.software.genepattern.module.analysis:00185:2", "PreviewFCS"))
# ),
# column(9,
# dashboardPage(
# skin = "blue",
# dashboardHeader(disable = TRUE),
# dashboardSidebar( width = "0px"),
# dashboardBody(
# #Módulo DeIdentifyFCS
# box(title = span ("DeIdentifyFCS", style="color:white"),
#
# status = "primary",
# solidHeader = TRUE,
# h5(strong("Description:")),
# p("DeIdentifyFCS an FCS data file; remove keywords from a list or matching a regular expression; useful to anonymize FCS data files and/or to remove specific (e.g., clinical) information."),
# id= "DeIdentifyFCS_module",
# collapsible=TRUE,
# collapsed = TRUE,
# p("esto es una prueba")
#
# ),
# #Módulo ExtractFCSKeywords
# box(title = span ("ExtractFCSKeywords", style="color:white"),
#
# status = "primary",
# solidHeader = TRUE,
# h5(strong("Description:")),
# p("Extracts keyword(s) value(s) from a Flow Cytometry Standard (FCS) file."),
# id= "ExtractFCSKeywords_module",
# collapsible=TRUE,
# collapsed = TRUE,
# p("esto es una prueba")
#
# ),
# #Módulo SetFCSKeywords
# box(title = span ("SetFCSKeywords", style="color:white"),
#
# status = "primary",
# solidHeader = TRUE,
# h5(strong("Description:")),
# p("Sets keyword/value(s) in a Flow Cytometry Standard (FCS) file."),
# id= "SetFCSKeywords_module",
# collapsible=TRUE,
# collapsed = TRUE,
# p("esto es una prueba")
#
# ),
#
#
#
#
# ))))),
# tabPanel("FCS dataset manipulation", #completar
# h3("Module for FCS dataset manipulation"),
# br(),
# h5(strong("Description:")),
# p("Includes several modules for FCS Dataset manipulation "),
# hr(),
# fluidRow(
#
# column(3, #lado izquierdo con todos los botones interactivos
# #style = "background-color:#F6f6fb;",
# h5("Parameters:"),
# fileInput('previewFCSfile', strong('Choose fcs file:'), multiple = FALSE, #de momento que el archivo sea único, en una mejora se podría mirar para meter varios
# accept = c('text/fcs', '.fcs')),
# hr(),
# #MEJORA: poner un botón
# #en genepattern dejan opción de elegir como formato de salida HTML o XML, yo voy a tratar que sea HTML proyectado dentro de la web, añadir la otra opción sería una mejora a posteriori
# hr(),
# div(style = "margin-top: 30px; width: 200px; ", HTML("Based on an implementation of GenePattern 2.0 Nature Genetics 38 no. 5 (2006): pp500-501 Google Scholar | Endnote | RIS")),
# div(style = "margin-top: 10px; ",
# tags$a(href="https://cloud.genepattern.org/gp/module/doc/urn:lsid:broad.mit.edu:cancer.software.genepattern.module.analysis:00185:2", "PreviewFCS"))
# ),
# column(9,
# dashboardPage(
# skin = "blue",
# dashboardHeader(disable = TRUE),
# dashboardSidebar( width = "0px"),
# dashboardBody(
# #Módulo AddFCSEventIndex
# box(title = span ("AddFCSEventIndex", style="color:white"),
#
# status = "primary",
# solidHeader = TRUE,
# h5(strong("Description:")),
# p("Adds indexes to events in a Flow Cytometry Standard (FCS) data file."),
# id= "AddFCSEventIndex_module",
# collapsible=TRUE,
# collapsed = TRUE,
# p("esto es una prueba")
#
# ),
# #Módulo AddFCSParameter
# box(title = span ("AddFCSParameter", style="color:white"),
#
# status = "primary",
# solidHeader = TRUE,
# h5(strong("Description:")),
# p("Adds parameters and their values to a Flow Cytometry Standard (FCS) data file."),
# id= "AddFCSParameter_module",
# collapsible=TRUE,
# collapsed = TRUE,
# p("esto es una prueba")
#
# ),
# #Módulo AddNoiseToFCS
# box(title = span ("AddNoiseToFCS", style="color:white"),
#
# status = "primary",
# solidHeader = TRUE,
# h5(strong("Description:")),
# p("Add noise to specified parameters in an FCS data file."),
# id= "AddNoiseToFCS_module",
# collapsible=TRUE,
# collapsed = TRUE,
# p("esto es una prueba")
#
# ),
# #Módulo ExtractFCSDataset
# box(title = span ("ExtractFCSDataset", style="color:white"),
#
# status = "primary",
# solidHeader = TRUE,
# h5(strong("Description:")),
# p("Extracts one or more Flow Cytometry Standard (FCS) data sets from an FCS data file."),
# id= "ExtractFCSDataset_module",
# collapsible=TRUE,
# collapsed = TRUE,
# p("esto es una prueba")
#
# ),
# #Módulo ExtractFCSParameters
# box(title = span ("ExtractFCSParameters", style="color:white"),
#
# status = "primary",
# solidHeader = TRUE,
# h5(strong("Description:")),
# p("Extracts specified parameters from a Flow Cytometry Standard (FCS) file."),
# id= "ExtractFCSParameters_module",
# collapsible=TRUE,
# collapsed = TRUE,
# p("esto es una prueba")
#
# ),
# #Módulo MergeFCSDataFiles
# box(title = span ("MergeFCSDataFiles", style="color:white"),
#
# status = "primary",
# solidHeader = TRUE,
# h5(strong("Description:")),
# p("Merge multiple Flow Cytometry Standard (FCS) data files into a single FCS dataset; includes sub-sampling option."),
# id= "MergeFCSDataFiles_module",
# collapsible=TRUE,
# collapsed = TRUE,
# p("esto es una prueba")
#
# ),
# #Módulo RemoveSaturatedFCSEvents
# box(title = span ("RemoveSaturatedFCSEvents", style="color:white"),
#
# status = "primary",
# solidHeader = TRUE,
# h5(strong("Description:")),
# p("Remove saturated events from an FCS data file."),
# id= "RemoveSaturatedFCSEvents_module",
# collapsible=TRUE,
# collapsed = TRUE,
# p("esto es una prueba")
#
# )
# )
# ))
# ))
),
#####
tabPanel("Quality Assessment", #esta va a ser la página de procesado de calidad
h3("Module for Data Quality Assessment"),
br(),
h5(strong("Description:")),
p("Perform quality control of a single panel from cytometry data"),
hr(),
fluidRow(
column(3, #lado izquierdo con todos los botones interactivos
fileInput('fcsFiles', strong('Choose fcs file(s):'), multiple = TRUE,
accept = c('text/fcs', '.fcs')),
actionButton("goButton", "Submit!"),
hr(),
downloadButton('downloadMarkers', 'Download markers table'),
br(),
downloadButton('downloadFCS', 'Download new FCS files'),
hr(),
## sample limits: 50
uiOutput("sample_select"),
#aparecerán checkbox con las muestras una vez leido el archivo
lapply(1:50, function(i) { #aplica la función a los elementos de una lista que vayan de 1-50
uiOutput(paste0('timeSlider', i))
}),
hr(),
uiOutput("marker_select"),
hr(),
div(style = "margin-top: 30px; width: 200px; ", HTML("Quality Assessment is based on flowiQC, Shiny app developed by Monaco G & Chen H, public code can be found:")),
div(style = "margin-top: 10px; ",
tags$a(href="https://github.com/SIgNBioinfo/flowiQC_shinyAPP", "Github Repository"))
),
column(9,
tabsetPanel(type = "pills", #crea los submenús de la página
tabPanel("Cell numbers",
hr(),
htmlOutput("cnplot")), #contenido de tipo html
tabPanel("Time flow", fluidPage(
hr(),
htmlOutput("tfplot"),
hr(),
fluidRow(
column(4, offset = 1,
numericInput("tf_binSize", "Bin size:", value = NA)
),
column(4,
numericInput("tf_varCut", "Variation cut:", value = 1)
)
),
textOutput("tf_text") #salida de texto interactiva
)),
tabPanel("Timeline", fluidPage(
tags$style(type="text/css",
".shiny-output-error { visibility: hidden; }",
".shiny-output-error:before { visibility: hidden; }"
),
hr(),
uiOutput("tl_sample_choose"), #va a ser dependiente del input
hr(),
h4("Timeline plot:"),
htmlOutput("tlplot"),
hr(),
h4("Expression table plot:"),
plotOutput("tabplot1"),
hr(),
fluidRow(
column(4, offset = 1,
numericInput("tl_binSize", "Bin size:", value = NA)
),
column(4,
numericInput("tl_varCut", "Variation cut:", value = 1)
)
),
textOutput("tl_text")
)),
tabPanel("Margin Events",
fluidPage(
hr(),
fluidRow(
column(4, offset = 1,
selectInput("side", "Select checking side:",
choices = c("both", "upper", "lower"),
selected = "both")
),
column(4,
numericInput("tol", "Tolerance value:", -.Machine$double.eps)
)
),
hr(),
plotOutput("meplot"),
hr(),
h4("Time Distribution of Margin Events:"),
fluidRow(
column(5, offset = 1, uiOutput("me_sample_choose") ),
column(3, uiOutput("me_channel_choose") )
),
hr(),
htmlOutput("upMeTimePlot"),
htmlOutput("lowMeTimePlot"),
br(),
br(),
textOutput("meTime_text")
)),
tabPanel("QA score", fluidPage(
hr(),
uiOutput("score_sample_choose"),
h4("QA score summary:"),
plotOutput("scoreplot"),
fluidRow(
column(width = 3,
numericInput("score_nrbins", "Row bins:", value = 100)
),
column(width = 3, offset = 1,
numericInput("scoreThres", "Threshold score:", value = 3, step = 0.1)
),
column(width = 4, offset = 1,
uiOutput("sort_ID")
)
)
)),
tabPanel("Summary",
fluidPage(
verticalLayout(
hr(),
h4("Cell Number check:"),
htmlOutput("cntable"),
hr(),
h4("Margin Events check:"),
htmlOutput("metable"),
hr(),
h4("Time flow check:"),
plotOutput("s_tfplot"),
hr(),
h4("Timeline check:"),
plotOutput("s_tlplot")
)
))
)
)
)),
#####
navbarMenu("Gating & Clustering", #Menú de gating y clústering
tabPanel("Gating",
h3("Module for Data visualization and Manual Gating"),
br(),
h5(strong("Description:")),
p("Allows compensation of an FCS file, FSC/SSC visualization and carrying out Manual gating over the data"),
hr(),
fluidRow(
column(3, #lado izquierdo con todos los botones interactivos
h5("Parameters:"),
fileInput('gatingFCSfile', strong('Choose fcs file:'), multiple = FALSE, #de momento que el archivo sea único, en una mejora se podría mirar para meter varios
accept = c('text/fcs', '.fcs')),
actionButton("gating1_Button", "Submit!"),
hr(),
checkboxInput("check_compensate1","To compensate FCS data please provide a compensation matrix , if compensation matrix is incluided in file ignore this button", value=FALSE),
conditionalPanel(
condition= "input.check_compensate1 == 1",
fileInput('compensate1FCSfile', strong('Choose compensation matrix:'), multiple = FALSE, #de momento que el archivo sea único, en una mejora se podría mirar para meter varios
accept = c('text/fcs', '.fcs'))
),
hr(),
div(style = "margin-top: 30px; width: 200px; ", HTML("Gating is based on CytoTree package: Dai Y (2021). CytoTree: A Toolkit for Flow And Mass Cytometry Data. ")),
div(style = "margin-top: 10px; ",
tags$a(href="https://github.com/JhuangLab/CytoTree", "Github Repository"))
),
column(9,
fluidRow(h5("Here you can observe your raw data on an FSC/SSC plot"),
plotOutput("FCSvsSSC_plot"),
downloadButton("gating_graph1", "Download plot")
),
hr(),
tags$script("$(document).on('shiny:connected', function(event) { #mejorar la resolución del gráfico: https://stackoverflow.com/questions/45642283/how-to-save-png-image-of-shiny-plot-so-it-matches-the-dimensions-on-my-screen
var myWidth = $(window).width();
Shiny.onInputChange('shiny_width',myWidth)
});"),
tags$script("$(document).on('shiny:connected', function(event) {
var myHeight = $(window).height();
Shiny.onInputChange('shiny_height',myHeight)
});"),
fluidRow(h5("Please, provide upper and lower gate values to get a subsample of your data."),
p("After clicking on “Gate Events” an updated FSC/SSC plot will appear. This process can take some time."),
column(width=3,
p("Upper Gate"),
numericInput("Upper_SSC", "SSC:", 0), #puede añadirse un campo indicando valor máximo o mínimo que se puede meter, esto sería una mejora
numericInput("Upper_FSC", "FSC:", 0),
),
column(width=1),
column(width=3,
p("Lower Gate"),
numericInput("Lower_SSC", "SSC:", 0),
numericInput("Lower_FSC", "FSC:", 0)
),
column(width=1,
br(),
actionButton("gating2_Button", "Gate Events!")),
plotOutput("FCSvsSSC_gated_plot"),
),
br(),
br(),
fluidRow(br(), #meto muchos espacios porque se me solapaban los gráficos
br(),
br(),
br(),
br(),
br(),
br(),
downloadButton("gating_graph2", "Download plot"),
hr(),
h5("Plot your gated events"),
p ("Here you can set xaxis and yaxis values :"),
uiOutput("gating_xaxis"),
uiOutput("gating_yaxis"),
plotlyOutput("gated_interactive_plot")
)
)
)),
tabPanel("Clustering",
h3("Module for Flow Cytometry Clustering"),
br(),
h5(strong("Description:")),
p("Allows Clustering FCS data using 6 clustering algorythms "),
hr(),
fluidRow(
column(3, #lado izquierdo con todos los botones interactivos
h5("Parameters:"),
selectInput("algorythm", "Please choose a clustering algorythm to show more options",
c("","SOM", "KMEANS","CLARA", "PHENOGRAPH", "MCLUST", "HCLUST"),selected=NULL,multiple = FALSE),
fileInput('clusteringFile', strong('Choose fcs file:'), multiple = FALSE, #de momento que el archivo sea único, en una mejora se podría mirar para meter varios
accept = c('text/fcs', '.fcs')),
actionButton("clustering1_Button", "Submit!"),
hr(),
#Uso un conditional panel para proporcionar la matriz de compensación
checkboxInput("check_compensate2","To compensate FCS data please provide a compensation matrix , if compensation matrix is incluided in file ignore this button", value=FALSE),
conditionalPanel(
condition= "input.check_compensate2 == 1",
fileInput('compensate2FCSfile', strong('Choose compensation matrix:'), multiple = FALSE, #de momento que el archivo sea único, en una mejora se podría mirar para meter varios
accept = c('text/fcs', '.fcs'))
),
hr(),
div(style = "margin-top: 30px; width: 200px; ", HTML("Clustering is based on CytoTree package: Dai Y (2021). CytoTree: A Toolkit for Flow And Mass Cytometry Data. ")),
div(style = "margin-top: 10px; ",
tags$a(href="https://github.com/JhuangLab/CytoTree", "Github Repository"))
),
column(9,
conditionalPanel(
condition= "input.algorythm=='' ",
fluidRow( h5(strong("Flow Cytometry Clustering")),
p("On the parameters menu, on the left-side part of the page you can select up to 6 different clustering algorithms to apply to your data:"),
h6("SOM: Self Organizing Maps"),
h6("K-MEANS"),
h6("CLARA :Clustering Large Applications"),
h6("PHENOGRAPH"),
h6("HCLUST:Hierarchical Clustering"),
h6("MCLUST: Model-Based Clustering"),
p("Once the algorithm is performed , four-dimensional reduction methods are applied to each cluster, including PCA, tSNE, diffusion maps, and UMAP, so on last instance you will get a 2D-visualization of your data:"),
br(),
tags$img(src="Ejemplo.png", width="937px", height="400px")
)
),
conditionalPanel(
condition= "input.algorythm == 'SOM'",
fluidRow(
h5(strong("SOM (Self Organizing Maps) algorithm")),
p("The Self-Organizing Map is one of the most popular neural network models, it is based on unsupervised learning. You can submitt your FCS file and select your clustering parameters. Results will be visualized on a 2D plot"),
p("If you wish to learn more about SOM algorithm on flow cytometry click:", tags$a(href="https://ytdai.github.io/CytoTree/ti.html", "here")),
br(),
br(),
p(strong("Clustering parameters:")),
numericInput("som_number", "Number of clusters:", 50),
p("For > 100,000 events is recommended to carry out downsampling. You can set percentage of downsampled cells (1= 100% of cells, 0.5= 50% of cells..)"),
numericInput("som_downsampling", "Downsampling percentage:", 1, min=0.000001, max=1),
p ("Here you can set xaxis and yaxis values :"),
uiOutput("som_xaxis"),
uiOutput("som_yaxis"),
hr(),
plotlyOutput("SOM_plot"))
),
conditionalPanel(
condition = "input.algorythm == 'KMEANS'",
fluidRow(
h5(strong("K-MEANS algorithm")),
p("K-Means is a widely used non supervised clustering algorithm. You can submitt your FCS file and select your clustering parameters. Results will be visualized on a 2D plot"),
p("If you wish to learn more about K-MEANS algorithm on flow cytometry click:", tags$a(href="https://ytdai.github.io/CytoTree/ti.html", "here")),
br(),
br(),
p(strong("Clustering parameters:")),
numericInput("k_number", "Number of clusters:", 50),
p("For > 100,000 events is recommended to carry out downsampling. You can set percentage of downsampled cells (1= 100% of cells, 0.5= 50% of cells..)"),
numericInput("k_downsampling", "Downsampling percentage:", 1, min=0.000001, max=1),
p ("Here you can set xaxis and yaxis values :"),
uiOutput("kmeans_xaxis"),
uiOutput("kmeans_yaxis"),
hr(),
plotlyOutput("KMEANS_plot")
)),
conditionalPanel(
condition = "input.algorythm == 'CLARA'",
fluidRow(
h5(strong("CLARA (Clustering Large Applications) algorithm ")),
p("CLARA is an extension to the PAM (Partitioning Around Medoids) clustering method. You can submitt your FCS file and select your clustering parameters. Results will be visualized on a 2D plot"),
p("If you wish to learn more about CLARA algorithm on flow cytometry click:", tags$a(href="https://ytdai.github.io/CytoTree/ti.html", "here")),
br(),
br(),
p(strong("Clustering parameters:")),
numericInput("clara_number", "Number of clusters:", 50),
p("For > 100,000 events is recommended to carry out downsampling. You can set percentage of downsampled cells (1= 100% of cells, 0.5= 50% of cells..)"),
numericInput("clara_downsampling", "Downsampling percentage:", 1, min=0.000001, max=1),
p ("Here you can set xaxis and yaxis values :"),
uiOutput("clara_xaxis"),
uiOutput("clara_yaxis"),
hr(),
plotlyOutput("CLARA_plot")
)),
conditionalPanel(
condition = "input.algorythm == 'PHENOGRAPH'",
fluidRow(
h5(strong("PHENOGRAPH")),
p("PhenoGraph is a clustering method designed for high-dimensional single-cell data. You can submitt your FCS file and select your clustering parameters. Results will be visualized on a 2D plot"),
p("This algorithm is not recommended for data with more than 10,000 events. Note that this process can take some time"),
p("If you wish to learn more about PhenoGraph algorithm on flow cytometry click:", tags$a(href="https://ytdai.github.io/CytoTree/ti.html", "here")),
br(),
br(),
p(strong("Clustering parameters:")),
#con el algoritmo de phenograph no se pueden modificar el número de clústers
p("For > 100,000 events is recommended to carry out downsampling. You can set percentage of downsampled cells (1= 100% of cells, 0.5= 50% of cells..)"),
numericInput("pheno_downsampling", "Downsampling percentage:", 1, min=0.000001, max=1),
p ("Here you can set xaxis and yaxis values :"),
uiOutput("pheno_xaxis"),
uiOutput("pheno_yaxis"),
hr(),
plotlyOutput("PHENO_plot")
)),
conditionalPanel(
condition = "input.algorythm == 'HCLUST'",
fluidRow(
h5(strong("HCLUST:Hierarchical Clustering ")),
p("You can submitt your FCS file and select your clustering parameters. Results will be visualized on a 2D plot"),
p("This algorithm is not recommended for data with more than 50,000 events. Note that this process can take some time"),
p("If you wish to learn more about HCLUST algorithm on flow cytometry click:", tags$a(href="https://ytdai.github.io/CytoTree/ti.html", "here")),
br(),
br(),
p(strong("Clustering parameters:")),
numericInput("h_number", "Number of clusters:", 50),
p("For > 100,000 events is recommended to carry out downsampling. You can set percentage of downsampled cells (1= 100% of cells, 0.5= 50% of cells..)"),
numericInput("h_downsampling", "Downsampling percentage:", 1, min=0.000001, max=1),
p ("Here you can set xaxis and yaxis values :"),
uiOutput("hclust_xaxis"),
uiOutput("hclust_yaxis"),
hr(),
plotlyOutput("HCLUST_plot")
)
),
conditionalPanel(
condition = "input.algorythm == 'MCLUST'",
fluidRow(
h5(strong("MCLUST: Model-Based Clustering")),
p("You can submitt your FCS file and select your clustering parameters. Results will be visualized on a 2D plot"),
p("This algorithm is not recommended for data with more than 10,000 events. Note that the process can take some time"),
p("If you wish to learn more about MCLUST algorithm on flow cytometry click:", tags$a(href="https://ytdai.github.io/CytoTree/ti.html", "here")),
br(),
br(),
p(strong("Clustering parameters:")),
numericInput("m_number", "Number of clusters:", 50),
p("For > 100,000 events is recommended to carry out downsampling. You can set percentage of downsampled cells (1= 100% of cells, 0.5= 50% of cells..)"),
numericInput("m_downsampling", "Downsampling percentage:", 1, min=0.000001, max=1),
sliderInput("m_perplexity", "Perplexity:", min=1, max=50, 2 ),
p ("Here you can set xaxis and yaxis values :"),
uiOutput("mclust_xaxis"),
uiOutput("mclust_yaxis"),
hr(),
plotlyOutput("MCLUST_plot")
)
)
)
)
)
))
)
################
options(shiny.maxRequestSize=900*1024^2) #esta línea de código permite subir archivos hasta esa limitación de tamaño
###Server (es la parte que procesa los datos)
server<- function(input,output) {
#el input es reactivo, es decir, cada vez que cambie $input, se reejecutará
###PREPROCESSING
#PreviewFCS
observeEvent(input$go_fcspreview,
{if (is.null(input$go_fcspreview)) return(NULL)
show_modal_spinner(
spin = "double-bounce",
color = "#112446",
text = "Please wait...",
)
FCSfile<-input$previewFCSfile$name
FCSfile_path<-input$previewFCSfile$datapath
previewfcs_result <- py$PreviewFCS_function(FCSfile, FCSfile_path) #desde aquí invoco la función de python creada por mi y la aplico sobre el archivo que toma como input la interfaz de shiny
output$fcspreviewresult=renderUI({
actionButton(inputId = "fcspreviewresult",
label= "Download your results",
icon= icon("download"),
onclick= paste( "window.open(","'", previewfcs_result,"',", "'_blank')")) #El resultado del procesado de genepattern devuelve un link de descarga automática del zip con los resultados
}
)
remove_modal_spinner()
})
#FCStoCSV
observeEvent(input$go_FCStoCSV,
{if (is.null(input$go_FCStoCSV)) return(NULL)
show_modal_spinner(
spin = "double-bounce",
color = "#112446",
text = "Please wait...",
)
FCSfile<-input$FCSfile_input_2convrt$name
FCSfile_path<-input$FCSfile_input_2convrt$datapath
csv_result <- py$FcsToCsv_function(FCSfile, FCSfile_path)
output$FCStoCSVresult=renderUI({
actionButton(inputId = "FCStoCSVresult",
label= "Download your results",
icon= icon("download"),
onclick= paste( "window.open(","'", csv_result,"',", "'_blank')"))
}
)
remove_modal_spinner()
})
#CSVtoFCS
observeEvent(input$go_CSVtoFCS,
{if (is.null(input$go_CSVtoFCS)) return(NULL)
show_modal_spinner(
spin = "double-bounce",
color = "#112446",
text = "Please wait...",
)
CSVfile<-input$csvfile_input$name
CSVfile_path<-input$csvfile_input$datapath
#print(CSVfile_path)
prueba <-system(paste0("java -jar csv2fcs.jar -InputFile:", CSVfile_path))
FCSfile<- gsub(".csv", ".fcs", CSVfile) #nombre del nuevo fichero
FCSfile_path<- gsub(".csv", ".fcs", CSVfile_path) #ruta al nuevo fichero
output$CSVtoFCSresult <- downloadHandler(
filename = function(){
paste(FCSfile)
},
content=function(file){
#print(file)
#print(FCSfile_path)
file.copy(FCSfile_path, file)
}
)
#)
remove_modal_spinner()
})
###QUALITY CONTROL
#Casi todo el código de este apartado se ha cogido de FlowiQC, de su repositorio de GitHub , realizo anotaciones y algunas modificaciones
## Lectura del archivo FCS
observeEvent(input$goButton, {
if (is.null(input$goButton)) return (NULL) #mientras el valor inicial del botón sea 0 (es decir no se ha pulsado nada aún)no va a devolver nada
isolate({fcsFiles <- input$fcsFiles #dentro de la función reactiva aislamos la lectura del fichero, para que una vez leido lo almacene y no rejecute código aunque cambien otros parámetros de esta expresión
if (is.null(fcsFiles))
return(NULL) #cuando no se suba ningún archivo no devuelve nada
set <- read.flowSet(fcsFiles$datapath) #si hay archivo y se ha dado a submit, lee el archivo FCS con la funcion del paquete flowCore
sampleNames(set) <- fcsFiles$name})
## Lectura de los distintos canales
channels <- reactive({
if(is.null(set))
return(NULL) #es reactivo, si no hay objeto set no habrá resultado en pantalla
pd <- set[[1]]@parameters@data #si lo he entendido bien se usa para crear un objeto de tipo S4 al que accedemos a sus variables por @
channels <- pd$name
return(channels)
})
## Obtención de los marcadores
markerNames <- reactive({ #Aquí generamos una variable con los nombres de los marcadores
if(is.null(set))
return(NULL) #de nuevo se hace reactivo y dependiente
pd <- set[[1]]@parameters@data
markers <- paste("<", pd$name, ">:", pd$desc, sep = "")
return(markers)