Esempio n. 1
0
def find_enclosing_circle(t):
    """Find center of trajectories

    It first tries to use external library miniball. If it fails, it resorts
    to a simpler algorithm.

    :param t: trajectory
    """
    try:
        import miniball
        assert not np.isnan(t).any()
        flat_t = t.reshape((-1, 2))
        P = [(x[0], x[1]) for x in flat_t]
        mb = miniball.Miniball(P)
        center_x, center_y = mb.center()
        radius = np.sqrt(mb.squared_radius())
    except ImportError:
        logging.warning("Miniball was not used for centre detection")
        logging.warning("Please, install https://github.com/weddige/miniball")
        center_x, center_y, radius = find_enclosing_circle_simple(t)
    except Exception:
        logging.error(traceback.format_exc())
        logging.error("Miniball was not used for centre detection")
        center_x, center_y, radius = find_enclosing_circle_simple(t)
    return center_x, center_y, radius
Esempio n. 2
0
def find_bounding_sphere(mrc, L):
    v = AIF.read_mrc(mrc)

    points = []
    density_max = v.max()
    contour_level = L * density_max
    for ijk in np.ndindex(v.shape):
        if v[ijk] >= contour_level:
            points.append([float(ijk[0]), float(ijk[1]), float(ijk[2])])

    points = np.asarray(points)

    # return boundingSphere.find_min_bounding_sphere(points)
    return miniball.Miniball(points)
Esempio n. 3
0
    def _normalizeMesh(self):
        mb = miniball.Miniball(iglhelpers.e2p(self._V))
        scale = BOUNDING_SPHERE_RADIUS / math.sqrt(mb.squared_radius())

        T = igl.eigen.Affine3d()
        T.setIdentity()
        T.translate(
            igl.eigen.MatrixXd([
                -mb.center()[0] * scale, -mb.center()[1] * scale,
                -mb.center()[2] * scale
            ]))
        print("[INFO] scaled down by", scale)
        Vscale = T.matrix().block(0, 0, 3, 3).transpose()
        Vtrans = igl.eigen.MatrixXd(self._V.rows(), self._V.cols())
        Vtrans.rowwiseSet(T.matrix().block(0, 3, 3, 1).transpose())

        self._V = (self._V * Vscale) * scale + Vtrans
Esempio n. 4
0
def find_enclosing_circle(t):
    """Find center of trajectories

    It first tries to use external library miniball. If it fails, it resorts
    to a simpler algorithm.

    :param t: trajectory
    """
    try:
        import miniball

        if not np.isnan(t).any():
            flat_t = t.reshape((-1, 2))
        else:
            flat_t_with_nans = t.reshape((-1, 2))
            no_nans = np.logical_not(np.any(np.isnan(flat_t_with_nans),
                                            axis=1))
            flat_t = flat_t_with_nans[np.where(no_nans)]
            logging.warning(
                "Some nans found and removed before aplying miniball")
        P = [(x[0], x[1]) for x in flat_t]
        mb = miniball.Miniball(P)
        center_x, center_y = mb.center()
        radius = np.sqrt(mb.squared_radius())
    except ImportError:
        logging.warning("Miniball was not used for centre detection")
        logging.warning("Please, install https://github.com/weddige/miniball")
        center_x, center_y, radius = find_enclosing_circle_simple(t)
    except Exception:
        # logging.error(traceback.format_exc())
        # print(sys.exc_info()[0])
        traceback.print_stack()
        logging.error(
            "Miniball was not used for centre detection. Reason unknown")
        center_x, center_y, radius = find_enclosing_circle_simple(t)
    return center_x, center_y, radius
Esempio n. 5
0
                    embedding_weights[index, :] = np.random.rand(
                        1, embeddings_dim)
                    affective_weights[index, :] = [5.0, 5.0, 5.0]

        log.write("Computing features based on semantic volume...\n")
        train_features = np.zeros((train_matrix.shape[0], 1))
        test_features = np.zeros((test_matrix.shape[0], 1))
        for i in range(train_features.shape[0]):
            aux = []
            for word in train_texts[i].split(" "):
                try:
                    aux.append(embeddings[word])
                except:
                    continue
            if len(aux) > 0:
                train_features[i, 0] = miniball.Miniball(
                    np.array(aux)).squared_radius()
        for i in range(test_features.shape[0]):
            aux = []
            for word in test_texts[i].split(" "):
                try:
                    aux.append(embeddings[word])
                except:
                    continue
            if len(aux) > 0:
                test_features[i, 0] = miniball.Miniball(
                    np.array(aux)).squared_radius()

        log.write("Computing features based on affective scores...\n")
        train_features_avg = np.zeros((train_matrix.shape[0], 3))
        test_features_avg = np.zeros((test_matrix.shape[0], 3))
        train_features_stdev = np.zeros((train_matrix.shape[0], 3))
Esempio n. 6
0
# Original author: Bastian Rieck

import itertools
import math
import miniball
import sys

