[565] | 1 | #!/usr/bin/env python3 |
---|
| 2 | # -*- coding: utf-8 -*- |
---|
[596] | 3 | |
---|
[565] | 4 | import sys |
---|
| 5 | import numpy as np |
---|
[602] | 6 | #from sklearn import manifold #was needed for manifold MDS http://scikit-learn.org/stable/auto_examples/manifold/plot_compare_methods.html |
---|
[596] | 7 | |
---|
| 8 | #to make it work in console, http://stackoverflow.com/questions/2801882/generating-a-png-with-matplotlib-when-display-is-undefined |
---|
| 9 | #import matplotlib |
---|
| 10 | #matplotlib.use('Agg') |
---|
| 11 | |
---|
[565] | 12 | import matplotlib.pyplot as plt |
---|
| 13 | from mpl_toolkits.mplot3d import Axes3D |
---|
| 14 | from matplotlib import cm |
---|
| 15 | import argparse |
---|
| 16 | |
---|
[596] | 17 | |
---|
[598] | 18 | #http://www.nervouscomputer.com/hfs/cmdscale-in-python/ |
---|
| 19 | def cmdscale(D): |
---|
| 20 | """ |
---|
| 21 | Classical multidimensional scaling (MDS) |
---|
| 22 | |
---|
| 23 | Parameters |
---|
| 24 | ---------- |
---|
| 25 | D : (n, n) array |
---|
| 26 | Symmetric distance matrix. |
---|
| 27 | |
---|
| 28 | Returns |
---|
| 29 | ------- |
---|
| 30 | Y : (n, p) array |
---|
| 31 | Configuration matrix. Each column represents a dimension. Only the |
---|
| 32 | p dimensions corresponding to positive eigenvalues of B are returned. |
---|
| 33 | Note that each dimension is only determined up to an overall sign, |
---|
| 34 | corresponding to a reflection. |
---|
| 35 | |
---|
| 36 | e : (n,) array |
---|
| 37 | Eigenvalues of B. |
---|
| 38 | |
---|
| 39 | """ |
---|
| 40 | # Number of points |
---|
| 41 | n = len(D) |
---|
| 42 | |
---|
| 43 | # Centering matrix |
---|
| 44 | H = np.eye(n) - np.ones((n, n))/n |
---|
| 45 | |
---|
| 46 | # YY^T |
---|
| 47 | B = -H.dot(D**2).dot(H)/2 |
---|
| 48 | |
---|
| 49 | # Diagonalize |
---|
| 50 | evals, evecs = np.linalg.eigh(B) |
---|
| 51 | |
---|
| 52 | # Sort by eigenvalue in descending order |
---|
| 53 | idx = np.argsort(evals)[::-1] |
---|
| 54 | evals = evals[idx] |
---|
| 55 | evecs = evecs[:,idx] |
---|
| 56 | |
---|
| 57 | # Compute the coordinates using positive-eigenvalued components only |
---|
| 58 | w, = np.where(evals > 0) |
---|
| 59 | L = np.diag(np.sqrt(evals[w])) |
---|
| 60 | V = evecs[:,w] |
---|
| 61 | Y = V.dot(L) |
---|
| 62 | |
---|
| 63 | return Y, evals |
---|
[596] | 64 | |
---|
[604] | 65 | def rand_jitter(arr, jitter): |
---|
| 66 | stdev = (arr.max()-arr.min()) / 100. * jitter #dispersion proportional to range |
---|
| 67 | return arr + np.random.randn(len(arr)) * stdev |
---|
[565] | 68 | |
---|
| 69 | |
---|
| 70 | def read_file(fname, separator): |
---|
| 71 | distances = np.genfromtxt(fname, delimiter=separator) |
---|
[602] | 72 | if (distances.shape[0]!=distances.shape[1]): |
---|
| 73 | print("Matrix is not square:",distances.shape) |
---|
[607] | 74 | if (distances.shape[0]>distances.shape[1]): |
---|
| 75 | raise ValueError('More rows than columns?') |
---|
| 76 | if (distances.shape[0]<distances.shape[1]): |
---|
[602] | 77 | minsize = min(distances.shape[0],distances.shape[1]) |
---|
[607] | 78 | firstsquarecolumn=distances.shape[1]-minsize |
---|
| 79 | distances = np.array([row[firstsquarecolumn:] for row in distances]) #this can only fix matrices with more columns than rows |
---|
[608] | 80 | print("Made the matrix square:",distances.shape) |
---|
[565] | 81 | |
---|
[607] | 82 | #if the file has more columns than rows, assume the first extra column on the left of the square matrix has labels |
---|
| 83 | labels = np.genfromtxt(fname, delimiter=separator, usecols=firstsquarecolumn-1,dtype=[('label','S10')]) |
---|
[602] | 84 | labels = [label[0].decode("utf-8") for label in labels] |
---|
[607] | 85 | else: |
---|
[602] | 86 | labels = None #no labels |
---|
| 87 | |
---|
| 88 | return distances,labels |
---|
[565] | 89 | |
---|
[602] | 90 | |
---|
[565] | 91 | def compute_mds(distance_matrix, dim): |
---|
[598] | 92 | embed, evals = cmdscale(distance_matrix) |
---|
[600] | 93 | |
---|
[599] | 94 | variances = [np.var(embed[:,i]) for i in range(len(embed[0]))] |
---|
[608] | 95 | variances_fraction = [sum(variances[:i+1])/sum(variances) for i in range(len(variances))] |
---|
| 96 | for i,pv in enumerate(variances_fraction): |
---|
[604] | 97 | print("In",i+1,"dimensions:",pv) |
---|
[598] | 98 | |
---|
[600] | 99 | dim = min(dim, len(embed[0])) |
---|
| 100 | embed = np.asarray([embed[:,i] for i in range(dim)]).T |
---|
| 101 | |
---|
[608] | 102 | return embed, variances_fraction[dim-1] |
---|
[565] | 103 | |
---|
| 104 | |
---|
[616] | 105 | def plot(coordinates, labels, dimensions, variance_fraction, jitter, flipX, flipY, swapXY, outname=""): |
---|
[565] | 106 | fig = plt.figure() |
---|
| 107 | |
---|
| 108 | if dimensions < 3: |
---|
| 109 | ax = fig.add_subplot(111) |
---|
| 110 | else: |
---|
| 111 | ax = fig.add_subplot(111, projection='3d') |
---|
| 112 | |
---|
| 113 | x_dim = len(coordinates[0]) |
---|
| 114 | y_dim = len(coordinates) |
---|
| 115 | |
---|
[613] | 116 | if flipX: |
---|
| 117 | coordinates=np.hstack((-coordinates[:, [0]], coordinates[:, [1]])) |
---|
| 118 | if flipY: |
---|
| 119 | coordinates=np.hstack((coordinates[:, [0]], -coordinates[:, [1]])) |
---|
[616] | 120 | if swapXY: |
---|
| 121 | coordinates[:,[0, 1]] = coordinates[:,[1, 0]] |
---|
[613] | 122 | |
---|
| 123 | add_jitter = lambda tab: rand_jitter(tab, jitter) if jitter>0 else tab |
---|
[602] | 124 | points = [add_jitter(coordinates[:, i]) for i in range(x_dim)] |
---|
| 125 | |
---|
[609] | 126 | if labels is not None and dimensions==2: #could be ported to 3D too |
---|
| 127 | ax.scatter(*points, alpha=0) #invisible points, because we will show labels instead |
---|
[613] | 128 | labelconvert={'velland_':'V','velwat_':'W','vpp_':'P','vpa_':'A'} #use this if you want to replace long names with short IDs |
---|
| 129 | colors={'velland_':'green','velwat_':'blue','vpp_':'red','vpa_':'violet'} |
---|
[602] | 130 | #for point in points: |
---|
| 131 | # print(point) |
---|
| 132 | for label, x, y in zip(labels, points[0], points[1]): |
---|
[609] | 133 | color='black' |
---|
[602] | 134 | for key in labelconvert: |
---|
| 135 | if label.startswith(key): |
---|
| 136 | label=labelconvert[key] |
---|
[609] | 137 | color=colors[key] |
---|
[602] | 138 | plt.annotate( |
---|
| 139 | label, |
---|
| 140 | xy = (x, y), xytext = (0, 0), |
---|
| 141 | textcoords = 'offset points', ha = 'center', va = 'center', |
---|
[609] | 142 | color = color, |
---|
| 143 | alpha = 0.8, |
---|
[602] | 144 | #bbox = dict(boxstyle = 'round,pad=0.5', fc = 'yellow', alpha = 0.5), |
---|
| 145 | #arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0') |
---|
| 146 | ) |
---|
| 147 | else: |
---|
| 148 | ax.scatter(*points, alpha=0.5) |
---|
[565] | 149 | |
---|
[602] | 150 | |
---|
[608] | 151 | plt.title('Projection of phenotype distances, variance preserved = %.1f%%' % (variance_fraction*100)) |
---|
[565] | 152 | plt.tight_layout() |
---|
| 153 | plt.axis('tight') |
---|
| 154 | |
---|
| 155 | if outname == "": |
---|
| 156 | plt.show() |
---|
| 157 | else: |
---|
| 158 | plt.savefig(outname+".pdf") |
---|
[598] | 159 | np.savetxt(outname+".csv", coordinates, delimiter=";") |
---|
[565] | 160 | |
---|
| 161 | |
---|
[616] | 162 | def main(filename, dimensions=3, outname="", jitter=0, separator='\t', flipX=False, flipY=False, swapXY=False): |
---|
[602] | 163 | distances,labels = read_file(filename, separator) |
---|
[608] | 164 | embed,variance_fraction = compute_mds(distances, dimensions) |
---|
[565] | 165 | |
---|
| 166 | if dimensions == 1: |
---|
| 167 | embed = np.array([np.insert(e, 0, 0, axis=0) for e in embed]) |
---|
| 168 | |
---|
[616] | 169 | plot(embed, labels, dimensions, variance_fraction, jitter, flipX, flipY, swapXY, outname) |
---|
[565] | 170 | |
---|
| 171 | |
---|
| 172 | if __name__ == '__main__': |
---|
| 173 | parser = argparse.ArgumentParser() |
---|
| 174 | parser.add_argument('--in', dest='input', required=True, help='input file with dissimilarity matrix') |
---|
[607] | 175 | parser.add_argument('--out', dest='output', required=False, help='output file name (without extension)') |
---|
[565] | 176 | parser.add_argument('--dim', required=False, help='number of dimensions of the new space') |
---|
| 177 | parser.add_argument('--sep', required=False, help='separator of the source file') |
---|
[604] | 178 | parser.add_argument('--j', required=False, help='for j>0, random jitter is added to points in the plot') |
---|
[613] | 179 | parser.add_argument('--flipX', required=False, dest='flipX', action='store_true') |
---|
| 180 | parser.add_argument('--flipY', required=False, dest='flipY', action='store_true') |
---|
[616] | 181 | parser.add_argument('--swapXY', required=False, dest='swapXY', action='store_true') |
---|
[613] | 182 | parser.set_defaults(flipX=False) |
---|
| 183 | parser.set_defaults(flipY=False) |
---|
[616] | 184 | parser.set_defaults(swapXY=False) |
---|
[565] | 185 | |
---|
| 186 | args = parser.parse_args() |
---|
[613] | 187 | set_value = lambda value, default: default if value == None else value |
---|
[616] | 188 | main(args.input, int(set_value(args.dim, 3)), set_value(args.output, ""), float(set_value(args.j, 0)), set_value(args.sep, "\t"), args.flipX, args.flipY, args.swapXY) |
---|