-
Notifications
You must be signed in to change notification settings - Fork 25
/
IO.R
2035 lines (1819 loc) · 75.2 KB
/
IO.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
## For specifications of FACS 3.0 see
## http://www.isac-net.org and the file
## fcs3.html in the doc directory
## ==========================================================================
## Determine which 'files' are valid FCS files
## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#' @export
isFCSfile <- function(files)
{
sapply(files, function(f){
if (file.exists(f)) {
con <- file(f, open="rb")
on.exit(close(con))
version <- readChar(con, 6)
isTRUE(version %in% c("FCS2.0", "FCS3.0", "FCS3.1"))
}
else FALSE
})
}
## ==========================================================================
## Reading FCS file header and TEXT section only
## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#' Read the TEXT section of a FCS file
#'
#' Read (part of) the TEXT section of a Data File Standard for Flow Cytometry
#' that contains FACS keywords.
#'
#' The function \code{read.FCSheader} works with the output of the FACS machine
#' software from a number of vendors (FCS 2.0, FCS 3.0 and List Mode Data LMD).
#' The output of the function is the TEXT section of the FCS files. The user
#' can specify some keywords to limit the output to the information of
#' interest.
#'
#' @name read.FCSheader
#'
#' @param files Character vector of filenames.
#' @param path Directory where to look for the files.
#' @param keyword An optional character vector that specifies the FCS keyword
#' to read.
#' @param ... other arguments passed to \code{link[flowCore]{read.FCS}}
#'
#' @return A list of character vectors. Each element of the list correspond to
#' one FCS file.
#' @author N.Le Meur
#' @seealso \code{link[flowCore]{read.flowSet}},
#' \code{link[flowCore]{read.FCS}}
#' @keywords IO
#' @examples
#'
#' samp <- read.FCSheader(system.file("extdata",
#' "0877408774.B08", package="flowCore"))
#' samp
#'
#' samp <- read.FCSheader(system.file("extdata",
#' "0877408774.B08", package="flowCore"), keyword=c("$DATE", "$FIL"))
#' samp
#'
#' @export
read.FCSheader <- function(files, path=".", keyword=NULL, ...)
{
stopifnot(is.character(files), length(files)>=1, files!="")
filenames <- files
if(path != ".")
files = file.path(path, files)
res <- lapply(files, function(file){
thisRes <- try(header(file, ...), silent = TRUE)
if(class(thisRes) == "try-error"){
stop(thisRes, file)
}else
thisRes
})
if (!is.null(keyword))
res <- lapply(res, function(x) x[keyword])
names(res) <- filenames
res
}
header <- function(files, ...){
con <- file(files, open="rb")
offsets <- findOffsets(con, ...)
txt <- readFCStext(con, offsets, ...)
close(con)
txt
}
## ==========================================================================
## main wrapper to read FCS files
## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#' Read an FCS file
#'
#' Check validity and Read Data File Standard for Flow Cytometry
#'
#'
#' The function \code{isFCSfile} determines whether its arguments are valid FCS
#' files.
#'
#' The function \code{read.FCS} works with the output of the FACS machine
#' software from a number of vendors (FCS 2.0, FCS 3.0 and List Mode Data LMD).
#' However, the FCS 3.0 standard includes some options that are not yet
#' implemented in this function. If you need extensions, please let me know.
#' The output of the function is an object of class \code{flowFrame}.
#'
#' For specifications of FCS 3.0 see \url{http://www.isac-net.org} and the file
#' \url{../doc/fcs3.html} in the \code{doc} directory of the package.
#'
#' The \code{which.lines} arguments allow you to read a subset of the record as
#' you might not want to read the thousands of events recorded in the FCS file.
#' It is mainly used when there is not enough memory to read one single FCS
#' (which probably will not happen). It will probably take more time than
#' reading the entire FCS (due to the multiple disk IO).
#' @name read.FCS
#' @aliases read.FCS cleanup isFCSfile
#' @usage
#' isFCSfile(files)
#'
#' read.FCS(filename, transformation="linearize", which.lines=NULL,
#' alter.names=FALSE, column.pattern=NULL, invert.pattern = FALSE,
#' decades=0, ncdf = FALSE, min.limit=NULL,
#' truncate_max_range = TRUE, dataset=NULL, emptyValue=TRUE,
#' channel_alias = NULL, ...)
#'
#' @param files A vector of filenames
#' @param filename Character of length 1: filename
#' @param transformation An character string that defines the type of
#' transformation. Valid values are \code{linearize} (default),
#' \code{linearize-with-PnG-scaling}, or \code{scale}. The \code{linearize}
#' transformation applies the appropriate power transform to the data. The
#' \code{linearize-with-PnG-scaling} transformation applies the appropriate
#' power transform for parameters stored on log scale, and also a linear
#' scaling transformation based on the 'gain' (FCS \$PnG keywords) for
#' parameters stored on a linear scale. The \code{scale} transformation scales
#' all columns to $[0,10^decades]$. defaulting to decades=0 as in the FCS4
#' specification. A logical can also be used: \code{TRUE} is equal to
#' \code{linearize} and \code{FALSE}(or \code{NULL}) corresponds to no
#' transformation. Also when the transformation keyword of the FCS header is
#' set to "custom" or "applied", no transformation will be used.
#' @param which.lines Numeric vector to specify the indices of the lines to be
#' read. If NULL all the records are read, if of length 1, a random sample of
#' the size indicated by \code{which.lines} is read in. It's used to achieve partial disk IO
#' for the large FCS that can't fit the full data into memory. Be aware the potential slow read
#' (especially for the large size of random sampling) due to the frequent disk seek operations.
#' @param alter.names boolean indicating whether or not we should rename the
#' columns to valid R names using \code{\link{make.names}}. The default is
#' FALSE.
#' @param column.pattern An optional regular expression defining parameters we
#' should keep when loading the file. The default is NULL.
#' @param invert.pattern logical. By default, \code{FALSE}. If \code{TRUE},
#' inverts the regular expression specified in \code{column.pattern}. This is
#' useful for indicating the channel names that we do not want to read. If
#' \code{column.pattern} is set to \code{NULL}, this argument is ignored.
#' @param decades When scaling is activated, the number of decades to use for
#' the output.
#' @param ncdf Deprecated. Please use 'ncdfFlow' package for cdf based storage.
#' @param min.limit The minimum value in the data range that is allowed. Some
#' instruments produce extreme artifactual values. The positive data range for
#' each parameter is completely defined by the measurement range of the
#' instrument and all larger values are set to this threshold. The lower data
#' boundary is not that well defined, since compensation might shift some
#' values below the original measurement range of the instrument. This can be
#' set to an arbitrary number or to \code{NULL} (the default value), in which
#' case the original values are kept. When the transformation keyword of the FCS header is
#' set (typically to "custom" or "applied"), no shift up to min.limit will occur.
#' @param truncate_max_range logical type. Default is TRUE. can be optionally
#' turned off to avoid truncating the extreme positive value to the instrument
#' measurement range .i.e.'$PnR'. When the transformation keyword of the FCS header is
#' set (typically to "custom" or "applied"), no truncation will occur.
#' @param dataset The FCS file specification allows for multiple data segments
#' in a single file. Since the output of \code{read.FCS} is a single
#' \code{flowFrame} we can't automatically read in all available sets. This
#' parameter allows to chose one of the subsets for import. Its value is
#' supposed to be an integer in the range of available data sets. This argument
#' is ignored if there is only a single data segment in the FCS file.
#' @param emptyValue boolean indicating whether or not we allow empty value for
#' keyword values in TEXT segment. It affects how the double delimiters are
#' treated. IF TRUE, The double delimiters are parsed as a pair of start and
#' end single delimiter for an empty value. Otherwise, double delimiters are
#' parsed one part of string as the keyword value. default is TRUE.
#' @param channel_alias an optional data.frame used to provide the alias of the channels
#' to standardize and solve the discrepancy across FCS files. It is expected to
#' contain 'alias' and 'channels' column of 'channel_alias'. Each row/entry specifies the common
#' alias name for a collection of channels (comma separated). See examples for
#' details.
#'
#' For each channel in the FCS file, read.FCS will first attempt
#' to find an exact match in the 'channels' column. If no exact match is found,
#' it will check for partial matches. That is, if "V545" is in the 'channels'
#' column of 'channel_alias' and "V545-A" is present in the FCS file, this
#' partial match will allow the corresponding 'alias' to be assigned. This partial
#' matching only works in this direction ("V545-A" in the 'channels' column will
#' not match "V545" in the FCS file) and care should be exercised to ensure no unintended
#' partial matching of other channel names. If no exact or partial match is found,
#' the channel is unchanged in the resulting \code{flowFrame}.
#'
#' @param ... ignore.text.offset: whether to ignore the keyword values in TEXT
#' segment when they don't agree with the HEADER. Default is FALSE, which
#' throws the error when such discrepancy is found. User can turn it on to
#' ignore TEXT segment when he is sure of the accuracy of HEADER so that the
#' file still can be read.
#'
#' @return
#'
#' \code{isFCSfile} returns a logical vector.
#'
#' \code{read.FCS} returns an object of class
#' \code{\link[flowCore:flowFrame-class]{flowFrame}} that contains the data in
#' the \code{exprs} slot, the parameters monitored in the \code{parameters}
#' slot and the keywords and value saved in the header of the FCS file.
#'
#' @author F. Hahne, N.Le Meur
#' @seealso \code{\link[flowCore]{read.flowSet}}
#' @keywords IO
#' @examples
#'
#' ## a sample file
#' fcsFile <- system.file("extdata", "0877408774.B08", package="flowCore")
#'
#' ## read file and linearize values
#' samp <- read.FCS(fcsFile, transformation="linearize")
#' exprs(samp[1:3,])
#' keyword(samp)[3:6]
#' class(samp)
#'
#' ## Only read in lines 2 to 5
#' subset <- read.FCS(fcsFile, which.lines=2:5, transformation="linearize")
#' exprs(subset)
#'
#' ## Read in a random sample of 100 lines
#' subset <- read.FCS(fcsFile, which.lines=100, transformation="linearize")
#' nrow(subset)
#'
#' #manually supply the alias vs channel options mapping as a data.frame
#' map <- data.frame(alias = c("A", "B")
#' , channels = c("FL2", "FL4")
#' )
#' fr <- read.FCS(fcsFile, channel_alias = map)
#' fr
#'
#' @export
read.FCS <- function(filename,
transformation="linearize",
which.lines=NULL,
alter.names=FALSE,
column.pattern=NULL,
invert.pattern = FALSE,
decades=0,
ncdf=FALSE,
min.limit=NULL,
truncate_max_range = TRUE,
dataset=NULL,
emptyValue=TRUE
, channel_alias = NULL
, ...)
{
channel_alias <- check_channel_alias(channel_alias)
if(ncdf)
.Deprecated("'ncdf' argument is deprecated!Please use 'ncdfFlow' package for disk-based data structure.")
## check file name
if(!is.character(filename) || length(filename)!=1)
stop("'filename' must be character scalar")
if(!file.exists(filename))
stop(paste("'", filename, "' is not a valid file", sep=""))
con <- file(filename, open="rb")
on.exit(close(con))
## transform or scale data?
fcsPnGtransform <- FALSE
if(is.logical(transformation) && transformation ||
!is.null(transformation) && transformation == "linearize") {
transformation <- TRUE
scale <- FALSE
} else if ( !is.null(transformation) && transformation == "scale") {
transformation <- TRUE
scale <- TRUE
} else if ( !is.null(transformation) && transformation == "linearize-with-PnG-scaling") {
transformation <- TRUE
scale <- FALSE
fcsPnGtransform <- TRUE
} else if (is.null(transformation) || is.logical(transformation) &&
!transformation) {
transformation <- FALSE
scale <- FALSE
}
## read the file
offsets <- findOffsets(con,emptyValue=emptyValue, dataset = dataset, ...)
txt <- readFCStext(con, offsets,emptyValue=emptyValue, ...)
## We only transform if the data in the FCS file hasn't already been
## transformed before
if (fcsPnGtransform) txt[["flowCore_fcsPnGtransform"]] <- "linearize-with-PnG-scaling"
if("transformation" %in% names(txt) &&
txt[["transformation"]] %in% c("applied", "custom"))
transformation <- FALSE
mat <- readFCSdata(con, offsets, txt, transformation, which.lines,
scale, alter.names, decades, min.limit, truncate_max_range, channel_alias)
matRanges <- attr(mat,"ranges")
id <- paste("$P",1:ncol(mat),sep="")
zeroVals <- as.numeric(sapply(strsplit(txt[paste(id,"E",sep="")], ","),
function(x) x[2]))
absMin <- colMins(mat,,na.rm=TRUE) # replace apply with matrixStats::colMins to speed up
# absMin <- apply(mat,2,min,na.rm=TRUE)
realMin <- pmin(zeroVals,pmax(-111, absMin, na.rm=TRUE), na.rm=TRUE)
keep_idx <- seq_along(colnames(mat))
remove_idx <- NULL
# Only keep certain parameters
if(!is.null(column.pattern)) {
n <- colnames(mat)
keep_idx <- grep(column.pattern, n, invert = invert.pattern)
remove_idx <- setdiff(seq_along(colnames(mat)), keep_idx)
cols <- names(attr(mat, "dimnames")[[2]])
mat <- mat[,keep_idx,drop=FALSE]
matRanges <- matRanges[keep_idx]
names(attr(mat, "dimnames")[[2]]) <- cols[keep_idx]
attr(mat, "ranges") <- matRanges
absMin <- absMin[keep_idx]
realMin <- realMin[keep_idx]
zeroVals <- zeroVals[keep_idx]
id <- id[keep_idx]
}
if("transformation" %in% names(txt) && txt[["transformation"]] == "custom") {
for(i in seq_along(colnames(mat))) {
realMin[i] <- as.numeric(txt[[sprintf("flowCore_$P%sRmin", keep_idx[i])]])
}
}
params <- makeFCSparameters(colnames(mat),txt, transformation, scale,
decades, realMin, id=keep_idx)
# Fill invalid/missing range values with channel maxima read from data
fix_pnr_idx <- which(is.na(params@data[, "maxRange"]))
if(length(fix_pnr_idx) > 0){
fix_pnr_vals <- matRanges[fix_pnr_idx]
params@data[fix_pnr_idx, "maxRange"] <- fix_pnr_vals
params@data[fix_pnr_idx, "range"] <- fix_pnr_vals + 1
}
## check for validity
if(is.null(which.lines)){
total_number_of_events <- as.integer(readFCSgetPar(txt, "$TOT"));
if(total_number_of_events != nrow(mat))
stop("file", filename, "seems to be corrupted. \n The actual number of cells in data section ("
, nrow(mat), ") is not consistent with keyword '$TOT' (", total_number_of_events , ")")
}
## set transformed flag and fix the PnE and the Datatype keywords
## also add our own PnR fields.
txt[["FILENAME"]] <- filename
if(transformation==TRUE) {
txt[["transformation"]] <-"applied"
for(p in seq_along(pData(params)$name)) {
txt[[sprintf("$P%sE", p)]] <- sprintf("0,%g", 0)
txt[[sprintf("flowCore_$P%sRmax", keep_idx[p])]] <- matRanges[p] +1
txt[[sprintf("flowCore_$P%sRmin", keep_idx[p])]] <- realMin[p]
}
txt[["$DATATYPE"]] <- "F"
}
## build description from FCS parameters
if(offsets["FCSversion"]<=2)
{
description <- strsplit(txt,split="\n")
names(description) <- names(txt)
}else
{
description <- strsplit(txt, split=NA) # not really splitting, but converting the data structure}
}
# Fill invalid/missing PnR values with channel maxima read from data
if(length(fix_pnr_idx) > 0)
description[paste0("$P", fix_pnr_idx, "R")] <- fix_pnr_vals + 1
# Remove keywords for removed parameters
if(!is.null(remove_idx)&&length(remove_idx)>0){
remove_regex <- paste0("\\$P", remove_idx, "[A-Z]+")
remove_keys <- lapply(remove_regex, function(rx) grep(rx, names(description), value=TRUE))
description <- description[!names(description) %in% do.call(c, remove_keys)]
}
## the spillover matrix
for(sn in .spillover_pattern){
sp <- description[[sn]]
if(!is.null(sp)){
sp <- txt2spillmatrix(sp)
if(is.matrix(sp))
{
cnames <- colnames(sp)
cnames <- update_channel_by_alias(cnames, channel_alias, silent = TRUE)
if(alter.names)
cnames <- make.names(cnames)
colnames(sp) <- cnames
description[[sn]] <- sp
}
}
}
tmp <- new("flowFrame", exprs=mat, description= description,
parameters=params)
identifier(tmp) <- basename(identifier(tmp))
return(tmp)
}
txt2spillmatrix <- function(txt, cpp = TRUE){
if(cpp)
{
string_to_spill(txt)
}else
{
splt <- strsplit(txt, ",")[[1]]
nrCols <- as.numeric(splt[1])
if(!is.na(nrCols)&&nrCols > 0)
{
cnames <- splt[2:(nrCols+1)]
vals <- as.numeric(splt[(nrCols+2):length(splt)])
matrix(vals, ncol=nrCols, byrow=TRUE, dimnames = list(NULL, cnames))
}else
txt
}
}
spill2txt <- function(mat, cpp = TRUE){
cols <- colnames(mat)
if(cpp)
{
spill_to_string(mat, cols)
}else
{
rNum <- as.character(nrow(mat))
clNames <- paste(cols,sep=",")
vec <- paste(c(t(mat)),sep=",",collapse=",")
paste(c(rNum,clNames,vec),sep=",",collapse=",")
}
}
## ==========================================================================
## create AnnotatedDataFrame describing the flow parameters (channels)
## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
makeFCSparameters <- function(cn, txt, transformation, scale, decades,
realMin, id) {
dattype <- switch(readFCSgetPar(txt, "$DATATYPE"),
"I" = "integer",
"F" = "numeric",
"D" = "numeric",
stop(paste("Don't know how to deal with $DATATYPE",
readFCSgetPar(txt, "$DATATYPE"))))
npar <- length(cn)
if(missing(id)){
id = 1:npar
}
id <- paste("$P", id ,sep="")
range <- sapply(id, function(this_id){
rid <- paste("flowCore_", this_id,"Rmax",sep="")
original <- is.na(txt[rid])
if(!original)
as.numeric(txt[rid]) + 1
else
suppressWarnings(as.numeric(txt[paste(this_id,"R",sep="")]))
})
origRange <- range
range <- rbind(realMin,range-1)
## make sure the ranges are transformed along with the data
if(transformation & !scale){
ampliPar <- txt[paste(id,"E",sep="")]
noPnE <- is.na(ampliPar)
if(any(noPnE))
ampliPar[noPnE] <- "0,0"
ampli <- do.call(rbind,lapply(ampliPar, function(x)
as.numeric(unlist(strsplit(x,",")))))
for (i in 1:npar)
if(ampli[i,1] > 0 && dattype == "integer")
{
if(ampli[i,2] == 0)
ampli[i,2] = 1 #correct f2 value for legacy FCS
range[,i] <- 10^(range[,i]/(origRange[i]-1)*ampli[i,1])*ampli[i,2]
}
}
else if(scale)
range[2,] <- rep(10^decades, npar)
desc <- txt[paste(id,"S",sep="")]
desc <- gsub("^\\s+|\\s+$", "", desc)#trim the leading and tailing whitespaces
# replace the empty desc with NA
desc <- sapply(desc, function(thisDesc){
if(!nzchar(thisDesc))
NA
else
thisDesc
})
suppressWarnings(new("AnnotatedDataFrame",
data=data.frame(row.names=I(id),name=I(cn),
desc=I(desc),
range=as.numeric(txt[paste(id,"R",sep="")]), minRange=range[1,], maxRange=range[2,]),
varMetadata=data.frame(row.names=I(c("name","desc","range",
"minRange", "maxRange")),
labelDescription=I(c("Name of Parameter","Description of Parameter",
"Range of Parameter", "Minimum Parameter Value after Transforamtion",
"Maximum Parameter Value after Transformation")))))
}
## ==========================================================================
## match FCS parameters
## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
readFCSgetPar <- function(x, pnam, strict=TRUE)
{
stopifnot(is.character(x), is.character(pnam))
i <- match(pnam, names(x))
if(any(is.na(i)) && strict)
stop(paste("Parameter(s)", pnam[is.na(i)], "not contained in 'x'\n"))
if(!strict)
{
if(!all(is.na(i)))
i[!is.na(i)] <- x[i[!is.na(i)]]
names(i) <- pnam
return(i)
}
return(x[i])
}
## ==========================================================================
## Find all data sections in a file and record their offsets.
## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
findOffsets <- function(con,emptyValue=TRUE, dataset = NULL, ...)
{
offsets <- readFCSheader(con)
offsets <- matrix(offsets, nrow = 1, dimnames = list(NULL, names(offsets)))
txt <- readFCStext(con, offsets[1, ],emptyValue=emptyValue, ...)
addOff <- 0
if("$NEXTDATA" %in% names(txt)){
nd <- as.numeric(txt[["$NEXTDATA"]])
}else
nd <- 0
txt.list <- list(txt)
i <- 1
while(nd != 0)
{
i <- i + 1
addOff <- addOff + nd
offsets <- rbind(offsets, readFCSheader(con, addOff))
this.txt <- readFCStext(con, offsets[nrow(offsets),],emptyValue=emptyValue, ...)
nd <- as.numeric(this.txt[["$NEXTDATA"]])
txt.list[[i]] <- this.txt
}
## check for multiple data sets
nDataset <- length(txt.list)
if(nDataset == 1)
dataset <- 1
else
{
if(is.null(dataset))
{
warning(sprintf("The file contains %d additional data segment%s.\n",
nDataset-1, ifelse(nDataset>2, "s", "")),
"The default is to read the first segment only.\nPlease consider ",
"setting the 'dataset' argument.", call.=FALSE)
dataset <- 1
}
}
if(!is.numeric(dataset) || !dataset %in% seq_len(nDataset))
stop(sprintf("Argument 'dataset' must be an integer value in [1,%d].",
nDataset))
offsets <- offsets[dataset,]
txt <- txt.list[[dataset]]
# browser()
offsets <- checkOffset(offsets, txt, ...)
return(offsets)
}
#' Fix the offset when its values recorded in header and TEXT don't agree
#' @param offsets the named vector returned by \code{findOffsets}
#' @param x the text segmented returned by \code{readFCStext}
#' @param ignore.text.offset whether to ignore the offset info stored in TEXT segment
#' @param ... not used.
#' @return the updated offsets
checkOffset <- function(offsets, x, ignore.text.offset = FALSE, ...){
##for DATA segment exceeding 99,999,999 byte.
if(offsets["FCSversion"] >= 3){
realOff <- offsets - offsets[8]
# Let's not be too strick here as unfortunatelly, some files exported from FlowJo
# are missing the $BEGINDATA and $ENDDATA keywords and we still need to read those
datastart <- as.numeric(readFCSgetPar(x, "$BEGINDATA", strict=FALSE))
if (is.na(datastart)) {
if (realOff["datastart"] != 0) {
datastart = realOff["datastart"]
warning("Missing the required $BEGINDATA keyword! Reading data based on information in the FCS HEADER only.", call.=FALSE)
} else {
stop("Don't know where the data segment begins, there was no $BEGINDATA keyword and the FCS HEADER does not say it either.")
}
}
dataend <- as.numeric(readFCSgetPar(x, "$ENDDATA", strict=FALSE))
if (is.na(dataend)) {
if (realOff["dataend"] != 0) {
dataend = realOff["dataend"]
warning("Missing the required $ENDDATA keyword! Reading data based on information in the FCS HEADER only.", call.=FALSE)
} else {
stop("Don't know where the data segment ends, there was no $ENDDATA keyword and the FCS HEADER does not say it either.")
}
}
# when both are present and they don't agree with each other
if(realOff["datastart"] != datastart && realOff["datastart"]== 0){ #use the TEXT when header is 0
offsets["datastart"] <- datastart+offsets[8]
}
if(realOff["datastart"] != datastart && realOff["datastart"]!= 0){#trust the header when it is non-zero
msg <- paste0("The HEADER and the TEXT segment define different starting point ("
, offsets["datastart"], ":", datastart
, ") to read the data.")
if(ignore.text.offset)
warning(msg, " The values in TEXT are ignored!")
else
stop(msg)
}
#both are present and they don't agree
if(realOff["dataend"] != dataend && (realOff["dataend"]== 0 || realOff["dataend"]== 99999999)) {#use TEXT when either header is 0 or TEXT is 99999999
offsets["dataend"] <- dataend+offsets[8]
}
if(realOff["dataend"] != dataend && realOff["dataend"]!= 0 && realOff["dataend"]!= 99999999) {#otherwise trust the header
msg <- paste0("The HEADER and the TEXT segment define different ending point ("
, offsets["dataend"], ":", dataend
, ") to read the data.")
if(ignore.text.offset)
warning(msg, " The values in TEXT are ignored!")
else
stop(msg)
}
}
offsets
}
## ==========================================================================
## parse FCS file header
## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
readFCSheader <- function(con, start=0)
{
seek(con, start)
version <- readChar(con, 6)
if(!version %in% c("FCS2.0", "FCS3.0", "FCS3.1"))
stop("This does not seem to be a valid FCS2.0, FCS3.0 or FCS3.1 file")
version <- substring(version, 4, nchar(version))
tmp <- readChar(con, 4)
stopifnot(tmp==" ")
coffs <- character(6)
for(i in 1:length(coffs))
coffs[i] <- readChar(con=con, nchars=8)
ioffs <- c(as.double(version), as.integer(coffs), as.integer(start))
names(ioffs) <- c("FCSversion", "textstart", "textend", "datastart",
"dataend", "anastart", "anaend", "additional")
ioffs[2:7] <- ioffs[2:7]+ioffs[8]
if(any(is.na(ioffs[2:5]) | ioffs[2:5]==""))
stop("Missing header information to start parsing the binary ",
"section of the file")
return(ioffs)
}
## ==========================================================================
## parse FCS file text section
## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
readFCStext <- function(con, offsets,emptyValue = TRUE, cpp = TRUE, ...)
{
seek(con, offsets["textstart"])
## Certain software (e.g. FlowJo 8 on OS X) likes to put characters into
## files that readChar can't read, yet readBin, rawToChar and iconv can
## handle just fine.
txt <- readBin(con,"raw", offsets["textend"]-offsets["textstart"]+1)
txt <- iconv(rawToChar(txt), "", "latin1", sub="byte")
txt <- trimws(txt, "right")
# browser()
if(offsets["FCSversion"]<=2)##
{
delimiter <- substr(txt, 1, 1)
sp <- strsplit(substr(txt, 2, nchar(txt)), split=delimiter,
fixed=TRUE)[[1]]
rv <- c(offsets["FCSversion"], sp[seq(2, length(sp), by=2)])
names(rv) <- gsub("^ *| *$", "", c("FCSversion", sp[seq(1, length(sp)-1, by=2)]))
}else
{
#only apply the patch parser to FCS3
if(cpp)
rv = fcsTextParse(txt,emptyValue=emptyValue)
else
rv = fcs_text_parse(txt,emptyValue=emptyValue)
if(!"FCSversion"%in%names(rv))
rv <- c(offsets["FCSversion"], rv)
names(rv) <- gsub("^ *| *$", "", names(rv))#trim the leading and trailing whitespaces
}
return(rv)
}
## ==========================================================================
## a patch to fix the parsing issue when delimiter exists in the keyword value
##,which is allowed only when it is followed by another delimiter immediately
## Note that it is only applies to FCS3.0 because empty value is not valid value.
##however,this does not conform to FCS2.0,so this patch only applies to FCS3.0
## - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
fcs_text_parse = function(str,emptyValue) {
# browser()
pairs = c()
div = substr(str, 1, 1)
if(nchar(div) != 1) {
return(c())
}
# regexes require double-escaping (*sigh*)
# if(div == "\\") {
# div = "\\\\"
# }
# if(div=="|")
div<-paste("\\",div,sep="")
i = 2
repeat {
remaining = substr(str, i, nchar(str))
if(nchar(gsub(" ","",remaining)) == 0) {##filter out white spaces before check the length
break
}
key_end_regex <- paste("([^",div,"]",div,")", sep="")
#############################################################################################
##1.when empty value is allowed, we assume there is no double delimiters in any values,
## otherwise,it would break the parser
##2.when empty value is not allowed, we safely parse the double delimiters as the valid values
#############################################################################################
if(emptyValue)
{
value_end_regex <- div
final_end_regex <- paste(div,"$", sep="")
}else
{
value_end_regex <- paste("([^",div,"]",div,"[^",div,"])", sep="")
final_end_regex <- paste("[^",div,"]",div,"$", sep="")
}
# browser()
# find key end
divider_index = regexpr(key_end_regex, remaining, perl=TRUE)
if(divider_index < 0) {
if(i==2)
stop("ERROR: No second divider found\n")
else
{
warning("keyword: ",remaining," is dropped because no value found!")
break
}
}
divider_index = divider_index + 1
value_search = substr(remaining, divider_index + 1, nchar(remaining))
# find value end
value_end_index = regexpr(value_end_regex, value_search, perl=TRUE)
if(emptyValue)
value_end_index<-value_end_index-1
if(value_end_index < 0) {
value_end_index = regexpr(final_end_regex, value_search, perl=TRUE)
if(value_end_index < 0) {
if(emptyValue)
stop("No end found\n There could be double delimiter existing in keyword value.\nPlease set argument 'emptyValue' as FALSE and try again!")
else
stop("No end found\n There could be empty keyword value.\nPlease set argument 'emptyValue' as TRUE and try again!")
# return(c())
# break
}
}
value_end_index = divider_index + value_end_index
key = substr(remaining, 1, divider_index - 1)
value = substr(remaining, divider_index + 1, value_end_index)
#replace double delimiters with single one in the final output
value = gsub(paste(div,div,sep=''), div, value)
# cat("key: ", key, "\n")
# cat("value: ", value, "\n")
# cat("-----------------------\n")
pairs = c(pairs, value)
names(pairs)[length(pairs)] = key
i = i + value_end_index + 1
}
return(pairs)
}
# deprecated by cpp version
sortBytes1 <- function(bytes, byte_order){
nBytes <- length(byte_order)
nTotal <- length(bytes)
nElement <- nTotal / nBytes
#relative byte order for the entire vector
byte_orders <- rep(byte_order + 1 , nElement)
#absolute byte order for the entire vector
byte_orders <- byte_orders + rep((seq_len(nElement)-1) * 4, each = nBytes)
#re-order
ind <- order(byte_orders)
bytes[ind]
}
# Read raw FCS data. This is a wrapper around .readFCSdataRaw that calls the
# function with at most .Machine$integer.max bytes each time.
.readFCSdataRawMultiple <- function(con, dattype, count, size, signed, endian,
splitInt = FALSE, byte_order) {
chunk_size <- floor(.Machine$integer.max / size)
num_chunks <- ceiling(count / chunk_size)
items <- c()
for (chunk in seq(num_chunks)) {
if (chunk == num_chunks) {
chunk_count <- count - chunk_size * floor(count / chunk_size)
} else {
chunk_count <- chunk_size
}
items <-
c(items, .readFCSdataRaw(con, dattype, chunk_count, size, signed, endian,
splitInt, byte_order))
}
items
}
##read odd bitwidth by reading raw and and operating on raw vector
.readFCSdataRaw <- function(con, dattype, count, size, signed, endian,
splitInt = FALSE, byte_order) {
nBytes <- count * size
if (splitInt && (size != 4 || dattype != "integer")) {
stop("'splitInt = TRUE' is only valid for uint32")
}
if (size %in% c(1, 2, 4, 8)) {
if (splitInt) {
# Reorder bytes for mixed endian.
if (endian == "mixed") {
byte_order <- as.integer(strsplit(byte_order, ",")[[1]]) - 1
if(length(byte_order) != size) {
stop("byte order not consistent with bidwidths")
}
bytes <- readBin(con = con, what = "raw", n = nBytes, size = 1)
newBytes <- sortBytes(bytes, byte_order)
con <- newBytes
endian <- "little"
}
# Read uint32 as two uint16. Coerce count again to make sure that it's
# within the integer limit.
splitted <- readBin(con = con, what = dattype, n = as.integer(count * 2),
size = size / 2, signed = FALSE, endian = endian)
uint2double(splitted, endian == "big")
} else {
readBin(con = con, what = dattype, n = count, size = size,
signed = signed, endian=endian)
}
} else {
# Read raw byte stream first.
oldBytes <- readBin(con = con, what = "raw", n = nBytes, size = 1)
# Convert to bit vector.
oldBits <- rawToBits(oldBytes)
# Convert the data element to the non-odd bitwidth.
oldBitWidth <- size * 8
newBitWidth <- 2 ^ ceiling(log(oldBitWidth, 2))
newBits <-
unlist(lapply(1:count, function(i) {
start <- (i - 1) * oldBitWidth + 1
# Padding zeros.
c(oldBits[start:(start + oldBitWidth - 1)],
raw(newBitWidth-oldBitWidth))
}))
# Convert raw byte to corresponding type by readBin. packBits is
# least-significant bit first, so we need to make sure endian is set to
# "little" instead of the endian used in original FCS.
readBin(packBits(newBits, "raw"), what = dattype, n = count,
size = newBitWidth / 8, signed = signed, endian = "little")
}
}
check_channel_alias <- function(channel_alias){
if(is.null(channel_alias))
return (new.env(parent = emptyenv()))
else if(is(channel_alias, "data.frame"))
{
if(!setequal(c("alias", "channels"), colnames(channel_alias)))
stop("channel_alias must contain only 'alias' and 'channels' columns")
env <- new.env(parent = emptyenv())
apply(channel_alias, 1, function(row){
channels <- strsplit(split = ",", row["channels"])[[1]]
for(c in channels)
{
c <- trimws(c)
if(is.null(env[[c]]))
env[[c]] <- trimws(row[["alias"]])
else
stop("multiple entries found in channel_alias for: ", c)
}
})
return (env)
}else if(is(channel_alias, "environment"))
return (channel_alias)
else
stop("channel_alias must be either an environment or a data.frame")
}
update_channel_by_alias <- function(orig_chnl_names, channel_alias, silent = FALSE)
{
keys <- ls(channel_alias)
new_channels <- unlist(lapply(orig_chnl_names, function(col){
alias <- channel_alias[[col]]
if(is.null(alias))
{
#try partial match with case insensitive maching
#escape special characters by enclosing it with \Q and \E
ind <- unlist(lapply(keys, function(key){grepl(paste0("\\Q", key, "\\E"), col, ignore.case = TRUE)}))
if(sum(ind)>1)
stop(col, " is matched to the multiple entries in the channel_alias: ", paste(keys[ind], " "), "\n Try to modify channel_alias so that channel names are more specific! ")
else if(sum(ind) == 0)
return (col)
else
return (channel_alias[[keys[ind]]])
}else
return (alias)
}))
#validity check
tb <- table(new_channels)
is.dup <- tb > 1
if(any(is.dup))
{
dup <- names(tb)[is.dup]
dup.ind <- which(new_channels %in% dup)
for(chnl in dup){
chnl.ind <- which(new_channels == chnl)
new_channels[chnl.ind] <- paste0(chnl, "-", seq(tb[chnl]))
}
dt <- data.frame(orig_channel_name = orig_chnl_names[dup.ind], new_channel_name = new_channels[dup.ind])
if(!silent){
print(dt)
warning(paste0("\nchannel_alias: Multiple channels from one FCS are matched to the same alias!\n",
"Integer suffixes added to disambiguate channels.\n",
"It is also recommended to verify correct mapping of spillover matrix columns.\n"))
}
}
return (new_channels)
}
## ==========================================================================