if __name__ == "__main__":
  filename  = sys.argv[1]
  radius    = float(sys.argv[2])
  dimension = int(sys.argv[3])
  points    = list()

  with open(filename) as f:
    for line in f:
      coordinates = [ float(x) for x in line.split() ]
      points.append( coordinates )

  n       = len(points)
  indices = list(range(0,n))

  for d in range(0,dimension+1):
    for simplex in itertools.combinations(indices, d):
      if len(simplex) >= 1:
        P = [ tuple( points[i] ) for i in simplex ] # points
        B = miniball.Miniball(P)                    # minimum enclosing ball
        r = math.sqrt( B.squared_radius() )         # radius

        if r <= radius:
          print(simplex)
Esempio n. 7
0
    def find_max_set_inliers(self,
                             X,
                             xm=None,
                             Xall=None,
                             n_indices=None,
                             plot_em=False,
                             min_inliers=0,
                             inlier_eps=None):

        distance_threshold = np.sqrt(2 * self.T * (1 - self.corr_threshold))

        if inlier_eps is None:
            inlier_eps = distance_threshold * 1.25

        N = X.shape[0]
        inliers = list(range(N))

        radius = np.inf

        keep_ptg_large_step = max(int(len(inliers) * 0.3), 1)
        keep_ptg_medium_step = max(int(len(inliers) * 0.16), 1)
        keep_ptg_small_step = max(int(len(inliers) * 0.05), 1)

        if self.super_intense_search:
            keep_ptg_large_step = max(int(len(inliers) * 0.15 * 0.5), 1)
            keep_ptg_medium_step = max(int(len(inliers) * 0.08 * 0.5), 1)
            keep_ptg_small_step = max(int(len(inliers) * 0.025 * 0.5), 1)

        if xm is not None:
            inliers = []
            for i in range(N):
                if np.linalg.norm(xm - X[i, :]) <= inlier_eps:
                    inliers.append(i)

        if inliers is None or len(inliers) == 0:
            inliers = list(range(N))

        mb = miniball.Miniball(X[inliers, :])
        radius = math.sqrt(mb.squared_radius())

        tightest_radius = distance_threshold * np.sqrt(self.T / (2 *
                                                                 (self.T + 1)))
        while radius > tightest_radius:
            if xm is None:
                xm = np.mean(X[inliers, :], axis=0)

            Xh = np.matlib.repmat(xm, len(inliers), 1)
            XD = Xh - X[inliers, :]
            XD2 = np.power(XD, 2)
            D = np.sqrt(np.sum(XD2, axis=1))

            mb = miniball.Miniball(X[inliers, :])

            if radius / tightest_radius > 1.20:
                keep_ptg = keep_ptg_large_step
            elif radius / tightest_radius > 1.15:
                keep_ptg = keep_ptg_medium_step
            else:
                keep_ptg = keep_ptg_small_step

            outliers = np.argsort(-D)[0:keep_ptg]
            outliers = np.sort(outliers)[::-1]

            for outlier in outliers:
                inliers.pop(outlier)

            if len(inliers) <= 1:
                break

            if len(inliers) < min_inliers:
                inliers = []
                break

            mb = miniball.Miniball(X[inliers, :])
            radius = math.sqrt(mb.squared_radius())

        radd_diff = tightest_radius - distance_threshold * 0.5

        num_iter = 0
        for i in range(len(inliers)):

            num_iter += 1
            Xh = np.matlib.repmat(mb.center(), len(inliers), 1)
            XD = Xh - X[inliers, :]
            XD2 = np.power(XD, 2)
            dists = np.sqrt(np.sum(XD2, axis=1))

            rem_idx = np.where(np.abs(dists - radius) < radd_diff)[0]
            Xred = X[np.array(inliers)[rem_idx]]
            d2 = scipy.spatial.distance.pdist(Xred, 'Euclidean')
            D2 = scipy.spatial.distance.squareform(d2)
            ### C2 = np.corrcoef(Xred)

            if np.max(D2) <= distance_threshold:
                break
            d2mean = np.mean(D2, axis=0)
            tmp = np.where(D2 >= distance_threshold)
            to_remove = []

            elems = []
            vals = []

            for ii in range(len(tmp[0])):
                ptx = tmp[0][ii]
                pty = tmp[1][ii]

                if d2mean[ptx] > d2mean[pty]:
                    elem = rem_idx[ptx]
                else:
                    elem = rem_idx[pty]

                if elem in elems:
                    continue
                elems.append(elem)
                vals.append(D2[ptx, pty])

            vals = np.array(vals)
            sidx = np.argsort(vals)[::-1]

            Nto_remove = max([1, int(2 * len(sidx) / 3)])

            if Nto_remove <= 2:
                Nto_remove = 1
            to_remove = np.array(elems)[sidx[0:Nto_remove]]
            to_remove = np.sort(np.array(to_remove))[::-1]

            for remove_idx in to_remove:
                inliers.pop(remove_idx)
            mb = miniball.Miniball(X[inliers, :])
            radius = math.sqrt(mb.squared_radius())

        # This is for debugging purposes
        # Need to uncomment C2 up above before runnning this
        print_output = False

        if print_output and len(inliers) > 0 and len(C2.shape) > 0:
            if C2.shape[0] > 0:
                print('DIST (ALLOWED): %.2f (%.2f)' %
                      (np.max(D2), distance_threshold))
                print('Corr: %.2f' % (np.min(C2)))

        return (inliers, radius, xm)