Esempio n. 1
0
 def clusters2hulls(self):
     """
     calculates a convex hull for each cluster.
     @return:
     """
     hulls = []
     n_clusters = self.total_clusters
     cluster_points = self.cluster_points
     for i in range(n_clusters):
         if len(cluster_points[i]) > 2:
             hull = ConvexHull(cluster_points[i])
         else:
             point = ogr.Geometry(ogr.wkbPoint)
             point.AddPoint(cluster_points[i][0][0], cluster_points[i][0][1])
             buffer = point.Buffer(0.01)
             boundary = buffer.Boundary()
             bufPoints = []
             for i in range(boundary.GetPointCount()):
                 x, y, not_needed = boundary.GetPoint(i)
                 bufPoints.append([x,y])
             hull = ConvexHull(bufPoints)
         '''else:
             self.total_clusters = self.total_clusters-1'''
         hulls.append(hull)
     self.cluster_hulls = hulls
Esempio n. 2
0
 def triangulate_surface_points(self):
     """Handles triangulation of surface points using QuickHull."""
     if self.is_hole:
         chull = ConvexHull(self.points)
         self.points, self.tris = chull.points, chull.simplices
     else:
         chull_points = np.vstack((self.points, self.i_loop_points(),
                                   self.i_loop_origin_points()))
         chull = ConvexHull(chull_points)
         surf_tris = self.extract_surface_tris_from_chull(chull)
         self.points, self.tris = reindex_tris(chull.points, surf_tris)
Esempio n. 3
0
    def __init__(self, pts_in: np.ndarray, expand: bool = True):
        """
        Parameters
        ----------
        pts_in : a 2d array of points/coordinates for the pores
        expand : Whether to add 1 to each combination of dimensions
            to make pore 3d
        """
        assert len(pts_in.shape) == 2, "pts must be 2d"
        self.pts_in = pts_in

        if expand:
            n_dims = pts_in.shape[1]
            pts = [pts_in]

            for i in range(1, n_dims + 1):
                combs = combinations(range(n_dims), i)

                for comb in combs:
                    x = pts_in.copy()
                    x[:, comb] += 1
                    pts.append(x)
            self.pts = pd.DataFrame(np.concatenate(
                pts, axis=0)).drop_duplicates().values
        else:
            self.pts = pts_in
        self.convex_hull: ConvexHull = ConvexHull(self.pts)
        self.ellipsoid: Ellipsoid = self.et.getMinVolEllipse(self.pts)
Esempio n. 4
0
 def __call__(self, data):
     if data.domain != self.domain:
         data = data.from_table(self.domain, data)
     xs, xsind, mon, X = _transform_to_sorted_features(data)
     x = xs[xsind]
     newd = np.zeros_like(data.X)
     for rowi, row in enumerate(X):
         # remove NaNs which ConvexHull can not handle
         source = np.column_stack((x, row))
         source = source[~np.isnan(source).any(axis=1)]
         try:
             v = ConvexHull(source).vertices
         except QhullError:
             # FIXME notify user
             baseline = np.zeros_like(row)
         else:
             if self.peak_dir == RubberbandBaseline.PeakPositive:
                 v = np.roll(v, -v.argmin())
                 v = v[:v.argmax() + 1]
             elif self.peak_dir == RubberbandBaseline.PeakNegative:
                 v = np.roll(v, -v.argmax())
                 v = v[:v.argmin() + 1]
             # If there are NaN values at the edges of data then convex hull
             # does not include the endpoints. Because the same values are also
             # NaN in the current row, we can fill them with NaN (bounds_error
             # achieves this).
             baseline = interp1d(source[v, 0],
                                 source[v, 1],
                                 bounds_error=False)(x)
         finally:
             if self.sub == 0:
                 newd[rowi] = row - baseline
             else:
                 newd[rowi] = baseline
     return _transform_back_to_features(xsind, mon, newd)
Esempio n. 5
0
def makeConvexHull(points, incremental=False, qhull_options=None):
    hull = ConvexHull(points, incremental=False, qhull_options=None)
    convexHullList = []
    for j in hull.vertices:
        convexHullList.append([points[j][0], points[j][1]])
    convexHullArray = np.array(convexHullList)
    return convexHullArray
