-
Notifications
You must be signed in to change notification settings - Fork 53
/
compute.py
1149 lines (977 loc) · 37.4 KB
/
compute.py
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
#!/usr/bin/env python
"""
Compute functions.
Authors:
- Arno Klein, 2012-2016 ([email protected]) http://binarybottle.com
Copyright 2016, Mindboggle team (http://mindboggle.info), Apache v2.0 License
"""
def distcorr(X, Y):
"""
Compute the distance correlation function.
Parameters
----------
X : list or array of numbers
Y : list or array of numbers
Returns
-------
dcor : float
distance correlation
Examples
--------
>>> from mindboggle.guts.compute import distcorr
>>> import numpy as np
>>> a = [1,2,3,4,5]
>>> b = [1,2,9,4,4]
>>> dcor = distcorr(a, b)
>>> np.float("{0:.{1}f}".format(dcor, 5))
0.76268
Copyright (2014-2015) MIT
Written by Satrajit S. Ghosh (Apache License v2.0) as part of the
mapalign GitHub repository (https://github.com/satra/mapalign)
"""
import numpy as np
from scipy.spatial.distance import pdist, squareform
X = np.atleast_1d(X)
Y = np.atleast_1d(Y)
if np.prod(X.shape) == len(X):
X = X[:, None]
if np.prod(Y.shape) == len(Y):
Y = Y[:, None]
X = np.atleast_2d(X)
Y = np.atleast_2d(Y)
n = X.shape[0]
if Y.shape[0] != X.shape[0]:
raise ValueError('Number of samples must match')
a = squareform(pdist(X))
b = squareform(pdist(Y))
A = a - a.mean(axis=0)[None, :] - a.mean(axis=1)[:, None] + a.mean()
B = b - b.mean(axis=0)[None, :] - b.mean(axis=1)[:, None] + b.mean()
dcov2_xy = (A * B).sum()/float(n * n)
dcov2_xx = (A * A).sum()/float(n * n)
dcov2_yy = (B * B).sum()/float(n * n)
dcor = np.sqrt(dcov2_xy)/np.sqrt(np.sqrt(dcov2_xx) * np.sqrt(dcov2_yy))
return dcor
def point_distance(point, points):
"""
Compute the Euclidean distance from one point to a second (set) of points.
Parameters
----------
point : list of three floats
coordinates for a single point
points : list with one or more lists of three floats
coordinates for a second point (or multiple points)
Returns
-------
min_distance : float
Euclidean distance between two points,
or the minimum distance between a point and a set of points
min_index : int
index of closest of the points (zero if only one)
Examples
--------
>>> from mindboggle.guts.compute import point_distance
>>> point = [1,2,3]
>>> points = [[10,2.0,3], [0,1.5,2]]
>>> point_distance(point, points)
(1.5, 1)
Notes
-----
Future plan is to use scipy.spatial.distance.cdist to compute distances
scipy.spatial.distance.cdist is available in scipy v0.12 or later
"""
import numpy as np
# If points is a single point
if np.ndim(points) == 1:
#return np.linalg.norm(np.array(point) - np.array(points))
return np.sqrt((point[0] - points[0]) ** 2 + \
(point[1] - points[1]) ** 2 + \
(point[2] - points[2]) ** 2), 0
# If points is a set of multiple points
elif np.ndim(points) == 2:
min_distance = np.Inf
min_index = 0
point = np.array(point)
for index, point2 in enumerate(points):
distance = np.sqrt((point[0] - point2[0]) ** 2 + \
(point[1] - point2[1]) ** 2 + \
(point[2] - point2[2]) ** 2)
#distance = np.linalg.norm(point - np.array(point2))
if distance < min_distance:
min_distance = distance
min_index = index
return min_distance, min_index
# Else return None
else:
return None, None
def vector_distance(vector1, vector2, normalize=False):
"""
Compute the Euclidean distance between two equal-sized vectors.
Parameters
----------
vector1 : numpy array of floats
vector of values
vector2 : numpy array of floats
vector of values
normalize : bool
normalize each element of the vectors?
Returns
-------
distance : float
Euclidean distance between two vectors
Examples
--------
>>> import numpy as np
>>> from mindboggle.guts.compute import vector_distance
>>> vector1 = np.array([1.,2.,3.])
>>> vector2 = np.array([0,1,5])
>>> distance = vector_distance(vector1, vector2)
>>> print('{0:0.5f}'.format(distance))
0.81650
"""
import numpy as np
if np.size(vector1) == np.size(vector2):
# Make sure arguments are numpy arrays
if not isinstance(vector1, np.ndarray):
vector1 = np.asarray(vector1)
if not isinstance(vector2, np.ndarray):
vector2 = np.asarray(vector2)
if normalize:
vector_diff = np.zeros(len(vector1))
for i in range(len(vector1)):
max_v1v2 = max([vector1[i], vector2[i]])
if max_v1v2 > 0:
vector_diff[i] = (vector1[i] - vector2[i]) / max_v1v2
else:
vector_diff = vector1 - vector2
return np.sqrt(sum((vector_diff)**2)) / np.size(vector1)
else:
print("Vectors have to be of equal size to compute distance.")
return None
def pairwise_vector_distances(vectors, save_file=False, normalize=False):
"""
Compare every pair of equal-sized vectors.
Parameters
----------
vectors : array of 1-D lists or arrays of integers or floats
save_file : bool
save file?
normalize : bool
normalize each element of the vectors?
Returns
-------
vector_distances : numpy array of integers or floats
distances between each pair of vectors
outfile : string [optional]
output filename for pairwise_vector_distances
Examples
--------
>>> import numpy as np
>>> from mindboggle.guts.compute import pairwise_vector_distances
>>> vectors = [[1,2,3],[0,3,5],[0,3.5,5],[1,1,1]]
>>> save_file = False
>>> normalize = False
>>> vector_distances, outfile = pairwise_vector_distances(vectors,
... save_file, normalize)
>>> print(np.array_str(np.array(vector_distances),
... precision=5, suppress_small=True))
[[0. 0.8165 0.89753 0.74536]
[0. 0. 0.16667 1.52753]
[0. 0. 0. 1.60728]
[0. 0. 0. 0. ]]
"""
import os
import numpy as np
from mindboggle.guts.compute import vector_distance
# Make sure argument is a numpy array
if not isinstance(vectors, np.ndarray):
vectors = np.array(vectors)
# Initialize output
vector_distances = np.zeros((len(vectors), len(vectors)))
# --------------------------------------------------------------------------
# Compute distance between each pair of vectors
# --------------------------------------------------------------------------
# Loop through every pair of vectors
for ihist1 in range(len(vectors)):
for ihist2 in range(len(vectors)):
if ihist2 >= ihist1:
# Store pairwise distances between histogram values
d = vector_distance(1.0*vectors[ihist1],
1.0*vectors[ihist2],
normalize=normalize)
vector_distances[ihist1, ihist2] = d
if save_file:
outfile = os.path.join(os.getcwd(), 'vector_distances.txt')
np.savetxt(outfile, vector_distances,
fmt=len(vectors) * '%.4f ', delimiter='\t', newline='\n')
if not os.path.exists(outfile):
raise IOError(outfile + " not found")
else:
outfile = ''
return vector_distances, outfile
def source_to_target_distances(sourceIDs, targetIDs, points,
segmentIDs=[], excludeIDs=[-1]):
"""
Create a Euclidean distance matrix between source and target points.
Compute the Euclidean distance from each source point to
its nearest target point, optionally within each segment.
Example::
Compute fundus-to-feature distances, the minimum distance
from each label boundary vertex (corresponding to a fundus
in the DKT cortical labeling protocol) to all of the
feature vertices in the same fold.
Parameters
----------
sourceIDs : list of N integers (N is the number of vertices)
source IDs, where any ID not in excludeIDs is a source point
targetIDs : list of N integers (N is the number of vertices)
target IDs, where any ID not in excludeIDs is a target point
points : list of N lists of three floats (N is the number of vertices)
coordinates of all vertices
segmentIDs : list of N integers (N is the number of vertices)
segment IDs, where each ID not in excludeIDs is considered a
different segment (unlike above, where value in sourceIDs or
targetIDs doesn't matter, so long as its not in excludeIDs);
source/target distances are computed within each segment
excludeIDs : list of integers
IDs to exclude
Returns
-------
distances : numpy array
distance value for each vertex (default -1)
distance_matrix : numpy array [#points by maximum segment ID + 1]
distances organized by segments (columns)
"""
import numpy as np
from mindboggle.guts.compute import point_distance
if isinstance(points, list):
points = np.asarray(points)
npoints = len(points)
# Extract unique segment IDs (or use all points as a single segment):
if np.size(segmentIDs):
segments = [x for x in np.unique(segmentIDs) if x not in excludeIDs]
else:
segmentIDs = np.zeros(npoints)
segments = [0]
nsegments = max(segments) + 1
# Initialize outputs:
distances = -1 * np.ones(npoints)
distance_matrix = -1 * np.ones((npoints, nsegments))
# For each segment:
for segment in segments:
segment_indices = [i for i,x in enumerate(segmentIDs)
if x == segment]
# Find all source points in the segment:
source_indices = [i for i,x in enumerate(sourceIDs)
if x not in excludeIDs
if i in segment_indices]
# Find all target points in the segment:
target_indices = [i for i,x in enumerate(targetIDs)
if x not in excludeIDs
if i in segment_indices]
if source_indices and target_indices:
# For each source point in the segment:
for isource in source_indices:
# Find the closest target point:
d, i = point_distance(points[isource],
points[target_indices])
distances[isource] = d
distance_matrix[isource, segment] = d
return distances, distance_matrix
def weighted_to_repeated_values(X, W=[], precision=1):
"""
Create a list of repeated values from weighted values.
This is useful for computing weighted statistics (ex: weighted median).
Adapted to allow for fractional weights from
http://stackoverflow.com/questions/966896/
code-golf-shortest-code-to-find-a-weighted-median
Parameters
----------
X : numpy array of floats or integers
values
W : numpy array of floats or integers
weights
precision : integer
number of decimal places to consider weights
Returns
-------
repeat_values : numpy array of floats or integers
repeated values according to their weight
Examples
--------
>>> import numpy as np
>>> from mindboggle.guts.compute import weighted_to_repeated_values
>>> X = np.array([1,2,4,7,8])
>>> W = np.array([.1,.1,.3,.2,.3])
>>> precision = 1
>>> weighted_to_repeated_values(X, W, precision)
[1, 2, 4, 4, 4, 7, 7, 8, 8, 8]
"""
import numpy as np
# Make sure arguments have the correct type:
if not isinstance(X, np.ndarray):
X = np.array(X)
if not isinstance(W, np.ndarray):
W = np.array(W)
if not isinstance(precision, int):
precision = int(precision)
if np.size(W):
# If weights are decimals, multiply by 10 until they are whole numbers.
# If after multiplying precision times they are not whole, round them:
whole = True
if any(np.mod(W,1)):
whole = False
for i in range(precision):
if any(np.mod(W,1)):
W *= 10
else:
whole = True
break
if not whole:
W = [int(np.round(x)) for x in W]
repeat_values = sum([[x]*w for x,w in zip(X,W)],[])
else:
repeat_values = X
return repeat_values
def weighted_median(X, W=[], precision=1):
"""
Compute a weighted median.
Parameters
----------
X : numpy array of floats or integers
values
W : numpy array of floats or integers
weights
precision : integer
number of decimal places to consider weights
Returns
-------
wmedian : float
weighted median
Examples
--------
>>> import numpy as np
>>> from mindboggle.guts.compute import weighted_median
>>> X = np.array([1,2,4,7,8])
>>> W = np.array([.1,.1,.3,.2,.3])
>>> precision = 1
>>> # [1, 2, 4, 4, 4, 7, 7, 8, 8, 8]
>>> weighted_median(X, W, precision)
5.5
"""
import numpy as np
from mindboggle.guts.compute import weighted_to_repeated_values
# Make sure arguments have the correct type:
if not isinstance(X, np.ndarray):
X = np.array(X)
if not isinstance(W, np.ndarray):
W = np.array(W)
if not isinstance(precision, int):
precision = int(precision)
wmedian = np.median(weighted_to_repeated_values(X, W, precision))
return wmedian
def median_abs_dev(X, W=[], precision=1, c=1.0):
"""
Compute the (weighted) median absolute deviation.
mad = median(abs(x - median(x))) / c
Parameters
----------
X : numpy array of floats or integers
values
W : numpy array of floats or integers
weights
precision : integer
number of decimal places to consider weights
c : float
constant used as divisor for mad computation;
c = 0.6745 is used to convert from mad to standard deviation
Returns
-------
mad : float
(weighted) median absolute deviation
Examples
--------
>>> import numpy as np
>>> from mindboggle.guts.compute import median_abs_dev
>>> X = np.array([1,2,4,7,8])
>>> W = np.array([.1,.1,.3,.2,.3])
>>> precision = 1
>>> # [1, 2, 4, 4, 4, 7, 7, 8, 8, 8]
>>> median_abs_dev(X, W, precision)
2.0
"""
import numpy as np
from mindboggle.guts.compute import weighted_to_repeated_values
# Make sure arguments have the correct type:
if not isinstance(X, np.ndarray):
X = np.array(X)
if not isinstance(W, np.ndarray):
W = np.array(W)
if not isinstance(precision, int):
precision = int(precision)
if np.size(W):
X = weighted_to_repeated_values(X, W, precision)
mad = np.median(np.abs(X - np.median(X))) / c
return mad
def means_per_label(values, labels, include_labels=[], exclude_labels=[], areas=[]):
"""
Compute the mean value across vertices per label,
optionally taking into account surface area per vertex (UNTESTED).
Formula:
average value = sum(a_i * v_i) / total_surface_area,
where *a_i* and *v_i* are the area and value for each vertex *i*.
Note ::
This function is different than stats_per_label() in two ways:
1. It only computes the (weighted) mean and sdev.
2. It can accept 2-D arrays (such as [x,y,z] coordinates).
Parameters
----------
values : numpy array of one or more lists of integers or floats
values to average per label
labels : list or array of integers
label for each value
include_labels : list of integers
labels to include
exclude_labels : list of integers
labels to be excluded
areas : numpy array of floats
surface areas (if provided, used to normalize means and sdevs)
Returns
-------
means : list of floats
mean(s) for each label
sdevs : list of floats
standard deviation(s) for each label
label_list : list of integers
unique label numbers
label_areas : list of floats (if normalize_by_area)
surface area for each labeled set of vertices
Examples
--------
>>> import numpy as np
>>> from mindboggle.mio.vtks import read_scalars, read_vtk
>>> from mindboggle.guts.compute import means_per_label
>>> from mindboggle.mio.fetch_data import prep_tests
>>> urls, fetch_data = prep_tests()
>>> values_file = fetch_data(urls['left_mean_curvature'], '', '.vtk')
>>> labels_file = fetch_data(urls['left_freesurfer_labels'], '', '.vtk')
>>> area_file = fetch_data(urls['left_area'], '', '.vtk')
>>> values, name = read_scalars(values_file, True, True)
>>> labels, name = read_scalars(labels_file)
>>> areas, name = read_scalars(area_file, True, True)
>>> include_labels = []
>>> exclude_labels = [-1]
>>> # Compute mean curvature per label normalized by area:
>>> means, sdevs, label_list, label_areas = means_per_label(values, labels,
... include_labels, exclude_labels, areas)
>>> [np.float("{0:.{1}f}".format(x, 5)) for x in means[0:5]]
[-1.1793, -1.21405, -2.49318, -3.58116, -3.34987]
>>> [np.float("{0:.{1}f}".format(x, 5)) for x in sdevs[0:5]]
[2.43827, 2.33857, 2.0185, 3.25964, 2.8274]
>>> # Compute mean curvature per label:
>>> areas = []
>>> means, sdevs, label_list, label_areas = means_per_label(values, labels,
... include_labels, exclude_labels, areas)
>>> [np.float("{0:.{1}f}".format(x, 5)) for x in means[0:5]]
[-0.99077, -0.3005, -1.59342, -2.03939, -2.31815]
>>> [np.float("{0:.{1}f}".format(x, 5)) for x in sdevs[0:5]]
[2.3486, 2.4023, 2.3253, 3.31023, 2.91794]
>>> # FIX: compute mean coordinates per label:
>>> #points, indices, lines, faces, labels, scalar_names, npoints, input_vtk = read_vtk(values_file)
>>> #means, sdevs, label_list, label_areas = means_per_label(points, labels,
>>> # include_labels, exclude_labels, areas)
>>> #means[0:3]
>>> #sdevs[0:3]
"""
import numpy as np
# Make sure arguments are numpy arrays
if not isinstance(values, np.ndarray):
values = np.asarray(values)
if not isinstance(areas, np.ndarray):
areas = np.asarray(areas)
if include_labels:
label_list = include_labels
else:
label_list = np.unique(labels)
label_list = [int(x) for x in label_list if int(x) not in exclude_labels]
means = []
sdevs = []
label_areas = []
if values.ndim > 1:
dim = np.shape(values)[1]
else:
dim = 1
for label in label_list:
I = [i for i,x in enumerate(labels) if x == label]
if I:
X = values[I]
if np.size(areas):
W = areas[I]
sumW = sum(W)
label_areas.append(sumW)
if sumW > 0:
if dim > 1:
W = np.transpose(np.tile(W, (dim,1)))
means.append(np.sum(W * X, axis=0) / sumW)
Xdiff = X - np.mean(X, axis=0)
sdevs.append(np.sqrt(np.sum(W * Xdiff**2, axis=0) / sumW))
else:
if dim > 1:
means.append(np.mean(X, axis=0))
sdevs.append(np.std(X, axis=0))
else:
means.append(np.mean(X))
sdevs.append(np.std(X))
else:
if dim > 1:
means.append(np.mean(X, axis=0))
sdevs.append(np.std(X, axis=0))
else:
means.append(np.mean(X))
sdevs.append(np.std(X))
else:
means.append(np.zeros(dim))
sdevs.append(np.zeros(dim))
label_areas.append(np.zeros(dim))
if dim > 1:
means = [x.tolist() for x in means]
sdevs = [x.tolist() for x in sdevs]
label_areas = [x.tolist() for x in label_areas]
return means, sdevs, label_list, label_areas
def sum_per_label(values, labels, include_labels=[], exclude_labels=[]):
"""
Compute the sum value across vertices per label.
Parameters
----------
values : numpy array of one or more lists of integers or floats
values to average per label
labels : list or array of integers
label for each value
include_labels : list of integers
labels to include
exclude_labels : list of integers
labels to be excluded
Returns
-------
sums : list of floats
sum for each label
label_list : list of integers
unique label numbers
Examples
--------
>>> import numpy as np
>>> from mindboggle.mio.vtks import read_scalars
>>> from mindboggle.guts.compute import sum_per_label
>>> from mindboggle.mio.fetch_data import prep_tests
>>> urls, fetch_data = prep_tests()
>>> values_file = fetch_data(urls['left_mean_curvature'], '', '.vtk')
>>> labels_file = fetch_data(urls['left_freesurfer_labels'], '', '.vtk')
>>> values, name = read_scalars(values_file, True, True)
>>> labels, name = read_scalars(labels_file)
>>> include_labels = []
>>> exclude_labels = [-1]
>>> # Compute sum area per label:
>>> sums, label_list = sum_per_label(values, labels, include_labels,
... exclude_labels)
>>> [np.float("{0:.{1}f}".format(x, 5)) for x in sums[0:5]]
[-8228.32913, -424.90109, -1865.8959, -8353.33769, -5130.06613]
"""
import numpy as np
# Make sure arguments are numpy arrays
if not isinstance(values, np.ndarray):
values = np.asarray(values)
if include_labels:
label_list = include_labels
else:
label_list = np.unique(labels)
label_list = [int(x) for x in label_list if int(x) not in exclude_labels]
sums = []
for label in label_list:
I = [i for i,x in enumerate(labels) if x == label]
if I:
X = values[I]
sums.append(np.sum(X))
else:
sums.append(0)
return sums, label_list
def stats_per_label(values, labels, include_labels=[], exclude_labels=[],
weights=[], precision=1):
"""
Compute various statistical measures across vertices per label,
optionally using weights (such as surface area per vertex).
Example (area-weighted mean):
average value = sum(a_i * v_i) / total_surface_area,
where *a_i* and *v_i* are the area and value for each vertex *i*.
Reference:
Weighted skewness and kurtosis unbiased by sample size
Lorenzo Rimoldini, arXiv:1304.6564 (2013)
http://arxiv.org/abs/1304.6564
Note ::
This function is different than means_per_label() in two ways:
1. It computes more than simply the (weighted) mean and sdev.
2. It only accepts 1-D arrays of values.
Parameters
----------
values : numpy array of individual or lists of integers or floats
values for all vertices
labels : list or array of integers
label for each value
include_labels : list of integers
labels to include
exclude_labels : list of integers
labels to be excluded
weights : numpy array of floats
weights to compute weighted statistical measures
precision : integer
number of decimal places to consider weights
Returns
-------
medians : list of floats
median for each label
mads : list of floats
median absolute deviation for each label
means : list of floats
mean for each label
sdevs : list of floats
standard deviation for each label
skews : list of floats
skew for each label
kurts : list of floats
kurtosis value for each label
lower_quarts : list of floats
lower quartile for each label
upper_quarts : list of floats
upper quartile for each label
label_list : list of integers
list of unique labels
Examples
--------
>>> import numpy as np
>>> from mindboggle.mio.vtks import read_scalars
>>> from mindboggle.guts.compute import stats_per_label
>>> from mindboggle.mio.fetch_data import prep_tests
>>> urls, fetch_data = prep_tests()
>>> values_file = fetch_data(urls['left_mean_curvature'], '', '.vtk')
>>> labels_file = fetch_data(urls['left_freesurfer_labels'], '', '.vtk')
>>> area_file = fetch_data(urls['left_area'], '', '.vtk')
>>> values, name = read_scalars(values_file, True, True)
>>> areas, name = read_scalars(area_file, True, True)
>>> labels, name = read_scalars(labels_file)
>>> include_labels = []
>>> exclude_labels = [-1]
>>> weights = areas
>>> precision = 1
>>> medians, mads, means, sdevs, skews, kurts, lower_quarts, upper_quarts, label_list = stats_per_label(values,
... labels, include_labels, exclude_labels, weights, precision)
>>> [np.float("{0:.{1}f}".format(x, 5)) for x in medians[0:5]]
[-1.13602, -1.22961, -2.49665, -3.80782, -3.37309]
>>> [np.float("{0:.{1}f}".format(x, 5)) for x in mads[0:5]]
[1.17026, 1.5045, 1.28234, 2.11515, 1.69333]
>>> [np.float("{0:.{1}f}".format(x, 5)) for x in means[0:5]]
[-1.1793, -1.21405, -2.49318, -3.58116, -3.34987]
>>> [np.float("{0:.{1}f}".format(x, 5)) for x in kurts[0:5]]
[2.34118, -0.3969, -0.55787, -0.73993, 0.3807]
"""
import numpy as np
from scipy.stats import skew, kurtosis, scoreatpercentile
from mindboggle.guts.compute import weighted_to_repeated_values, median_abs_dev
# Make sure arguments are numpy arrays:
if not isinstance(values, np.ndarray):
values = np.asarray(values)
if not isinstance(weights, np.ndarray):
weights = np.asarray(weights)
# Initialize all statistical lists:
if include_labels:
label_list = include_labels
else:
label_list = np.unique(labels)
label_list = [int(x) for x in label_list if int(x) not in exclude_labels]
medians = []
mads = []
means = []
sdevs = []
skews = []
kurts = []
lower_quarts = []
upper_quarts = []
# Extract all vertex indices for each label:
for label in label_list:
I = [i for i,x in enumerate(labels) if x == label]
if I:
# Get the vertex values:
X = values[I]
if len([x for x in X if x != 0]):
# If there are as many weights as values, apply the weights to the values:
if np.size(weights) == np.size(values):
W = weights[I]
sumW = np.sum(W)
# If the sum of the weights and the standard deviation is non-zero,
# compute all statistics of the weighted values:
if sumW > 0:
Xdiff = X - np.mean(X)
Xstd = np.sqrt(np.sum(W * Xdiff**2) / sumW)
means.append(np.sum(W * X) / sumW)
sdevs.append(Xstd)
if Xstd > 0:
skews.append((np.sum(W * Xdiff**3) / sumW) / Xstd**3)
kurts.append((np.sum(W * Xdiff**4) / sumW) / Xstd**4 - 3)
else:
skews.append(skew(X))
kurts.append(kurtosis(X))
X = weighted_to_repeated_values(X, W, precision)
# If the sum of the weights equals zero, simply compute the statistics:
else:
means.append(np.mean(X))
sdevs.append(np.std(X))
skews.append(skew(X))
kurts.append(kurtosis(X))
# If there are no (or not enough) weights, simply compute the statistics:
else:
means.append(np.mean(X))
sdevs.append(np.std(X))
skews.append(skew(X))
kurts.append(kurtosis(X))
# Compute median, median absolute deviation, and lower and upper quartiles:
if np.size(X):
medians.append(np.median(X))
mads.append(median_abs_dev(X))
lower_quarts.append(scoreatpercentile(X, 25))
upper_quarts.append(scoreatpercentile(X, 75))
# If the weights are all smaller than the precision, then X will disappear,
# so set the above statistics (in the 'if' block) to zero:
else:
medians.append(0)
mads.append(0)
lower_quarts.append(0)
upper_quarts.append(0)
# If all values are equal to zero, set all statistics to zero:
else:
medians.append(0)
mads.append(0)
means.append(0)
sdevs.append(0)
skews.append(0)
kurts.append(0)
lower_quarts.append(0)
upper_quarts.append(0)
# If there are no vertices for the label, set all statistics to zero:
else:
medians.append(0)
mads.append(0)
means.append(0)
sdevs.append(0)
skews.append(0)
kurts.append(0)
lower_quarts.append(0)
upper_quarts.append(0)
return medians, mads, means, sdevs, skews, kurts, \
lower_quarts, upper_quarts, label_list
def count_per_label(labels, include_labels=[], exclude_labels=[]):
"""
Compute the number of times each label occurs.
Parameters
----------
labels : numpy 1-D array of integers
labels (e.g., one label per vertex of a mesh)
include_labels : list of integers
labels to include
(if empty, use unique numbers in image volume file)
exclude_labels : list of integers
labels to be excluded
Returns
-------
unique_labels : list of integers
unique label numbers
counts : list of floats
number of times each label occurs
Examples
--------
>>> from mindboggle.guts.compute import count_per_label
>>> labels = [8,8,8,8,8,10,11,12,10,10,11,11,11,12,12,12,12,13]
>>> include_labels = [9,10,11,12]
>>> exclude_labels = [13]
>>> unique_labels, counts = count_per_label(labels, include_labels,
... exclude_labels)
>>> unique_labels
[9, 10, 11, 12]
>>> counts
[0, 3, 4, 5]
>>> import nibabel as nb
>>> from mindboggle.mio.vtks import read_scalars
>>> from mindboggle.mio.labels import DKTprotocol
>>> from mindboggle.guts.compute import count_per_label
>>> from mindboggle.mio.fetch_data import prep_tests
>>> urls, fetch_data = prep_tests()
>>> labels_file = fetch_data(urls['freesurfer_labels'], '', '.nii.gz')
>>> img = nb.load(labels_file)
>>> hdr = img.get_header()
>>> labels = img.get_data().ravel()
>>> dkt = DKTprotocol()
>>> include_labels = dkt.label_numbers
>>> exclude_labels = []
>>> unique_labels, counts = count_per_label(labels,
... include_labels, exclude_labels)
>>> counts[0:10]
[0, 0, 0, 972, 2414, 2193, 8329, 2941, 1998, 10906]
"""
import numpy as np
# Make sure labels is a numpy array:
if isinstance(labels, list):
labels = np.array(labels)
elif isinstance(labels, np.ndarray):
pass
else:
raise IOError("labels should be a numpy array.")
# Unique list of labels:
if include_labels:
label_list = include_labels
else:
label_list = np.unique(labels).tolist()
label_list = [int(x) for x in label_list if int(x) not in exclude_labels]
# Loop through labels:
unique_labels = []
counts = []
for ilabel, label in enumerate(label_list):
# Find which voxels contain the label in each volume:
indices = np.where(labels == label)[0]
count = len(indices)
unique_labels.append(label)
counts.append(count)
return unique_labels, counts
def compute_overlaps(targets, list1, list2, output_file='', save_output=True,
verbose=False):
"""
Compute overlap for each target between two lists of numbers.
Parameters
----------
targets : list of integers
targets to find in lists
list1 : 1-D numpy array (or list) of numbers
list2 : 1-D numpy array (or list) of numbers
output_file : string
(optional) output file name
save_output : bool
save output file?
verbose : bool