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
|
\chapter{Cluster analysis}
Cluster analysis is the grouping of items into clusters based on the similarity of the items to each other. In bioinformatics, clustering is widely used in gene expression data analysis to find groups of genes with similar gene expression profiles. This may identify functionally related genes, as well as suggest the function of presently unknown genes.
The Biopython module \verb|Bio.Cluster| provides commonly used clustering algorithms and was designed with the application to gene expression data in mind. However, this module can also be used for cluster analysis of other types of data. \verb|Bio.Cluster| and the underlying C Clustering Library is described by De Hoon \textit{et al.} \cite{dehoon2004}.
The following four clustering approaches are implemented in \verb|Bio.Cluster|:
\begin{itemize}
\item
Hierarchical clustering (pairwise centroid-, single-, complete-, and average-linkage);
\item
$k$-means, $k$-medians, and $k$-medoids clustering;
\item
Self-Organizing Maps;
\item
Principal Component Analysis.
\end{itemize}
\subsection*{Data representation}
The data to be clustered are represented by a $n \times m$ Numerical Python array \verb|data|. Within the context of gene expression data clustering, typically the rows correspond to different genes whereas the columns correspond to different experimental conditions. The clustering algorithms in \verb|Bio.Cluster| can be applied both to rows (genes) and to columns (experiments).
\subsection*{Missing values}
Often in microarray experiments, some of the data values are missing, which is indicated by an additional $n \times m$ Numerical Python integer array \verb|mask|. If \verb|mask[i,j]==0|, then \verb|data[i,j]| is missing and is ignored in the analysis.
\subsection*{Random number generator}
The $k$-means/medians/medoids clustering algorithms and Self-Organizing Maps (SOMs) include the use of a random number generator. The uniform random number generator in \verb|Bio.Cluster| is based on the algorithm by L'Ecuyer \cite{lecuyer1988}, while random numbers following the binomial distribution are generated using the BTPE algorithm by Kachitvichyanukul and Schmeiser \cite{kachitvichyanukul1988}. The random number generator is initialized automatically during its first call. As this random number generator uses a combination of two multiplicative linear congruential generators, two (integer) seeds are needed for initialization, for which we use the system-supplied random number generator \verb|rand| (in the C standard library). We initialize this generator by calling \verb|srand| with the epoch time in seconds, and use the first two random numbers generated by \verb|rand| as seeds for the uniform random number generator in \verb|Bio.Cluster|.
\section{Distance functions}
\label{sec:distancefunctions}
In order to cluster items into groups based on their similarity, we should first define what exactly we mean by \emph{similar}. \verb|Bio.Cluster| provides eight distance functions, indicated by a single character, to measure similarity, or conversely, distance:
\begin{itemize}
\item \verb|'e'|:
Euclidean distance;
\item \verb|'b'|:
City-block distance.
\item \verb|'c'|:
Pearson correlation coefficient;
\item \verb|'a'|:
Absolute value of the Pearson correlation coefficient;
\item \verb|'u'|:
Uncentered Pearson correlation (equivalent to the cosine of the angle between two data vectors);
\item \verb|'x'|:
Absolute uncentered Pearson correlation;
\item \verb|'s'|:
Spearman's rank correlation;
\item \verb|'k'|:
Kendall's $\tau$.
\end{itemize}
The first two are true distance functions that satisfy the triangle inequality:
$$d\left(\underline{u},\underline{v}\right) \leq d\left(\underline{u},\underline{w}\right) + d\left(\underline{w},\underline{v}\right) \textrm{ for all } \underline{u}, \underline{v}, \underline{w},$$
and are therefore refered to as \emph{metrics}. In everyday language, this means that the shortest distance between two points is a straight line.
The remaining six distance measures are related to the correlation coefficient, where the distance $d$ is defined in terms of the correlation $r$ by $d=1-r$. Note that these distance functions are \emph{semi-metrics} that do not satisfy the triangle inequality. For example, for
$$\underline{u}=\left(1,0,-1\right);$$
$$\underline{v}=\left(1,1,0\right);$$
$$\underline{w}=\left(0,1,1\right);$$
we find a Pearson distance
$d\left(\underline{u},\underline{w}\right) = 1.8660$, while
$d\left(\underline{u},\underline{v}\right)+d\left(\underline{v},\underline{w}\right) = 1.6340$.
\subsection*{Euclidean distance}
In \verb|Bio.Cluster|, we define the Euclidean distance as
$$d = {1 \over n} \sum_{i=1}^{n} \left(x_i-y_i\right)^{2}.$$
Only those terms are included in the summation for which both
$x_i$ and $y_i$ are present, and the denominator $n$ is chosen accordingly.
As the expression data $x_i$ and $y_i$ are subtracted directly from each other, we should make sure that the expression data are properly normalized when using the Euclidean distance.
\subsection*{City-block distance}
The city-block distance, alternatively known as the Manhattan distance, is related to the Euclidean distance. Whereas the Euclidean distance corresponds to the length of the shortest path between two points, the city-block distance is the sum of distances along each dimension. As gene expression data tend to have missing values, in \verb|Bio.Cluster| we define the city-block distance as the sum of distances divided by the number of dimensions:
$$d = {1 \over n} \sum_{i=1}^n \left|x_i-y_i\right|.$$
This is equal to the distance you would have to walk between two points in a city, where you have to walk along city blocks. As for the Euclidean distance,
the expression data are subtracted directly from each other, and we should therefore make sure that they are properly normalized.
\subsection*{The Pearson correlation coefficient}
The Pearson correlation coefficient is defined as
$$r = \frac{1}{n} \sum_{i=1}^n \left( \frac{x_i -\bar{x}}{\sigma_x} \right) \left(\frac{y_i -\bar{y}}{\sigma_y} \right),$$
in which
$\bar{x}, \bar{y}$
are the sample mean of $x$ and $y$ respectively, and
$\sigma_x, \sigma_y$
are the sample standard deviation of $x$ and $y$.
The Pearson correlation coefficient is a measure for how well a straight line can be fitted to a scatterplot of $x$ and $y$.
If all the points in the scatterplot lie on a straight line, the Pearson correlation coefficient is either +1 or -1, depending on whether the slope of line is positive or negative. If the Pearson correlation coefficient is equal to zero, there is no correlation between $x$ and $y$.
The \emph{Pearson distance} is then defined as
$$d_{\textrm{P}} \equiv 1 - r.$$
As the Pearson correlation coefficient lies between -1 and 1, the Pearson distance lies between 0 and 2.
\subsection*{Absolute Pearson correlation}
By taking the absolute value of the Pearson correlation, we find a number between 0 and 1. If the absolute value is 1, all the points in the scatter plot lie on a straight line with either a positive or a negative slope. If the absolute value is equal to zero, there is no correlation between $x$ and $y$.
The corresponding distance is defined as
$$d_{\textrm A} \equiv 1 - \left|r\right|,$$
where $r$ is the Pearson correlation coefficient. As the absolute value of the Pearson correlation coefficient lies between 0 and 1, the corresponding distance lies between 0 and 1 as well.
In the context of gene expression experiments, the absolute correlation is equal to 1 if the gene expression profiles of two genes are either exactly the same or exactly opposite. The absolute correlation coefficient should therefore be used with care.
\subsection*{Uncentered correlation (cosine of the angle)}
In some cases, it may be preferable to use the \emph{uncentered correlation} instead of the regular Pearson correlation coefficient. The uncentered correlation is defined as
$$r_{\textrm U} = \frac{1}{n} \sum_{i=1}^{n} \left(\frac{x_i}{\sigma_x^{(0)}} \right) \left(\frac{y_i}{\sigma_y^{(0)}} \right),$$
where
\begin{eqnarray}
\sigma_x^{(0)} & = & \sqrt{{\frac{1}{n}} \sum_{i=1}^{n}x_i^2}; \nonumber \\
\sigma_y^{(0)} & = & \sqrt{{\frac{1}{n}} \sum_{i=1}^{n}y_i^2}. \nonumber
\end{eqnarray}
This is the same expression as for the regular Pearson correlation coefficient, except that the sample means
$\bar{x}, \bar{y}$
are set equal to zero. The uncentered correlation may be appropriate if there is a zero reference state. For instance, in the case of gene expression data given in terms of log-ratios, a log-ratio equal to zero corresponds to the green and red signal being equal, which means that the experimental manipulation did not affect the gene expression.
The distance corresponding to the uncentered correlation coefficient is defined as
$$d_{\mbox{U}} \equiv 1 - r_{\mbox{U}},$$
where
$r_{\mbox{U}}$
is the uncentered correlation.
As the uncentered correlation coefficient lies between -1 and 1, the corresponding distance lies between 0 and 2.
The uncentered correlation is equal to the cosine of the angle of the two data vectors in $n$-dimensional space, and is often referred to as such.
\subsection*{Absolute uncentered correlation}
As for the regular Pearson correlation, we can define a distance measure using the absolute value of the uncentered correlation:
$$d_{\mbox{AU}} \equiv 1 - \left|r_{\mbox{U}}\right|,$$
where
$r_{\mbox{U}}$
is the uncentered correlation coefficient. As the absolute value of the uncentered correlation coefficient lies between 0 and 1, the corresponding distance lies between 0 and 1 as well.
Geometrically, the absolute value of the uncentered correlation is equal to the cosine between the supporting lines of the two data vectors (i.e., the angle without taking the direction of the vectors into consideration).
\subsection*{Spearman rank correlation}
The Spearman rank correlation is an example of a non-parametric similarity measure, and tends to be more robust against outliers than the Pearson correlation.
To calculate the Spearman rank correlation, we replace each data value by their rank if we would order the data in each vector by their value. We then calculate the Pearson correlation between the two rank vectors instead of the data vectors.
As in the case of the Pearson correlation, we can define a distance measure corresponding to the Spearman rank correlation as
$$d_{\mbox{S}} \equiv 1 - r_{\mbox{S}},$$
where
$r_{\mbox{S}}$
is the Spearman rank correlation.
\subsection*{Kendall's $\tau$}
Kendall's $\tau$
is another example of a non-parametric similarity measure. It is similar to the Spearman rank correlation, but instead of the ranks themselves only the relative ranks are used to calculate $\tau$ (see Snedecor \& Cochran \cite{snedecor1989}).
We can define a distance measure corresponding to Kendall's $\tau$
as $$d_{\mbox{K}} \equiv 1 - \tau.$$
As Kendall's $\tau$ is always between -1 and 1, the corresponding distance will be between 0 and 2.
\subsection*{Weighting}
For most of the distance functions available in \verb|Bio.Cluster|, a weight vector can be applied. The weight vector contains weights for the items in the data vector. If the weight for item $i$ is $w_i$, then that item is treated as if it occurred $w_i$ times in the data. The weight do not have to be integers.
For the Spearman rank correlation and Kendall's
$\tau$,
weights do not have a well-defined meaning and are therefore not implemented.
\subsection*{Calculating the distance matrix}
\label{subsec:distancematrix}
The distance matrix is a square matrix with all pairwise distances between the items in \verb|data|, and can be calculated by the function \verb|distancematrix| in the \verb|Bio.Cluster| module:
\begin{verbatim}
>>> from Bio.Cluster import distancematrix
>>> matrix = distancematrix(data)
\end{verbatim}
where the following arguments are defined:
\begin{itemize}
\item \verb|data| (required)\\
Array containing the data for the items.
\item \verb|mask| (default: \verb|None|) \\
Array of integers showing which data are missing. If \verb|mask[i,j]==0|, then \verb|data[i,j]| is missing. If \verb|mask==None|, then all data are present.
\item \verb|weight| (default: \verb|None|) \\
The weights to be used when calculating distances. If \verb|weight==None|, then equal weights are assumed.
\item \verb|transpose| (default: \verb|0|) \\
Determines if the distances between the rows of \verb|data| are to be calculated (\verb|transpose==0|), or between the columns of \verb|data| (\verb|transpose==1|).
\item \verb|dist| (default: \verb|'e'|, Euclidean distance) \\
Defines the distance function to be used (see \ref{sec:distancefunctions}).
\end{itemize}
To save memory, the distance matrix is returned as a list of 1D arrays.
The number of columns in each row is equal to the row number. Hence, the first row has zero elements. An example of the return value is
\begin{verbatim}
[array([]),
array([1.]),
array([7., 3.]),
array([4., 2., 6.])]
\end{verbatim}
This corresponds to the distance matrix
$$
\left(
\begin{array}{cccc}
0 & 1 & 7 & 4 \\
1 & 0 & 3 & 2 \\
7 & 3 & 0 & 6 \\
4 & 2 & 6 & 0
\end{array}
\right).
$$
\section{Calculating cluster properties}
\subsection*{Calculating the cluster centroids}
\label{subsec:clustercentroids}
The centroid of a cluster can be defined either as the mean or as the median of each dimension over all cluster items. The function \verb|clustercentroids| in \verb|Bio.Cluster| can be used to calculate either:
\begin{verbatim}
>>> from Bio.Cluster import clustercentroids
>>> cdata, cmask = clustercentroids(data)
\end{verbatim}
where the following arguments are defined:
\begin{itemize}
\item \verb|data| (required) \\
Array containing the data for the items.
\item \verb|mask| (default: \verb|None|) \\
Array of integers showing which data are missing. If \verb|mask[i,j]==0|, then \verb|data[i,j]| is missing. If \verb|mask==None|, then all data are present.
\item \verb|clusterid| (default: \verb|None|) \\
Vector of integers showing to which cluster each item belongs. If \verb|clusterid| is \verb|None|, then all items are assumed to belong to the same cluster.
\item \verb|method| (default: \verb|'a'|) \\
Specifies whether the arithmetic mean (\verb|method=='a'|) or the median (\verb|method=='m'|) is used to calculate the cluster center.
\item \verb|transpose| (default: \verb|0|) \\
Determines if the centroids of the rows of \verb|data| are to be calculated (\verb|transpose==0|), or the centroids of the columns of \verb|data| (\verb|transpose==1|).
\end{itemize}
This function returns the tuple \verb|(cdata, cmask)|. The centroid data are stored in the 2D Numerical Python array \verb|cdata|, with missing data indicated by the 2D Numerical Python integer array \verb|cmask|. The dimensions of these arrays are $\left(\textrm{number of clusters}, \textrm{number of columns}\right)$ if \verb|transpose| is \verb|0|, or $\left(\textrm{number of rows}, \textrm{number of clusters}\right)$ if \verb|transpose| is \verb|1|. Each row (if \verb|transpose| is \verb|0|) or column (if \verb|transpose| is \verb|1|) contains the averaged data corresponding to the centroid of each cluster.
\subsection*{Calculating the distance between clusters}
Given a distance function between \emph{items}, we can define the distance between two \emph{clusters} in several ways. The distance between the arithmetic means of the two clusters is used in pairwise centroid-linkage clustering and in $k$-means clustering. In $k$-medoids clustering, the distance between the medians of the two clusters is used instead. The shortest pairwise distance between items of the two clusters is used in pairwise single-linkage clustering, while the longest pairwise distance is used in pairwise maximum-linkage clustering. In pairwise average-linkage clustering, the distance between two clusters is defined as the average over the pairwise distances.
To calculate the distance between two clusters, use
\begin{verbatim}
>>> from Bio.Cluster import clusterdistance
>>> distance = clusterdistance(data)
\end{verbatim}
where the following arguments are defined:
\begin{itemize}
\item \verb|data| (required)\\
Array containing the data for the items.
\item \verb|mask| (default: \verb|None|) \\
Array of integers showing which data are missing. If \verb|mask[i,j]==0|, then \verb|data[i,j]| is missing. If \verb|mask==None|, then all data are present.
\item \verb|weight| (default: \verb|None|) \\
The weights to be used when calculating distances. If \verb|weight==None|, then equal weights are assumed.
\item \verb|index1| (default: \verb|0|) \\
A list containing the indices of the items belonging to the first cluster. A cluster containing only one item $i$ can be represented either as a list \verb|[i]|, or as an integer \verb|i|.
\item \verb|index2| (default: \verb|0|) \\
A list containing the indices of the items belonging to the second cluster. A cluster containing only one items $i$ can be represented either as a list \verb|[i]|, or as an integer \verb|i|.
\item \verb|method| (default: \verb|'a'|) \\
Specifies how the distance between clusters is defined:
\begin{itemize}
\item \verb|'a'|: Distance between the two cluster centroids (arithmetic mean);
\item \verb|'m'|: Distance between the two cluster centroids (median);
\item \verb|'s'|: Shortest pairwise distance between items in the two clusters;
\item \verb|'x'|: Longest pairwise distance between items in the two clusters;
\item \verb|'v'|: Average over the pairwise distances between items in the two clusters.
\end{itemize}
\item \verb|dist| (default: \verb|'e'|, Euclidean distance) \\
Defines the distance function to be used (see \ref{sec:distancefunctions}).
\item \verb|transpose| (default: \verb|0|) \\
If \verb|transpose==0|, calculate the distance between the rows of \verb|data|. If \verb|transpose==1|, calculate the distance between the columns of \verb|data|.
\end{itemize}
\section{Partitioning algorithms}
Partitioning algorithms divide items into $k$ clusters such that the sum of distances over the items to their cluster centers is minimal.
The number of clusters $k$ is specified by the user.
Three partitioning algorithms are available in \verb|Bio.Cluster|:
\begin{itemize}
\item $k$-means clustering
\item $k$-medians clustering
\item $k$-medoids clustering
\end{itemize}
These algorithms differ in how the cluster center is defined. In $k$-means clustering, the cluster center is defined as the mean data vector averaged over all items in the cluster. Instead of the mean, in $k$-medians clustering the median is calculated for each dimension in the data vector. Finally, in $k$-medoids clustering the cluster center is defined as the item which has the smallest sum of distances to the other items in the cluster. This clustering algorithm is suitable for cases in which the distance matrix is known but the original data matrix is not available, for example when clustering proteins based on their structural similarity.
The expectation-maximization (EM) algorithm is used to find this partitioning into $k$ groups.
In the initialization of the EM algorithm, we randomly assign items to clusters. To ensure that no empty clusters are produced, we use the binomial distribution to randomly choose the number of items in each cluster to be one or more. We then randomly permute the cluster assignments to items such that each item has an equal probability to be in any cluster. Each cluster is thus guaranteed to contain at least one item.
We then iterate:
\begin{itemize}
\item Calculate the centroid of each cluster, defined as either the mean, the median, or the medoid of the cluster;
\item Calculate the distances of each item to the cluster centers;
\item For each item, determine which cluster centroid is closest;
\item Reassign each item to its closest cluster, or stop the iteration if no further item reassignments take place.
\end{itemize}
To avoid clusters becoming empty during the iteration, in $k$-means and $k$-medians clustering the algorithm keeps track of the number of items in each cluster, and prohibits the last remaining item in a cluster from being reassigned to a different cluster. For $k$-medoids clustering, such a check is not needed, as the item that functions as the cluster centroid has a zero distance to itself, and will therefore never be closer to a different cluster.
As the initial assignment of items to clusters is done randomly, usually a different clustering solution is found each time the EM algorithm is executed.
To find the optimal clustering solution, the $k$-means algorithm is repeated many times, each time starting from a different initial random clustering. The sum of distances of the items to their cluster center is saved for each run, and the solution with the smallest value of this sum will be returned as the overall clustering solution.
How often the EM algorithm should be run depends on the number of items being clustered. As a rule of thumb, we can consider how often the optimal solution was found; this number is returned by the partitioning algorithms as implemented in this library. If the optimal solution was found many times, it is unlikely that better solutions exist than the one that was found. However, if the optimal solution was found only once, there may well be other solutions with a smaller within-cluster sum of distances. If the number of items is large (more than several hundreds), it may be difficult to find the globally optimal solution.
The EM algorithm terminates when no further reassignments take place. We noticed that for some sets of initial cluster assignments, the EM algorithm fails to converge due to the same clustering solution reappearing periodically after a small number of iteration steps. We therefore check for the occurrence of such periodic solutions during the iteration. After a given number of iteration steps, the current clustering result is saved as a reference. By comparing the clustering result after each subsequent iteration step to the reference state, we can determine if a previously encountered clustering result is found. In such a case, the iteration is halted. If after a given number of iterations the reference state has not yet been encountered, the current clustering solution is saved to be used as the new reference state. Initially, ten iteration steps are executed before resaving the reference state. This number of iteration steps is doubled each time, to ensure that periodic behavior with longer periods can also be detected.
\subsection*{$k$-means and $k$-medians}
The $k$-means and $k$-medians algorithms are implemented as the function \verb|kcluster| in \verb|Bio.Cluster|:
\begin{verbatim}
>>> from Bio.Cluster import kcluster
>>> clusterid, error, nfound = kcluster(data)
\end{verbatim}
where the following arguments are defined:
\begin{itemize}
\item \verb|data| (required)\\
Array containing the data for the items.
\item \verb|nclusters| (default: \verb|2|) \\
The number of clusters $k$.
\item \verb|mask| (default: \verb|None|) \\
Array of integers showing which data are missing. If \verb|mask[i,j]==0|, then \verb|data[i,j]| is missing. If \verb|mask==None|, then all data are present.
\item \verb|weight| (default: \verb|None|) \\
The weights to be used when calculating distances. If \verb|weight==None|, then equal weights are assumed.
\item \verb|transpose| (default: \verb|0|) \\
Determines if rows (\verb|transpose| is \verb|0|) or columns (\verb|transpose| is \verb|1|) are to be clustered.
\item \verb|npass| (default: \verb|1|) \\
The number of times the $k$-means/-medians clustering algorithm is performed, each time with a different (random) initial condition. If \verb|initialid| is given, the value of \verb|npass| is ignored and the clustering algorithm is run only once, as it behaves deterministically in that case.
\item \verb|method| (default: \verb|a|) \\
describes how the center of a cluster is found:
\begin{itemize}
\item \verb|method=='a'|: arithmetic mean ($k$-means clustering);
\item \verb|method=='m'|: median ($k$-medians clustering).
\end{itemize}
For other values of \verb|method|, the arithmetic mean is used.
\item \verb|dist| (default: \verb|'e'|, Euclidean distance) \\
Defines the distance function to be used (see \ref{sec:distancefunctions}).
Whereas all eight distance measures are accepted by \verb|kcluster|, from a theoretical viewpoint it is best to use the Euclidean distance for the $k$-means algorithm, and the city-block distance for $k$-medians.
\item \verb|initialid| (default: \verb|None|) \\
Specifies the initial clustering to be used for the EM algorithm. If \verb|initialid==None|, then a different random initial clustering is used for each of the \verb|npass| runs of the EM algorithm. If \verb|initialid| is not \verb|None|, then it should be equal to a 1D array containing the cluster number (between \verb|0| and \verb|nclusters-1|) for each item. Each cluster should contain at least one item. With the initial clustering specified, the EM algorithm is deterministic.
\end{itemize}
This function returns a tuple \verb|(clusterid, error, nfound)|, where \verb|clusterid| is an integer array containing the number of the cluster to which each row or cluster was assigned, \verb|error| is the within-cluster sum of distances for the optimal clustering solution, and \verb|nfound| is the number of times this optimal solution was found.
\subsection*{$k$-medoids clustering}
The \verb+kmedoids+ routine performs $k$-medoids clustering on a given set of items, using the distance matrix and the number of clusters passed by the user:
\begin{verbatim}
>>> from Bio.Cluster import kmedoids
>>> clusterid, error, nfound = kmedoids(distance)
\end{verbatim}
where the following arguments are defined:
, nclusters=2, npass=1, initialid=None)|
\begin{itemize}
\item{\verb|distance|} (required) \\
The matrix containing the distances between the items; this matrix can be specified in three ways:
\begin{itemize}
\item as a 2D Numerical Python array (in which only the left-lower part of the array will be accessed):
\begin{verbatim}
distance = array([[0.0, 1.1, 2.3],
[1.1, 0.0, 4.5],
[2.3, 4.5, 0.0]])
\end{verbatim}
\item as a 1D Numerical Python array containing consecutively the distances in the left-lower part of the distance matrix:
\begin{verbatim}
distance = array([1.1, 2.3, 4.5])
\end{verbatim}
\item as a list containing the rows of the left-lower part of the distance matrix:
\begin{verbatim}
distance = [array([]|,
array([1.1]),
array([2.3, 4.5])
]
\end{verbatim}
\end{itemize}
These three expressions correspond to the same distance matrix.
\item \verb|nclusters| (default: \verb|2|) \\
The number of clusters $k$.
\item \verb|npass| (default: \verb|1|) \\
The number of times the $k$-medoids clustering algorithm is performed, each time with a different (random) initial condition. If \verb|initialid| is given, the value of \verb|npass| is ignored, as the clustering algorithm behaves deterministically in that case.
\item \verb|initialid| (default: \verb|None|) \\
Specifies the initial clustering to be used for the EM algorithm. If \verb|initialid==None|, then a different random initial clustering is used for each of the \verb|npass| runs of the EM algorithm. If \verb|initialid| is not \verb|None|, then it should be equal to a 1D array containing the cluster number (between \verb|0| and \verb|nclusters-1|) for each item. Each cluster should contain at least one item. With the initial clustering specified, the EM algorithm is deterministic.
\end{itemize}
This function returns a tuple \verb|(clusterid, error, nfound)|, where \verb|clusterid| is an array containing the number of the cluster to which each item was assigned, \verb|error| is the within-cluster sum of distances for the optimal $k$-medoids clustering solution, and \verb|nfound| is the number of times the optimal solution was found. Note that the cluster number in \verb|clusterid| is defined as the item number of the item representing the cluster centroid.
\section{Hierarchical clustering}
Hierarchical clustering methods are inherently different from the $k$-means clustering method. In hierarchical clustering, the similarity in the expression profile between genes or experimental conditions are represented in the form of a tree structure. This tree structure can be shown graphically by programs such as Treeview and Java Treeview, which has contributed to the popularity of hierarchical clustering in the analysis of gene expression data.
The first step in hierarchical clustering is to calculate the distance matrix, specifying all the distances between the items to be clustered. Next, we create a node by joining the two closest items. Subsequent nodes are created by pairwise joining of items or nodes based on the distance between them, until all items belong to the same node. A tree structure can then be created by retracing which items and nodes were merged. Unlike the EM algorithm, which is used in $k$-means clustering, the complete process of hierarchical clustering is deterministic.
Several flavors of hierarchical clustering exist, which differ in how the distance between subnodes is defined in terms of their members. In \verb|Bio.Cluster|, pairwise single, maximum, average, and centroid linkage are available.
\begin{itemize}
\item
In pairwise single-linkage clustering, the distance between two nodes is defined as the shortest distance among the pairwise distances between the members of the two nodes.
\item
In pairwise maximum-linkage clustering, alternatively known as pairwise complete-linkage clustering, the distance between two nodes is defined as the longest distance among the pairwise distances between the members of the two nodes.
\item
In pairwise average-linkage clustering, the distance between two nodes is defined as the average over all pairwise distances between the items of the two nodes.
\item
In pairwise centroid-linkage clustering, the distance between two nodes is defined as the distance between their centroids. The centroids are calculated by taking the mean over all the items in a cluster. As the distance from each newly formed node to existing nodes and items need to be calculated at each step, the computing time of pairwise centroid-linkage clustering may be significantly longer than for the other hierarchical clustering methods. Another peculiarity is that (for a distance measure based on the Pearson correlation), the distances do not necessarily increase when going up in the clustering tree, and may even decrease. This is caused by an inconsistency between the centroid calculation and the distance calculation when using the Pearson correlation: Whereas the Pearson correlation effectively normalizes the data for the distance calculation, no such normalization occurs for the centroid calculation.
\end{itemize}
For pairwise single-, complete-, and average-linkage clustering, the distance between two nodes can be found directly from the distances between the individual items. Therefore, the clustering algorithm does not need access to the original gene expression data, once the distance matrix is known. For pairwise centroid-linkage clustering, however, the centroids of newly formed subnodes can only be calculated from the original data and not from the distance matrix.
The implementation of pairwise single-linkage hierarchical clustering is based on the SLINK algorithm (R. Sibson, 1973), which is much faster and more memory-efficient than a straightforward implementation of pairwise single-linkage clustering. The clustering result produced by this algorithm is identical to the clustering solution found by the conventional single-linkage algorithm. The single-linkage hierarchical clustering algorithm implemented in this library can be used to cluster large gene expression data sets, for which conventional hierarchical clustering algorithms fail due to excessive memory requirements and running time.
\subsection*{Representing a hierarchical clustering solution}
The result of hierarchical clustering consists of a tree of nodes, in which each node joins two items or subnodes. Usually, we are not only interested in which items or subnodes are joined at each node, but also in their similarity (or distance) as they are joined. To store one node in the hierarchical clustering tree, we make use of the class \verb|Node|, which defined in \verb|Bio.Cluster|. An instance of \verb|Node| has three attributes:
\begin{itemize}
\item \verb|left|
\item \verb|right|
\item \verb|distance|
\end{itemize}
Here, \verb|left| and \verb|right| are integers referring to the two items or subnodes that are joined at this node, and \verb|distance| is the distance between them. The items being clustered are numbered from 0 to $\left(\textrm{number of items} - 1\right)$, while clusters are numbered from -1 to $-\left(\textrm{number of items}-1\right)$. Note that the number of nodes is one less than the number of items.
To create a new \verb|Node| object, we need to specify \verb|left| and \verb|right|; \verb|distance| is optional.
\begin{verbatim}
>>> from Bio.Cluster import Node
>>> Node(2, 3)
(2, 3): 0
>>> Node(2, 3, 0.91)
(2, 3): 0.91
\end{verbatim}
The attributes \verb|left|, \verb|right|, and \verb|distance| of an existing \verb|Node| object can be modified directly:
\begin{verbatim}
>>> node = Node(4, 5)
>>> node.left = 6
>>> node.right = 2
>>> node.distance = 0.73
>>> node
(6, 2): 0.73
\end{verbatim}
An error is raised if \verb|left| and \verb|right| are not integers, or if \verb|distance| cannot be converted to a floating-point value.
The Python class \verb|Tree| represents a full hierarchical clustering solution. A \verb|Tree| object can be created from a list of \verb|Node| objects:
\begin{verbatim}
>>> from Bio.Cluster import Node, Tree
>>> nodes = [Node(1, 2, 0.2), Node(0, 3, 0.5), Node(-2, 4, 0.6), Node(-1, -3, 0.9)]
>>> tree = Tree(nodes)
>>> print(tree)
(1, 2): 0.2
(0, 3): 0.5
(-2, 4): 0.6
(-1, -3): 0.9
\end{verbatim}
The \verb|Tree| initializer checks if the list of nodes is a valid hierarchical clustering result:
\begin{verbatim}
>>> nodes = [Node(1, 2, 0.2), Node(0, 2, 0.5)]
>>> Tree(nodes)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: Inconsistent tree
\end{verbatim}
Individual nodes in a \verb|Tree| object can be accessed using square brackets:
\begin{verbatim}
>>> nodes = [Node(1, 2, 0.2), Node(0, -1, 0.5)]
>>> tree = Tree(nodes)
>>> tree[0]
(1, 2): 0.2
>>> tree[1]
(0, -1): 0.5
>>> tree[-1]
(0, -1): 0.5
\end{verbatim}
As a \verb|Tree| object is read-only, we cannot change individual nodes in a \verb|Tree| object. However, we can convert the tree to a list of nodes, modify this list, and create a new tree from this list:
\begin{verbatim}
>>> tree = Tree([Node(1, 2, 0.1), Node(0, -1, 0.5), Node(-2, 3, 0.9)])
>>> print(tree)
(1, 2): 0.1
(0, -1): 0.5
(-2, 3): 0.9
>>> nodes = tree[:]
>>> nodes[0] = Node(0, 1, 0.2)
>>> nodes[1].left = 2
>>> tree = Tree(nodes)
>>> print(tree)
(0, 1): 0.2
(2, -1): 0.5
(-2, 3): 0.9
\end{verbatim}
This guarantees that any \verb|Tree| object is always well-formed.
To display a hierarchical clustering solution with visualization programs such as Java Treeview, it is better to scale all node distances such that they are between zero and one. This can be accomplished by calling the \verb|scale| method on an existing \verb|Tree| object:
\begin{verbatim}
>>> tree.scale()
\end{verbatim}
This method takes no arguments, and returns \verb|None|.
After hierarchical clustering, the items can be grouped into $k$ clusters based on the tree structure stored in the \verb|Tree| object by cutting the tree:
\begin{verbatim}
>>> clusterid = tree.cut(nclusters=1)
\end{verbatim}
where \verb|nclusters| (defaulting to \verb|1|) is the desired number of clusters $k$.
This method ignores the top $k-1$ linking events in the tree structure, resulting in $k$ separated clusters of items. The number of clusters $k$ should be positive, and less than or equal to the number of items.
This method returns an array \verb|clusterid| containing the number of the cluster to which each item is assigned.
\subsection*{Performing hierarchical clustering}
To perform hierarchical clustering, use the \verb|treecluster| function in \verb|Bio.Cluster|.
\begin{verbatim}
>>> from Bio.Cluster import treecluster
>>> tree = treecluster(data)
\end{verbatim}
where the following arguments are defined:
\begin{itemize}
\item \verb|data| \\
Array containing the data for the items.
\item \verb|mask| (default: \verb|None|) \\
Array of integers showing which data are missing. If \verb|mask[i,j]==0|, then \verb|data[i,j]| is missing. If \verb|mask==None|, then all data are present.
\item \verb|weight| (default: \verb|None|) \\
The weights to be used when calculating distances. If \verb|weight==None|, then equal weights are assumed.
\item \verb|transpose| (default: \verb|0|) \\
Determines if rows (\verb|transpose==0|) or columns (\verb|transpose==1|) are to be clustered.
\item \verb|method| (default: \verb|'m'|) \\
defines the linkage method to be used:
\begin{itemize}
\item \verb|method=='s'|: pairwise single-linkage clustering
\item \verb|method=='m'|: pairwise maximum- (or complete-) linkage clustering
\item \verb|method=='c'|: pairwise centroid-linkage clustering
\item \verb|method=='a'|: pairwise average-linkage clustering
\end{itemize}
\item \verb|dist| (default: \verb|'e'|, Euclidean distance) \\
Defines the distance function to be used (see \ref{sec:distancefunctions}).
\end{itemize}
To apply hierarchical clustering on a precalculated distance matrix, specify the \verb|distancematrix| argument when calling \verb|treecluster| function instead of the \verb|data| argument:
\begin{verbatim}
>>> from Bio.Cluster import treecluster
>>> tree = treecluster(distancematrix=distance)
\end{verbatim}
In this case, the following arguments are defined:
\begin{itemize}
\item \verb|distancematrix| \\
The distance matrix, which can be specified in three ways:
\begin{itemize}
\item as a 2D Numerical Python array (in which only the left-lower part of the array will be accessed):
\begin{verbatim}
distance = array([[0.0, 1.1, 2.3],
[1.1, 0.0, 4.5],
[2.3, 4.5, 0.0]])
\end{verbatim}
\item as a 1D Numerical Python array containing consecutively the distances in the left-lower part of the distance matrix:
\begin{verbatim}
distance = array([1.1, 2.3, 4.5])
\end{verbatim}
\item as a list containing the rows of the left-lower part of the distance matrix:
\begin{verbatim}
distance = [array([]),
array([1.1]),
array([2.3, 4.5])
\end{verbatim}
\end{itemize}
These three expressions correspond to the same distance matrix.
As \verb|treecluster| may shuffle the values in the distance matrix as part of the clustering algorithm, be sure to save this array in a different variable before calling \verb|treecluster| if you need it later.
\item \verb|method| \\
The linkage method to be used:
\begin{itemize}
\item \verb|method=='s'|: pairwise single-linkage clustering
\item \verb|method=='m'|: pairwise maximum- (or complete-) linkage clustering
\item \verb|method=='a'|: pairwise average-linkage clustering
\end{itemize}
While pairwise single-, maximum-, and average-linkage clustering can be calculated from the distance matrix alone, pairwise centroid-linkage cannot.
\end{itemize}
When calling \verb|treecluster|, either \verb|data| or \verb|distancematrix| should be \verb|None|.
This function returns a \verb|Tree| object. This object contains $\left(\textrm{number of items} - 1\right)$ nodes, where the number of items is the number of rows if rows were clustered, or the number of columns if columns were clustered. Each node describes a pairwise linking event, where the node attributes \verb|left| and \verb|right| each contain the number of one item or subnode, and \verb|distance| the distance between them. Items are numbered from 0 to $\left(\textrm{number of items} - 1\right)$, while clusters are numbered -1 to $-\left(\textrm{number of items}-1\right)$.
\section{Self-Organizing Maps}
Self-Organizing Maps (SOMs) were invented by Kohonen to describe neural networks (see for instance Kohonen, 1997 \cite{kohonen1997}). Tamayo (1999) first applied Self-Organizing Maps to gene expression data \cite{tamayo1999}.
SOMs organize items into clusters that are situated in some topology. Usually a rectangular topology is chosen. The clusters generated by SOMs are such that neighboring clusters in the topology are more similar to each other than clusters far from each other in the topology.
The first step to calculate a SOM is to randomly assign a data vector to each cluster in the topology. If rows are being clustered, then the number of elements in each data vector is equal to the number of columns.
An SOM is then generated by taking rows one at a time, and finding which cluster in the topology has the closest data vector. The data vector of that cluster, as well as those of the neighboring clusters, are adjusted using the data vector of the row under consideration. The adjustment is given by
$$\Delta \underline{x}_{\textrm{cell}} = \tau \cdot \left(\underline{x}_{\textrm{row}} - \underline{x}_{\textrm{cell}} \right).$$
The parameter
$\tau$
is a parameter that decreases at each iteration step. We have used a simple linear function of the iteration step:
$$\tau = \tau_{\textrm{init}} \cdot \left(1 - {i \over n}\right),$$
$\tau_{\textrm{init}}$
is the initial value of $\tau$ as specified by the user, $i$ is the number of the current iteration step, and $n$ is the total number of iteration steps to be performed. While changes are made rapidly in the beginning of the iteration, at the end of iteration only small changes are made.
All clusters within a radius $R$ are adjusted to the gene under consideration. This radius decreases as the calculation progresses as
$$R = R_{\textrm{max}} \cdot \left(1 - {i \over n}\right),$$
in which the maximum radius is defined as
$$R_{\textrm{max}} = \sqrt{N_x^2 + N_y^2},$$
where
$\left(N_x, N_y\right)$
are the dimensions of the rectangle defining the topology.
The function \verb|somcluster| implements the complete algorithm to calculate a Self-Organizing Map on a rectangular grid. First it initializes the random number generator. The node data are then initialized using the random number generator. The order in which genes or microarrays are used to modify the SOM is also randomized. The total number of iterations in the SOM algorithm is specified by the user.
To run \verb|somcluster|, use
\begin{verbatim}
>>> from Bio.Cluster import somcluster
>>> clusterid, celldata = somcluster(data)
\end{verbatim}
where the following arguments are defined:
\begin{itemize}
\item \verb|data| (required) \\
Array containing the data for the items.
\item \verb|mask| (default: \verb|None|) \\
Array of integers showing which data are missing. If \verb|mask[i,j]==0|, then \verb|data[i,j]| is missing. If \verb|mask==None|, then all data are present.
\item \verb|weight| (default: \verb|None|) \\
contains the weights to be used when calculating distances. If \verb|weight==None|, then equal weights are assumed.
\item \verb|transpose| (default: \verb|0|) \\
Determines if rows (\verb|transpose| is \verb|0|) or columns (\verb|transpose| is \verb|1|) are to be clustered.
\item \verb|nxgrid, nygrid| (default: \verb|2, 1|) \\
The number of cells horizontally and vertically in the rectangular grid on which the Self-Organizing Map is calculated.
\item \verb|inittau| (default: \verb|0.02|) \\
The initial value for the parameter $\tau$ that is used in the SOM algorithm. The default value for \verb|inittau| is 0.02, which was used in Michael Eisen's Cluster/TreeView program.
\item \verb|niter| (default: \verb|1|) \\
The number of iterations to be performed.
\item \verb|dist| (default: \verb|'e'|, Euclidean distance) \\
Defines the distance function to be used (see \ref{sec:distancefunctions}).
\end{itemize}
This function returns the tuple \verb|(clusterid, celldata)|:
\begin{itemize}
\item \verb|clusterid|: \\
An array with two columns, where the number of rows is equal to the number of items that were clustered. Each row contains the $x$ and $y$ coordinates of the cell in the rectangular SOM grid to which the item was assigned.
\item \verb|celldata|: \\
An array with dimensions $\left(\verb|nxgrid|, \verb|nygrid|, \textrm{number of columns}\right)$ if rows are being clustered, or $\left(\verb|nxgrid|, \verb|nygrid|, \textrm{number of rows}\right)$ if columns are being clustered. Each element \verb|[ix][iy]| of this array is a 1D vector containing the gene expression data for the centroid of the cluster in the grid cell with coordinates \verb|[ix][iy]|.
\end{itemize}
\section{Principal Component Analysis}
Principal Component Analysis (PCA) is a widely used technique for analyzing multivariate data. A practical example of applying Principal Component Analysis to gene expression data is presented by Yeung and Ruzzo (2001) \cite{yeung2001}.
In essence, PCA is a coordinate transformation in which each row in the data matrix is written as a linear sum over basis vectors called principal components, which are ordered and chosen such that each maximally explains the remaining variance in the data vectors. For example, an $n \times 3$ data matrix can be represented as an ellipsoidal cloud of $n$ points in three dimensional space. The first principal component is the longest axis of the ellipsoid, the second principal component the second longest axis of the ellipsoid, and the third principal component is the shortest axis. Each row in the data matrix can be reconstructed as a suitable linear combination of the principal components. However, in order to reduce the dimensionality of the data, usually only the most important principal components are retained. The remaining variance present in the data is then regarded as unexplained variance.
The principal components can be found by calculating the eigenvectors of the covariance matrix of the data. The corresponding eigenvalues determine how much of the variance present in the data is explained by each principal component.
Before applying principal component analysis, typically the mean is subtracted from each column in the data matrix. In the example above, this effectively centers the ellipsoidal cloud around its centroid in 3D space, with the principal components describing the variation of points in the ellipsoidal cloud with respect to their centroid.
The function \verb|pca| below first uses the singular value decomposition to calculate the eigenvalues and eigenvectors of the data matrix. The singular value decomposition is implemented as a translation in C of the Algol procedure \verb|svd| \cite{golub1971}, which uses Householder bidiagonalization and a variant of the QR algorithm. The principal components, the coordinates of each data vector along the principal components, and the eigenvalues corresponding to the principal components are then evaluated and returned in decreasing order of the magnitude of the eigenvalue. If data centering is desired, the mean should be subtracted from each column in the data matrix before calling the \verb|pca| routine.
To apply Principal Component Analysis to a rectangular matrix \verb|data|, use
\begin{verbatim}
>>> from Bio.Cluster import pca
>>> columnmean, coordinates, components, eigenvalues = pca(data)
\end{verbatim}
This function returns a tuple \verb|columnmean, coordinates, components, eigenvalues|:
\begin{itemize}
\item \verb|columnmean| \\
Array containing the mean over each column in \verb|data|.
\item \verb|coordinates| \\
The coordinates of each row in \verb|data| with respect to the principal components.
\item \verb|components| \\
The principal components.
\item \verb|eigenvalues| \\
The eigenvalues corresponding to each of the principal components.
\end{itemize}
The original matrix \verb|data| can be recreated by calculating \verb|columnmean + dot(coordinates, components)|.
\section{Handling Cluster/TreeView-type files}
Cluster/TreeView are GUI-based codes for clustering gene expression data. They were originally written by \href{http://rana.lbl.gov}{Michael Eisen} while at Stanford University. \verb|Bio.Cluster| contains functions for reading and writing data files that correspond to the format specified for Cluster/TreeView. In particular, by saving a clustering result in that format, TreeView can be used to visualize the clustering results. We recommend using Alok Saldanha's \url{http://jtreeview.sourceforge.net/}{Java TreeView program}, which can display hierarchical as well as $k$-means clustering results.
An object of the class \verb|Record| contains all information stored in a Cluster/TreeView-type data file. To store the information contained in the data file in a \verb|Record| object, we first open the file and then read it:
\begin{verbatim}
>>> from Bio import Cluster
>>> handle = open("mydatafile.txt")
>>> record = Cluster.read(handle)
>>> handle.close()
\end{verbatim}
This two-step process gives you some flexibility in the source of the data.
For example, you can use
\begin{verbatim}
>>> import gzip # Python standard library
>>> handle = gzip.open("mydatafile.txt.gz")
\end{verbatim}
to open a gzipped file, or
\begin{verbatim}
>>> import urllib # Python standard library
>>> handle = urllib.urlopen("http://somewhere.org/mydatafile.txt")
\end{verbatim}
to open a file stored on the Internet before calling \verb|read|.
The \verb|read| command reads the tab-delimited text file \verb|mydatafile.txt| containing gene expression data in the format specified for Michael Eisen's Cluster/TreeView program. In this file format, rows represent genes and columns represent samples or observations. For a simple time course, a minimal input file would look like this:
\begin{table}[!htbp]
\begin{center}
\begin{tabular}{|l|r|r|r|r|r|}
\hline
YORF & 0 minutes & 30 minutes & 1 hour & 2 hours & 4 hours\\
YAL001C & 1 & 1.3 & 2.4 & 5.8 & 2.4 \\
YAL002W & 0.9 & 0.8 & 0.7 & 0.5 & 0.2 \\
YAL003W & 0.8 & 2.1 & 4.2 & 10.1 & 10.1 \\
YAL005C & 1.1 & 1.3 & 0.8 & & 0.4 \\
YAL010C & 1.2 & 1 & 1.1 & 4.5 & 8.3 \\
\hline
\end{tabular}
\end{center}
\end{table}
\noindent Each row (gene) has an identifier that always goes in the first column. In this example, we are using yeast open reading frame codes. Each column (sample) has a label in the first row. In this example, the labels describe the time at which a sample was taken. The first column of the first row contains a special field that tells the program what kind of objects are in each row. In this case, YORF stands for yeast open reading frame. This field can be any alpha-numeric value. The remaining cells in the table contain data for the appropriate gene and sample. The 5.8 in row 2 column 4 means that the observed value for gene YAL001C at 2 hours was 5.8. Missing values are acceptable and are designated by empty cells (e.g. YAL004C at 2 hours).
The input file may contain additional information. A maximal input file would look like this:
\begin{table}[!htbp]
\begin{center}
\begin{tabular}{|l|l|r|r|r|r|r|r|r|}
\hline
YORF & NAME & GWEIGHT & GORDER & 0 & 30 & 1 & 2 & 4 \\
EWEIGHT & & & & 1 & 1 & 1 & 1 & 0 \\
EORDER & & & & 5 & 3 & 2 & 1 & 1 \\
YAL001C & TFIIIC 138 KD SUBUNIT & 1 & 1 & 1 & 1.3 & 2.4 & 5.8 & 2.4 \\
YAL002W & UNKNOWN & 0.4 & 3 & 0.9 & 0.8 & 0.7 & 0.5 & 0.2 \\
YAL003W & ELONGATION FACTOR EF1-BETA & 0.4 & 2 & 0.8 & 2.1 & 4.2 & 10.1 & 10.1 \\
YAL005C & CYTOSOLIC HSP70 & 0.4 & 5 & 1.1 & 1.3 & 0.8 & & 0.4 \\
\hline
\end{tabular}
\end{center}
\end{table}
\noindent The added columns NAME, GWEIGHT, and GORDER and rows EWEIGHT and EORDER are optional. The NAME column allows you to specify a label for each gene that is distinct from the ID in column 1.
A \verb|Record| object has the following attributes:
\begin{itemize}
\item \verb|data| \\
The data array containing the gene expression data. Genes are stored row-wise, while microarrays are stored column-wise.
\item \verb|mask| \\
This array shows which elements in the \verb|data| array, if any, are missing. If \verb|mask[i,j]==0|, then \verb|data[i,j]| is missing. If no data were found to be missing, \verb|mask| is set to \verb|None|.
\item \verb|geneid| \\
This is a list containing a unique description for each gene (i.e., ORF numbers).
\item \verb|genename| \\
This is a list containing a description for each gene (i.e., gene name). If not present in the data file, \verb|genename| is set to \verb|None|.
\item \verb|gweight| \\
The weights that are to be used to calculate the distance in expression profile between genes. If not present in the data file, \verb|gweight| is set to \verb|None|.
\item \verb|gorder| \\
The preferred order in which genes should be stored in an output file. If not present in the data file, \verb|gorder| is set to \verb|None|.
\item \verb|expid| \\
This is a list containing a description of each microarray, e.g. experimental condition.
\item \verb|eweight| \\
The weights that are to be used to calculate the distance in expression profile between microarrays. If not present in the data file, \verb|eweight| is set to \verb|None|.
\item \verb|eorder| \\
The preferred order in which microarrays should be stored in an output file. If not present in the data file, \verb|eorder| is set to \verb|None|.
\item \verb|uniqid| \\
The string that was used instead of UNIQID in the data file.
\end{itemize}
After loading a \verb|Record| object, each of these attributes can be accessed and modified directly. For example, the data can be log-transformed by taking the logarithm of \verb|record.data|.
\subsection*{Calculating the distance matrix}
To calculate the distance matrix between the items stored in the record, use
\begin{verbatim}
>>> matrix = record.distancematrix()
\end{verbatim}
where the following arguments are defined:
\begin{itemize}
\item \verb|transpose| (default: \verb|0|) \\
Determines if the distances between the rows of \verb|data| are to be calculated (\verb|transpose==0|), or between the columns of \verb|data| (\verb|transpose==1|).
\item \verb|dist| (default: \verb|'e'|, Euclidean distance) \\
Defines the distance function to be used (see \ref{sec:distancefunctions}).
\end{itemize}
This function returns the distance matrix as a list of rows, where the number of columns of each row is equal to the row number (see section \ref{subsec:distancematrix}).
\subsection*{Calculating the cluster centroids}
To calculate the centroids of clusters of items stored in the record, use
\begin{verbatim}
>>> cdata, cmask = record.clustercentroids()
\end{verbatim}
\begin{itemize}
\item \verb|clusterid| (default: \verb|None|) \\
Vector of integers showing to which cluster each item belongs. If \verb|clusterid| is not given, then all items are assumed to belong to the same cluster.
\item \verb|method| (default: \verb|'a'|) \\
Specifies whether the arithmetic mean (\verb|method=='a'|) or the median (\verb|method=='m'|) is used to calculate the cluster center.
\item \verb|transpose| (default: \verb|0|) \\
Determines if the centroids of the rows of \verb|data| are to be calculated (\verb|transpose==0|), or the centroids of the columns of \verb|data| (\verb|transpose==1|).
\end{itemize}
This function returns the tuple \verb|cdata, cmask|; see section \ref{subsec:clustercentroids} for a description.
\subsection*{Calculating the distance between clusters}
To calculate the distance between clusters of items stored in the record, use
\begin{verbatim}
>>> distance = record.clusterdistance()
\end{verbatim}
where the following arguments are defined:
\begin{itemize}
\item \verb|index1| (default: \verb|0|) \\
A list containing the indices of the items belonging to the first cluster. A cluster containing only one item $i$ can be represented either as a list \verb|[i]|, or as an integer \verb|i|.
\item \verb|index2| (default: \verb|0|) \\
A list containing the indices of the items belonging to the second cluster. A cluster containing only one item $i$ can be represented either as a list \verb|[i]|, or as an integer \verb|i|.
\item \verb|method| (default: \verb|'a'|) \\
Specifies how the distance between clusters is defined:
\begin{itemize}
\item \verb|'a'|: Distance between the two cluster centroids (arithmetic mean);
\item \verb|'m'|: Distance between the two cluster centroids (median);
\item \verb|'s'|: Shortest pairwise distance between items in the two clusters;
\item \verb|'x'|: Longest pairwise distance between items in the two clusters;
\item \verb|'v'|: Average over the pairwise distances between items in the two clusters.
\end{itemize}
\item \verb|dist| (default: \verb|'e'|, Euclidean distance) \\
Defines the distance function to be used (see \ref{sec:distancefunctions}).
\item \verb|transpose| (default: \verb|0|) \\
If \verb|transpose==0|, calculate the distance between the rows of \verb|data|. If \verb|transpose==1|, calculate the distance between the columns of \verb|data|.
\end{itemize}
\subsection*{Performing hierarchical clustering}
To perform hierarchical clustering on the items stored in the record, use
\begin{verbatim}
>>> tree = record.treecluster()
\end{verbatim}
where the following arguments are defined:
\begin{itemize}
\item \verb|transpose| (default: \verb|0|) \\
Determines if rows (\verb|transpose==0|) or columns (\verb|transpose==1|) are to be clustered.
\item \verb|method| (default: \verb|'m'|) \\
defines the linkage method to be used:
\begin{itemize}
\item \verb|method=='s'|: pairwise single-linkage clustering
\item \verb|method=='m'|: pairwise maximum- (or complete-) linkage clustering
\item \verb|method=='c'|: pairwise centroid-linkage clustering
\item \verb|method=='a'|: pairwise average-linkage clustering
\end{itemize}
\item \verb|dist| (default: \verb|'e'|, Euclidean distance) \\
Defines the distance function to be used (see \ref{sec:distancefunctions}).
\item \verb|transpose| \\
Determines if genes or microarrays are being clustered. If \verb|transpose==0|, genes (rows) are being clustered. If \verb|transpose==1|, microarrays (columns) are clustered.
\end{itemize}
This function returns a \verb|Tree| object. This object contains $\left(\textrm{number of items} - 1\right)$ nodes, where the number of items is the number of rows if rows were clustered, or the number of columns if columns were clustered. Each node describes a pairwise linking event, where the node attributes \verb|left| and \verb|right| each contain the number of one item or subnode, and \verb|distance| the distance between them. Items are numbered from 0 to $\left(\textrm{number of items} - 1\right)$, while clusters are numbered -1 to $-\left(\textrm{number of items}-1\right)$.
\subsection*{Performing $k$-means or $k$-medians clustering}
To perform $k$-means or $k$-medians clustering on the items stored in the record, use
\begin{verbatim}
>>> clusterid, error, nfound = record.kcluster()
\end{verbatim}
where the following arguments are defined:
\begin{itemize}
\item \verb|nclusters| (default: \verb|2|) \\
The number of clusters $k$.
\item \verb|transpose| (default: \verb|0|) \\
Determines if rows (\verb|transpose| is \verb|0|) or columns (\verb|transpose| is \verb|1|) are to be clustered.
\item \verb|npass| (default: \verb|1|) \\
The number of times the $k$-means/-medians clustering algorithm is performed, each time with a different (random) initial condition. If \verb|initialid| is given, the value of \verb|npass| is ignored and the clustering algorithm is run only once, as it behaves deterministically in that case.
\item \verb|method| (default: \verb|a|) \\
describes how the center of a cluster is found:
\begin{itemize}
\item \verb|method=='a'|: arithmetic mean ($k$-means clustering);
\item \verb|method=='m'|: median ($k$-medians clustering).
\end{itemize}
For other values of \verb|method|, the arithmetic mean is used.
\item \verb|dist| (default: \verb|'e'|, Euclidean distance) \\
Defines the distance function to be used (see \ref{sec:distancefunctions}).
\end{itemize}
This function returns a tuple \verb|(clusterid, error, nfound)|, where \verb|clusterid| is an integer array containing the number of the cluster to which each row or cluster was assigned, \verb|error| is the within-cluster sum of distances for the optimal clustering solution, and \verb|nfound| is the number of times this optimal solution was found.
\subsection*{Calculating a Self-Organizing Map}
To calculate a Self-Organizing Map of the items stored in the record, use
\begin{verbatim}
>>> clusterid, celldata = record.somcluster()
\end{verbatim}
where the following arguments are defined:
\begin{itemize}
\item \verb|transpose| (default: \verb|0|) \\
Determines if rows (\verb|transpose| is \verb|0|) or columns (\verb|transpose| is \verb|1|) are to be clustered.
\item \verb|nxgrid, nygrid| (default: \verb|2, 1|) \\
The number of cells horizontally and vertically in the rectangular grid on which the Self-Organizing Map is calculated.
\item \verb|inittau| (default: \verb|0.02|) \\
The initial value for the parameter $\tau$ that is used in the SOM algorithm. The default value for \verb|inittau| is 0.02, which was used in Michael Eisen's Cluster/TreeView program.
\item \verb|niter| (default: \verb|1|) \\
The number of iterations to be performed.
\item \verb|dist| (default: \verb|'e'|, Euclidean distance) \\
Defines the distance function to be used (see \ref{sec:distancefunctions}).
\end{itemize}
This function returns the tuple \verb|(clusterid, celldata)|:
\begin{itemize}
\item \verb|clusterid|: \\
An array with two columns, where the number of rows is equal to the number of items that were clustered. Each row contains the $x$ and $y$ coordinates of the cell in the rectangular SOM grid to which the item was assigned.
\item \verb|celldata|: \\
An array with dimensions $\left(\verb|nxgrid|, \verb|nygrid|, \textrm{number of columns}\right)$ if rows are being clustered, or $\left(\verb|nxgrid|, \verb|nygrid|, \textrm{number of rows}\right)$ if columns are being clustered. Each element \verb|[ix][iy]| of this array is a 1D vector containing the gene expression data for the centroid of the cluster in the grid cell with coordinates \verb|[ix][iy]|.
\end{itemize}
\subsection*{Saving the clustering result}
To save the clustering result, use
\begin{verbatim}
>>> record.save(jobname, geneclusters, expclusters)
\end{verbatim}
where the following arguments are defined:
\begin{itemize}
\item \verb|jobname| \\
The string \verb|jobname| is used as the base name for names of the files that are to be saved.
\item \verb|geneclusters| \\
This argument describes the gene (row-wise) clustering result. In case of $k$-means clustering, this is a 1D array containing the number of the cluster each gene belongs to. It can be calculated using \verb|kcluster|. In case of hierarchical clustering, \verb|geneclusters| is a \verb|Tree| object.
\item \verb|expclusters| \\
This argument describes the (column-wise) clustering result for the experimental conditions. In case of $k$-means clustering, this is a 1D array containing the number of the cluster each experimental condition belongs to. It can be calculated using \verb|kcluster|. In case of hierarchical clustering, \verb|expclusters| is a \verb|Tree| object.
\end{itemize}
This method writes the text file \verb|jobname.cdt|, \verb|jobname.gtr|, \verb|jobname.atr|, \verb|jobname*.kgg|, and/or \verb|jobname*.kag| for subsequent reading by the Java TreeView program. If \verb|geneclusters| and \verb|expclusters| are both \verb|None|, this method only writes the text file \verb|jobname.cdt|; this file can subsequently be read into a new \verb|Record| object.
\section{Example calculation}
This is an example of a hierarchical clustering calculation, using single linkage clustering for genes and maximum linkage clustering for experimental conditions. As the Euclidean distance is being used for gene clustering, it is necessary to scale the node distances \verb|genetree| such that they are all between zero and one. This is needed for the Java TreeView code to display the tree diagram correctly. To cluster the experimental conditions, the uncentered correlation is being used. No scaling is needed in this case, as the distances in \verb|exptree| are already between zero and two. The example data \verb|cyano.txt| can be found in the \verb|data| subdirectory.
\begin{verbatim}
>>> from Bio import Cluster
>>> handle = open("cyano.txt")
>>> record = Cluster.read(handle)
>>> handle.close()
>>> genetree = record.treecluster(method='s')
>>> genetree.scale()
>>> exptree = record.treecluster(dist='u', transpose=1)
>>> record.save("cyano_result", genetree, exptree)
\end{verbatim}
This will create the files \verb|cyano_result.cdt|, \verb|cyano_result.gtr|, and \verb|cyano_result.atr|.
Similarly, we can save a $k$-means clustering solution:
\begin{verbatim}
>>> from Bio import Cluster
>>> handle = open("cyano.txt")
>>> record = Cluster.read(handle)
>>> handle.close()
>>> (geneclusters, error, ifound) = record.kcluster(nclusters=5, npass=1000)
>>> (expclusters, error, ifound) = record.kcluster(nclusters=2, npass=100, transpose=1)
>>> record.save("cyano_result", geneclusters, expclusters)
\end{verbatim}
This will create the files \verb|cyano_result_K_G2_A2.cdt|, \verb|cyano_result_K_G2.kgg|, and \verb|cyano_result_K_A2.kag|.
\section{Auxiliary functions}
\verb|median(data)|
returns the median of the 1D array \verb|data|.
\verb|mean(data)|
returns the mean of the 1D array \verb|data|.
\verb|version()|
returns the version number of the underlying C Clustering Library as a string.
|