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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260
|
#!/usr/bin/env python
""" matrix based distance metrics, and related coordinate transforms
functions to compute distance matrices row by row from abundance matrices,
typically samples (rows) vs. species/OTU's (cols)
DISTANCE FUNCTIONS
For distance functions, the API resembles the following (but see function
docstring for specifics):
* comparisons are between rows (samples)
* input: 2D numpy array. Limited support for non-2D arrays if
strict==False
* output: numpy 2D array float ('d') type. shape (inputrows, inputrows)
for sane input data
* two rows of all zeros *typically* returns 0 distance between them
* negative values are only allowed for some distance metrics,
in these cases if strict==True, negative input values return a ValueError,
and if strict==False, errors or misleading return values may result
* functions prefaced with "binary" consider only presense/absense in
input data (qualitative rather than quantitative)
TRANSFORM FUNCTIONS
* For transform functions, very little error checking exists. 0/0 evals
in transform fomulas will throw errors, and negative data will return
spurious results or throw errors
* The transform functions are as described in
Legendre, P. and E. Gallagher. 2001. Ecologically meaningful
transformations for ordination of species data. Oecologia: 129: 271-280.
These and allow the use
of ordination methods such as PCA and RDA, which are Euclidean-based,
for the analysis of community data, while circumventing the problems associated
with the Euclidean distance. The matrix that is returned still has samples as
rows and species as columns, but the values are transformed so that when
programs such as PCA calculate euclidean distances on the matrix, chord,
chisquare, 'species profile', or hellinger distances will result.
EXAMPLE USAGE:
>from distance_transform import dist_euclidean
>from numpy import array
>abundance_data = array([[1, 3],
[5, 2],
[0.1, 22]],'d')
>dists = dist_euclidean(abundance_data)
>print dists
array([[ 0. , 4.12310563, 19.02130385],
[ 4.12310563, 0. , 20.5915031 ],
[ 19.02130385, 20.5915031 , 0. ]])
"""
from __future__ import division
from numpy import (array, zeros, logical_and, logical_or, logical_xor, where,
mean, std, argsort, take, ravel, logical_not, shape, sqrt, abs,
sum, square, asmatrix, asarray, multiply, min, rank, any, all, isfinite,
nonzero, nan_to_num, geterr, seterr)
# any, all from numpy override built in any, all, preventing:
# ValueError: The truth value of an array with more than one element is
# ambiguous. Use a.any() or a.all()
from numpy.linalg import norm
__author__ = "Justin Kuczynski"
__copyright__ = "Copyright 2007-2009, The Cogent Project"
__credits__ = ["Rob Knight", "Micah Hamady", "Justin Kuczynski",
"Zongzhi Liu", "Catherine Lozupone"]
__license__ = "GPL"
__version__ = "1.4.1"
__maintainer__ = "Justin Kuczynski"
__email__ = "justinak@gmail.com"
__status__ = "Prototype"
def _rankdata(a):
""" Ranks the data in a, dealing with ties appropritely. First ravels
a. Adapted from Gary Perlman's |Stat ranksort.
private helper function
Returns: array of length equal to a, containing rank scores
"""
a = ravel(a)
n = len(a)
ivec = argsort(a)
svec = take(a, ivec)
sumranks = dupcount = 0
newarray = zeros(n,'d')
for i in range(n):
sumranks = sumranks + i
dupcount = dupcount + 1
if i==n-1 or svec[i] <> svec[i+1]:
averank = sumranks / float(dupcount) + 1
for j in range(i-dupcount+1,i+1):
newarray[ivec[j]] = averank
sumranks = dupcount = 0
return newarray
def trans_chord(m):
"""perform a chord distance transformation on the rows of m
transforms m to m' so that the euclidean dist between the rows of m' equals
the chord dist between the rows of m.
Ref:
Legendre, P. and E. Gallagher. 2001. Ecologically meaningful
transformations for ordination of species data. Oecologia: 129: 271-280.
"""
m = asmatrix(m)
row_norms = sqrt(sum(square(m), axis=1))
result = m / row_norms
return result
def trans_chisq(m):
"""perform a chi squared distance transformation on the rows of m
transforms m to m' so that the euclidean dist between the rows of m' equals
the chi squared dist between the rows of m.
Ref:
Legendre, P. and E. Gallagher. 2001. Ecologically meaningful
transformations for ordination of species data. Oecologia: 129: 271-280.
"""
m = asmatrix(m)
grand_sum, row_sums, col_sums = m.sum(), m.sum(1), m.sum(0)
result = m * sqrt(grand_sum)
result /= row_sums
result /= sqrt(col_sums)
return result
def trans_specprof(m):
"""perform a species profile distance transformation on the rows of m
transforms m to m' so that the euclidean dist between the rows of m' equals
the species profile dist between the rows of m.
Ref:
Legendre, P. and E. Gallagher. 2001. Ecologically meaningful
transformations for ordination of species data. Oecologia: 129: 271-280.
"""
m = asmatrix(m)
row_sums = sum(m, axis=1)
result = m / row_sums
return result
def trans_hellinger(m):
"""perform a hellinger distance transformation on the rows of m
transforms m to m' so that the euclidean dist between the rows of m' equals
the hellinger dist between the rows of m.
Ref:
Legendre, P. and E. Gallagher. 2001. Ecologically meaningful
transformations for ordination of species data. Oecologia: 129: 271-280.
"""
m = asmatrix(m)
row_sums = sum(m, axis=1)
result = sqrt(m / row_sums)
return result
def dist_bray_curtis(datamtx, strict=True):
""" returns bray curtis distance (normalized manhattan distance) btw rows
dist(a,b) = manhattan distance / sum on i( (a_i + b_i) )
see for example:
Faith et al. 1987
Compositional dissimilarity as a robust measure of ecological distance
Vegitatio
* comparisons are between rows (samples)
* input: 2D numpy array. Limited support for non-2D arrays if
strict==False
* output: numpy 2D array float ('d') type. shape (inputrows, inputrows)
for sane input data
* two rows of all zeros returns 0 distance between them
* if strict==True, raises ValueError if any of the input data is negative,
not finite, or if the input data is not a rank 2 array (a matrix).
* if strict==False, assumes input data is a matrix with nonnegative
entries. If rank of input data is < 2, returns an empty 2d array (shape:
(0, 0) ). If 0 rows or 0 colunms, also returns an empty 2d array.
"""
if strict:
if not all(isfinite(datamtx)):
raise ValueError("non finite number in input matrix")
if any(datamtx<0.0):
raise ValueError("negative value in input matrix")
if rank(datamtx) != 2:
raise ValueError("input matrix not 2D")
numrows, numcols = shape(datamtx)
else:
try:
numrows, numcols = shape(datamtx)
except ValueError:
return zeros((0,0),'d')
if numrows == 0 or numcols == 0:
return zeros((0,0),'d')
dists = zeros((numrows,numrows),'d')
for i in range(numrows):
r1 = datamtx[i,:]
for j in range(i):
r2 = datamtx[j,:]
abs_v = float(sum(abs(r1 - r2)))
v = sum(r1 + r2)
cur_d = 0.0
if v > 0:
cur_d = abs_v/v
dists[i][j] = dists[j][i] = cur_d
return dists
def dist_canberra(datamtx, strict=True):
"""returns a row-row canberra dist matrix
see for example:
Faith et al. 1987
Compositional dissimilarity as a robust measure of ecological distance
Vegitatio
* comparisons are between rows (samples)
* input: 2D numpy array. Limited support for non-2D arrays if
strict==False
* output: numpy 2D array float ('d') type. shape (inputrows, inputrows)
for sane input data
* two rows of all zeros returns 0 distance between them
* if strict==True, raises ValueError if any of the input data is negative,
not finite, or if the input data is not a rank 2 array (a matrix).
* if strict==False, assumes input data is a matrix with nonnegative
entries. If rank of input data is < 2, returns an empty 2d array (shape:
(0, 0) ). If 0 rows or 0 colunms, also returns an empty 2d array.
* chisq dist normalizes by column sums - empty columns (all zeros) are
ignored here
"""
if strict:
if not all(isfinite(datamtx)):
raise ValueError("non finite number in input matrix")
if any(datamtx<0.0):
raise ValueError("negative value in input matrix")
if rank(datamtx) != 2:
raise ValueError("input matrix not 2D")
numrows, numcols = shape(datamtx)
else:
try:
numrows, numcols = shape(datamtx)
except ValueError:
return zeros((0,0),'d')
oldstate = seterr(divide='ignore')
if numrows == 0 or numcols == 0:
return zeros((0,0),'d')
dists = zeros((numrows,numrows),'d')
for i in range(numrows):
r1 = datamtx[i]
for j in range(i):
r2 = datamtx[j]
dist = 0.0
net = abs( r1 - r2 ) / (r1 + r2)
net = nan_to_num(net)
num_nonzeros = nonzero(net)[0].size
dists[i,j] = dists[j,i] = nan_to_num(net.sum()/num_nonzeros)
seterr(**oldstate)
return dists
def dist_chisq(datamtx, strict=True):
"""returns a row-row chisq dist matrix
see for example:
Faith et al. 1987
Compositional dissimilarity as a robust measure of ecological distance
Vegitatio
* comparisons are between rows (samples)
* input: 2D numpy array. Limited support for non-2D arrays if
strict==False
* output: numpy 2D array float ('d') type. shape (inputrows, inputrows)
for sane input data
* two rows of all zeros returns 0 distance between them
* an all zero row compared with a not all zero row returns a distance of 1
* if strict==True, raises ValueError if any of the input data is negative,
not finite, or if the input data is not a rank 2 array (a matrix).
* if strict==False, assumes input data is a matrix with nonnegative
entries. If rank of input data is < 2, returns an empty 2d array (shape:
(0, 0) ). If 0 rows or 0 colunms, also returns an empty 2d array.
* chisq dist normalizes by column sums - empty columns (all zeros) are
ignored here
"""
if strict:
if not all(isfinite(datamtx)):
raise ValueError("non finite number in input matrix")
if any(datamtx<0.0):
raise ValueError("negative value in input matrix")
if rank(datamtx) != 2:
raise ValueError("input matrix not 2D")
numrows, numcols = shape(datamtx)
else:
try:
numrows, numcols = shape(datamtx)
except ValueError:
return zeros((0,0),'d')
if numrows == 0 or numcols == 0:
return zeros((0,0),'d')
dists = zeros((numrows,numrows),'d')
sqrt_grand_sum = sqrt(sum(datamtx))
rowsums, colsums = sum(datamtx, axis=1), sum(datamtx, axis=0)
if not colsums.all():
for i in range(len(colsums)):
if colsums[i] == 0.0:
colsums[i] = 1.0
for i in range(numrows):
r1 = datamtx[i]
r1sum = rowsums[i]
for j in range(i):
r2 = datamtx[j]
r2sum = rowsums[j]
if r1sum == 0.0 or r2sum == 0.0:
if r1sum == 0.0 and r2sum == 0.0:
dist = 0.0
else: dist = 1.0
else:
dist = sqrt_grand_sum *\
sqrt(sum( multiply((1./colsums) ,
square(r1/r1sum - r2/r2sum)) ))
dists[i,j] = dists[j,i] = dist
return dists
def dist_chord(datamtx, strict=True):
"""returns a row-row chord dist matrix
attributed to Orloci (with accent). see Legendre 2001,
ecologically meaningful...
* comparisons are between rows (samples)
* input: 2D numpy array. Limited support for non-2D arrays if
strict==False
* output: numpy 2D array float ('d') type. shape (inputrows, inputrows)
for sane input data
* two rows of all zeros returns 0 distance between them
* an all zero row compared with a not all zero row returns a distance of 1
* if strict==True, raises ValueError if any of the input data is
not finite, or if the input data is not a rank 2 array (a matrix).
* if strict==False, assumes input data is a 2d matrix.
If rank of input data is < 2, returns an empty 2d array (shape:
(0, 0) ). If 0 rows or 0 colunms, also returns an empty 2d array.
"""
if strict:
if not all(isfinite(datamtx)):
raise ValueError("non finite number in input matrix")
if rank(datamtx) != 2:
raise ValueError("input matrix not 2D")
numrows, numcols = shape(datamtx)
else:
try:
numrows, numcols = shape(datamtx)
except ValueError:
return zeros((0,0),'d')
if numrows == 0 or numcols == 0:
return zeros((0,0),'d')
dists = zeros((numrows,numrows),'d')
for i in range(numrows):
r1 = datamtx[i] # cache here
r1norm = norm(r1)
for j in range(i):
r2 = datamtx[j]
r2norm = norm(r2)
if r1norm == 0.0 or r2norm == 0.0:
if r1norm == 0.0 and r2norm == 0.0:
dist = 0.0
else: dist = 1.0
else:
dist = norm(r1/r1norm - r2/r2norm)
dists[i,j] = dists[j,i] = dist
return dists
def dist_euclidean(datamtx, strict=True):
"""returns a row by row euclidean dist matrix
returns the euclidean norm of row1 - row2 for all rows in datamtx
* comparisons are between rows (samples)
* input: 2D numpy array. Limited support for non-2D arrays if
strict==False
* output: numpy 2D array float ('d') type. shape (inputrows, inputrows)
for sane input data
* if strict==True, raises ValueError if any of the input data is
not finite, or if the input data is not a rank 2 array (a matrix).
* if strict==False, assumes input data is a 2d matrix.
If rank of input data is < 2, returns an empty 2d array (shape:
(0, 0) ). If 0 rows or 0 colunms, also returns an empty 2d array.
"""
if strict:
if not all(isfinite(datamtx)):
raise ValueError("non finite number in input matrix")
if rank(datamtx) != 2:
raise ValueError("input matrix not 2D")
numrows, numcols = shape(datamtx)
else:
try:
numrows, numcols = shape(datamtx)
except ValueError:
return zeros((0,0),'d')
if numrows == 0 or numcols == 0:
return zeros((0,0),'d')
dists = zeros((numrows,numrows),'d')
for r in range(numrows):
for c in range(r):
dist = norm(datamtx[r] - datamtx[c])
dists[r,c] = dists[c,r] = dist
return dists
def dist_gower(datamtx, strict=True):
"""returns a row-row gower dist matrix
see for example, Faith et al., 1987
* note that the comparison between any two rows is dependent on the entire
data matrix, d_ij is a fn of all of datamtx, not just i,j
* comparisons are between rows (samples)
* any column containing identical data for all rows is ignored (this
prevents a 0/0 error in the formula for gower distance
* input: 2D numpy array. Limited support for non-2D arrays if
strict==False
* output: numpy 2D array float ('d') type. shape (inputrows, inputrows)
for sane input data
* two rows of all zeros returns 0 distance between them
* if strict==True, raises ValueError if any of the input data is
not finite, or if the input data is not a rank 2 array (a matrix).
* if strict==False, assumes input data is a 2d matrix.
If rank of input data is < 2, returns an empty 2d array (shape:
(0, 0) ). If 0 rows or 0 colunms, also returns an empty 2d array.
"""
if strict:
if not all(isfinite(datamtx)):
raise ValueError("non finite number in input matrix")
if rank(datamtx) != 2:
raise ValueError("input matrix not 2D")
numrows, numcols = shape(datamtx)
else:
try:
numrows, numcols = shape(datamtx)
except ValueError:
return zeros((0,0),'d')
if numrows == 0 or numcols == 0:
return zeros((0,0),'d')
dists = zeros((numrows,numrows),'d')
coldiffs = datamtx.max(axis=0) - datamtx.min(axis=0)
for i in range(numcols):
if coldiffs[i] == 0.0:
coldiffs[i] = 1.0 # numerator will be zero anyway
for i in range(numrows):
r1 = datamtx[i]
for j in range(i):
r2 = datamtx[j]
rowdiff = r2 - r1
dist = sum(abs(r1 - r2) / coldiffs)
dists[i,j] = dists[j,i] = dist
return dists
def dist_hellinger(datamtx, strict=True):
"""returns a row-row hellinger dist matrix
* comparisons are between rows (samples)
* input: 2D numpy array. Limited support for non-2D arrays if
strict==False
* output: numpy 2D array float ('d') type. shape (inputrows, inputrows)
for sane input data
* two rows of all zeros returns 0 distance between them
* an all zero row compared with a not all zero row returns a distance of 1
* if strict==True, raises ValueError if any of the input data is negative,
not finite, or if the input data is not a rank 2 array (a matrix).
* if strict==False, assumes input data is a matrix with nonnegative
entries. If rank of input data is < 2, returns an empty 2d array (shape:
(0, 0) ). If 0 rows or 0 colunms, also returns an empty 2d array.
"""
if strict:
if not all(isfinite(datamtx)):
raise ValueError("non finite number in input matrix")
if any(datamtx<0.0):
raise ValueError("negative value in input matrix")
if rank(datamtx) != 2:
raise ValueError("input matrix not 2D")
numrows, numcols = shape(datamtx)
else:
try:
numrows, numcols = shape(datamtx)
except ValueError:
return zeros((0,0),'d')
if numrows == 0 or numcols == 0:
return zeros((0,0),'d')
dists = zeros((numrows,numrows),'d')
for i in range(numrows):
r1 = datamtx[i]
r1sum = sum(r1)
for j in range(i):
r2 = datamtx[j]
r2sum = sum(r2)
if r1sum == 0.0 or r2sum == 0.0:
if r1sum == 0.0 and r2sum == 0.0:
dist = 0.0
else: dist = 1.0
else:
dist = norm(sqrt(r1/r1sum) - sqrt(r2/r2sum))
dists[i,j] = dists[j,i] = dist
return dists
def dist_kulczynski(datamtx, strict=True):
""" calculates the kulczynski distances between rows of a matrix
see for example Faith et al., composiitonal dissimilarity, 1987
returns a distance of 1 between a row of zeros and a row with at least one
nonzero element
* comparisons are between rows (samples)
* input: 2D numpy array. Limited support for non-2D arrays if
strict==False
* output: numpy 2D array float ('d') type. shape (inputrows, inputrows)
for sane input data
* two rows of all zeros returns 0 distance between them
* an all zero row compared with a not all zero row returns a distance of 1
* if strict==True, raises ValueError if any of the input data is negative,
not finite, or if the input data is not a rank 2 array (a matrix).
* if strict==False, assumes input data is a matrix with nonnegative
entries. If rank of input data is < 2, returns an empty 2d array (shape:
(0, 0) ). If 0 rows or 0 colunms, also returns an empty 2d array.
"""
if strict:
if not all(isfinite(datamtx)):
raise ValueError("non finite number in input matrix")
if any(datamtx<0.0):
raise ValueError("negative value in input matrix")
if rank(datamtx) != 2:
raise ValueError("input matrix not 2D")
numrows, numcols = shape(datamtx)
else:
try:
numrows, numcols = shape(datamtx)
except ValueError:
return zeros((0,0),'d')
if numrows == 0 or numcols == 0:
return zeros((0,0),'d')
dists = zeros((numrows,numrows),'d')
rowsums = datamtx.sum(axis=1)
# rowsum: the sum of elements in a row
# cache to avoid recalculating for each pair
for i in range(numrows):
irowsum = rowsums[i]
r1 = datamtx[i]
for j in range(i):
r2 = datamtx[j]
jrowsum = rowsums[j]
rowminsum = float(sum(where(r1<r2, r1,r2)))
if (irowsum == 0.0 and jrowsum == 0.0):
cur_d = 0.0 # => two rows of zeros
elif (irowsum == 0.0 or jrowsum == 0.0):
cur_d = 1.0 # one row zeros, one not all zeros
else:
cur_d = 1.0 - (((rowminsum/irowsum) + (rowminsum/jrowsum))/2.0)
dists[i][j] = dists[j][i] = cur_d
return dists
def dist_manhattan(datamtx, strict=True):
""" returns manhattan (city block) distance between rows
dist(a,b) = sum on i( abs(a_i - b_i) )
negative values ok (but not tested)
* comparisons are between rows (samples)
* input: 2D numpy array. Limited support for non-2D arrays if
strict==False
* output: numpy 2D array float ('d') type. shape (inputrows, inputrows)
for sane input data
* if strict==True, raises ValueError if any of the input data is
not finite, or if the input data is not a rank 2 array (a matrix).
* if strict==False, assumes input data is a 2d matrix.
If rank of input data is < 2, returns an empty 2d array (shape:
(0, 0) ). If 0 rows or 0 colunms, also returns an empty 2d array.
"""
if strict:
if not all(isfinite(datamtx)):
raise ValueError("non finite number in input matrix")
if rank(datamtx) != 2:
raise ValueError("input matrix not 2D")
numrows, numcols = shape(datamtx)
else:
try:
numrows, numcols = shape(datamtx)
except ValueError:
return zeros((0,0),'d')
if numrows == 0 or numcols == 0:
return zeros((0,0),'d')
dists = zeros((numrows,numrows),'d')
for i in range(numrows):
r1 = datamtx[i] # cache here
for j in range(i):
dists[i,j] = dists[j,i] = sum(abs(r1 - datamtx[j]))
return dists
def dist_morisita_horn(datamtx, strict=True):
""" returns morisita-horn distance between rows
dist(a,b) = 1 - 2*sum(a_i * b_i) /( (d_a + d_b)* N_a * N_b )
see book: magurran 2004 pg 246
* comparisons are between rows (samples)
* input: 2D numpy array. Limited support for non-2D arrays if
strict==False
* output: numpy 2D array float ('d') type. shape (inputrows, inputrows)
for sane input data
* two rows of all zeros returns 0 distance between them
* an all zero row compared with a not all zero row returns a distance of 1
* if strict==True, raises ValueError if any of the input data is negative,
not finite, or if the input data is not a rank 2 array (a matrix).
* if strict==False, assumes input data is a matrix with nonnegative
entries. If rank of input data is < 2, returns an empty 2d array (shape:
(0, 0) ). If 0 rows or 0 colunms, also returns an empty 2d array.
"""
if strict:
if not all(isfinite(datamtx)):
raise ValueError("non finite number in input matrix")
if any(datamtx<0.0):
raise ValueError("negative value in input matrix")
if rank(datamtx) != 2:
raise ValueError("input matrix not 2D")
numrows, numcols = shape(datamtx)
else:
try:
numrows, numcols = shape(datamtx)
except ValueError:
return zeros((0,0),'d')
if numrows == 0 or numcols == 0:
return zeros((0,0),'d')
dists = zeros((numrows,numrows),'d')
rowsums = datamtx.sum(axis=1, dtype='float')
row_ds = (datamtx**2).sum(axis=1, dtype='float') # these are d_a, etc
for i in range(numrows):
if row_ds[i] !=0.:
row_ds[i] = row_ds[i] / rowsums[i]**2
# this leaves row_ds zero if actually 0/0
for i in range(numrows):
row1 = datamtx[i]
N1 = rowsums[i]
d1 = row_ds[i]
for j in range(i):
row2 = datamtx[j]
N2 = rowsums[j]
d2 = row_ds[j]
if N2 == 0.0 and N1==0.0:
dist = 0.0
elif N2 == 0.0 or N1==0.0:
dist = 1.0
else:
# d's zero only if N's zero, and we already checked for that
similarity = 2*sum(row1*row2)
similarity = similarity / ( (d1 + d2) * N1 * N2 )
dist = 1 - similarity
dists[i][j] = dists[j][i] = dist
return dists
def dist_pearson(datamtx, strict=True):
""" Calculates pearson distance (1-r) between rows
note that the literature sometimer refers to the pearson dissimilarity
as (1 - r)/2 (e.g.: BC Blaxall et al. 2003: Differential Myocardial Gene
Expression in the Development and Rescue of Murine Heart Failure)
for pearson's r, see for example: Thirteen Ways to Look at the
Correlation Coefficient by J rodgers, 1988
* distance varies between 0-2, inclusive.
* Flat rows (all elements itentical) will return a distance of 1 relative
to any non-flat row, and a distance of zero to another flat row
* comparisons are between rows (samples)
* input: 2D numpy array. Limited support for non-2D arrays if
strict==False
* output: numpy 2D array float ('d') type. shape (inputrows, inputrows)
for sane input data
* two rows of all zeros returns 0 distance between them
* an all zero row compared with a not all zero row returns a distance of 1
* if strict==True, raises ValueError if any of the input data is
not finite, or if the input data is not a rank 2 array (a matrix).
* if strict==False, assumes input data is a 2d matrix
If rank of input data is < 2, returns an empty 2d array (shape:
(0, 0) ). If 0 rows or 0 colunms, also returns an empty 2d array.
"""
if strict:
if not all(isfinite(datamtx)):
raise ValueError("non finite number in input matrix")
if rank(datamtx) != 2:
raise ValueError("input matrix not 2D")
numrows, numcols = shape(datamtx)
else:
try:
numrows, numcols = shape(datamtx)
except ValueError:
return zeros((0,0),'d')
if numrows == 0 or numcols == 0:
return zeros((0,0),'d')
rowmeans = mean(datamtx, axis=1)
rowstds = std(datamtx, axis=1)
dists = zeros((numrows,numrows),'d')
n = float(numrows)
for i in range(numrows):
r1 = datamtx[i,:]
r1m = rowmeans[i]
r1dev = r1 - r1m
for j in range(i):
r2 = datamtx[j,:]
r2m = rowmeans[j]
r2dev = r2 - r2m
top = sum(r1dev*r2dev)
sum1 = sum(r1dev**2)
sum2 = sum(r2dev**2)
if (sum1 == 0.0 and sum2 == 0.0):
r = 1.0
elif (sum1 == 0.0 or sum2 == 0.0):
r = 0.0
else:
bottom = sqrt(sum1 * sum2)
r = top/bottom
dists[i][j] = dists[j][i] = 1.0 - r
return dists
def dist_soergel(datamtx, strict=True):
""" Calculate soergel distance between rows of a matrix
see for example Evaluation of Distance Metrics..., Fechner 2004
dist(a,b) = sum on i( abs(a_i - b_i) ) / sum on i( max(a_i, b_i) )
returns: a symmetric distance matrix, numrows X numrows
* comparisons are between rows (samples)
* input: 2D numpy array. Limited support for non-2D arrays if
strict==False
* output: numpy 2D array float ('d') type. shape (inputrows, inputrows)
for sane input data
* two rows of all zeros returns 0 distance between them
* if strict==True, raises ValueError if any of the input data is negative,
not finite, or if the input data is not a rank 2 array (a matrix).
* if strict==False, assumes input data is a matrix with nonnegative
entries. If rank of input data is < 2, returns an empty 2d array (shape:
(0, 0) ). If 0 rows or 0 colunms, also returns an empty 2d array.
"""
if strict:
if not all(isfinite(datamtx)):
raise ValueError("non finite number in input matrix")
if any(datamtx<0.0):
raise ValueError("negative value in input matrix")
if rank(datamtx) != 2:
raise ValueError("input matrix not 2D")
numrows, numcols = shape(datamtx)
else:
try:
numrows, numcols = shape(datamtx)
except ValueError:
return zeros((0,0),'d')
if numrows == 0 or numcols == 0:
return zeros((0,0),'d')
dists = zeros((numrows,numrows),'d')
for i in range(numrows):
r1 = datamtx[i,:]
for j in range(i):
r2 = datamtx[j,:]
top = float(sum(abs(r1 - r2)))
bot = float(sum(where(r1>r2, r1,r2)))
if bot <= 0.0:
cur_d = 0.0
else:
cur_d = top/bot
dists[i][j] = dists[j][i] = cur_d
return dists
def dist_spearman_approx(datamtx, strict=True):
""" Calculate spearman rank distance (1-r) using an approximation formula
considers only rank order of elements in a row, averaging ties
[19.2, 2.1, 0.03, 2.1] -> [3, 1.5, 0, 1.5]
then performs dist(a,b) = 6 * sum(D^2) / (N*(N^2 - 1))
where D is difference in rank of element i between row a and row b,
N is the length of either row
* formula fails for < 2 columns, returns a zeros matrix
* comparisons are between rows (samples)
* input: 2D numpy array. Limited support for non-2D arrays if
strict==False
* output: numpy 2D array float ('d') type. shape (inputrows, inputrows)
for sane input data
* if strict==True, raises ValueError if any of the input data is
not finite, or if the input data is not a rank 2 array (a matrix), or if
there are less than 2 colunms
* if strict==False, assumes input data is a 2d matrix.
If rank of input data is < 2, returns an empty 2d array (shape:
(0, 0) ). If 0 rows or 0 colunms, also returns an empty 2d array.
"""
if strict:
if not all(isfinite(datamtx)):
raise ValueError("non finite number in input matrix")
if rank(datamtx) != 2:
raise ValueError("input matrix not 2D")
numrows, numcols = shape(datamtx)
if numcols < 2:
raise ValueError("input matrix has < 2 colunms")
else:
try:
numrows, numcols = shape(datamtx)
except ValueError:
return zeros((0,0),'d')
if numrows == 0 or numcols == 0:
return zeros((0,0),'d')
dists = zeros((numrows,numrows),'d')
if numcols < 2:
return dists # formula fails for < 2 elements per row
for i in range(numrows):
r1 = datamtx[i,:]
rank1 = _rankdata(r1)
for j in range(i):
r2 = datamtx[j,:]
rank2 = _rankdata(r2)
rankdiff = rank1 - rank2
dsqsum = sum((rankdiff)**2)
dist = 6*dsqsum / float(numcols*(numcols**2-1))
dists[i][j] = dists[j][i] = dist
return dists
def dist_specprof(datamtx, strict=True):
"""returns a row-row species profile distance matrix
* comparisons are between rows (samples)
* input: 2D numpy array. Limited support for non-2D arrays if
strict==False
* output: numpy 2D array float ('d') type. shape (inputrows, inputrows)
for sane input data
* two rows of all zeros returns 0 distance between them
* an all zero row compared with a not all zero row returns a distance of 1
* if strict==True, raises ValueError if any of the input data is negative,
not finite, or if the input data is not a rank 2 array (a matrix).
* if strict==False, assumes input data is a matrix with nonnegative
entries. If rank of input data is < 2, returns an empty 2d array (shape:
(0, 0) ). If 0 rows or 0 colunms, also returns an empty 2d array.
"""
if strict:
if not all(isfinite(datamtx)):
raise ValueError("non finite number in input matrix")
if any(datamtx<0.0):
raise ValueError("negative value in input matrix")
if rank(datamtx) != 2:
raise ValueError("input matrix not 2D")
numrows, numcols = shape(datamtx)
else:
try:
numrows, numcols = shape(datamtx)
except ValueError:
return zeros((0,0),'d')
if numrows == 0 or numcols == 0:
return zeros((0,0),'d')
dists = zeros((numrows,numrows),'d')
for i in range(numrows):
r1 = datamtx[i]
r1sum = sum(r1)
for j in range(i):
r2 = datamtx[j]
r2sum = sum(r2)
if r1sum == 0.0 or r2sum == 0.0:
if r1sum == 0.0 and r2sum == 0.0:
dist = 0.0
else: dist = 1.0
else:
dist = norm((r1/r1sum) - (r2/r2sum))
dists[i,j] = dists[j,i] = dist
return dists
def binary_dist_chisq(datamtx, strict=True):
"""Calculates binary chi-square dist between rows, returns dist matrix.
converts input array to bool, then uses dist_chisq
"""
datamtx = datamtx.astype(bool)
datamtx = datamtx.astype(float)
return dist_chisq(datamtx, strict=True)
def binary_dist_chord(datamtx, strict=True):
"""Calculates binary chord dist between rows, returns dist matrix.
converts input array to bool, then uses dist_chisq
for binary data, this is identical to a binary hellinger distance
"""
datamtx = datamtx.astype(bool)
datamtx = datamtx.astype(float)
return dist_chord(datamtx, strict=True)
def binary_dist_sorensen_dice(datamtx, strict=True):
"""Calculates Sorensen-Dice distance btw rows, returning distance matrix.
Note: Treats array as bool. This distance = 1 - dice's coincidence index
see Measures of the Amount of Ecologic Association Between Species
Author(s): Lee R. Dice, 1945
The 'o' in sorensen should be a non-ascii char, but isn't here for ease
of use
this is identical to a binary bray-curtis distance, as well as the
binary whittaker distance metric.
a = num 1's in a
b = num 1's in b
c = num that are 1's in both a and b
Dice dist = 1 - (2*c)/(a + b).
also known as whittaker:
whittaker = (a + b - c)/( 0.5*(a+b) ) - 1
* comparisons are between rows (samples)
* input: 2D numpy array. Limited support for non-2D arrays if
strict==False
* output: numpy 2D array float ('d') type. shape (inputrows, inputrows)
for sane input data
* two rows of all zeros returns 0 distance between them
* negative input values are not allowed - will return nonsensical results
and/or throw errors
"""
datamtx = datamtx.astype(bool)
datamtx = datamtx.astype(float)
if strict:
if not all(isfinite(datamtx)):
raise ValueError("non finite number in input matrix")
if any(datamtx<0.0):
raise ValueError("negative value in input matrix")
if rank(datamtx) != 2:
raise ValueError("input matrix not 2D")
numrows, numcols = shape(datamtx)
else:
try:
numrows, numcols = shape(datamtx)
except ValueError:
return zeros((0,0),'d')
if numrows == 0 or numcols == 0:
return zeros((0,0),'d')
dists = zeros((numrows,numrows),'d')
rowsums = datamtx.sum(axis=1)
for i in range(numrows):
row1 = datamtx[i]
for j in range(i):
row2 = datamtx[j]
bottom = float(rowsums[i] + rowsums[j])
cur_d = 0.0
if bottom:
cur_d = 1-(2*logical_and(row1,row2).sum()/bottom)
dists[i][j] = dists[j][i] = cur_d
return dists
def binary_dist_euclidean(datamtx, strict=True):
"""Calculates binary euclidean distance between rows, returns dist matrix.
converts input array to bool, then uses dist_euclidean
"""
datamtx = datamtx.astype(bool)
datamtx = datamtx.astype(float)
return dist_euclidean(datamtx, strict=True)
def binary_dist_hamming(datamtx, strict=True):
"""Calculates hamming distance btw rows, returning distance matrix.
Note: Treats array as bool.
see for example wikipedia hamming_distance, 20 jan 2008
hamming is identical to binary manhattan distance
Binary hamming:
a = num 1's in a
b = num 1's in b
c = num that are 1's in both a and b
hamm = a + b - 2c
* comparisons are between rows (samples)
* input: 2D numpy array. Limited support for non-2D arrays if
strict==False
* output: numpy 2D array float ('d') type. shape (inputrows, inputrows)
for sane input data
* two rows of all zeros returns 0 distance between them
* if strict==True, raises ValueError if any of the input data is negative,
not finite, or if the input data is not a rank 2 array (a matrix).
* if strict==False, assumes input data is a matrix with nonnegative
entries. If rank of input data is < 2, returns an empty 2d array (shape:
(0, 0) ). If 0 rows or 0 colunms, also returns an empty 2d array.
"""
datamtx = datamtx.astype(bool)
datamtx = datamtx.astype(float)
if strict:
if not all(isfinite(datamtx)):
raise ValueError("non finite number in input matrix")
if any(datamtx<0.0):
raise ValueError("negative value in input matrix")
if rank(datamtx) != 2:
raise ValueError("input matrix not 2D")
numrows, numcols = shape(datamtx)
else:
try:
numrows, numcols = shape(datamtx)
except ValueError:
return zeros((0,0),'d')
if numrows == 0 or numcols == 0:
return zeros((0,0),'d')
dists = zeros((numrows,numrows),'d')
rowsums = datamtx.sum(axis=1)
for i in range(numrows):
first = datamtx[i]
a = rowsums[i]
for j in range(i):
second = datamtx[j]
b = rowsums[j]
c = float(logical_and(first, second).sum())
dist = a + b - (2.0*c)
dists[i][j] = dists[j][i] = dist
return dists
def binary_dist_jaccard(datamtx, strict=True):
"""Calculates jaccard distance between rows, returns distance matrix.
converts matrix to boolean. jaccard dist = 1 - jaccard index
see for example: wikipedia jaccard index (20 jan 2009)
this is identical to a binary version of the soergel distance
Binary jaccard:
a = num 1's in a
b = num 1's in b
c = num that are 1's in both a and b
jaccard = 1 - (c/(a+b-c))
* comparisons are between rows (samples)
* input: 2D numpy array. Limited support for non-2D arrays if
strict==False
* output: numpy 2D array float ('d') type. shape (inputrows, inputrows)
for sane input data
* two rows of all zeros returns 0 distance between them
* if strict==True, raises ValueError if any of the input data is negative,
not finite, or if the input data is not a rank 2 array (a matrix).
* if strict==False, assumes input data is a matrix with nonnegative
entries. If rank of input data is < 2, returns an empty 2d array (shape:
(0, 0) ). If 0 rows or 0 colunms, also returns an empty 2d array.
"""
datamtx = datamtx.astype(bool)
datamtx = datamtx.astype(float)
if strict:
if not all(isfinite(datamtx)):
raise ValueError("non finite number in input matrix")
if any(datamtx<0.0):
raise ValueError("negative value in input matrix")
if rank(datamtx) != 2:
raise ValueError("input matrix not 2D")
numrows, numcols = shape(datamtx)
else:
try:
numrows, numcols = shape(datamtx)
except ValueError:
return zeros((0,0),'d')
if numrows == 0 or numcols == 0:
return zeros((0,0),'d')
dists = zeros((numrows,numrows),'d')
rowsums = datamtx.sum(axis=1)
for i in range(numrows):
first = datamtx[i]
a = rowsums[i]
for j in range(i):
second = datamtx[j]
b = rowsums[j]
c = float(logical_and(first, second).sum())
if a==0.0 and b==0.0:
dist = 0.0
else:
dist = 1.0 - (c/(a+b-c))
dists[i][j] = dists[j][i] = dist
return dists
def binary_dist_lennon(datamtx, strict=True):
"""Calculates lennon distance between rows, returns distance matrix.
converts matrix to boolean. jaccard dist = 1 - lennon similarity
lennon's similarity is a modification of simpson's index
see Jack J. Lennon, The geographical structure of British bird
distributions: diversity, spatial turnover and scale
Binary lennon:
a = num 1's in a
b = num 1's in b
c = num that are 1's in both a and b
lennon = 1 - (c/(c + min(a-c,b-c)))
* comparisons are between rows (samples)
* input: 2D numpy array. Limited support for non-2D arrays if
strict==False
* output: numpy 2D array float ('d') type. shape (inputrows, inputrows)
for sane input data
* two rows of all zeros returns 0 distance between them
* if strict==True, raises ValueError if any of the input data is negative,
not finite, or if the input data is not a rank 2 array (a matrix).
* if strict==False, assumes input data is a matrix with nonnegative
entries. If rank of input data is < 2, returns an empty 2d array (shape:
(0, 0) ). If 0 rows or 0 colunms, also returns an empty 2d array.
"""
datamtx = datamtx.astype(bool)
datamtx = datamtx.astype(float)
if strict:
if not all(isfinite(datamtx)):
raise ValueError("non finite number in input matrix")
if any(datamtx<0.0):
raise ValueError("negative value in input matrix")
if rank(datamtx) != 2:
raise ValueError("input matrix not 2D")
numrows, numcols = shape(datamtx)
else:
try:
numrows, numcols = shape(datamtx)
except ValueError:
return zeros((0,0),'d')
if numrows == 0 or numcols == 0:
return zeros((0,0),'d')
dists = zeros((numrows,numrows),'d')
rowsums = datamtx.sum(axis=1)
for i in range(numrows):
first = datamtx[i]
a = rowsums[i]
for j in range(i):
second = datamtx[j]
b = rowsums[j]
c = float(logical_and(first, second).sum())
if a==0.0 and b==0.0:
dist = 0.0
elif c==0.0:
dist = 1.0
else:
dist = 1.0 - (c/(c + min([a-c,b-c])))
dists[i][j] = dists[j][i] = dist
return dists
def binary_dist_ochiai(datamtx, strict=True):
"""Calculates ochiai distance btw rows, returning distance matrix.
Note: Treats array as bool.
see for example:
On the Mathematical Significance of the Similarity Index of Ochiai...
Bolton, 1991
a = num 1's in a
b = num 1's in b
c = num that are 1's in both a and b
ochiai = 1 - (c/sqrt(a*b))
* comparisons are between rows (samples)
* input: 2D numpy array. Limited support for non-2D arrays if
strict==False
* output: numpy 2D array float ('d') type. shape (inputrows, inputrows)
for sane input data
* two rows of all zeros returns 0 distance between them
* an all zero row compared with a not all zero row returns a distance of 1
* if strict==True, raises ValueError if any of the input data is negative,
not finite, or if the input data is not a rank 2 array (a matrix).
* if strict==False, assumes input data is a matrix with nonnegative
entries. If rank of input data is < 2, returns an empty 2d array (shape:
(0, 0) ). If 0 rows or 0 colunms, also returns an empty 2d array.
"""
datamtx = datamtx.astype(bool)
datamtx = datamtx.astype(float)
if strict:
if not all(isfinite(datamtx)):
raise ValueError("non finite number in input matrix")
if any(datamtx<0.0):
raise ValueError("negative value in input matrix")
if rank(datamtx) != 2:
raise ValueError("input matrix not 2D")
numrows, numcols = shape(datamtx)
else:
try:
numrows, numcols = shape(datamtx)
except ValueError:
return zeros((0,0),'d')
if numrows == 0 or numcols == 0:
return zeros((0,0),'d')
dists = zeros((numrows,numrows),'d')
rowsums = datamtx.sum(axis=1)
for i in range(numrows):
first = datamtx[i]
a = rowsums[i]
for j in range(i):
second = datamtx[j]
b = rowsums[j]
c = float(logical_and(first, second).sum())
if a==0.0 and b==0.0:
dist = 0.0
elif a==0.0 or b==0.0:
dist = 1.0
else:
dist = 1.0 - (c/sqrt(a*b))
dists[i][j] = dists[j][i] = dist
return dists
def binary_dist_pearson(datamtx, strict=True):
"""Calculates binary pearson distance between rows, returns distance matrix
converts input array to bool, then uses dist_pearson
"""
datamtx = datamtx.astype(bool)
datamtx = datamtx.astype(float)
return dist_pearson(datamtx, strict=True)
if __name__ == "__main__":
""" just a test run"""
matrix1 = array( [ [10,8,4,1],
[8,6,2,1],
[0,0,0,0],
[0,0,1,0],
[1,1,0,1],
[1,0,8,10],
[0,0,0,0],
[8,6,2,1],
])
res = dist_euclidean(matrix1)
print "euclidean distance result: \n"
print res
|