[242173]: / R / make_predictors.R

Download this file

721 lines (660 with data), 20.8 kB

  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
#' @title Make CT Predictors
#'
#' @description Create a set of predictors for ICH segmentation
#' for CT
#' @param img Filename of image intensities
#' @param mask Filename of brain mask
#' @param roi Filename of ROI for Y
#' @param nvoxels Voxel neighborhood
#' @param moments Moments of neighborhood to take
#' @param center Center the moments
#' @param lthresh Lower threshold for neighborhood setting
#' @param uthresh Upper threshold for neighborhood setting
#' @param sigmas Sigma values for Gaussian smoothed images (in mm)
#' @param save_imgs Logical to save all images that are created as
#' predictors
#' @param outdir Output directory of saved images, needs to be set
#' if \code{save_imgs = TRUE}
#' @param stub Basename to write image names if \code{save_imgs = TRUE}
#' @param overwrite If \code{save_imgs} is \code{TRUE},
#' then should
#' the files be overwritten? If not, then files will be read
#' instead instead of code being re-run.
#' @param template.file Template to register to (CT Template)
#' @param mean.img Mean image in template space for z-scoring
#' @param sd.img SD image in template space for z-scoring
#' @param zscore.typeofTransform type of transform for z-scoring
#' @param zscore.interpolator type of interpolator for z-scoring
#' @param flip.typeofTransform type of transform for flipped difference
#' @param flip.interpolator type of interpolator for flipped difference
#' @param low_thresh Threshold for forcing values to zero
#' @param verbose Logical indicator if output messages should be
#' printed
#' @param shiny Should shiny progress be called?
#' @param erode_mask Should the brain mask be eroded?
#' @param ... options passed to \code{\link{get_neighbors}}
#' @importFrom neurobase readnii checkimg zscore_img finite_img
#' @importFrom fslr fslerode fsl_smooth
#' @importFrom oro.nifti zero_trans cal_img voxdim pixdim convert.datatype convert.bitpix
#' @importFrom extrantsr zscore_template otropos reg_flip perona_malik
#' @importFrom stats sd quantile predict complete.cases
#' @export
#' @return List of a data.frame of Predictors and set of
#' indices to
#' keep in mask and an empty nifti object for plotting.
#' Also the number of voxels of the roi that were not in the
#' mask
make_predictors <- function(img, mask, roi = NULL,
nvoxels = 1, moments = 1:4,
center = c(FALSE, TRUE, TRUE, TRUE),
lthresh = 40, uthresh = 80,
sigmas = c(5, 10, 20),
save_imgs = TRUE,
outdir = NULL,
stub = NULL,
overwrite = FALSE,
template.file = system.file(
"scct_unsmooth_SS_0.01.nii.gz",
package = "ichseg"),
mean.img = system.file(
"Mean_Image.nii.gz",
package = "ichseg"),
sd.img = system.file(
"SD_Image.nii.gz",
package = "ichseg"),
zscore.typeofTransform = "SyN",
zscore.interpolator = "Linear",
flip.typeofTransform = "Affine",
flip.interpolator = "LanczosWindowedSinc",
low_thresh = 1e-13,
verbose= TRUE,
shiny = FALSE,
erode_mask = TRUE,
...) {
make_fname = function(addstub){
fname = addstub
fname = file.path(outdir, paste0(stub, "_", fname, ".nii.gz"))
fname
}
write_img = function(arr, addstub){
fname = addstub
fname = file.path(outdir, paste0(stub, "_", fname))
if ( !inherits( arr, "nifti")){
mom = nim
mom@.Data = array(arr, dim = dim(mom))
} else {
mom = arr
}
mom = cal_img(mom)
mom = zero_trans(mom)
mom = datatyper(mom,
datatype = convert.datatype()$FLOAT32,
bitpix = convert.bitpix()$FLOAT32)
writenii(mom, filename = fname)
}
make_moment_list = function(){
mom.exist = sapply(moments, function(moment){
addstub = paste0("moment", moment)
fname = make_fname(addstub)
file.exists(fname)
})
### if all data does not exist or rewrite - remake data
if (!all(mom.exist) | overwrite) {
msg = "# Running Local_Moment"
if (verbose){
message(msg)
}
if (shiny) {
shiny::incProgress(message = msg, amount = 0.02)
}
moms = local_moment(
img,
mask = mask,
nvoxels = nvoxels,
moment = moments, center = center,
invert = FALSE,
...)
if (save_imgs) {
for (imom in seq_along(moments)) {
moment = moments[imom]
addstub = paste0("moment", moment)
fname = make_fname(addstub)
mom.img = moms[[imom]]
write_img(mom.img, addstub)
}
}
}
### if all data exists and not to rewrite - just read in
if (all(mom.exist) & !overwrite) {
moms = lapply(moments, function(moment){
addstub = paste0("moment", moment)
fname = make_fname(addstub)
mom.img = readnii(fname, reorient = FALSE)
return(mom.img)
})
}
msg = "# Creating Moment Matrix"
if (verbose) {
message(msg)
}
if (shiny) {
shiny::incProgress(message = msg, amount = 0.02)
}
mat = matrix(NA,
ncol = length(moms),
nrow = prod(dim(mask))
)
for (imom in seq_along(moms)) {
mat[, imom] = c(moms[[imom]])
}
# moms = sapply(moms, c)
rm(list = "moms"); gc(); gc();
colnames(mat) = paste0("moment", moments)
mat = as.data.frame(mat)
return(mat)
}
img.fname = checkimg(img)
img = check_nifti(img)
mask.fname = checkimg(mask)
orig.mask = mask = check_nifti(mask)
if (!is.null(roi)) {
# roi.fname = roi
roi = check_nifti(roi)
}
# stopifnot(class(roi) == "character")
# stopifnot(class(img) == "character")
# stopifnot(class(mask) == "character")
if (save_imgs){
stopifnot(!is.null(outdir))
stopifnot(!is.null(stub))
}
if (is.null(outdir)){
outdir = tempdir()
}
if (is.null(stub)){
stub = nii.stub(img.fname, bn = TRUE)
}
msg = "# Reading Images"
if (verbose) {
message(msg)
}
if (shiny) {
shiny::incProgress(message = msg, amount = 0.02)
}
# img = readnii(img.fname, reorient= FALSE)
orig.img = img
# stub = nii.stub(img.fname, bn=TRUE)
nim = niftiarr(img, array(NA, dim = dim(orig.img)))
nim = datatyper(nim,
datatype = convert.datatype()$FLOAT32,
bitpix = convert.bitpix()$FLOAT32)
dimg = dim(nim)
vdim = voxdim(nim)
# if (is.null(roi)){
# roi = niftiarr(img, array(0, dim = dim(nim)))
# }
msg = "# Eroding Mask"
addstub = "usemask"
fname = make_fname(addstub)
if (verbose) {
message(msg)
}
if (shiny) {
shiny::incProgress(message = msg, amount = 0.02)
}
if (file.exists(fname) & !overwrite){
mask = readnii(fname, reorient = FALSE)
} else {
if (erode_mask) {
# erode the mask
mask = fslerode(file = mask.fname,
kopts = "-kernel box 3x3x1",
reorient = FALSE, retimg = TRUE,
verbose = verbose > 1)
} else {
mask = readnii(mask.fname)
}
#### may add this - think about it
# mask = fslfill(mask, bin=TRUE, retimg = TRUE)
mask = mask > 0
mask = datatyper(mask)
if (save_imgs){
write_img(mask, addstub)
}
}
if (sum(mask) == 0) {
msg = paste0(
"Eroded mask is empty! Something went wrong with eroding ",
"or Skull stripping")
stop(msg)
}
orig.masked.img = mask_img(orig.img, orig.mask)
masked.img = mask_img(orig.img, mask)
if (!is.null(roi)){
miss.roi = sum(mask == 0 & roi > 0 )
} else {
miss.roi = NULL
}
keep.ind = which(mask > 0)
msg = "# Getting Moments"
if (verbose) {
message(msg)
}
if (shiny) {
shiny::incProgress(message = msg, amount = 0.02)
}
################################################
# Making Moment Images
################################################
df = make_moment_list()
###########
# Creating Skew/Kurtosis
###########
df$skew = df$moment3/df$moment2 ^ {3/2}
df$kurtosis = df$moment4/df$moment2 ^ {2}
df$moment3 = df$moment4 = NULL
###########
# Writing Skew
###########
addstub = "skew"
fname = make_fname(addstub)
if (file.exists(fname) & !overwrite) {
} else {
skew = niftiarr(img, df$skew)
if (save_imgs) {
write_img(skew, addstub)
}
rm(list = c("skew")); gc(); gc();
}
###########
# Writing Kurtosis
###########
addstub = "kurtosis"
fname = make_fname(addstub)
if (file.exists(fname) & !overwrite) {
} else {
kurtosis = niftiarr(img, df$kurtosis)
if (save_imgs) {
write_img(kurtosis, addstub)
}
rm(list = c("kurtosis")); gc(); gc();
}
################################################
# Making Percent threshold image
################################################
msg = paste0("# Getting thresholded from ",
lthresh, " to ", uthresh, "\n")
if (verbose) {
message(msg)
}
if (shiny) {
shiny::incProgress(message = msg, amount = 0.02)
}
addstub = paste0("thresh_", lthresh, "_", uthresh)
fname = make_fname(addstub)
if (file.exists(fname) & !overwrite){
thresh_img = readnii(fname, reorient=FALSE)
} else {
thresh_img = niftiarr(img, img >= lthresh & img <= uthresh)
if (save_imgs){
write_img(thresh_img, addstub)
}
}
df$value = c(masked.img)
df$thresh = c(thresh_img)
cn = colnames(df)
################################################
# Making Z-score Images
################################################
msg = "# Getting Z-scored images"
if (verbose) {
message(msg)
}
if (shiny) {
shiny::incProgress(message = msg, amount = 0.02)
}
zimgs = lapply(1:3, function(i){
addstub = paste0("zscore", i)
fname = make_fname(addstub)
if (file.exists(fname) & !overwrite){
img = readnii(fname, reorient=FALSE)
} else {
img = zscore_img(masked.img, mask = mask, margin = i)
if (save_imgs){
write_img(img, addstub)
}
}
return(img)
})
zimgs = sapply(zimgs, c)
colnames(zimgs) = paste0("zscore", 1:3)
zimgs = as.data.frame(zimgs)
for (i in 1:3) {
df[, paste0("zscore", i)] = zimgs[, paste0("zscore", i)]
}
rm(list = c("zimgs")); gc(); gc();
# wmean2 = function(img, mask, trim = 0.2){
# x = img[ mask == 1]
# mn = psych::winsor.mean(x, trim = trim)
# s = psych::winsor.sd(x, trim = trim)
# z = (x-mn)/s
# img[mask == 1] = z
# img[mask == 0] = 0
# img = cal_img(img)
# return(img)
# }
wmean = function(img, mask, trim = 0.2){
x = img[ mask == 1 ]
stopifnot(length(trim) == 1)
stopifnot(trim > 0)
stopifnot(trim <= 0.5)
qtrim <- quantile(x,
c(trim, 0.5, 1 - trim),
na.rm = TRUE)
xbot <- qtrim[1]
xtop <- qtrim[3]
if (trim < 0.5) {
x[x < xbot] <- xbot
x[x > xtop] <- xtop
} else {
x[!is.na(x)] <- qtrim[2]
}
mn = mean(x, na.rm=TRUE)
s = sd(x, na.rm=TRUE)
img = (img-mn)/s
img = mask_img(img, mask)
img = finite_img(img)
return(img)
}
msg = "# Getting Winsorized Image"
if (verbose) {
message(msg)
}
if (shiny) {
shiny::incProgress(message = msg, amount = 0.02)
}
addstub = paste0("win_z")
fname = make_fname(addstub)
if (file.exists(fname) & !overwrite){
wmean_img = readnii(fname, reorient=FALSE)
} else {
wmean_img = wmean(orig.img, mask = mask, trim = 0.2)
if (save_imgs){
write_img(wmean_img, addstub)
}
}
df$win_z = c(wmean_img)
rm(list = c("wmean_img")); gc(); gc();
################################################
# Making Percent threshold image
################################################
msg = paste0("# Getting Percent thresholded from ",
lthresh, " to ", uthresh)
if (verbose) {
message(msg)
}
if (shiny) {
shiny::incProgress(message = msg, amount = 0.02)
}
addstub = paste0("pct_thresh_", lthresh, "_", uthresh)
fname = make_fname(addstub)
if (file.exists(fname) & !overwrite){
pct_thresh = readnii(fname, reorient=FALSE)
} else {
pct_thresh = local_moment(thresh_img, mask = mask,
nvoxels = nvoxels,
moment = 1, center = FALSE,
...)[[1]]
if (save_imgs){
write_img(pct_thresh, addstub)
}
}
df$pct_thresh = c(pct_thresh)
rm(list = c("thresh_img", "pct_thresh")); gc(); gc();
################################################
# Making Probability
################################################
msg = "# Getting Top Probability Segmentation from Atropos"
if (verbose) {
message(msg)
}
if (shiny) {
shiny::incProgress(message = msg, amount = 0.02)
}
addstub = paste0("prob_img")
fname = make_fname(addstub)
if (file.exists(fname) & !overwrite){
prob_img = readnii(fname, reorient = FALSE)
} else {
window.masked.img = window_img(masked.img, window = c(0, 100))
seg = otropos( window.masked.img, i = "KMeans[4]", verbose = verbose > 1)
prob_img = seg$probabilityimages[[3]] + seg$probabilityimages[[4]]
rm(list = c("seg")); gc(); gc();
if (save_imgs){
write_img(prob_img, addstub)
}
}
df$prob_img = c(prob_img)
rm(list = c("prob_img")); gc(); gc();
################################################
# Making Percent that are 0
################################################
msg = "# Getting Percent 0"
if (verbose) {
message(msg)
}
if (shiny) {
shiny::incProgress(message = msg, amount = 0.02)
}
###### changed to masked.img
thresh_0 = niftiarr(masked.img, masked.img == 0)
addstub = "pct_zero_neighbor"
fname = make_fname(addstub)
if (file.exists(fname) & !overwrite){
pct_zero_neighbor = readnii(fname, reorient=FALSE)
} else {
pct_zero_neighbor = local_moment(thresh_0, mask = NULL,
nvoxels = nvoxels,
moment = 1, center = FALSE,
...)[[1]]
pct_zero_neighbor = mask_img(pct_zero_neighbor, mask)
if (save_imgs){
write_img(pct_zero_neighbor, addstub)
}
}
df$pct_zero_neighbor = c(pct_zero_neighbor)
rm(list = c("pct_zero_neighbor", "thresh_0")); gc(); gc();
msg = "# Getting Any 0 Neighbors"
if (verbose) {
message(msg)
}
if (shiny) {
shiny::incProgress(message = msg, amount = 0.02)
}
addstub = "any_zero_neighbor"
df$any_zero_neighbor = (df$pct_zero_neighbor > 0) *1
################################################
# Making Distance to centroid
################################################
msg = "# Getting Distance to centroid"
if (verbose) {
message(msg)
}
if (shiny) {
shiny::incProgress(message = msg, amount = 0.02)
}
addstub = "dist_centroid"
fname = make_fname(addstub)
if (file.exists(fname) & !overwrite){
dist.img = readnii(fname, reorient=FALSE)
} else {
centroid = t(which(mask > 0, arr.ind=TRUE))
all.ind = expand.grid(lapply(dimg, seq))
colnames(all.ind) = paste0("dim", seq(length(dimg)))
all.ind = t(as.matrix(all.ind))
all.ind = all.ind * vdim
centroid = centroid * vdim
dist.img = t(all.ind - rowMeans(centroid))
rm(list = c("all.ind")); gc(); gc();
dist.img = sqrt(rowSums(dist.img^2))
dist.img = niftiarr(img, array(dist.img, dim =dimg))
dist.img = mask_img(dist.img, mask)
dist.img = datatyper(dist.img,
datatype= convert.datatype()$FLOAT32,
bitpix= convert.bitpix()$FLOAT32)
if (save_imgs){
write_img(dist.img, addstub)
}
}
df$dist_centroid = c(dist.img)
rm(list = c("dist.img")); gc(); gc();
################################################
# Making Distance to centroid
################################################
msg = "# Perona Malik Smoother"
if (verbose) {
message(msg)
}
if (shiny) {
shiny::incProgress(message = msg, amount = 0.02)
}
addstub = "perona_malik"
fname = make_fname(addstub)
if (file.exists(fname) & !overwrite) {
dist.img = readnii(fname, reorient = FALSE)
} else {
pm_img = extrantsr::perona_malik(
masked.img, n_iter = 10,
conductance = 5)
if (save_imgs) {
write_img(pm_img, addstub)
}
rm(list = c("seg")); gc(); gc();
}
df$perona_malik = c(pm_img)
rm(list = c("pm_img")); gc(); gc();
################################################
# Making 10mm and 20mm smoother
################################################
make_smooth_img = function(sigma){
msg = paste0("# Getting Smooth ", sigma)
if (verbose) {
message(msg)
}
if (shiny) {
shiny::incProgress(message = msg, amount = 0.02)
}
addstub = paste0("smooth", sigma)
if (save_imgs){
fname = make_fname(addstub)
} else {
fname = tempfile()
if (file.exists(fname)){
file.remove(fname)
}
}
if (file.exists(fname) & !overwrite) {
smooth.img = readnii(fname, reorient = FALSE)
} else {
smooth.mask = fslr::fsl_smooth(
file = mask,
sigma = sigma,
mask = NULL,
smooth_mask = FALSE,
verbose = verbose > 1)
smooth.img = fslsmooth(img.fname, sigma=sigma,
mask = mask, retimg = TRUE,
outfile = fname,
verbose = verbose > 1)
}
return(c(smooth.img))
}
# df$smooth2 = make_smooth_img(sigma=2)
# df$smooth5 = make_smooth_img(sigma=5)
smooths = sapply(sigmas, make_smooth_img)
colnames(smooths) = paste0("smooth", sigmas)
df = cbind(df, smooths)
rm(list = c("smooths")); gc(); gc();
msg = "# Z-score to template"
if (verbose) {
message(msg)
}
if (shiny) {
shiny::incProgress(message = msg, amount = 0.02)
}
addstub = "zscore_template"
fname = make_fname(addstub)
if (file.exists(fname) & !overwrite) {
zscore = readnii(fname, reorient = FALSE)
} else {
zscore = extrantsr::zscore_template(img = orig.masked.img,
template.file = template.file,
mean.img = mean.img,
sd.img = sd.img,
typeofTransform = zscore.typeofTransform,
interpolator = zscore.interpolator,
verbose = verbose > 1)
if (save_imgs){
write_img(zscore, addstub)
}
}
df$zscore_template = c(zscore)
rm(list = c("zscore")); gc(); gc();
msg = "# Flipped Difference"
if (verbose) {
message(msg)
}
if (shiny) {
shiny::incProgress(message = msg, amount = 0.02)
}
addstub = "flipped_value"
fname = make_fname(addstub)
if (file.exists(fname) & !overwrite) {
flipped_value = readnii(fname, reorient=FALSE)
} else {
flipper = extrantsr::reg_flip(
t1 = orig.masked.img,
mask = orig.mask,
template.file = template.file,
typeofTransform = flip.typeofTransform,
interpolator = flip.interpolator,
verbose = verbose > 1)
flipper = flipper$t1
##########################
# Take difference
##########################
flipped_value = orig.masked.img - flipper
rm(list = c("flipper")); gc(); gc();
if (save_imgs) {
write_img(flipped_value, addstub)
}
}
df$flipped_value = c(flipped_value)
rm(list = c("flipped_value")); gc(); gc();
msg = "# Thresholding small values"
if (verbose) {
message(msg)
}
if (shiny) {
shiny::incProgress(message = msg, amount = 0.02)
}
for (icn in seq(ncol(df))) {
x = df[, icn]
if (!(class(x) %in% c("factor", "character"))) {
x[ !is.finite(x) ] = 0
}
df[, icn] = x
}
df = as.matrix(df)
low = abs(df) < low_thresh
df[ low ] = 0
df = data.frame(df, stringsAsFactors = FALSE)
if (!is.null(roi)) {
df$Y = c(roi)
} else {
df$Y = NA
}
df$mask = c(mask)
return(list(df = df, keep.ind = keep.ind, nim = nim,
miss.roi = miss.roi))
}