Fit a plane to values in input array
17621
def ma_fitpoly(bma, order=1, gt=None, perc=(2,98), origmask=True):
    
    if gt is None:
        gt = [0, 1, 0, 0, 0, -1] 
    #Filter, can be useful to remove outliers
    if perc is not None:
        from pygeotools.lib import filtlib
        bma_f = filtlib.perc_fltr(bma, perc)
    else:
        bma_f = bma
    #Get indices
    x, y = get_xy_ma(bma_f, gt, origmask=origmask)
    #Fit only where we have valid data
    bma_mask = np.ma.getmaskarray(bma)
    coeff = polyfit2d(x[~bma_mask].data, y[~bma_mask].data, bma[~bma_mask].data, order=order) 
    #For 1D, these are: c, y, x, xy
    print(coeff)
    #Compute values for all x and y, unless origmask=True
    vals = polyval2d(x, y, coeff) 
    resid = bma - vals
    return vals, resid, coeff
436547
def create_horizontal_plane():
    '''
    
    '''
    v = np.array([
        [1., 0., 0.],
        [-1., 0., 0.],
        [0., 0., 1.],
        [0., 0., -1.]
    ])
    f = [[0, 1, 2], [3, 1, 0]]
    return Mesh(v=v, f=f)
561028
def process_values(self):
        """"""

        if self.padding>0:
            channels = np.zeros((self.vals.shape[0], self.vals.shape[1]+self.padding))
            channels[:, 0:self.vals.shape[0]] = self.vals
        else:
            channels = self.vals
        vals_mat = self.skel.to_xyz(channels.flatten())
        self.vals = np.zeros_like(vals_mat)
        # Flip the Y and Z axes
        self.vals[:, 0] = vals_mat[:, 0].copy()
        self.vals[:, 1] = vals_mat[:, 2].copy()
        self.vals[:, 2] = vals_mat[:, 1].copy()
1226472
def splinefit2d(x, y, z, px, py, mask=None):
    ''''''
    
    if mask is None:
        V = np.array(spline_matrix2d(x, y, px, py))
        a = np.array(z.T.flatten())
        pz = np.linalg.lstsq(V.T, a.T)[0].T
    else:
        V = np.array(spline_matrix2d(x,y,px,py,mask))
        indices = np.nonzero(np.array(mask).T.flatten())
        if len(indices[0])==0:
            pz = np.zeros((len(py),len(px)))
        #indices is empty when mask changes to all zeros
        else:
            a = np.array((z.T.flatten()[indices[0]]))
            pz = np.linalg.lstsq(V.T, a.T)[0].T
            
    pz=pz.reshape((len(py),len(px)))
    return pz.transpose()
931908
public void fit(INDArray x) {
        this.data = x;
        for(int i = 0; i < numTrees; i++) {
            RPTree tree = new RPTree(data.columns(),maxSize,similarityFunction);
            tree.buildTree(x);
            trees.add(tree);
        }
    }
1056643
def fromarray(A):
    """"""
    subs = np.nonzero(A)
    vals = A[subs]
    return sptensor(subs, vals, shape=A.shape, dtype=A.dtype)
1137855
def delaunay_2d(self, tol=1e-05, alpha=0.0, offset=1.0, bound=False, inplace=False):
        """"""
        alg = vtk.vtkDelaunay2D()
        alg.SetProjectionPlaneMode(vtk.VTK_BEST_FITTING_PLANE)
        alg.SetInputDataObject(self)
        alg.SetTolerance(tol)
        alg.SetAlpha(alpha)
        alg.SetOffset(offset)
        alg.SetBoundingTriangulation(bound)
        alg.Update()

        mesh = _get_output(alg)
        if inplace:
            self.overwrite(mesh)
        else:
            return mesh
500742
def fromfits(infilename, hdu = 0, verbose = True):
    
    
    pixelarray, hdr = pyfits.getdata(infilename, hdu, header=True)
    pixelarray = np.asarray(pixelarray).transpose()
    
    pixelarrayshape = pixelarray.shape
    if verbose :
        print "FITS import shape : (%i, %i)" % (pixelarrayshape[0], pixelarrayshape[1])
        print "FITS file BITPIX : %s" % (hdr["BITPIX"])
        print "Internal array type :", pixelarray.dtype.name
    
    return pixelarray, hdr
