code: def proj_simplex(x, diameter=1, out=None):
      r
      if out is None:
          out = x.space.element()
  
      # sort values in descending order
      x_sor = x.asarray().flatten()
      x_sor.sort()
      x_sor = x_sor[::-1]
  
      # find critical index
      j = np.arange(1, x.size + 1)
      x_avrg = (1 / j) * (np.cumsum(x_sor) - diameter)
      crit = x_sor - x_avrg
      i = np.argwhere(crit >= 0).flatten().max()
  
      # output is a shifted and thresholded version of the input
      out[:] = np.maximum(x - x_avrg[i], 0)
  
      return out
docs: r"""Projection onto simplex.
  
      Projection onto::
  
          ``{ x \in X | x_i \geq 0, \sum_i x_i = r}``
  
      with :math:`r` being the diameter. It is computed by the formula proposed
      in [D+2008].
  
      Parameters
      ----------
      space : `LinearSpace`
          Space / domain ``X``.
      diameter : positive float, optional
          Diameter of the simplex.
  
      Returns
      -------
      prox_factory : callable
          Factory for the proximal operator to be initialized.
  
      Notes
      -----
      The projection onto a simplex is not of closed-form but can be solved by a
      non-iterative algorithm, see [D+2008] for details.
  
      References
      ----------
      [D+2008] Duchi, J., Shalev-Shwartz, S., Singer, Y., and Chandra, T.
      *Efficient Projections onto the L1-ball for Learning in High dimensions*.
      ICML 2008, pp. 272-279. http://doi.org/10.1145/1390156.1390191
  
      See Also
      --------
      proj_l1 : projection onto l1-norm ball