-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQuickAnalysis.Rmd
863 lines (793 loc) · 30.8 KB
/
QuickAnalysis.Rmd
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
---
title: "Quick Analysis Example"
output:
flexdashboard::flex_dashboard:
orientation: rows
theme: paper
navbar:
- {icon: "ion-social-github", href: "https://github.com/AdeelK93/QuickAnalysis", align: right}
runtime: shiny
---
```{r setup, include=FALSE}
library(flexdashboard)
library(Cairo)
options(shiny.usecairo=T)
library(dygraphs)
library(rhandsontable)
suppressMessages(library(DT))
source('QuickAnalysis.R')
```
Import {data-orientation=columns}
=====================================
Column {.sidebar}
-----------------------------------------------------------------------
An example for importing data and making plots
```{r Sidebar}
options(shiny.maxRequestSize=30*1024^2) #30 mb limit
fileInput(
'fileschosen',
'Accepted formats: csv, xls, xlsx (any combination)',
multiple = T,
accept = c('.csv', '.xls', '.xlsx')
)
imported.orig <- reactive({
validate(need(!is.null(input$fileschosen),F))
x <- tryCatch(import(input$fileschosen),error=function(e) NULL)
validate(need(x,"add more descriptive error messages here"))
x
})
```
* For excel files with multiple sheets, only sheets with the max number of columns will be imported
* Data must have column names present in order to be successfully imported
* You can download the merged dataset as a zipped csv below:
```{r Download}
output$download <- downloadHandler(paste('data-', Sys.Date(), '.zip', sep=''),
content = function(file) if(!is.null(imported())) {
setwd(tempdir())
names <- paste0(levels(as.factor(imported()$Battery.ID)),".csv")
#split up the data by ID and reduce file size
spl <- lapply(split(imported(),imported()$Battery.ID),
function(x) select(x,-Battery.ID,-Type,-Filename,
-TimeHr,-TimeMin,-StepTimeHr,-StepTimeMin))
mapply(write_csv,spl,names)
#the warning is to deal with windows computers
tryCatch(zip(zipfile=file, files=names),warning=function(e) zip(zipfile=file, files=names,
zip = "C:/Program Files/Rtools/bin/zip"))
},
contentType = "application/zip"
)
fluidPage(downloadButton('download', 'Download csv'))
```
Column {data-width=400 .tabset .tabset-fade}
-------------------------------------
###Choose variables
```{r vars.input}
#remove text columns
graphnames.orig <- reactive(colnames(imported.orig()[sapply(imported.orig(), is.numeric)]))
output$voltage <- renderUI({
selectInput("voltage","Voltage:",graphnames.orig(),
agrep.best("Voltage",colnames(imported.orig())),T)
})
voltage.sorted <- reactive(if(!is.null(imported.orig())) {
#rowMeans=merging columns in a moderately efficient way
#rowSums can't handle 0s well
rowMeans(imported.orig()[input$voltage],na.rm=T)
})
output$current <- renderUI({
selectInput("current","Current:",graphnames.orig(),
agrep.best("Current",colnames(imported.orig())),T)
})
current.sorted <- reactive(if(!is.null(imported.orig())) {
rowMeans(imported.orig()[input$current],na.rm=T)
})
output$amphours <- renderUI({
selectInput("amphours","Capacity (Amp-hours):",graphnames.orig(),
agrep.best("Amp.Hours",colnames(imported.orig())),T)
})
amphours.sorted <- reactive(if(!is.null(imported.orig())) {
rowMeans(imported.orig()[input$amphours],na.rm=T)
})
output$totaltime <- renderUI({
selectInput("totaltime","Total elapsed time:",graphnames.orig(),
agrep.best("Total.Time",colnames(imported.orig())),T)
})
totaltime.sorted <- reactive(if(!is.null(imported.orig())) {
x <- rowMeans(imported.orig()[input$totaltime],na.rm=T)
if(min(x[x>0.00001],na.rm=T)<0.05) { #time in days?
x <- ave(x,imported.orig()$Filename,FUN=function(x) {
#only modify files with time reporting in days
if(min(x[x>0.00001],na.rm=T)<0.01) x*24*3600
else x
})
}
if(sum(is.na(x))) return(x)
#verify that data is monotonic
x <- ave(x,imported.orig()$Filename,FUN=function(y) {
if(!all(y==cummax(y))) y <- as.monotonic(y) #nonmonotonic
else y
})
x
})
output$steptime <- renderUI({
selectInput("steptime","Step time:",graphnames.orig(),
agrep.best("Step.Time",colnames(imported.orig())),T)
})
steptime.sorted <- reactive(if(!is.null(imported.orig())) {
x <- rowMeans(imported.orig()[input$steptime],na.rm=T)
if(min(x[x>0.00001],na.rm=T)<0.05) { #time in days?
x <- ave(x,imported.orig()$Filename,FUN=function(x) {
#only modify files with time reporting in days
if(min(x[x>0.00001],na.rm=T)<0.01) x*24*3600
else x
})
}
x
})
output$step <- renderUI({
selectInput("step","Step index:",graphnames.orig(),
agrep.best("Step",colnames(imported.orig())),T)
})
step.sorted <- reactive(if(!is.null(imported.orig())) {
rowMeans(imported.orig()[input$step],na.rm=T)
})
output$cycle <- renderUI({
selectInput("cycle","Cycle counter:",graphnames.orig(),
agrep.best("Cycle",colnames(imported.orig())),T)
})
cycle.sorted <- reactive(if(!is.null(imported.orig())) {
x <- rowMeans(imported.orig()[input$cycle],na.rm=T)
if(sum(is.na(x))) return(x)
#verify that data is monotonic
x <- ave(x,imported.orig()$Filename,FUN=function(y) {
if(!all(y==cummax(y))) y <- as.monotonic(y) #nonmonotonic
else y
})
x
})
incomplete <- reactive({if(is.null(imported())) return(NULL)
#count the number of missing values, for heatmap and diagnostics
sum(sapply(imported()[c("Battery.ID",stdnames)], function(x) sum(is.na(x))))
})
```
```{r import.vars}
fluidPage(column(12,div(
style = "height:70px;",
htmlOutput("voltage"),
htmlOutput("current"),
htmlOutput("amphours"),
htmlOutput("totaltime"),
htmlOutput("steptime"),
htmlOutput("step"),
htmlOutput("cycle"),
renderText(if(!is.null(imported())) paste("If your dataset has different column names between files, you must select all applicable columns above.",incomplete(),
"missing values found, see heatmap for more details."))
)))
imported.sorted <- reactive({
if(is.null(imported.orig())) return(NULL)
x <- imported.orig()[setdiff(colnames(imported.orig()),c(
input$voltage,input$current,input$amphours,input$totaltime,
input$steptime,input$step,input$cycle))] #drop columns
x <- data.frame(Voltage=voltage.sorted(),Current=current.sorted(),
Amp.Hours=amphours.sorted(),Total.Time=totaltime.sorted(),
Step.Time=steptime.sorted(),Step=step.sorted(),
Cycle=cycle.sorted(),x)
x <- mutate(x, #add time data
TimeMin=Total.Time/60, TimeHr=Total.Time/3600,
StepTimeMin=Step.Time/60, StepTimeHr=Step.Time/3600
)
tryCatch(calculaterechargefactor(x),error=function(e) x)
})
imported <- reactive({ #this is the final sorted dataset to be used by analytical functions
if(is.null(imported.sorted())) return(NULL)
x <- select(imported.sorted(), -Type, -Battery.ID)
suppressMessages(left_join(x,labs())) %>%
arrange(Type,Battery.ID) %>%
seg.stitch() %>%
mutate(Type=as.factor(Type),Battery.ID=as.factor(Battery.ID)) %>%
filter(Type!="skip")
})
```
###Heatmap
Heatmap shows where missing values are concentrated (if applicable)
```{r heatmap}
output$heatmap <- renderPlotly(if(!is.null(imported())){
tryCatch(ggplotly({
heat <- aggregate(imported()[stdnames],list(imported()$Battery.ID),function(x) sum(is.na(x)))
heat <- suppressMessages(melt(heat))
colnames(heat) <- c("Battery.ID","Column","Missing.Values")
ggplot(heat,aes(Column,Battery.ID,fill=Missing.Values)) +
geom_tile()+scale_fill_continuous(low="gray95",high="firebrick") +
theme_minimal() + theme(axis.text.x = element_text(angle = 30,
hjust = 1),legend.position="none")+ylab(" ")+xlab(" ")
}) %>% config(displayModeBar = F),error=function(e) ggplotly(ggplot()))
})
plotlyOutput("heatmap")
#renderText(if(identical(incomplete(),0)) return("No missing values remain! All data has been accounted for."))
```
###Diagnostic
```{r diagnostic}
radioButtons("diag.choice",NULL,c("Summary","Structure","Head","Tail"),inline=T)
renderPrint(switch(input$diag.choice,
"Summary"=summary(imported()),
"Structure"=str(imported()),
"Head"=head(imported()),
"Tail"=tail(imported())
))
```
Column {data-width=600}
-------------------------------------
###Label Table
Will ignore files with type "skip".
```{r labeltable}
values <- reactiveValues(labels=NULL)
observeEvent(imported.orig(), {
values$labels <- data.frame(Filename=imported.orig()$Filename,
Type=as.character(imported.orig()$Type),
Battery.ID=as.character(imported.orig()$Battery.ID),
stringsAsFactors=F)[!duplicated(imported.orig()$Filename),]
})
output$labels.hot <- renderRHandsontable(if(!is.null(values$labels)){
rhandsontable(values$labels, contextMenu=F, maxRows=length(unique(imported.orig()$Filename)),
rowHeaders = NULL, stretchH = "all") %>%
hot_col("Filename", readOnly = T)
})
rHandsontableOutput("labels.hot")
labs <- reactive({
if(!is.null(input$labels.hot)) hot_to_r(input$labels.hot)
else values$labels
})
```
###Customize Colors
Hex colors or any of [these named colors](http://www.stat.columbia.edu/~tzheng/files/Rcolor.pdf).
```{r colortable}
values <- reactiveValues(colors=NULL)
observeEvent(labs(), {
values$colors <- data.frame(Type=sort(unique(labs()$Type[labs()$Type!="skip"])),
Color=rainbow_hcl(length(unique(labs()$Type[labs()$Type!="skip"])),70),
stringsAsFactors=F)
})
observeEvent(imported.orig(), {
values$colors <- data.frame(Type=sort(unique(labs()$Type[labs()$Type!="skip"])),
Color=rainbow_hcl(length(unique(labs()$Type[labs()$Type!="skip"])),70),
stringsAsFactors=F)
})
output$colors.hot <- renderRHandsontable(if(!is.null(values$colors)){
rhandsontable(values$colors, contextMenu=F,
maxRows=length(unique(labs()$Type[labs()$Type!="skip"])),
rowHeaders = NULL) %>%
hot_col("Type", readOnly = T)
})
rHandsontableOutput("colors.hot")
cols <- reactive({ #this is the color data, by type
if(!is.null(input$colors.hot)) hot_to_r(input$colors.hot)
else values$colors
})
cols.cast <- reactive({ #this is the color data, by ID
if(!is.null(cols())){
x <- suppressMessages(arrange(left_join(filter(labs(),Type!="skip"),
cols()),Battery.ID))
x$Battery.ID <- gsub(" ?#[[:digit:]]+$","",x$Battery.ID)
x
}
})
```
Explore {data-orientation=columns data-navmenu="Continuous"}
=====================================
Column {data-width=200 .tabset .tabset-fade}
-------------------------------------
### Choose options
Select continuous variables for graphing
```{r xy.options}
graphnames <- reactive(if(!is.null(imported())) colnames(imported()[sapply(imported(),
is.numeric)]))
timeunits <- reactive(if(!is.null(imported.sorted())) {
x <- max(imported.sorted()$Total.Time, na.rm = T)
if(x<300) return("Total.Time") #under 5 minutes -> seconds
else if(x<7200) return("TimeMin") #under 2 hours -> minutes
else return("TimeHr") #hours
})
#this data is fed into the continuous variable graph
imported.xy <- reactive(if(!is.null(imported())) {
if(is.null(input$xy.cycle)) return(imported())
else if(input$xy.cycle==0) x <- imported()
else { #baseline time stamp correction
x <- imported()[imported()$Cycle==input$xy.cycle,] %>%
within({Total.Time <- ave(Total.Time, Battery.ID, FUN=function(x) x-min(x))}) %>%
mutate(TimeHr=Total.Time/3600,TimeMin=Total.Time/60)
}
if(input$xy.step) x <- filter(x,Step==input$xy.step)
x <- tryCatch(filter(x,
Voltage>=input$xy.voltage[1],Voltage<=input$xy.voltage[2],
Current>=input$xy.current[1],Current<=input$xy.current[2],
Amp.Hours>=input$xy.amphours[1],Amp.Hours<=input$xy.amphours[2],
Total.Time>=input$xy.totaltime[1],Total.Time<=input$xy.totaltime[2],
Step.Time>=input$xy.steptime[1],Step.Time<=input$xy.steptime[2]
),error=function(e) x)
if(input$xy.avg & !is.null(x)) {
x <- avgsem(select_(x,input$top.yn,input$bottom.yn,input$bottom.xn,
"Type","Battery.ID"),input$bottom.xn)
}
return(x)
})
#remove filtered out colors
xy.cols <- reactive(if(!is.null(imported.xy())) {
cols()$Color[cols()$Type %in% imported.xy()$Type]
})
xy.cols.cast <- reactive(if(!is.null(imported.xy())) {
cols.cast()$Color[cols.cast()$Battery.ID %in% imported.xy()$Battery.ID]
})
output$top.yn <- renderUI({
selectInput("top.yn","Top y-axis:",graphnames(),"Current")
})
output$bottom.yn <- renderUI({
selectInput("bottom.yn","Bottom y-axis:",graphnames(),"Voltage")
})
output$bottom.xn <- renderUI({
selectInput("bottom.xn","Common x-axis:",graphnames(),timeunits())
})
fluidPage(column(12,div(
style = "height:80px;",
htmlOutput("top.yn"),
htmlOutput("bottom.yn"),
htmlOutput("bottom.xn"),
checkboxInput("xy.avg","Average/SEM by type"),
textOutput("legendDivID")
)))
```
###Filter
```{r xy.filter}
#filter dataset for continuous variable analysis
#filter min/max determine the bounds of the sliders
output$xy.voltage <- renderUI({
sliderInput("xy.voltage","Select a voltage range:",filter.min()[1],filter.max()[1],
c(filter.min()[1],filter.max()[1]),0.1)
})
output$xy.current <- renderUI({
sliderInput("xy.current","Select a current range:",filter.min()[2],filter.max()[2],
c(filter.min()[2],filter.max()[2]),0.1)
})
output$xy.amphours <- renderUI({
sliderInput("xy.amphours","Select a capacity range:",filter.min()[3],filter.max()[3],
c(filter.min()[3],filter.max()[3]),0.1)
})
output$xy.totaltime <- renderUI({
sliderInput("xy.totaltime","Select a total time range:",filter.min()[4],filter.max()[4],
c(filter.min()[4],filter.max()[4]),1)
})
output$xy.steptime <- renderUI({
sliderInput("xy.steptime","Select a step time range:",filter.min()[5],filter.max()[5],
c(filter.min()[5],filter.max()[5]),1)
})
output$xy.step <- renderUI({
sliderInput("xy.step","Is there a step to isolate? (0 for no)",0,
tryCatch(max(imported.sorted()$Step),
error=function(e) 1),0,1,T)
})
output$xy.cycle <- renderUI({
sliderInput("xy.cycle","Is there a cycle to isolate? (0 for no)",0,
tryCatch(max(imported.sorted()$Cycle),
error=function(e) 1),0,1,T)
})
fluidPage(column(12,div(
style = "height:80px;",
htmlOutput("xy.voltage"),
htmlOutput("xy.current"),
htmlOutput("xy.amphours"),
htmlOutput("xy.totaltime"),
htmlOutput("xy.steptime"),
htmlOutput("xy.step"),
htmlOutput("xy.cycle")
)))
```
Column
-----------------------------------------------------------------------
### Top Graph {.no-title}
```{r top.graph}
renderDygraph(withProgress(
message="Rendering plot...",
dygraph.cast(imported.xy(),input$bottom.xn,input$top.yn,input$bottom.xn,
input$top.yn,xy.cols.cast(),xy.cols(),group="brc")
))
```
### Bottom Graph {.no-title}
```{r bottom.graph}
renderDygraph(withProgress(
message="Rendering plot...",
dygraph.cast(imported.xy(),input$bottom.xn,input$bottom.yn,input$bottom.xn,
input$bottom.yn,xy.cols.cast(),xy.cols(),group="brc")
))
```
Share {data-orientation=columns data-navmenu="Continuous"}
=====================================
Column {data-width=250 .tabset .tabset-fade}
-------------------------------------
### Choose options
Customize continuous variable chart for sharing:
```{r xypublish.options}
fluidPage(
#checkboxInput("xypub.both","Include bottom graph (not yet working)"),
selectInput("xypub.theme","Graph theme:",c("Default","Minimal","Grayscale")),
selectInput("xypub.legend","Legend position:",c("None","Side"="right","Above"="top",
"Below"="bottom","Top-left"="c(0,1)","Top-right"="c(1,1)",
"Bottom-left"="c(0,0)","Bottom-right"="c(1,0)")),
sliderInput("xypub.fsize","Font size:",10,20,12,0.5),
textInput("xypub.title","Chart title:",""),
helpText("Download chart options:"),
splitLayout(
numericInput("xypub.savew","Width:",12),
numericInput("xypub.saveh","Height:",8),
downloadButton("xypub.png","PNG"),
downloadButton("xypub.svg","SVG")
)
)
#linesize?
```
###Additional Options
Customize continuous variable chart for sharing:
```{r xypublish.options2}
fluidPage(
helpText("X-axis options:"),
textInput("xypub.xlab","X-axis label:",""),
splitLayout(
numericInput("xypub.x1","X start:",NA),
numericInput("xypub.x2","X end:",NA)
),
helpText("Y-axis options:"),
textInput("xypub.ylab","Y-axis label:",""),
splitLayout(
numericInput("xypub.y1","Y start:",NA),
numericInput("xypub.y2","Y end:",NA)
),
#splitLayout(
# textInput("xypub.y1b","Y2 start:"),
# textInput("xypub.y2b","Y2 end:")
#),
helpText("Horizontal line options:"),
splitLayout(
textInput("xyhline.col","Color:","None"),
numericInput("xyhline.val","Position:",0),
numericInput("xyhline.size","Size:",0.8,step=.2)
)
)
```
Column {data-width=700}
-------------------------------------
### Graph {.no-title}
```{r xypublish.graph}
xyline1 <- reactive(if(!is.null(imported.xy())) {
gg <- linegraph(imported.xy(),input$bottom.xn,input$top.yn) #avg/sem
if(input$xy.avg) gg <- gg + scale_color_manual(values=xy.cols(),name="") +
scale_fill_manual(values=xy.cols(),name="")
else gg <- gg + scale_color_manual(values=xy.cols.cast(),name="") #regular
gg
})
renderPlot(withProgress(message="Rendering...",xypub.graph()))
xypub.graph <- reactive(if(!is.null(imported.xy())) {
#these are the x-y limits
xlim <- c(input$xypub.x1,input$xypub.x2)
if(any(is.na(xlim))) xlim <- NULL
ylim <- c(input$xypub.y1,input$xypub.y2)
if(any(is.na(ylim))) ylim <- NULL
gg <- xyline1() + coord_cartesian(xlim=xlim,ylim=ylim)
#if(input$xypub.both){
# gg2 <- xyline2()
#}
if(input$xyhline.col!="None" & input$xyhline.col!="none" & nchar(input$xyhline.col)){
gg <- gg + geom_hline(aes_(yintercept=input$xyhline.val),linetype=2,
color=input$xyhline.col,size=input$xyhline.size)
}
if(input$xypub.theme=="Default") gg <- gg + theme_gray(base_size=input$xypub.fsize)
if(input$xypub.theme=="Minimal") gg <- gg + theme_bw(base_size=input$xypub.fsize)
if(input$xypub.theme=="Grayscale") gg <- gg + theme_pub(base_size=input$xypub.fsize) +
scale_fill_grey(start=0,end=.9,name="") + scale_color_grey(start=0,end=.9,name="")
if(!length(grep(",",input$xypub.legend))) gg <- gg + theme(legend.position=input$xypub.legend,
legend.title=element_blank())
else gg <- gg + theme(legend.position=eval(parse(text=input$xypub.legend)),
legend.justification=eval(parse(text=input$xypub.legend)),
legend.title=element_blank())
if(nchar(input$xypub.title)) gg <- gg + ggtitle(input$xypub.title)
if(nchar(input$xypub.ylab)) gg <- gg + ylab(input$xypub.ylab)
if(nchar(input$xypub.xlab)) gg <- gg + xlab(input$xypub.xlab)
gg
})
output$xypub.png <- downloadHandler(paste('plot-', Sys.Date(), '.png', sep=''),
content = function(file) if(!is.null(imported.xy())) {
ggsave(file,device="png",width=input$xypub.savew,height=input$xypub.saveh)
}
)
output$xypub.svg <- downloadHandler(paste('plot-', Sys.Date(), '.svg', sep=''),
content = function(file) if(!is.null(imported.xy())) {
ggsave(file,device="svg",width=input$xypub.savew,height=input$xypub.saveh)
}
)
```
Explore {data-orientation=columns data-navmenu="Discrete"}
=====================================
Column {data-width=250 .tabset .tabset-fade}
-------------------------------------
### Choose options
Select discrete variables for graphing, eg: When Voltage is 6, what is Time?
Use the 'filter' tab to further narrow down your dataset.
```{r options}
output$varnames.yn <- renderUI({
selectInput("options.yn","Name of the known variable:",graphnames())
})
output$varnames.xn <- renderUI({
selectInput("options.xn","Name of the unknown variable:",graphnames())
})
fluidPage(
htmlOutput("varnames.yn"),
splitLayout(
textInput("options.yv","Value of known variable:",
placeholder="Numeric, or min/max"),
numericInput("options.scalar","Scalar to multiply by:",1)
),
htmlOutput("varnames.xn"),
checkboxInput("avg","Average/SEM by type"),
textInput("options.name","Name for this new variable:","Variable")
)
```
```{r calculating}
#this will calculatethe reduced dataset for discrete variable analysis
reduced <- reactive(if(!is.null(imported.filtered())){
if(!nchar(input$options.yn) | !nchar(input$options.yv) | !nchar(input$options.xn) | !nchar(input$options.name)) return(NULL)
options.data <- imported.filtered()
options.name.orig <<- input$options.name
options.name <<- make.names(input$options.name)
options.data <- tryCatch(reducer(options.data,options.name,
input$options.yn,input$options.yv,input$options.xn),
error=function(e) NULL)
if(input$options.scalar!=1 & !is.na(input$options.scalar)) {
options.data[,options.name] <- options.data[,options.name]*input$options.scalar
}
if(input$avg & !is.null(options.data)) return(avgsem(options.data))
options.data
})
#remove filtered out colors
reduced.cols <- reactive(if(!is.null(reduced())) {
cols()$Color[cols()$Type %in% reduced()$Type]
})
reduced.cols.cast <- reactive(if(!is.null(reduced())) {
cols.cast()$Color[cols.cast()$Battery.ID %in% reduced()$Battery.ID]
})
wide <- reactive({
if("Battery.ID" %in% colnames(reduced())){
return(dcast(reduced(), Cycle~Battery.ID,mean,value.var=options.name))
} else{
casted <- dcast(reduced(), Cycle~Type,mean,value.var=options.name)
casted.sem <- dcast(reduced(),Cycle~Type,mean,
value.var=paste0(options.name,".SEM"))
cnames.orig <- c(colnames(casted),
paste0(colnames(casted.sem[2:ncol(casted)]),".SEM"))
#this is some shiny bug
casted <- cbind(casted,casted.sem[,2:ncol(casted)])
colnames(casted) <- cnames.orig
return(casted)
}
})
```
###Filter
```{r filter}
#filter dataset for discrete variable analysis
#filter min/max determine the bounds of the sliders
filter.min <- reactive({if(is.null(imported.sorted())) return(rep(NaN,5))
sapply(imported.sorted()[stdnames],min)
})
filter.max <- reactive({if(is.null(imported.sorted())) return(rep(NaN,5))
sapply(imported.sorted()[stdnames],max)
})
output$filter.voltage <- renderUI({
sliderInput("filter.voltage","Select a voltage range:",filter.min()[1],filter.max()[1],
c(filter.min()[1],filter.max()[1]),0.1)
})
output$filter.current <- renderUI({
sliderInput("filter.current","Select a current range:",filter.min()[2],filter.max()[2],
c(filter.min()[2],filter.max()[2]),0.1)
})
output$filter.amphours <- renderUI({
sliderInput("filter.amphours","Select a capacity range:",filter.min()[3],filter.max()[3],
c(filter.min()[3],filter.max()[3]),0.1)
})
output$filter.totaltime <- renderUI({
sliderInput("filter.totaltime","Select a total time range:",filter.min()[4],filter.max()[4],
c(filter.min()[4],filter.max()[4]),1)
})
output$filter.steptime <- renderUI({
sliderInput("filter.steptime","Select a step time range:",filter.min()[5],filter.max()[5],
c(filter.min()[5],filter.max()[5]),1)
})
output$filter.step <- renderUI({
sliderInput("filter.step","Is there a step to isolate? (0 for no)",0,
tryCatch(max(imported.sorted()$Step[imported.sorted()$Step<=ceiling(quantile(
imported.sorted()$Step,.99))]),error=function(e) 1),0,1)
})
output$filter.cycle <- renderUI({
sliderInput("filter.cycle","Is there a cycle to isolate? (0 for no)",0,
tryCatch(max(imported.sorted()$Cycle),
error=function(e) 1),0,1,T)
})
fluidPage(column(12,div(
style = "height:80px;",
htmlOutput("filter.voltage"),
htmlOutput("filter.current"),
htmlOutput("filter.amphours"),
htmlOutput("filter.totaltime"),
htmlOutput("filter.steptime"),
htmlOutput("filter.step"),
htmlOutput("filter.cycle")
)))
#will perform calculations on this filtered dataset
imported.filtered <- reactive(if(!is.null(imported())){
if(is.null(input$filter.step)) return(imported())
if(input$filter.cycle==0) x <- imported()
else { #baseline time stamp correction
x <- imported()[imported()$Cycle==input$filter.cycle,] %>%
within({Total.Time <- ave(Total.Time, Battery.ID, FUN=function(x) x-min(x))}) %>%
mutate(TimeHr=Total.Time/3600,TimeMin=Total.Time/60)
}
if(input$filter.step) x <- filter(x,Step==input$filter.step)
tryCatch(filter(x,
Voltage>=input$filter.voltage[1],Voltage<=input$filter.voltage[2],
Current>=input$filter.current[1],Current<=input$filter.current[2],
Amp.Hours>=input$filter.amphours[1],Amp.Hours<=input$filter.amphours[2],
Total.Time>=input$filter.totaltime[1],Total.Time<=input$filter.totaltime[2],
Step.Time>=input$filter.steptime[1],Step.Time<=input$filter.steptime[2]
),error=function(e) imported())
})
```
###Protocol
Best attempt at deriving protocol from dataset. If there is a mismatch in step numbers, you may be able to isolate what you need using the 'filter' tab.
```{r protocol}
output$protocol.ids <- renderUI({
selectInput("protocol.ids","Filter prediction by Battery ID:",
c("All",levels(imported()$Battery.ID)))
})
fluidPage(
htmlOutput("protocol.ids"),
renderTable(if(!is.null(imported.sorted())){
if(input$protocol.ids=="All") Protocol(imported())
else Protocol(filter(imported(),Battery.ID==input$protocol.ids))
},include.rownames=F)
)
```
Column {data-width=700 .tabset .tabset-fade}
-------------------------------------
### Graph
```{r graph}
#ticker<-function(x) paste0("`",x,"`")
bar <- reactive(if(!is.null(reduced())) bargraph(reduced(),options.name,
options.name.orig)+scale_fill_manual(values=reduced.cols(),name=""))
line <- reactive(if(!is.null(reduced())) dygraph.cast(reduced(),
"Cycle",options.name,"Cycle",options.name.orig,
reduced.cols.cast(),reduced.cols()))
ggline <- reactive(if(!is.null(reduced())) {
gg <- linegraph(reduced(),"Cycle",options.name)+ylab(options.name.orig) #avg/sem
if(input$avg) gg <- gg + scale_color_manual(values=reduced.cols(),name="") +
scale_fill_manual(values=reduced.cols(),name="")
else gg <- gg + scale_color_manual(values=reduced.cols.cast(),name="") #regular
gg
})
shinyApp(
ui = fluidPage(
radioButtons("graphtype",NULL,c("Line"=2,"Bar"=1),inline=T),
conditionalPanel(
condition = "input.graphtype==1", plotlyOutput("bar")
),
conditionalPanel(
condition = "input.graphtype==2", dygraphOutput("line"),
tags$br(),
textOutput("legendDivID")
)
),
server = function(input, output, session){
output$bar <- renderPlotly(withProgress(message="Calculating...",ggplotly2(bar())))
output$line <- renderDygraph(withProgress(message="Calculating...",line()))
}
)
```
### Table
```{r table}
radioButtons("tabletype",NULL,c("Long","Wide"),inline=T)
red.table <- reactive({
if(input$tabletype=="Long") return(reduced())
if(input$tabletype=="Wide") return(wide())
})
renderDataTable(datatable(red.table(),
filter = 'top', rownames = F,extensions = 'Buttons',fillContainer = F,
options = list(
scrollX = TRUE, scrollY = TRUE, fixedColumns = TRUE,
pageLength = 10, dom = 'Blftip',buttons = list('copy', 'csv'))),
server=F)
```
Share {data-orientation=columns data-navmenu="Discrete"}
=====================================
Column {data-width=250 .tabset .tabset-fade}
-------------------------------------
### Choose options
Customize discrete variable chart for sharing:
```{r publish.options}
fluidPage(
radioButtons("pub.type",NULL,c("Line","Bar"),inline=T),
selectInput("pub.theme","Graph theme:",c("Default","Minimal","Grayscale")),
selectInput("pub.legend","Legend position:",c("None","Side"="right","Above"="top",
"Below"="bottom","Top-left"="c(0,1)","Top-right"="c(1,1)",
"Bottom-left"="c(0,0)","Bottom-right"="c(1,0)")),
sliderInput("pub.fsize","Font size:",10,20,12,0.5),
textInput("pub.title","Chart title:",""),
helpText("Download chart options:"),
splitLayout(
numericInput("pub.savew","Width:",12),
numericInput("pub.saveh","Height:",8),
downloadButton("pub.png","PNG"),
downloadButton("pub.svg","SVG")
)
)
#linesize?
```
###Additional Options
Customize discrete variable chart for sharing:
```{r publish.options2}
fluidPage(
helpText("Include axis ranges:"),
splitLayout(
numericInput("pub.x1","X start:",NA),
numericInput("pub.x2","X end:",NA)
),
splitLayout(
numericInput("pub.y1","Y start:",NA),
numericInput("pub.y2","Y end:",NA)
),
helpText("Horizontal line options:"),
splitLayout(
textInput("hline.col","Color:","None"),
numericInput("hline.val","Position:",0),
numericInput("hline.size","Size:",0.8,step=.2)
),
checkboxInput("pub.rotatex","Rotate x-axis labels")
)
```
Column {data-width=700}
-------------------------------------
### Graph {.no-title}
```{r publish.graph}
renderPlot(withProgress(message="Rendering...",pub.graph()))
pub.graph <- reactive(if(!is.null(reduced())) {
#these are the x-y limits
xlim <- c(input$pub.x1,input$pub.x2)
if(any(is.na(xlim))) xlim <- NULL
ylim <- c(input$pub.y1,input$pub.y2)
if(any(is.na(ylim))) ylim <- NULL
if(input$pub.type=="Bar"){
gg <- bar() + coord_cartesian(ylim=ylim)
}
else { #line
gg <- ggline() + coord_cartesian(xlim=xlim,ylim=ylim)
}
if(input$hline.col!="None" & input$hline.col!="none" & nchar(input$hline.col)){
gg <- gg + geom_hline(aes_(yintercept=input$hline.val),linetype=2,
color=input$hline.col,size=input$hline.size)
}
if(input$pub.theme=="Default") gg <- gg + theme_gray(base_size=input$pub.fsize)
if(input$pub.theme=="Minimal") gg <- gg + theme_bw(base_size=input$pub.fsize)
if(input$pub.theme=="Grayscale") gg <- gg + theme_pub(base_size=input$pub.fsize) +
scale_fill_grey(start=0,end=.9,name="") + scale_color_grey(start=0,end=.9,name="")
if(!length(grep(",",input$pub.legend))) gg <- gg + theme(legend.position=input$pub.legend,
legend.title=element_blank())
else gg <- gg + theme(legend.position=eval(parse(text=input$pub.legend)),
legend.justification=eval(parse(text=input$pub.legend)),
legend.title=element_blank())
if(nchar(input$pub.title)) gg <- gg + ggtitle(input$pub.title)
if(input$pub.rotatex) gg <- gg + theme(axis.text.x = element_text(angle = 60, hjust = 1))
gg
})
output$pub.png <- downloadHandler(paste('plot-', Sys.Date(), '.png', sep=''),
content = function(file) if(!is.null(reduced())) {
ggsave(file,device="png",width=input$pub.savew,height=input$pub.saveh)
}
)
output$pub.svg <- downloadHandler(paste('plot-', Sys.Date(), '.svg', sep=''),
content = function(file) if(!is.null(reduced())) {
ggsave(file,device="svg",width=input$pub.savew,height=input$pub.saveh)
}
)
```