329155
def array_map(f, ar):
    ""
    flat_ar = ravel(ar)
    out = zeros(len(flat_ar), flat_ar.typecode())
    for i in range(len(flat_ar)):
        out[i] = f(flat_ar[i])
    out.shape = ar.shape
    return out
112974
function makePlane(u, v, w, su, sv, nu, nv, pw, flipu, flipv) {
    var vertShift = vertexIndex;
    for (var j=0; j<=nv; j++) {
      for (var i=0; i<=nu; i++) {
        vert = vertices[vertexIndex] = Vec3.create();
        vert[u] = (-su / 2 + i * su / nu) * flipu;
        vert[v] = (-sv / 2 + j * sv / nv) * flipv;
        vert[w] = pw;
        normal = normals[vertexIndex] = Vec3.create();
        normal[u] = 0;
        normal[v] = 0;
        normal[w] = pw / Math.abs(pw);
        texCoord = texCoords[vertexIndex] = Vec2.create();
        texCoord.x = i / nu;
        texCoord.y = 1.0 - j / nv;
        ++vertexIndex;
      }
    }
    for (var j=0; j<=nv-1; j++) {
      for (var i=0; i<=nu-1; i++) {
        var n = vertShift + j * (nu + 1) + i;
        faces.push([n, n + nu + 1, n + nu + 2, n + 1]);
      }
    }
  }
975472
def map_fit(interface, state, label, inp):
    
    import numpy as np
    out = interface.output(0)

    H, J, grad = 0, 0, 0
    for row in inp:
        row = row.strip().split(state["delimiter"])  # split row
        if len(row) > 1:  # check if row is empty
            # add intercept term to every sample
            x = np.array([1] + [(0 if v in state["missing_vals"] else float(v)) for i, v in enumerate(row) if
                                i in state["X_indices"]])
            # map label value to 0 or 1. If label does not match set error
            y = 0 if state["y_map"][0] == row[state["y_index"]] else 1 if state["y_map"][1] == row[
                state["y_index"]] else "Error"

            g = 1. / (1 + np.exp(-np.dot(x, state["thetas"])))  # sigmoid function
            grad += x * (g - y)  # gradient
            H += np.multiply(np.outer(x, x), g * (1 - g))  # Hessian matrix
            J -= np.log(g) if y == 1 else np.log(1 - g)  # J cost function
    out.add("grad", grad)
    out.add("J", J)
    for i, row in enumerate(H):
        out.add(i, row)
84752
def Rectangle(p1=(0, 0, 0), p2=(2, 1, 0), c="k", bc="dg", lw=1, alpha=1, texture=None):
    """"""
    p1 = np.array(p1)
    p2 = np.array(p2)
    pos = (p1 + p2) / 2
    length = abs(p2[0] - p1[0])
    height = abs(p2[1] - p1[1])
    return Plane(pos, [0, 0, -1], length, height, c, bc, alpha, texture)
362056
def best_fit_plane(self):
        
        X = np.c_[self.x_coords, self.y_coords, np.ones(self.num_points)]
        y = self.z_coords
        A = X.T.dot(X)
        b = X.T.dot(y)
        w = np.linalg.inv(A).dot(b)
        n = np.array([w[0], w[1], -1])
        n = n / np.linalg.norm(n)
        n = Direction(n, self._frame)
        x0 = self.mean()
        return n, x0
923043
def best_fit(li, value):
    """"""

    index = min(bisect_left(li, value), len(li) - 1)

    if index in (0, len(li)):
        return index

    if li[index] - value < value - li[index-1]:
        return index
    else:
        return index-1
1089300
def get_array_shape(self, key):
        """"""
        data = self.model.get_data()
        return data[key].shape
40375
def _bounds_to_array(bounds):
    """"""
    elements = []
    for value in bounds:
        if all_elements_equal(value):
            elements.append(Scalar(get_single_value(value), ctype='mot_float_type'))
        else:
            elements.append(Array(value, ctype='mot_float_type', as_scalar=True))
    return CompositeArray(elements, 'mot_float_type', address_space='local')
193451
def fit(self, x):
        
        assert x.ndim > 1
        self.data_min_ = np.min(x, axis=tuple(range(x.ndim - 1)))
        self.data_max_ = np.max(x, axis=tuple(range(x.ndim - 1)))

        if self.share_knots:
            self.data_min_[:] = np.min(self.data_min_)
            self.data_max_[:] = np.max(self.data_max_)