natural breaks helper function

    Jenks natural breaks is kmeans in one dimension
325228
def natural_breaks(values, k=5):
    
    values = np.array(values)
    uv = np.unique(values)
    uvk = len(uv)
    if uvk < k:
        Warn('Warning: Not enough unique values in array to form k classes',
             UserWarning)
        Warn('Warning: setting k to %d' % uvk, UserWarning)
        k = uvk
    kres = _kmeans(values, k)
    sids = kres[-1]  # centroids
    fit = kres[-2]
    class_ids = kres[0]
    cuts = kres[1]
    return (sids, class_ids, fit, cuts)
429349
def AchillesHeel(*xs, simplify=True):
    
    """
    nargs = len(xs)
    if nargs & 1:
        fstr = "expected an even number of arguments, got {}"
        raise ValueError(fstr.format(nargs))
    xs = [Expression.box(x).node for x in xs]
    y = exprnode.and_(*[exprnode.or_(xs[2*i], xs[2*i+1])
                        for i in range(nargs // 2)])
    if simplify:
        y = y.simplify()
    return _expr(y)
545758
def _full(self, k):
        
        G = np.ones((self.m, self.m))
        #np.fill_diagonal(G, 0) # erroneous code from prefpy
        return G
752544
def astensor(array: TensorLike) -> BKTensor:
    
    array = np.asarray(array, dtype=CTYPE)
    return array
1231533
def _kmeans(X, n_clusters, max_iter, n_trials, tol):
    
    n_samples, n_features = X.shape[0], X.shape[1]

    centers_best = np.empty(shape=(n_clusters,n_features), dtype=float)
    labels_best  = np.empty(shape=n_samples, dtype=int)
    for i in range(n_trials):
        centers, labels, sse_tot, sse_arr, n_iter  = _kmeans_run(X, n_clusters, max_iter, tol)
        if i==0:
            sse_tot_best = sse_tot
            sse_arr_best = sse_arr
            n_iter_best = n_iter
            centers_best = centers.copy()
            labels_best  = labels.copy()
        if sse_tot < sse_tot_best:
            sse_tot_best = sse_tot
            sse_arr_best = sse_arr
            n_iter_best = n_iter
            centers_best = centers.copy()
            labels_best  = labels.copy()

    return(centers_best, labels_best, sse_arr_best, n_iter_best)
882793
function breakNodes()
			{
				var startPath = new CKEDITOR.dom.elementPath( startNode.getParent() ),
					endPath = new CKEDITOR.dom.elementPath( endNode.getParent() ),
					breakStart = null,
					breakEnd = null;
				for ( var i = 0 ; i < startPath.elements.length ; i++ )
				{
					var element = startPath.elements[ i ];

					if ( element == startPath.block || element == startPath.blockLimit )
						break;

					if ( me.checkElementRemovable( element ) )
						breakStart = element;
				}
				for ( i = 0 ; i < endPath.elements.length ; i++ )
				{
					element = endPath.elements[ i ];

					if ( element == endPath.block || element == endPath.blockLimit )
						break;

					if ( me.checkElementRemovable( element ) )
						breakEnd = element;
				}

				if ( breakEnd )
					endNode.breakParent( breakEnd );
				if ( breakStart )
					startNode.breakParent( breakStart );
			}
497078
def _rspiral(width, height):
        

        x0 = 0
        y0 = 0
        x1 = width - 1
        y1 = height - 1

        while x0 < x1 and y0 < y1:
            for x in range(x0, x1):
                yield x, y0
            for y in range(y0, y1):
                yield x1, y
            for x in range(x1, x0, -1):
                yield x, y1
            for y in range(y1, y0, -1):
                yield x0, y

            x0 += 1
            y0 += 1
            x1 -= 1
            y1 -= 1

        if x0 == x1:
            for y in range(y0, y1 + 1):
                yield x0, y
        elif y0 == y1:
            for x in range(x0, x1 + 1):
                yield x, y0
861117
def _kmeans(y, k=5):
    

    y = y * 1.  # KMEANS needs float or double dtype
    centroids = KMEANS(y, k)[0]
    centroids.sort()
    try:
        class_ids = np.abs(y - centroids).argmin(axis=1)
    except:
        class_ids = np.abs(y[:, np.newaxis] - centroids).argmin(axis=1)

    uc = np.unique(class_ids)
    cuts = np.array([y[class_ids == c].max() for c in uc])
    y_cent = np.zeros_like(y)
    for c in uc:
        y_cent[class_ids == c] = centroids[c]
    diffs = y - y_cent
    diffs *= diffs

    return class_ids, cuts, diffs.sum(), centroids
139840
public static double[] breaks(double min, double max, int k) {
        if (k <= 1) {
            throw new IllegalArgumentException("Invalid number of bins: " + k);
        }

        if (min > max) {
            throw new IllegalArgumentException("Invalid lower and upper bounds: " + min + " > " + max);
        }
        
        double h = (max - min) / k;
        return breaks(min, max, h);
    }
125847
function _reduce (mat, dim, callback) {
  let i, ret, val, tran

  if (dim <= 0) {
    if (!Array.isArray(mat[0])) {
      val = mat[0]
      for (i = 1; i < mat.length; i++) {
        val = callback(val, mat[i])
      }
      return val
    } else {
      tran = _switch(mat)
      ret = []
      for (i = 0; i < tran.length; i++) {
        ret[i] = _reduce(tran[i], dim - 1, callback)
      }
      return ret
    }
  } else {
    ret = []
    for (i = 0; i < mat.length; i++) {
      ret[i] = _reduce(mat[i], dim - 1, callback)
    }
    return ret
  }
}
738226
private PolynomialApproximation approximateKnnDistances(double[] knnDistances) {
    StringBuilder msg = new StringBuilder();

    // count the zero distances (necessary of log-log space is used)
    int k_0 = 0;
    if(settings.log) {
      for(int i = 0; i < settings.kmax; i++) {
        double dist = knnDistances[i];
        if(dist == 0) {
          k_0++;
        }
        else {
          break;
        }
      }
    }

    double[] x = new double[settings.kmax - k_0];
    double[] y = new double[settings.kmax - k_0];

    for(int k = 0; k < settings.kmax - k_0; k++) {
      if(settings.log) {
        x[k] = FastMath.log(k + k_0);
        y[k] = FastMath.log(knnDistances[k + k_0]);
      }
      else {
        x[k] = k + k_0;
        y[k] = knnDistances[k + k_0];
      }
    }

    PolynomialRegression regression = new PolynomialRegression(y, x, settings.p);
    PolynomialApproximation approximation = new PolynomialApproximation(regression.getEstimatedCoefficients());

    if(LOG.isDebugging()) {
      msg.append("approximation ").append(approximation);
      LOG.debugFine(msg.toString());
    }
    return approximation;

  }
74394
function kmp(s, w) {
    if (kmp.isNumber(w)) w = ''+w;
    if (kmp.isNumber(s)) s = ''+s;
    if (!(kmp.isString(s) || kmp.isArray(s))) return -1;
    if (!(kmp.isString(w) || kmp.isArray(w))) return -1;
    var m = 0; // start of s
    var i = 0; // start of w
    var t = kmp.table(w);

    while (m + i < s.length) {
      if (w[i] === s[m+i]) {
        if (i === w.length - 1) {
          return m;
        }
        i = i + 1;
      } else {
        if (t[i] > -1) {
          m = m+i - t[i];
          i = t[i];
        } else {
          i = 0;
          m = m + 1;
        }
      }
    }

    return -1;
  }
74100
function hessenbergQRStep (M) {
  const n = M.dimension;
  const me = M.elements;
  const csr = [0, 0, 0];
  const cs = [];
  for (let k = 0; k < n - 1; ++k) {
    const row1 = k;
    const row2 = k + 1;
    const colK = k * n;
    const a = me[row1 + colK];
    const b = me[row2 + colK];
    rotg(a, b, csr);
    const c = csr[0];
    const s = csr[1];
    const r = csr[2];
    cs[k] = [c, s];
    for (let x = k; x < n; ++x) {
      const colX = x * n;
      const tmp1 = me[row1 + colX];
      const tmp2 = me[row2 + colX];
      me[row1 + colX] = c * tmp1 + s * tmp2;
      me[row2 + colX] = -s * tmp1 + c * tmp2;
    }
    me[row1 + colK] = r;
    me[row2 + colK] = 0;
  }
  for (let k = 0; k < n - 1; ++k) {
    const col1 = k * n;
    const col2 = (k + 1) * n;
    const [c, s] = cs[k];
    for (let x = 0; x <= k + 1; ++x) {
      const rowX = x;
      const tmp1 = me[rowX + col1];
      const tmp2 = me[rowX + col2];
      me[rowX + col1] = tmp1 * c + tmp2 * s;
      me[rowX + col2] = -tmp1 * s + tmp2 * c;
    }
  }
  return M;
}
210928
@Override
  protected void linearScanBatchKNN(List<O> objs, List<KNNHeap> heaps) {
    final SquaredEuclideanDistanceFunction squared = SquaredEuclideanDistanceFunction.STATIC;
    final Relation<? extends O> relation = getRelation();
    final int size = objs.size();
    // Linear scan style KNN.
    for(DBIDIter iter = relation.getDBIDs().iter(); iter.valid(); iter.advance()) {
      O candidate = relation.get(iter);
      for(int index = 0; index < size; index++) {
        final KNNHeap heap = heaps.get(index);
        final double dist = squared.distance(objs.get(index), candidate);
        if(dist <= heap.getKNNDistance()) {
          heap.insert(dist, iter);
        }
      }
    }
  }
61491
function mmult(A, B, n) {
  var C = new Array(n * n);

  for (var i = 0; i < n; i++) {
    for (var j = 0; j < n; j++) {
      C[i * n + j] = 0;
    }

    for (var k = 0; k < n; k++) {
      for (var _j = 0; _j < n; _j++) {
        C[i * n + _j] += A[i * n + k] * B[k * n + _j];
      }
    }
  }

  return C;
}
1331586
def arange(start,stop,step=1,**kwargs):
    
    expand_value = 1 if step > 0 else -1
    return matlabarray(np.arange(start,
                                 stop+expand_value,
                                 step,
                                 **kwargs).reshape(1,-1),**kwargs)
1098827
def natural_neighbor(xp, yp, variable, grid_x, grid_y):
    """"""
    return natural_neighbor_to_grid(xp, yp, variable, grid_x, grid_y)