def convex_hull_method(A, b, resiudal_dimensions): """ Given a bouned polyhedron in the form P := {x | A x <= b}, returns the orthogonal projection to the given dimensions. Dividing the space in the residual dimensions y and the dropped dimensions z, we have proj_y(P) := {y | exists z s.t. A_y y + A_z z < b}. The projection is returned in both the halfspace representation {x | E x <= f} and the vertices representation {x in conv(vertices)}. This is an implementation of the Convex Hull Method for orthogonal projections of polytopes, see, e.g., http://www.ece.drexel.edu/walsh/JayantCHM.pdf. The polyhedron is assumed to be bounded and full dimensional. Arguments ---------- A : numpy.ndarray Left-hand side of the inequalities describing the higher dimensional polytope. b : numpy.ndarray Right-hand side of the inequalities describing the higher dimensional polytope. residual_dimensions : list of int Indices of the dimensions onto which the polytope has to be projected. Returns ---------- E : numpy.ndarray Left-hand side of the inequalities describing the projection. f : numpy.ndarray Right-hand side of the inequalities describing the projection. vertices : list of numpy.ndarray List of the vertices of the projection. """ # reorder coordinates n = len(resiudal_dimensions) dropped_dimensions = [i for i in range(A.shape[1]) if i not in resiudal_dimensions] A = np.hstack(( A[:, resiudal_dimensions], A[:, dropped_dimensions] )) # initialize projection vertices = _get_two_vertices(A, b, n) if n == 1: E = np.array([[1.],[-1.]]) f = np.array([ [max(v[0,0] for v in vertices)], [- min(v[0,0] for v in vertices)] ]) return E, f, vertices vertices = _get_inner_simplex(A, b, vertices) # expand facets hull = ConvexHull( np.hstack(vertices).T, incremental=True ) hull = _expand_simplex(A, b, hull) hull.close() # get outputs E = hull.equations[:, :-1] f = - hull.equations[:, -1:] vertices = [np.reshape(v, (v.shape[0], 1)) for v in hull.points] return E, f, vertices
def findBoundary(data, points): """ use convex hull algorithm to find the boundary of the image and make the pixels that are used to construct the polygon in convex hull. :param data: 2 d array of image :param points: corresponding coordinates of the pixels that are black (0) :return: modified 2-d array """ hull = ConvexHull(points) plt.plot(points[:, 0], points[:, 1], 'o') for simplex in hull.simplices: plt.plot(points[simplex, 0], points[simplex, 1], 'k-') p1 = points[simplex] p2 = points[simplex] data[p1[0][0]][p1[0][1]] = 1 data[p1[1][0]][p1[1][1]] = 1 data[p2[0][0]][p2[0][1]] = 1 data[p2[1][0]][p2[1][1]] = 1 ### display the convexHull result # toimage(data).show() # plt.show() hull.close() return data
def plot_convex_hull(data: pd.DataFrame): x, y, z = last_pos(data) positions = np.asarray([x, y, z]) pts = positions.transpose() hull = ConvexHull(pts) print("Volume in m^3: ", hull.volume * 10**(-18)) print("Surface area in m^2 : ", hull.area * 10**(-12)) fig = plt.figure() ax = fig.add_subplot(111, projection="3d") # Plot defining corner points ax.plot(pts.T[0], pts.T[1], pts.T[2], "ko") # 12 = 2 * 6 faces are the simplices (2 simplices per square face) for s in hull.simplices: s = np.append(s, s[0]) # Here we cycle back to the first coordinate ax.plot(pts[s, 0], pts[s, 1], pts[s, 2], "r-") hull.close() # Make axis label for i in ["x", "y", "z"]: eval("ax.set_{:s}label('{:s}')".format(i, i)) plt.show()
def call_main_with_surfaces_file(): """Call the main program.""" # open the dataset ds = xr.open_dataset(args.input[0]) # open a reference frame, for debuging only if args.debug: frame = plt.imread(args.frame[0]) outpath = "debug_mbg" os.makedirs(outpath, exist_ok=True) # scale scale = float(args.scale[0]) # timeloop top_left_i = [] top_left_j = [] length = [] width = [] for t, time in enumerate(ds["T"].values): print(" - processing time {} of {}".format(t + 1, len(ds["T"].values)), end="\r") # slice in time tds = ds.isel(T=t) # load variables xgrid = tds["iR"].values ygrid = tds["jR"].values z = tds["Z"].values # mask z[z == z.min()] = np.nan # open a debug plot if args.debug: fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 6)) ax1.pcolormesh(tds["X_grid"], tds["Y_grid"], tds["Z"], vmin=-10, vmax=10, cmap="RdBu_r") ax2.imshow(frame, cmap="Greys_r") ax1.set_aspect("equal") try: # compute a convex hull of the grid points = np.vstack( [xgrid[~np.isnan(z)].flatten(), ygrid[~np.isnan(z)].flatten()]).T hull = ConvexHull(points) hull.close() # hull vertices vertices = np.vstack( [points[hull.vertices, 0], points[hull.vertices, 1]]).T vertices = np.insert(vertices, -1, [vertices[0, 0], vertices[0, 1]], axis=0) # get a rectangle imin = vertices[:, 0].min() jmin = vertices[:, 1].min() dx = vertices[:, 0].max() - vertices[:, 0].min() dy = vertices[:, 1].max() - vertices[:, 1].min() # scale dxnew = dx * scale dynew = dy * scale inew = imin + dx / 2 - dxnew / 2 jnew = jmin + dy / 2 - dynew / 2 # append to output top_left_i.append(int(np.ceil(inew))) top_left_j.append(int(np.ceil(jnew))) length.append(int(dxnew)) width.append(int(dynew)) # add to plot if args.debug: rec_patch = patches.Rectangle((inew, jnew), dxnew, dynew, linewidth=2, edgecolor='r', facecolor='none', linestyle="--") ax2.plot(vertices[:, 0], vertices[:, 1], 'r-', lw=3) ax2.add_patch(rec_patch) plt.savefig("{}/{}".format(outpath, str(t).zfill(6))) plt.show() plt.close() except Exception: print(" - error in frame {} \n".format(t)) top_left_i.append(np.nan) top_left_j.append(np.nan) length.append(np.nan) width.append(np.nan) # save output file df = pd.DataFrame(np.vstack([top_left_i, top_left_j, length, width]).T, columns=["i", "j", "width", "height"]) df.index.name = "frame" df.to_csv(args.output[0])
def __init__(self, X, times, J=2, K=None, Subsampling=False, Mean_version=False): self.X = X self.times = times self.J = J self.subsampling = Subsampling self.Mean_version = Mean_version if (self.Mean_version == True): if (self.subsampling == True): self.J_Subsampling = J if K is None: self.K = 5 * self.X.shape[0] else: self.K = K self.V = [0] * self.K n0 = self.X.shape[0] p0 = self.X.shape[1] s = 0 for k in range(self.K): # On commence à 2 ici : weight = np.zeros((self.J_Subsampling - 1)) for z in np.arange(2, self.J_Subsampling+1): weight[z-2] = comb(n0,z) weight = weight / np.sum(weight) r = np.random.choice(np.arange(2, self.J_Subsampling+1), size=1) subsample = np.random.choice(np.arange(n0), size=r, replace=False) ## Mise en forme des données pour Qhull function : Y = np.zeros((p0 * len(subsample), 2)) for l in range(len(subsample)): Y[(p0 * (l)):(p0 * (l+1)) ,0] = self.times Y[(p0 * (l)):(p0 * (l+1)) ,1] = self.X[subsample[l],:] ################################################ #self.Y.append(Y) hull = ConvexHull(Y) self.V[s] = [subsample, hull.volume] s += 1 hull.close() else: self.V = [0] * (J-1) n0 = self.X.shape[0] p0 = self.X.shape[1] s = 0 for j in range(2,J+1): combi = list(combinations(np.arange(n0), j)) V1 = [0]* len(combi) # On construit une matrice de dimension 2 (ou d+1) contenant les points # pour calculer l'enveloppe convexe : k = 0 for j in combi: # Compute the convex Hull of all combinations of the data. Y = np.zeros((p0 * len(j), 2)) for l in range(len(j)): Y[(p0*(l)):(p0 * (l+1)) ,0] = self.times Y[(p0*(l)):(p0 * (l+1)) ,1] = X[j[l],:] ################################################ #self.Y.append(Y) hull = ConvexHull(Y) V1[k] = [j, hull.volume] k += 1 hull.close() self.V[s] = V1 s += 1 else: if (self.subsampling == True): self.J_Subsampling = J if K is None: self.K = 5 * self.X.shape[0] else: self.K = K self.V = [0] * self.K n0 = self.X.shape[0] p0 = self.X.shape[1] s = 0 for k in range(self.K): subsample = np.random.choice(np.arange(n0), size=self.J, replace=False) ## Mise en forme des données pour Qhull function : Y = np.zeros((p0 * len(subsample), 2)) for l in range(len(subsample)): Y[(p0 * (l)):(p0 * (l+1)) ,0] = self.times Y[(p0 * (l)):(p0 * (l+1)) ,1] = self.X[subsample[l],:] ################################################ #self.Y.append(Y) hull = ConvexHull(Y) self.V[s] = [subsample, hull.volume] s += 1 hull.close() else: self.V = [0] * (J-1) n0 = self.X.shape[0] p0 = self.X.shape[1] s = 0 combi = list(combinations(np.arange(n0), self.J)) V1 = [0]* len(combi) # On construit une matrice de dimension 2 (ou d+1) contenant les points # pour calculer l'enveloppe convexe : k = 0 for j in combi: # Compute the convex Hull of all combinations of the data. Y = np.zeros((p0 * len(j), 2)) for l in range(len(j)): Y[(p0*(l)):(p0 * (l+1)) ,0] = self.times Y[(p0*(l)):(p0 * (l+1)) ,1] = X[j[l],:] ################################################ #self.Y.append(Y) hull = ConvexHull(Y) V1[k] = [j, hull.volume] k += 1 hull.close() self.V[s] = V1 s += 1
def compute_depth(self, X_new=None): """ compute_depth(X_new = None) The depth of an input sample is computed w.r.t. the sample X. Parameters ---------- X_in : Array-like Data to be scored. Returns ------- float Depth score for a given data curve (or dataset). """ if X_new is None: X_new = self.X # Ici, on calcule la profondeur pour certaines U-statistics choisies # dans l'initialisation de la classe. if (self.Mean_version == True): if (self.subsampling == True): p0 = X_new.shape[1] n0 = X_new.shape[0] Score = np.zeros((n0)) for i in range(n0): for j in range(len(self.V)): Ytmp = np.vstack((self.times, X_new[i])) Y = np.zeros((p0 * len(self.V[j][0]), 2)) for l in range(len(self.V[j][0])): Y[(p0*(l)):(p0 * (l+1)) ,0] = self.times Y[(p0*(l)):(p0 * (l+1)) ,1] = self.X[self.V[j][0][l],:] hull = ConvexHull(np.concatenate((Y,Ytmp.T),axis=0)) Score[i] += self.V[j][1] / (1. * hull.volume) hull.close() # Normalisation Score[i] = Score[i] / (1. * len(self.V)) else: n0 = X_new.shape[0] p0 = self.X.shape[1] n = self.X.shape[0] #p0 = X_new.shape[1] score = np.zeros((n0,self.J-1)) for i in range(n0): for m in range(2,self.J+1): combi = list(combinations(np.arange(n), m)) k = 0 for j in combi: Ytmp = np.vstack((self.times, X_new[i])) Y = np.zeros((p0 * len(j), 2)) for l in range(len(j)): Y[(p0*(l)):(p0 * (l+1)) ,0] = self.times Y[(p0*(l)):(p0 * (l+1)) ,1] = self.X[j[l],:] hull = ConvexHull(np.concatenate((Y, Ytmp.T),axis=0)) score[i, m-2] += self.V[m-2][k][1] / (1. * hull.volume) k += 1 hull.close() score[i,m-2] = score[i,m-2] / (1. * len(combi)) # Normalisation Score = np.mean(score,axis = 1) else: if (self.subsampling == True): p0 = X_new.shape[1] n0 = X_new.shape[0] Score = np.zeros((n0)) for i in range(n0): for j in range(len(self.V)): Ytmp = np.vstack((self.times, X_new[i])) Y = np.zeros((p0 * len(self.V[j][0]), 2)) for l in range(len(self.V[j][0])): Y[(p0*(l)):(p0 * (l+1)) ,0] = self.times Y[(p0*(l)):(p0 * (l+1)) ,1] = self.X[self.V[j][0][l],:] hull = ConvexHull(np.concatenate((Y,Ytmp.T),axis=0)) Score[i] += self.V[j][1] / (1. * hull.volume) hull.close() # Normalisation Score[i] = Score[i] / (1. * len(self.V)) else: n0 = X_new.shape[0] p0 = self.X.shape[1] n = self.X.shape[0] #p0 = X_new.shape[1] score = np.zeros(n0) for i in range(n0): combi = list(combinations(np.arange(n), self.J)) k = 0 for j in combi: Ytmp = np.vstack((self.times, X_new[i])) Y = np.zeros((p0 * len(j), 2)) for l in range(len(j)): Y[(p0*(l)):(p0 * (l+1)) ,0] = self.times Y[(p0*(l)):(p0 * (l+1)) ,1] = self.X[j[l],:] hull = ConvexHull(np.concatenate((Y, Ytmp.T),axis=0)) score[i] += self.V[0][k][1] / (1. * hull.volume) k += 1 hull.close() score[i] = score[i] / (1. * len(combi)) Score = score return Score
hullVerts = initHull.points[initHull.vertices] hull = ConvexHull(points=hullVerts, incremental=True) inHullPnts = [] for p in binPnts[ -1]: # Exclude points from largest cpocket threshold that are exterior to convex hull first, then check for those points prescence in the smaller pocket threshold point sets newVertInd = len( hull.points ) # If a new vert shows up with this index, it is outside of the convex hull hull.add_points(np.array([p])) if newVertInd in hull.vertices: # if point is outside convex hull hull = ConvexHull( points=hullVerts, incremental=True) # reset convex hull else: inHullPnts.append(p) hull.close() # coords2Mol2('./data/unilectin/structures/bSites/pntsb4DBSCAN/' + pdb + '_' + bs.replace(':','-') + '.mol2', inHullPnts) logFH.write('From ' + str(len(binPnts[-1])) + ' points, ' + str(len(inHullPnts)) + ' points found within the convex hull\n\n') # print('From ' + str(len(binPnts[-1])) + ' points, ' + str(len(inHullPnts)) + ' points found within the convex hull\n') # Drop points outside of the convex hull from the binned points as well for i in range(len(binPnts)): binPnts[i] = [p for p in binPnts[i] if p in inHullPnts] # for b in binPnts: print(len(b)) # Cluster points together to identify individual pockets and eliminate pockets far from the ligand # prevHit = False
def compute_hull(points): """ @author Simon Woelzmueller <*****@*****.**> :param points: the points we need the hull to :return: the convex hull """ # find out dimension points_dimension = len(points[0]) def all_same(items): return all(x == items[0] for x in items) points = remove_duplicates(points) if len(points) <= len(points[0]) + 2: return points # dim with same points reduction dim = [] for i in xrange(points_dimension): column = np.array([points[u][i] for u in xrange(len(points))]) if all_same(column): dim.append(i) if points_dimension - len(dim) <= 1: conv_hull = [] for i in xrange(points_dimension): if not dim.count(i): column = [points[u][i] for u in xrange(len(points))] maxind = column.index(max(column)) minind = column.index(min(column)) conv_hull.append(points[maxind]) conv_hull.append(points[minind]) return conv_hull if points_dimension - len(dim) <= 2: temp = [] for u in xrange(len(points)): temp_point = [] for i in xrange(points_dimension): if not dim.count(i): temp_point.append(points[u][i]) temp.append(temp_point) temp = np.array([np.array(p) for p in temp]) if [all_same(temp[i]) for i in xrange(len(temp))].count(True) == len(temp): conv_hull = [] column = [points[u][0] for u in xrange(len(points))] maxind = column.index(max(column)) minind = column.index(min(column)) conv_hull.append(points[maxind]) conv_hull.append(points[minind]) return conv_hull hull = ConvexHull(temp) hullp = [points[i] for i in hull.vertices] hull.close() return np.array(hullp) if len(points) <= len(points[0]) + 2: return points points = np.array([np.array(p) for p in points]) hull = ConvexHull(points) hullp = [points[i] for i in hull.vertices] hull.close() return np.array(hullp)