Esempio n. 6
0
    def get_convex_hull_area(self, composition_space):
        """
        Prints out the area or volume of the convex hull defined by the
        organisms in the promotion set.
        """

        # make a phase diagram of just the organisms in the promotion set
        # (on the lower convex hull)
        pdentries = []
        for organism in self.promotion_set:
            pdentries.append(
                PDEntry(organism.composition, organism.total_energy))
        compound_pd = CompoundPhaseDiagram(pdentries,
                                           composition_space.endpoints)

        # get the data for the convex hull
        qhull_data = compound_pd.qhull_data
        # for some reason, the last point is positive, so remove it
        hull_data = np.delete(qhull_data, -1, 0)

        # make a ConvexHull object from the hull data
        try:
            convex_hull = ConvexHull(hull_data)
        except:
            return None
        if len(composition_space.endpoints) == 2:
            return convex_hull.area
        else:
            return convex_hull.volume
Esempio n. 7
0
def get_skyline(
    selection: pd.DataFrame,
    columns: List[str],
    smaller_is_better: Tuple[bool, ...],
):
    """
    Finds the skyline which contains all entries which are not dominated by another entry.

    :param columns: name of columns of the skyline
    :param selection: numpy.ndarray, shape: (n_eval, d), dtype: numpy.float
        A selection of entries which will be reduced to the skyline.
    :param smaller_is_better:
        Whether smaller or larger values are better.

    :return: The skyline.
    """
    # pylint: disable=unsubscriptable-object
    x = selection[columns].values.copy()

    # skyline candidates can only be found in the convex hull
    hull = ConvexHull(x)
    candidates = hull.vertices
    x = x[candidates]

    # turn sign for values where smaller is better => larger is always better
    x[:, smaller_is_better] *= -1

    # x[i, :] is dominated by x[j, :] if stronger(x[i, k], x[j, k]).all()
    # the skyline consists of points which are **not** dominated
    selected_candidates, = (
        ~(x[:, None, :] < x[None, :, :]).all(axis=-1).any(axis=1)).nonzero()
    return selection.iloc[[candidates[i] for i in selected_candidates
                           ]].sort_values(by=columns)
Esempio n. 8
0
def calc_bounding_rec(shape: float):
    ch = ConvexHull(circles)
    cur_max_volume = 0
    for i in range(ch.nsimplex):
        # initialize current max distance on both directions
        cur_max_dist_axis = 0
        cur_dist_perps = []
        for j in range(num):
            cur_edge = ch.equations[i]
            dist_axis = -(cur_edge[0] * circles[j][0] +
                          cur_edge[1] * circles[j][1] + cur_edge[2])
            if dist_axis > cur_max_dist_axis:
                cur_max_dist_axis = dist_axis
            dist_perp = cur_edge[1] * circles[j][0] - cur_edge[0] * circles[j][
                1]
            cur_dist_perps.append(dist_perp)
        # both "+1" since we are considering circle centres before, and diameter = 1
        cur_max_dist_axis += 1
        cur_max_dist_perp = max(cur_dist_perps) - min(cur_dist_perps) + 1
        # handle squares independently
        if shape == 1:
            cur_volume = np.power(max(cur_max_dist_axis, cur_max_dist_perp), 2)
        # not a square
        elif cur_max_dist_axis > shape * cur_max_dist_perp:
            cur_volume = np.power(cur_max_dist_axis, 2) * shape
        elif cur_max_dist_perp > shape * cur_max_dist_axis:
            cur_volume = np.power(cur_max_dist_perp, 2) * shape
        else:
            cur_volume = np.power(min(cur_max_dist_axis, cur_max_dist_perp),
                                  2) * shape
        if cur_volume > cur_max_volume:
            cur_max_volume = cur_volume
    return cur_max_volume
Esempio n. 9
0
def _get_volume(indices, vertices):
    if -1 in indices:
        # some regions can be open
        return np.inf

    else:
        return ConvexHull(vertices).volume
Esempio n. 10
0
 def transformed(self, X, x):
     newd = np.zeros_like(X)
     for rowi, row in enumerate(X):
         # remove NaNs which ConvexHull can not handle
         source = np.column_stack((x, row))
         source = source[~np.isnan(source).any(axis=1)]
         try:
             v = ConvexHull(source).vertices
         except (QhullError, ValueError):
             # FIXME notify user
             baseline = np.zeros_like(row)
         else:
             if self.peak_dir == RubberbandBaseline.PeakPositive:
                 v = np.roll(v, -v.argmin())
                 v = v[:v.argmax() + 1]
             elif self.peak_dir == RubberbandBaseline.PeakNegative:
                 v = np.roll(v, -v.argmax())
                 v = v[:v.argmin() + 1]
             # If there are NaN values at the edges of data then convex hull
             # does not include the endpoints. Because the same values are also
             # NaN in the current row, we can fill them with NaN (bounds_error
             # achieves this).
             baseline = interp1d(source[v, 0],
                                 source[v, 1],
                                 bounds_error=False)(x)
         finally:
             if self.sub == 0:
                 newd[rowi] = row - baseline
             else:
                 newd[rowi] = baseline
     return newd
Esempio n. 11
0
def mc_met(shape: float, acc: float, stick_rate: float):
    mover = np.random.randint(num)
    if is_pinned(mover):
        mover = np.random.randint(num)
    mover_old_parameter = (circles[mover][0], circles[mover][1])
    print("Old location: ", mover_old_parameter)
    old_energy = calc_bounding_rec(shape)
    print("Old energy: ", old_energy)

    pivots = []
    for i in range(num):
        if adj_matrix[i][mover] == 0:
            pivots.append(i)

    if not pivots or len(
            pivots) == 1:  # TODO split this to detect lone pair move
        ch = ConvexHull(circles)
        for j in range(len(ch.vertices)):
            pivots.append(j)
    # TODO lone pair move
    if len(pivots) == 1:
        ch = ConvexHull(circles)

    k = np.random.randint(len(pivots))
    pivot = pivots[k]

    mover_new_parameter = step(mover, pivot, stick_rate)
    circles[mover] = mover_new_parameter
    print("New location: ", mover_new_parameter)
    new_energy = calc_bounding_rec(shape)
    print("New energy: ", new_energy)

    if new_energy - old_energy <= 1e-6:
        print("Taking step with energy falling.")
        calc_adj_matrix()
        return new_energy
    else:
        threshold = np.power(np.e, (new_energy - old_energy) * -acc)
        accept = np.random.rand()
        if accept < threshold:
            print("Taking step with energy raising.")
            calc_adj_matrix()
            return new_energy
        else:
            print("Refusing step with energy raising.")
            circles[mover] = mover_old_parameter
            return old_energy
Esempio n. 12
0
 def compute_diameter(self):
     coordinates = np.ndarray((0, 3))
     for residue in self.residues:
         coordinates = np.vstack((coordinates, residue.get_coordinates()))
     hull = ConvexHull(coordinates)
     boundary = coordinates[hull.vertices]
     diam = np.max(cdist(boundary, boundary))
     return diam
Esempio n. 13
0
def _create_mesh(points,
                 color="black",
                 solid=False,
                 lines=True,
                 triangle_indices=None,
                 line_indices=None):
    """ create an ipyvolume mesh from a number of points

    Parameters
    ----------
    points: list
        [[x, y, z], ...]
    color: str
    solid: bool
    triangle_indices: list or None
        [[i, j, k], ...], if None then computed from scipy.spatial.qhull.ConvexHull triangles
    line_indices: list or None
        [[i, j], ...], if None then computed from scipy.spatial.qhull.ConvexHull triangles

    Returns
    -------

    """
    x, y, z = np.array(points).T
    try:
        hull = ConvexHull(points)
    except:
        hull = ConvexHull(points, qhull_options='QJ')
    if triangle_indices is None:
        triangle_indices = hull.simplices.tolist()
    if line_indices is None:
        line_indices = []
        for i, j, k in hull.simplices.tolist():
            line_indices += [[i, j], [i, k], [j, k]]

    mesh = p3.plot_trisurf(x,
                           y,
                           z,
                           triangles=triangle_indices,
                           lines=line_indices,
                           color=color)
    if not solid:
        mesh.visible_faces = False
    if not lines:
        mesh.visible_lines = False
    return mesh
def plot_hull(c1, c2, label=None):
    points = np.array([c1, c2]).T
    hull = ConvexHull(points)
    for simplex in hull.simplices:
        if label:
            plt.plot(points[simplex, 0], points[simplex, 1], label=label,
                     color='black')  # , config['z_colors'][str(z_bpz)]
        else:
            plt.plot(points[simplex, 0], points[simplex, 1], color='black')  # , config['z_colors'][str(z_bpz)])
Esempio n. 15
0
def convexhull_volume(data, offset=10):
    points = np.ndarray(shape=(0,3), dtype=int)
    for i in range(0, data.shape[0], offset):
        for j in range(0, data.shape[1], offset):
            for k in range(0, data.shape[2], offset):
                if data[i][j][k] > 0:
                    points = np.append(points, [[i,j,k]], axis=0)
    print(points.shape)
    hull = ConvexHull(points)
    return hull
Esempio n. 16
0
 def get_initial_qhull(self):
     try:
         self.convex_hull = ConvexHull(np.array([v for v in self.vertices]),
                                       incremental=True)
     except Exception as e:
         print(e)
     if self.convex_hull is None:
         for vtx in self.run_exact_solver():
             self.vertices[vtx.position] = vtx
             if len(self.vertices) >= len(self.limits) + 1:
                 try:
                     self.convex_hull = ConvexHull(np.array(
                         [v for v in self.vertices]),
                                                   incremental=True)
                 except Exception as e:
                     print(e)
                 # run exact ILP sorver until all points are found
             if self.convex_hull is not None:
                 print("Initial hull found")
                 break
Esempio n. 17
0
def _convex_fill(array: np.ndarray):
    if array.ndim != 2:
        raise ValueError("Convex fill need to be called on 2d array.")
    points = np.transpose(np.nonzero(array))
    try:
        convex = ConvexHull(points)
        convex_points = points[convex.vertices]
        convex.close()
        return create_polygon(array.shape, convex_points[::-1])
    except (QhullError, ValueError):
        return None
Esempio n. 18
0
def get_eclipse_boundary_path(hull):
    """
    Return `matplotlib.path.Path` object which represents boundary of component projection
    to plane `yz`.

    :param hull: numpy.array;
    :return: matplotlib.path.Path;
    """
    cover_bound = ConvexHull(hull)
    hull_points = hull[cover_bound.vertices]
    bb_path = mpltpath.Path(hull_points)
    return bb_path
Esempio n. 19
0
def get_corners_of_piece(piece):
    plot = False

    if plot:
        imshow(piece.T)

    points = np.transpose(np.nonzero(piece))
    x = ConvexHull(points)
    cvx_hull_pts = points[x.vertices, 0:2]

    if plot:
        pylab.plot(cvx_hull_pts[:, 0], cvx_hull_pts[:, 1], 'rx')

    squares = combinations(range(cvx_hull_pts.shape[0]), 4)

    res = []
    for i, square_idxs in enumerate(squares):
        sc = eval_pts_as_rect(
            cvx_hull_pts[square_idxs[0]],
            cvx_hull_pts[square_idxs[1]],
            cvx_hull_pts[square_idxs[2]],
            cvx_hull_pts[square_idxs[3]],
        )
        area = eval_area_pts(
            cvx_hull_pts[square_idxs[0]],
            cvx_hull_pts[square_idxs[1]],
            cvx_hull_pts[square_idxs[2]],
            cvx_hull_pts[square_idxs[3]],
        )
        res.append((sc, area, square_idxs))

    res.sort()
    res = res[0:5]

    if plot:
        for sc, area, inds in res:
            pylab.plot(cvx_hull_pts[inds, 0], cvx_hull_pts[inds, 1], 'g-')
            pylab.plot([cvx_hull_pts[inds[-1], 0], cvx_hull_pts[inds[0], 0]],
                       [cvx_hull_pts[inds[-1], 1], cvx_hull_pts[inds[0], 1]],
                       'g-')

    # Lets pick the res with the biggest area:
    res.sort(key=lambda e: e[1], reverse=True)

    _, _, inds_max = res[0]

    pt1 = cvx_hull_pts[inds_max[0], :]
    pt2 = cvx_hull_pts[inds_max[1], :]
    pt3 = cvx_hull_pts[inds_max[2], :]
    pt4 = cvx_hull_pts[inds_max[3], :]
    return [pt1, pt2, pt3, pt4]
def animate(i):
    global theta_iter
    ax.clear()
    sns.scatterplot(test[:, 0], test[:, 1], hue=test[:, 2])
    ax.legend(['Alcohol 1', 'Alcohol 2/3'], loc='upper left')
    ax.set_xlabel(x1)
    ax.set_ylabel(x2)
    ax.set_title(f'Alcohol Type Based On {x1} And {x2}')
    p_x = decision_boundary(boundary_x, boundary_y, theta_iter[i], features,
                            mean, std)
    if len(p_x) > 2:
        hull = ConvexHull(p_x)
        for simplex in hull.simplices:
            ax.plot(p_x[simplex, 0], p_x[simplex, 1], 'k-')
Esempio n. 21
0
def hull(spectra, div=True):
    """
    Detrend a 1D spectra by performing a hull correction. Note that this performs the correction in-situ.

    *Arguments*:
     - div = True if the spectra should be divided by it's hull (default). False if the hull should be subtracted.
    *Returns*:
     - corr = hull corrected spectra.
     - trend = the (hull) trend that was subtracted to give the corrected spectra

    Returns an unchanged spectra and trend = [0,0,...] if the spectra contains nans or infs.
    """

    # calculate convex hull
    hull = ConvexHull(
        np.array([
            np.hstack([0, np.arange(len(spectra)),
                       len(spectra) - 1]),
            np.hstack([0, spectra, 0])
        ]).T)

    # remove unwanted simplices (e.g. along sides and base)
    mask = (hull.simplices != 0).all(
        axis=1) & (hull.simplices != len(spectra) + 1).all(axis=1)

    # build piecewise equations
    x = np.arange(len(spectra), dtype=np.float32)
    if not mask.any(
    ):  # edge case - convex hull is one simplex between first and last points!
        y = spectra[0] + (spectra[-1] - spectra[0]) / x[-1]
    else:
        grad = -hull.equations[mask, 0]
        itc = -hull.equations[mask, 2]
        dom = [(min(x[s[0]], x[s[1]]), max(x[s[0]], x[s[1]]))
               for s in (hull.simplices[mask] - 1)]
        cl = [(x >= d[0]) & (x <= d[1]) for d in dom]

        # evaluate piecewise functions
        fn = [(lambda x, m=grad[i], c=itc[i]: m * x + c)
              for i in range(len(grad))]
        y = np.piecewise(x, cl, fn)

    # return
    if div:
        return spectra / y, y
    else:
        return 1 + spectra - y, y
Esempio n. 22
0
    def color(self, geometry, dual=False):
            """
            A rainbow color function exactly as the one found in lolcat.
            (see https://github.com/busyloop/lolcat)

            Color depends on distance from color center. Feel free to
            experiment with the frequency.

            One could easily use any ol' function, so long as the function's
            output is an integer between 0 and 255.
            """
            if dual:
                factor = ConvexHull(geometry).area
            else:
                factor = np.linalg.norm(self.color_center.loc - geometry)
            color = (127 * np.sin(.01 * factor + np.array((0, 2 * np.pi / 3, 4 * np.pi / 3)))
                     + 128).astype(int)
            return self.palette(color)
Esempio n. 23
0
def contour(x, y):
    # convex = convex_hull(x, y, offset=1.1)
    points = np.ndarray((len(x), 2))
    points[:, 0] = np.array(x)
    points[:, 1] = np.array(y)
    hull = ConvexHull(points)
    convex = []
    for v in hull.vertices:
        convex.append(points[v].tolist())

    # https://stackoverflow.com/questions/47948453/scipy-interpolate-splprep-error-invalid-inputs
    # Fitpack has a fit if it two consecutive inputs are identical. The error happens deep enough that it depends on how the libraries were compiled and linked, hence the assortment of errors.
    prev_xc, prev_yc = convex[-1][0], convex[-1][1]
    x_conv, y_conv = [], []
    for c in convex:
        xc, yc = c[0], c[1]
        if not ((xc == prev_xc) and (yc == prev_yc)):
            x_conv.append(xc)
            y_conv.append(yc)
        prev_xc, prev_yc = xc, yc

    # x_conv, y_conv = [p[0] for p in convex], [p[1] for p in convex]

    x_conv.append(x_conv[0])
    y_conv.append(y_conv[0])

    # taken from https://stackoverflow.com/questions/33962717/interpolating-a-closed-curve-using-scipy
    # fit splines to x=f(u) and y=g(u), treating both as periodic. also note that s=0
    # is needed in order to force the spline fit to pass through all the input points.

    base = 10
    log_x = [math.log(xi, base) for xi in x_conv]
    log_y = [math.log(yi, base) for yi in y_conv]

    # tck, u = interpolate.splprep([np.array(x_conv), np.array(y_conv)], s=0, per=True, k=3)
    tck, u = interpolate.splprep([np.array(log_x), np.array(log_y)], s=0, per=True, k=1)

    # evaluate the spline fits for n evenly spaced distance values
    xi, yi = interpolate.splev(np.linspace(0, 1, 1000), tck)

    xi = [base ** xii for xii in xi]
    yi = [base ** yii for yii in yi]

    return xi, yi
Esempio n. 24
0
def calculate_polygon(points):
    """Calculate polygon
    This function will calculate the polygon
    enclosing all the points provided as argument.
    It will use the convex-hull geometric function."""
    points = np.array([list(p.coords[0]) for p in points])
    try:
        hull = ConvexHull(points)
        x = points[hull.vertices, 0]
        y = points[hull.vertices, 1]
        boundaries = list(zip(x, y))
        return Polygon(boundaries)
    except QhullError:
        logging.warning(
            f"There was an error calculating the polygon for cluster with points: {points}. "
            f"This wil be skipped from the final results",
            exc_info=True)

    return None
Esempio n. 25
0
def create_convex_hull(x_values: np.array, y_values: np.array):
    """
    Given the x and y coordinates of a cloud of data points, generate a convex hull,
    returning the x and y coordinates of its vertices.

    Parameters
    ----------
    x_values: Numpy.array
    y_values: Numpy.array

    Returns
    -------
    Numpy.array, Numpy.array
    """
    xy = np.array([[i[0], i[1]] for i in zip(x_values, y_values)])
    hull = ConvexHull(xy)
    x = [float(i) for i in xy[hull.vertices, 0]]
    y = [float(i) for i in xy[hull.vertices, 1]]
    return x, y
Esempio n. 26
0
def upload_file():
    if request.method == 'POST':
        user = request.form['id']
        file = request.files['file']
        # team 유저 프로필 이미지 
        # team1 유저 프로필에서 얼굴만 크롭하여 저장
        file.save('/var/www/html/team/' + user + '.jpg')

        file_name = '/var/www/html/team/' + user + '.jpg'
        image = cv2.imread(file_name)
        image = imutils.resize(image, width=1010)
        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

        rects = detector(gray, 1)

        for rect in rects:
            (x, y, w, h) = rect_to_bb(rect)
            sp = predictor(image, rect)
            landmarks = np.array([[p.x, p.y] for p in sp.parts()])

            vertices = ConvexHull(landmarks).vertices
            Y, X = skimage.draw.polygon(landmarks[vertices, 1], landmarks[vertices, 0])
            cropped_img = np.zeros(image.shape, dtype=np.uint8)
            cropped_img[Y, X] = image[Y, X]

            image = imutils.resize(cropped_img, width=1000, height=1000)
            faceAligned = fa.align(image, gray, rect)

            cv2.imwrite("/var/www/html/team1/{}.jpg".format(user), faceAligned)

            src = cv2.imread("/var/www/html/team1/{}.jpg".format(user), 1)

            tmp = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
            _, alpha = cv2.threshold(tmp, 0, 255, cv2.THRESH_BINARY)
            b, g, r = cv2.split(src)
            rgba = [b, g, r, alpha]
            dst = cv2.merge(rgba, 4)
            cv2.imwrite("/var/www/html/team1/{}.jpg".format(user), dst)
            cv2.waitKey(0)

    # return "success"
    return jsonify({'insert' : 'ok'}), 200
Esempio n. 27
0
    def getProjectedHull(self, returnPoly: bool = False):
        """
        The convex hull of the part projected in the Z-direction. This is for convenience when trying to find the
        approximate boundary of the part when used for optimising the layout of parts.

        :return: The convex hull of the part
        """

        coords = self.geometry.vertices[:, :2]

        chull = ConvexHull(coords)

        hullCoords = coords[chull.vertices]

        if returnPoly:
            hullCoords = np.append(hullCoords,
                                   hullCoords[0, :].reshape(-1, 2),
                                   axis=0)
            return Polygon(hullCoords)
        else:
            return hullCoords
Esempio n. 28
0
def debug_plot():
    points = np.array(get_from_file(float, POINTS_FILE_NAME))

    chull = ConvexHull(points)
    vertices = chull.vertices
    faces = chull.simplices

    fig = plt.figure(num='debug')
    ax = fig.add_subplot(GRID_DIMENSIONS, projection=PROJECTION_TYPE)

    plot_inside_points(ax, points)
    plot_defining_vertices(ax, points, vertices)

    for face in faces:
        face_pts = np.array(
            [points[face[0]], points[face[1]], points[face[2]]])
        color_face(ax, face_pts, ALPHA)
        print(face)

    for label in LABELS:
        eval("ax.set_{:s}label('{:s}')".format(label, label))
    plt.show()
Esempio n. 29
0
    def convex_hullify(self, points, kmean_pols=False):
        """
        Makes a 2d convex hull around around a set of points.

        :param points: [pd.DataFrame] The points to hullify around
        :param kmean_pols: [bool] switch for chosing between the kmean polygons hullifier or not

        :return: writes to polygons in self.tree_df (initialized in init)
        """

        # empties the tree.df if it exists
        try:
            self.tree_df.drop(self.tree_df.index, inplace=True)
        except:
            pass

        for name, group in points.groupby('Classification'):
            if group.shape[0] <= 3:
                # remove polygons that contain too little points to hullify around
                try:
                    points.drop(points.groupby('Classification').get_group(name).index)
                except:
                    pass
            else:
                # performs convexhull
                coords = np.array([group.X, group.Y]).T
                # :TODO can I do this better? Params?
                polygon = ConvexHull(coords)

                # build wkt string
                wkt = 'POLYGON (('
                for group_id in polygon.vertices:
                    x, y = polygon.points[group_id]
                    wkt += f'{x} {y},'
                # close the polygon
                firstx, firsty = polygon.points[polygon.vertices[0]]
                wkt = wkt + f'{firstx} {firsty}))'

                points = self.add_group_to_result(group, kmean_pols, name, points, wkt)
Esempio n. 30
0
    def get_convex_hull_area(self, composition_space):
        """
        Returns the area/volume of the current convex hull.

        Args:
            composition_space: the CompositionSpace of the search
        """

        # check if the initial population contains organisms at all the
        # endpoints of the composition space
        if self.has_endpoints(composition_space) and \
                self.has_non_endpoint(composition_space):

            # compute and print the area or volume of the convex hull
            pdentries = []
            for organism in self.initial_population:
                pdentries.append(
                    PDEntry(organism.composition, organism.total_energy))
            compound_pd = CompoundPhaseDiagram(pdentries,
                                               composition_space.endpoints)

            # get the data for the convex hull
            qhull_data = compound_pd.qhull_data
            # for some reason, the last point is positive, so remove it
            hull_data = np.delete(qhull_data, -1, 0)

            # make a ConvexHull object from the hull data
            # Sometime this fails, saying that only two points were given to
            # construct the convex hull, even though the if statement above
            # checks that there are enough points.
            try:
                convex_hull = ConvexHull(hull_data)
            except:
                return None
            if len(composition_space.endpoints) == 2:
                return convex_hull.area
            else:
                return convex_hull.volume