In [3]:
import numpy as np
import mpl_toolkits.mplot3d as mpl3
import matplotlib.pyplot as pl

%matplotlib notebook

In [13]:
x = np.array([1, 2, 3], dtype=float)
x /= np.sum(x)

In [15]:
np.sort?

In [16]:
a = np.random.randn(10)

In [17]:
o = np.argsort(a)

In [21]:
def invert_sort(order):
    result = np.empty(len(order), dtype=order.dtype)
    for i, j in enumerate(order):
        result[j] = i
    return result

In [32]:
import pdb

In [35]:
def proj(x):
    order = np.argsort(x)[::-1]
    x_sorted = x[order]
    
    a = 0
    i = len(x)
    while x_sorted[i - 1] + a / i < 0:
        a += x_sorted[i - 1]
        i -= 1
    
    result = np.zeros(len(x), dtype=float)
    result[:i] = x_sorted[:i] + a / i
    return result[invert_sort(order)]

In [42]:
psimplex = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])

fig = pl.figure(0, figsize=(10, 10))
ax = mpl3.Axes3D(fig)
smplx = mpl3.art3d.Poly3DCollection([psimplex])
ax.add_collection3d(smplx)

for x in np.random.randn(10, 3):
    x /= sum(x)
    y = proj(x)
    print(x, y)
    pl.plot((x[0], y[0]), (x[1], y[1]), (x[2], y[2]), color='r')


[ 0.89847516  1.86793351 -1.76640867] [ 0.01527083  0.98472917  0.        ]
[-0.80432058  3.08888224 -1.28456166] [ 0.  1.  0.]
[ 0.11856083  0.14317407  0.7382651 ] [ 0.11856083  0.14317407  0.7382651 ]
[-36.80773652  45.10045218  -7.29271566] [ 0.  1.  0.]
[-0.24330727  0.87800566  0.36530161] [ 0.          0.75635203  0.24364797]
[ 0.22079454  0.12813049  0.65107497] [ 0.22079454  0.12813049  0.65107497]
[ 0.95298155  0.0189639   0.02805455] [ 0.95298155  0.0189639   0.02805455]
[-0.11026583  0.17244159  0.93782424] [ 0.          0.11730867  0.88269133]
[ 1.31641475 -0.16496961 -0.15144514] [ 1.  0.  0.]
[ 1.14613312 -0.57667182  0.4305387 ] [ 0.85779721  0.          0.14220279]

In [ ]: