from matplotlib.patches import RegularPolygon import matplotlib.pyplot as plt import random as rd import numpy as np fg, ax = plt.subplots() sqr = RegularPolygon(xy=(5, 4), numVertices=4, edgecolor='k', fill=False) vrt = sqr.get_verts()[:sqr.numvertices] x = np.linspace(vrt.min(0)[0], vrt.max(0)[0], 100) y = np.linspace(vrt.min(0)[1], vrt.max(0)[1], 100) rx, ry = 5, 4 while sqr.contains_point((rx, ry), 0): rx = rd.choice(x) ry = rd.choice(y) pix = rd.choice(range(0, sqr.numvertices)) n = int(input("Enter iteration(min 1000): ")) for i in range(0, n): l = [*range(0, sqr.numvertices)] l.remove(pix) pix = rd.choice(l) cx, cy = vrt[pix] rx = (rx + cx) / 2 ry = (ry + cy) / 2 ax.scatter(rx, ry, s=0.25, c='b') print('\t\t', ['|', '/', '-', '\\'][i % 4], end='\r') ax.add_patch(sqr) ax.set_title("Square: vertex different from previous") ax.axes.axis('equal') ax.axes.axis('off')
x += startx y += starty if x > 0 and y > 0: for index in range(6): ta = array[la][index] if ta < 0: continue elif hcoord[ta] + startx > 0 and vcoord[ta] + starty > 0: continue else: array[la][index] = -1 hex = RegularPolygon((x, y), numVertices=6, radius=2. / 3. * a / 2, orientation=np.radians(30), alpha=0.2, edgecolor='k', facecolor='red') # check_points에 해당하는 점을 포함하는 경우 greenhex tpoints = [] t = 0 while (t < 6): tx = x + hex.radius * math.cos(math.pi / 3 * t) ty = y + hex.radius * math.sin(math.pi / 3 * t) tpoints.append([tx, ty]) t += 1 for p in tpoints: checknum = 0 k = 0 while k < leng:
def __standard_som_hit_histogram(som: StandardSOM, cmap: str): """ Plot the hit histogram for a standard SOM. Plot depends on the topology of the neighborhood (hexagonal or rectangular). Parameters: ----------- som: StandardSOM The SOM for which the hit histogram should be plotted. cmap: str The matplotlib color map for the map. Returns: -------- None """ if som.codebook is not None and som.trained: first_bmus = som.get_first_bmus() # init hit result array hits = np.zeros(len(som.positions)) # aggregate for each position with hits agg = {k: len(v) for k, v in first_bmus.items()} # fill up values at the resp. positions hits[list(agg.keys())] = list(agg.values()) # define normalizer for matplotlib colors normalized = Normalize(vmin=np.min(hits), vmax=np.max(hits)) # plot fig, ax = plt.subplots(1) ax.set_aspect("equal") plt.axis('off') cmap = cm.get_cmap(cmap) if som.topology == "rectangular": # axis limits ax.set_xlim(-1, som.map_size[1]) ax.set_ylim(-1, som.map_size[0]) for pos, hit in zip(som.positions, hits): # noinspection PyTypeChecker rect = RegularPolygon((pos[1], pos[0]), numVertices=4, radius=np.sqrt(0.5), orientation=np.radians(45), edgecolor='k', facecolor=cmap(normalized(hit)), alpha=0.2) ax.add_patch(rect) else: # hexagonal topology # Horizontal cartesian coords hcoord = [c[0] for c in som.positions] # Vertical cartersian coords vcoord = [ 2. * np.sin(np.radians(60)) * (c[1] - c[2]) / 3. for c in som.positions ] # axis limits ax.set_xlim(np.min(hcoord) - 2, np.max(hcoord) + 2) ax.set_ylim(np.min(vcoord) - 2, np.max(vcoord) + 2) for x, y, hit in zip(hcoord, vcoord, hits): # noinspection PyTypeChecker rect = RegularPolygon((x, y), numVertices=6, radius=2. / 3., orientation=np.radians(30), edgecolor='k', facecolor=cmap(normalized(hit)), alpha=0.2) ax.add_patch(rect) # add colorbar plt.colorbar(cm.ScalarMappable(norm=normalized, cmap=cmap), ax=ax) # show plt.show()
def plot_model(dataset, grid, layer_size): colors = {0: 'red', 1: 'blue', 2: 'green'} color_map = np.zeros((layer_size, layer_size), dtype=str) for (i, j) in np.ndindex(layer_size, layer_size): dist = np.sqrt( np.sum(np.power(grid[i, j] - dataset.iloc[:, :-1].values, 2), axis=1)) color_map[i, j] = (colors.get(int(dataset.iloc[:, -1][dist.argmin()]))) # Mapeando as coordenadas dos hexágonos. coord = [] for x in np.arange(10): for i in range(10): if (x % 2 == 0): coord.append([x, i, -i]) else: if (i != 0): coord.append([x, i, -i + i / i]) # Coordenadas horizontais. hcoord = [c[0] for c in coord] # Coordenadas verticais. vcoord = [2. * np.sin(np.radians(60)) * (c[1] - c[2]) / 3. for c in coord] colors = color_map.reshape(-1) fig, ax = plt.subplots(1, figsize=(15, 15)) ax.set_aspect('equal') # Adicionando os hexágonos. for (i, j, color) in zip(hcoord, vcoord, colors): hex = RegularPolygon((i, j), numVertices=6, radius=2. / 3., orientation=np.radians(30), facecolor=color, alpha=0.5, edgecolor='k') ax.add_patch(hex) plt.rcParams.update({'font.size': 22}) plt.axis('off') # legendas. r = mlines.Line2D([], [], color='red', marker='H', markersize=20, label='Class 0') b = mlines.Line2D([], [], color='blue', marker='H', markersize=20, label='Class 1') g = mlines.Line2D([], [], color='green', marker='H', markersize=20, label='Class 2') plt.legend(handles=[r, b, g]) ax.plot() plt.show()
>>>>>>> e72d06c33da3409d3341ff2f016d5721a272f90e # Horizontal cartesian coords hcoord = [c[0] for c in coord] # Vertical cartersian coords vcoord = [2. * np.sin(np.radians(60)) * (c[1] - c[2]) /3. for c in coord] fig, ax = plt.subplots(1) ax.set_aspect('equal') # Add some coloured hexagons for x, y, c, l in zip(hcoord, vcoord, colors, labels): color = c[0].lower() # matplotlib understands lower case words for colours <<<<<<< HEAD hex = RegularPolygon((x, y), numVertices=6, radius=2, orientation=np.radians(30), #con 60 grados funciona perfecto, pero las coordenadas cambian. Antes 30 facecolor=color, alpha=0.2, edgecolor='k') #cambiar radius=2. / 3. , cuando se usa coord_0 ======= hex = RegularPolygon((x, y), numVertices=6, radius=2. / 3., orientation=np.radians(30), facecolor=color, alpha=0.2, edgecolor='k') >>>>>>> e72d06c33da3409d3341ff2f016d5721a272f90e ax.add_patch(hex) # Also add a text label ax.text(x, y+0.2, l[0], ha='center', va='center', size=20) # Also add scatter points in hexagon centres ax.scatter(hcoord, vcoord, c=[c[0].lower() for c in colors], alpha=0.5) plt.grid(True) plt.show()
def show(self): player_colors = {0: "green", 1: "red", 2: "blue"} colors = [ player_colors[tile.tree.owner] if tile.tree else "green" for tile in self.data.tiles ] shadows = [ "black" if tile.is_shadow else "orange" for tile in self.data.tiles ] labels = [ tile.tree.size if tile.tree else "" for tile in self.data.tiles ] hcoord = [c[0] for c in self.tile_coords] vcoord = [ 2.0 * np.sin(np.radians(60)) * (c[1] - c[2]) / 3.0 for c in self.tile_coords ] fig, ax = plt.subplots(1) fig.set_size_inches(12.5, 8.5) plt.axis([-5, 10, -5, 5]) ax.set_aspect("equal") # Add some coloured hexagons for x, y, c, l in zip(hcoord, vcoord, colors, labels): hexagon = RegularPolygon( (x, y), numVertices=6, radius=2.0 / 3.0, orientation=np.radians(30), facecolor=c, alpha=0.2, edgecolor="k", ) ax.add_patch(hexagon) # Add a text label ax.text(x, y + 0.3, l, ha="center", va="center", size=10) sun_coords = self.suns[self.sun_position] * 4 sun_y_coord = 2 * np.sin( np.radians(60)) * (sun_coords[1] - sun_coords[2]) / 3 ax.text(sun_coords[0], sun_y_coord, "SUN", ha="center", va="center", size=20, color="orange") for player in self.data.players: ax.text( 7, 2 - player.number / 2, f"Player {player.name}: Light Points: {player.l_points}, score: {player.score}", ha="center", va="center", size=10, color="black", ) ax.text( 7, 4, f"Round number {self.round_number}.{self.round_turn}", ha="center", va="center", size=10, color="black", ) # Add scatter points in hexagon centres ax.scatter(hcoord, vcoord, c=shadows, alpha=0.5) plt.axis("off") plt.show()
def __init__( self, geometry, image=None, ax=None, title=None, norm="lin", cmap=None, allow_pick=False, autoupdate=True, autoscale=True, show_frame=True, ): self.axes = ax if ax is not None else plt.gca() self.pixels = None self.colorbar = None self.autoupdate = autoupdate self.autoscale = autoscale self._active_pixel = None self._active_pixel_label = None self._axes_overlays = [] self.geom = geometry if title is None: title = f"{geometry.camera_name}" # initialize the plot and generate the pixels as a # RegularPolyCollection patches = [] if hasattr(self.geom, "mask"): self.mask = self.geom.mask else: self.mask = np.ones_like(self.geom.pix_x.value, dtype=bool) pix_x = self.geom.pix_x.value[self.mask] pix_y = self.geom.pix_y.value[self.mask] pix_width = self.geom.pixel_width.value[self.mask] for x, y, w in zip(pix_x, pix_y, pix_width): if self.geom.pix_type == PixelShape.HEXAGON: r = w / np.sqrt(3) patch = RegularPolygon( (x, y), 6, radius=r, orientation=self.geom.pix_rotation.to_value(u.rad), fill=True, ) elif self.geom.pix_type == PixelShape.CIRCLE: patch = Circle((x, y), radius=w / 2, fill=True) elif self.geom.pix_type == PixelShape.SQUARE: patch = Rectangle( (x - w / 2, y - w / 2), width=w, height=w, angle=self.geom.pix_rotation.to_value(u.deg), fill=True, ) else: raise ValueError( f"Unsupported pixel_shape {self.geom.pix_type}") patches.append(patch) self.pixels = PatchCollection(patches, cmap=cmap, linewidth=0) self.axes.add_collection(self.pixels) self.pixel_highlighting = copy.copy(self.pixels) self.pixel_highlighting.set_facecolor("none") self.pixel_highlighting.set_linewidth(0) self.axes.add_collection(self.pixel_highlighting) # Set up some nice plot defaults self.axes.set_aspect("equal", "datalim") self.axes.set_title(title) self.axes.autoscale_view() if show_frame: self.add_frame_name() # set up a patch to display when a pixel is clicked (and # pixel_picker is enabled): self._active_pixel = copy.copy(patches[0]) self._active_pixel.set_facecolor("r") self._active_pixel.set_alpha(0.5) self._active_pixel.set_linewidth(2.0) self._active_pixel.set_visible(False) self.axes.add_patch(self._active_pixel) if hasattr(self._active_pixel, "xy"): center = self._active_pixel.xy else: center = self._active_pixel.center self._active_pixel_label = self.axes.text(*center, "0", horizontalalignment="center", verticalalignment="center") self._active_pixel_label.set_visible(False) # enable ability to click on pixel and do something (can be # enabled on-the-fly later as well: if allow_pick: self.enable_pixel_picker() if image is not None: self.image = image else: self.image = np.zeros_like(self.geom.pix_id, dtype=np.float64) self.norm = norm self.auto_set_axes_labels()
'brown': brown, 'orange': orange, 'orchid': orchid, 'teal': teal } # generate static world for color in color_dict: for ij in color_dict[color]: color_ij(ij, color) # add houses # east house1 = RegularPolygon((w / 2 + w * 4, h / 2 + h * 3), 5, 0.5, fc='k', alpha=1) ax.add_patch(house1) # west house2 = RegularPolygon((w / 2 + w * 0, h / 2 + h * 4), 5, 0.5, fc='k', alpha=0.9) ax.add_patch(house2) # south / storage house3 = RegularPolygon((w / 2 + w * 2, h / 2 + h * 0), 5, 0.5, fc='k',
def sgen_patches(node_coords, size, angles, **kwargs): """ Creation function of patches for static generators. :param node_coords: coordinates of the nodes that the static generators belong to. :type node_coords: iterable :param size: size of the patch :type size: float :param angles: angles by which to rotate the patches (in radians) :type angles: iterable(float), float :param kwargs: additional keyword arguments (might contain parameters "offset", "r_triangle",\ "patch_edgecolor" and "patch_facecolor") :type kwargs: :return: Return values are: \ - lines (list) - list of coordinates for lines leading to static generator patches\ - polys (list of RegularPolygon) - list containing the static generator patches\ - keywords (set) - set of keywords removed from kwargs """ polys, lines = list(), list() offset = kwargs.get("offset", 2 * size) r_triangle = kwargs.get("r_triangles", size * 0.4) edgecolor = kwargs.get("patch_edgecolor", "w") facecolor = kwargs.get("patch_facecolor", "w") edgecolors = get_color_list(edgecolor, len(node_coords)) facecolors = get_color_list(facecolor, len(node_coords)) for i, node_geo in enumerate(node_coords): mid_circ = node_geo + _rotate_dim2(np.array([0, offset + size]), angles[i]) circ_edge = node_geo + _rotate_dim2(np.array([0, offset]), angles[i]) mid_tri1 = mid_circ + _rotate_dim2( np.array([r_triangle, -r_triangle / 4]), angles[i]) mid_tri2 = mid_circ + _rotate_dim2( np.array([-r_triangle, r_triangle / 4]), angles[i]) # dropped perpendicular foot of triangle1 perp_foot1 = mid_tri1 + _rotate_dim2(np.array([0, -r_triangle / 2]), angles[i]) line_end1 = perp_foot1 + +_rotate_dim2( np.array([-2.5 * r_triangle, 0]), angles[i]) perp_foot2 = mid_tri2 + _rotate_dim2(np.array([0, r_triangle / 2]), angles[i]) line_end2 = perp_foot2 + +_rotate_dim2(np.array([2.5 * r_triangle, 0]), angles[i]) polys.append(Circle(mid_circ, size, fc=facecolors[i], ec=edgecolors[i])) polys.append( RegularPolygon(mid_tri1, numVertices=3, radius=r_triangle, orientation=-angles[i], fc=facecolors[i], ec=edgecolors[i])) polys.append( RegularPolygon(mid_tri2, numVertices=3, radius=r_triangle, orientation=np.pi - angles[i], fc=facecolors[i], ec=edgecolors[i])) lines.append((node_geo, circ_edge)) lines.append((perp_foot1, line_end1)) lines.append((perp_foot2, line_end2)) return lines, polys, { "offset", "r_triangle", "patch_edgecolor", "patch_facecolor" }
def _gen_axes_patch(self): return RegularPolygon((0.5, 0.5), 4, radius=.5, edgecolor="k")
hexArray[0] = [0, 0, 0.055, 0] # In[35]: get_ipython().magic(u'') # In[20]: fig, ax = plt.subplots(1) ax.set_aspect('equal') for x, y, c, l in zip([0, 0], [0, 1], ['0.0', '1.0'], ['red', 'blue']): # color = c[0] # matplotlib understands lower case words for colours hex = RegularPolygon((x, y), numVertices=6, radius=2. / 3., orientation=np.radians(30), facecolor=c, edgecolor='k') ax.add_patch(hex) # Also add a text label ax.text(x, y + 0.2, l[0], ha='center', va='center', size=20) plt.show() # In[18]: import numpy as np import matplotlib.pyplot as plt np.random.seed(0) n = 100 x = np.random.standard_normal(n)
def bubbles(diameters, positions, data, color_map=None, size=10, text=None, borders=False, norm=True, labels=None, intensity=None, title=None, connections=None, reverse=None, display_empty_nodes=True): """ Plot the map with nodes as circles with a position (center) and a diameter with a color according to the input data. Parameters ---------- diameters: array_like Diameters of each node. Dimensions should be (x, y). Values should be greater than 0. positions: ndarray Cartesian coordinates of the nodes in the 2D virtual space. Dimensions should be (x, y, 2). data: array_like Value of each node. Dimensions should be (x, y). color_map: colormap (optional, default None) Color map to paint the nodes. size: int (optional, default 10) Horizontal and vertical size of the final plot. text: array_like (optional, default None) Text to display for each node. Dimensions should be (x, y). borders: bool (optional, default False) Draw nodes borders. norm: bool (optional, default True) Normalize the input data to the range [0, 1]. labels: array_like (optional, default None) A 1D array containing each node label (could be their class or cluster) as a numeric value. Length should be (x * y). intensity: array_like (optional, default None) Alpha value of each node. This value affects nodes colors. A low value makes them lighter. Dimensions should be (x, y). Values should be in the range [0, 1]. title: string (optional, default None) Plot some title. connections: ndarray (optional, default None) Matrix indicating intensity of connections between nodes. Use nan to represent that there is no connection between two nodes. Dimensions should be (x * y, x * y). reverse: array_like (optional, default None) Matrix of bool values indicating for each connection whether it should be drawn straight or be drawn "going around" the toroidal space. Dimensions should be (x * y, x * y). display_empty_nodes: bool (optional, default True) Draw nodes with a ``diameter`` value equals to 0 as grey diamonds. """ if intensity is None: intensity = ones((positions.shape[0], positions.shape[1])) if color_map is None: if labels is not None: color_map = plt.cm.get_cmap('hsv', len(labels) + 1) else: color_map = plt.cm.get_cmap('RdYlGn_r') if text is None: text = [[''] * positions.shape[1]] * positions.shape[0] d_max = diameters.max() data_c = data.copy() data_max = nanmax(data_c) data_min = nanmin(data_c) if data_max == data_min: data_max = 1. data_min = 0. if norm: data_c = data_c.astype(float) data_c = data_c.astype(float) data_c -= data_min data_c /= data_max - data_min figure = plt.figure(figsize=(size, size)) axes = figure.add_subplot(111) axes.set_aspect('equal') if title is not None: axes.title.set_text(title) if connections is not None: if reverse is None: reverse = connections.copy() * 0 cm_min = nanmin(connections) width = positions[..., 0].max() height = positions[..., 1].max() for i in range(connections.shape[0]): for j in range(connections.shape[1]): if not isnan(connections[i, j]): first_pos = positions[unravel_index( i, (positions.shape[0], positions.shape[1]))].copy() second_pos = positions[unravel_index( j, (positions.shape[0], positions.shape[1]))].copy() if reverse[i, j]: edges_connection = False if first_pos[0] - second_pos[0] > width / 2: edges_connection = True second_pos[0] += 1 + width if second_pos[0] - first_pos[0] > width / 2: edges_connection = True second_pos[0] -= 1 + width if first_pos[1] - second_pos[1] > height / 2: edges_connection = True second_pos[1] += 1 + height if second_pos[1] - first_pos[1] > height / 2: edges_connection = True second_pos[1] -= 1 + height if edges_connection: second_pos = (second_pos + first_pos) / 2 plt.plot([first_pos[0], second_pos[0]], [first_pos[1], second_pos[1]], zorder=-d_max * 2, color='black', alpha=(0.2 + cm_min / connections[i, j]) / 1.2) for i in range(data_c.shape[0]): for j in range(data_c.shape[1]): if diameters[i, j] > 0: if isinstance(data_c[i, j], ndarray): start = 0 for k in range(data_c[i, j].shape[0]): end = start + data_c[i, j, k] * 360 / diameters[i, j] if data_c[i, j, k]: radius = 0.8 * sqrt(diameters[i, j] / d_max) / 3 axes.add_patch( Wedge(positions[i, j], r=radius, theta1=start, theta2=end, facecolor=color_map( k / data_c[i, j].shape[0]), edgecolor=color_map( k / data_c[i, j].shape[0]), zorder=-diameters[i, j], alpha=intensity[i, j])) start = end if borders: radius = 0.8 * sqrt(diameters[i, j] / d_max) / 3 axes.add_patch( Circle(positions[i, j], radius=radius, facecolor='None', edgecolor='black', zorder=-diameters[i, j], alpha=intensity[i, j])) axes.text(*positions[i, j], text[i][j], ha="center", va="center") else: if borders: edge_color = 'black' else: edge_color = color_map(data_c[i, j]) radius = 0.8 * sqrt(diameters[i, j] / d_max) / 3 axes.add_patch( Circle(positions[i, j], radius=radius, facecolor=color_map(data_c[i, j]), edgecolor=edge_color, zorder=-diameters[i, j], alpha=intensity[i, j])) axes.text(*positions[i, j], text[i][j], ha="center", va="center") else: if display_empty_nodes: radius = 0.8 * sqrt(1 / d_max) / 3 axes.add_patch( RegularPolygon(positions[i, j], numVertices=4, radius=radius, facecolor='lightgrey', edgecolor='lightgrey', zorder=-d_max, alpha=intensity[i, j])) axes.text(*positions[i, j], text[i][j], ha="center", va="center") legend_or_bar([positions[..., 0].max(), positions[..., 1].max()], [positions[..., 0].min(), positions[..., 1].min()], data_min, data_max, color_map, figure, axes, labels=labels)
def update(positions, hexagonal, data, dimensions=10, bmu=None, relative_positions=None, displacement=None, color_map=plt.cm.get_cmap('RdYlGn_r')): """ Plot the update value of each node and their relative position displacement. Parameters ---------- positions: ndarray Cartesian coordinates of the nodes in the 2D virtual space. Dimensions should be (x, y, 2). hexagonal: bool Whether the nodes have an hexagonal shape or squared. data: array_like Update value of each node. Dimensions should be (x, y). dimensions: array_like Horizontal and vertical measure of the map in the virtual space. Dimensions should be (2). bmu: tuple or array_like (optional, default None) Cartesian coordinate of the best matching unit in the 2D virtual space. Dimensions should be (2). relative_positions: ndarray (optional, default None) Cartesian coordinates of the relative positions of the nodes. Dimensions should be (x, y, 2). displacement: array_like (optional, default None) Displacement vector of each node over the relative positions space. Dimensions should be (x, y, 2). color_map: colormap (optional, default plt.cm.get_cmap('RdYlGn_r')) Color map to paint the nodes. """ data_c = data.copy() data_max = nanmax(data_c) data_min = nanmin(data_c) if data_max == data_min: data_max = 1. data_min = 0. data_c -= data_min data_c /= data_max - data_min x_range = arange(positions.shape[0]) y_range = arange(positions.shape[1]) figure = plt.figure(figsize=(dimensions, dimensions)) axes = figure.add_subplot(111) axes.set_aspect('equal') if hexagonal: num_vertices = 6 radius = (3**0.5) / 3 orientation = 0 axes.set_xticks(x_range) axes.set_yticks(y_range * (3**0.5) / 2) else: num_vertices = 4 radius = (2**0.5) / 2 orientation = pi / 4 axes.set_xticks(x_range) axes.set_yticks(y_range) axes.set_xticklabels(x_range) axes.set_yticklabels(y_range) for i in range(data_c.shape[0]): for j in range(data_c.shape[1]): axes.add_patch( RegularPolygon(positions[i, j], numVertices=num_vertices, radius=radius, orientation=orientation, facecolor=color_map(data_c[i, j]), edgecolor=color_map(data_c[i, j]))) if bmu is not None: axes.add_patch( Circle(bmu, radius=radius / 3, facecolor='white', edgecolor='white')) if relative_positions is not None and displacement is not None: axes.quiver(relative_positions[..., 0], relative_positions[..., 1], displacement[..., 0], displacement[..., 1], angles='xy', scale_units='xy', scale=1, zorder=10) legend_or_bar([positions[..., 0].max(), positions[..., 1].max()], [positions[..., 0].min(), positions[..., 1].min()], data_min, data_max, color_map, figure, axes)
def tiles(positions, hexagonal, data, color_map=plt.cm.get_cmap('RdYlGn_r'), size=10, text=None, borders=False, norm=True, labels=None, intensity=None, title=None): """ Plot the map with nodes having colors according to their values (or set of values). Nodes have an hexagonal or squared shape that completely fill the space. Parameters ---------- positions: ndarray Cartesian coordinates of the nodes in the 2D virtual space. Dimensions should be (x, y, 2). hexagonal: bool Whether the nodes have an hexagonal shape or squared. data: array_like Value of each node. Dimensions should be (x, y). color_map: colormap (optional, default plt.cm.get_cmap('RdYlGn_r')) Color map to paint the nodes. Ignored if entered a ``labels`` value. size: int (optional, default 10) Horizontal and vertical size of the final plot. text: array_like (optional, default None) Text to display for each node. Dimensions should be (x, y). borders: bool (optional, default False) Draw nodes borders. norm: bool (optional, default True) Normalize input ``data`` to the range [0, 1]. labels: array_like (optional, default None) A 1D array containing each node label (could be their class or cluster) as an integer value. Length should be (x * y). intensity: array_like (optional, default None) Alpha value of each node. This value affects nodes colors. A lower value makes them lighter. Dimensions should be (x, y). Values should be in the range [0, 1]. title: string (optional, default None) Plot some title. """ if intensity is None: intensity = ones((positions.shape[0], positions.shape[1])) if labels is not None: color_map = plt.cm.get_cmap('hsv', len(labels) + 1) if text is None: text = [[''] * positions.shape[1]] * positions.shape[0] data_c = data.copy() data_max = nanmax(data_c) data_min = nanmin(data_c) if data_max == data_min: data_max = 1. data_min = 0. if norm: data_c = data_c.astype(float) data_c -= data_min data_c /= data_max - data_min x_range = arange(positions.shape[0]) y_range = arange(positions.shape[1]) figure = plt.figure(figsize=(size, size)) axes = figure.add_subplot(111) axes.set_aspect('equal') if title is not None: axes.title.set_text(title) if hexagonal: num_vertices = 6 radius = (3**0.5) / 3 orientation = 0 axes.set_xticks(x_range) axes.set_yticks(y_range * (3**0.5) / 2) else: num_vertices = 4 radius = (2**0.5) / 2 orientation = pi / 4 axes.set_xticks(x_range) axes.set_yticks(y_range) half_radius = radius / 2 axes.set_xticklabels(x_range) axes.set_yticklabels(y_range) for i in range(data_c.shape[0]): for j in range(data_c.shape[1]): if isinstance(data_c[i, j], ndarray): x_position = positions[(i, j, 0)] y_position = positions[(i, j, 1)] if hexagonal: if not isnan(data_c[i, j, 0]): axes.add_patch( Polygon(([ (x_position + .25, y_position - half_radius / 2), (x_position + .25, y_position + half_radius / 2), (x_position + .5, y_position + half_radius), (x_position + .5, y_position - half_radius) ]), facecolor=color_map(data_c[i, j, 0]), edgecolor=color_map(data_c[i, j, 0]), alpha=intensity[i, j])) if not isnan(data_c[i, j, 1]): axes.add_patch( Polygon(([ (x_position + .25, y_position + half_radius / 2), (x_position, y_position + half_radius), (x_position, y_position + 2 * half_radius), (x_position + .5, y_position + half_radius) ]), facecolor=color_map(data_c[i, j, 1]), edgecolor=color_map(data_c[i, j, 1]), alpha=intensity[i, j])) if not isnan(data_c[i, j, 2]): axes.add_patch( Polygon( ([(x_position, y_position + half_radius), (x_position - .25, y_position + half_radius / 2), (x_position - .5, y_position + half_radius), (x_position, y_position + 2 * half_radius)]), facecolor=color_map(data_c[i, j, 2]), edgecolor=color_map(data_c[i, j, 2]), alpha=intensity[i, j])) if not isnan(data_c[i, j, 3]): axes.add_patch( Polygon(([ (x_position - .25, y_position + half_radius / 2), (x_position - .25, y_position - half_radius / 2), (x_position - .5, y_position - half_radius), (x_position - .5, y_position + half_radius) ]), facecolor=color_map(data_c[i, j, 3]), edgecolor=color_map(data_c[i, j, 3]), alpha=intensity[i, j])) if not isnan(data_c[i, j, 4]): axes.add_patch( Polygon(([ (x_position - .25, y_position - half_radius / 2), (x_position, y_position - half_radius), (x_position, y_position - 2 * half_radius), (x_position - .5, y_position - half_radius) ]), facecolor=color_map(data_c[i, j, 4]), edgecolor=color_map(data_c[i, j, 4]), alpha=intensity[i, j])) if not isnan(data_c[i, j, 5]): axes.add_patch( Polygon( ([(x_position, y_position - half_radius), (x_position + .25, y_position - half_radius / 2), (x_position + .5, y_position - half_radius), (x_position, y_position - 2 * half_radius)]), facecolor=color_map(data_c[i, j, 5]), edgecolor=color_map(data_c[i, j, 5]), alpha=intensity[i, j])) else: if not isnan(data_c[i, j, 0]): axes.add_patch( Polygon(([(x_position + .25, y_position - .25), (x_position + .5, y_position - .5), (x_position + .5, y_position + .5), (x_position + .25, y_position + .25)]), facecolor=color_map(data_c[i, j, 0]), edgecolor=color_map(data_c[i, j, 0]), alpha=intensity[i, j])) if not isnan(data_c[i, j, 1]): axes.add_patch( Polygon(([(x_position + .5, y_position + .5), (x_position + .25, y_position + .25), (x_position - .25, y_position + .25), (x_position - .5, y_position + .5)]), facecolor=color_map(data_c[i, j, 1]), edgecolor=color_map(data_c[i, j, 1]), alpha=intensity[i, j])) if not isnan(data_c[i, j, 2]): axes.add_patch( Polygon(([(x_position - .25, y_position + .25), (x_position - .5, y_position + .5), (x_position - .5, y_position - .5), (x_position - .25, y_position - .25)]), facecolor=color_map(data_c[i, j, 2]), edgecolor=color_map(data_c[i, j, 2]), alpha=intensity[i, j])) if not isnan(data_c[i, j, 3]): axes.add_patch( Polygon(([(x_position - .5, y_position - .5), (x_position - .25, y_position - .25), (x_position + .25, y_position - .25), (x_position + .5, y_position - .5)]), facecolor=color_map(data_c[i, j, 3]), edgecolor=color_map(data_c[i, j, 3]), alpha=intensity[i, j])) if not isnan(data_c[i, j, num_vertices]): axes.add_patch( RegularPolygon( (x_position, y_position), numVertices=num_vertices, radius=half_radius, orientation=orientation, facecolor=color_map(data_c[i, j, num_vertices]), edgecolor=color_map(data_c[i, j, num_vertices]), alpha=intensity[i, j])) if borders: axes.add_patch( RegularPolygon((x_position, y_position), numVertices=num_vertices, radius=radius, orientation=orientation, fill=0, edgecolor='black', alpha=intensity[i, j])) axes.text(*positions[i, j], text[i][j], ha="center", va="center") else: if not isnan(data_c[i, j]): if borders: edge_color = 'black' else: edge_color = color_map(data_c[i, j]) axes.add_patch( RegularPolygon(positions[i, j], numVertices=num_vertices, radius=radius, orientation=orientation, facecolor=color_map(data_c[i, j]), edgecolor=edge_color, alpha=intensity[i, j])) axes.text(*positions[i, j], text[i][j], ha="center", va="center") legend_or_bar([positions[..., 0].max(), positions[..., 1].max()], [positions[..., 0].min(), positions[..., 1].min()], data_min, data_max, color_map, figure, axes, labels=labels)
# plot axes ax.arrow(-1, 0, 9, 0, head_width=0.1, fc='k') ax.arrow(0, -1, 0, 9, head_width=0.1, fc='k') # plot ellipses and circles for i in range(3): ax.add_patch( Ellipse((3, 5), 3.5 * np.sqrt(2 * i + 1), 1.7 * np.sqrt(2 * i + 1), -15, fc='none', lw=2)) ax.add_patch(RegularPolygon((0, 0), 4, 4.4, np.pi, fc='none', lw=2)) # plot arrows ax.arrow(0, 0, 0, 4.4, head_width=0.2, fc='k', length_includes_head=True) ax.arrow(0, 0, 3, 5, head_width=0.2, fc='k', length_includes_head=True) ax.arrow(0, -0.2, 4.2, 0, head_width=0.1, fc='k', length_includes_head=True) ax.arrow(4.2, -0.2, -4.2, 0, head_width=0.1, fc='k', length_includes_head=True) # annotate plot ax.text(7.5, -0.1, r'$\theta_1$', va='top', fontsize=20) ax.text(-0.1, 7.5, r'$\theta_2$', ha='right', fontsize=20) ax.text(3, 5 + 0.2, r'$\rm \theta_{normal\ equation}$', fontsize=20, ha='center',
def draw_map(self, fig=None, _cmap="viridis", v_min=None, v_max=None, title=None, title_kwargs=None): """ Create the map. :param fig: optional matplotlib fig object. If not provided, one is created. :param _cmap: optional string. Colormap to use in the plot. Default is viridis. :param v_min: optional float. The minimum value for the colormap. If not provided, and a value column is, it's taken as minimum value in the dataframe. :param v_max: optional float. The maximum value for the colormap. If not provided, and a value column is, it's taken as maximum value in the dataframe. :param title: optional string. Title to the figure :param title_kwargs: optional dict. Kwargs to the title :return: a matplotlib figure with the hex map drawn onto it. """ if fig is None: fig, ax = plt.subplots(1, figsize=(8, 8)) ax.axis("off") else: ax = fig.axes[0] y_min = 1000 y_max = -1000 # TODO allow other hex orientations. We assume odd-r here. d = 0.5 / np.sin(np.pi / 3) y_diff = np.sqrt(1 - 0.5**2) patches = [] colours = [] for i in range(self._map_df.shape[0]): r = self._map_df.loc[i, "r"] q = self._map_df.loc[i, "q"] if self._value_column is not None: c = self._map_df.loc[i, self._value_column] else: c = 0.0 if r % 2 == 1: # if in an odd row, we need to shift right q = q + 0.5 r = y_diff * r hexagon = RegularPolygon((q, r), numVertices=6, radius=d, edgecolor='k') patches.append(hexagon) colours.append(c) # Get plot limits if r < y_min: y_min = r - 1. if r > y_max: y_max = r + 1. x_min = self._map_df["q"].min() - 1.0 x_max = self._map_df["q"].max() + 1.0 _cmap = _cmap if self._value_column is not None else None p = PatchCollection(patches, cmap=plt.get_cmap(_cmap), alpha=1.0) p.set_array(np.array(colours)) if self._value_column is not None: # Set colorbar limits if v_min is None: v_min = self._map_df[self._value_column].min() if v_max is None: v_max = self._map_df[self._value_column].max() p.set_clim([v_min, v_max]) plt.colorbar(p, shrink=0.5) ax.add_collection(p) ax.set_xlim([x_min, x_max]) ax.set_ylim([y_min, y_max]) if title is not None: ax.set_title(title, fontdict=title_kwargs) self._map_fig = fig return fig
import matplotlib.pyplot as plt from matplotlib.patches import RegularPolygon Coord = [[4, 4]] fig, ax = plt.subplots(1) ax.set_aspect('equal') for c in Coord: hex = RegularPolygon((c[0], c[1]), numVertices=6, radius=2. / 3., alpha=0.2, edgecolor='b') ax.add_patch(hex) circle = plt.Circle((4, 4), radius=0.5, fc='r') rectangle = plt.Rectangle((3.75, 3.75), width=0.5, height=0.5, fc='b') plt.gca().add_patch(circle) plt.gca().add_patch(rectangle) plt.autoscale(enable=True) plt.show()
from matplotlib.patches import RegularPolygon import matplotlib.pyplot as plt import random as rd import numpy as np fg, ax = plt.subplots() tr = RegularPolygon((5, 4), 3, 0.3, edgecolor='k', fill=False) vrt = tr.get_verts()[:3] x = np.linspace(vrt.min(0)[0], vrt.max(0)[0], 100) y = np.linspace(vrt.min(0)[1], vrt.max(0)[1], 100) rx, ry = 5, 4 while tr.contains_point((rx, ry), 0): rx = rd.choice(x) ry = rd.choice(y) n = int(input("Enter iteration(min 1000): ")) for i in range(0, n): cx, cy = vrt[rd.choice(range(0, 3))] rx = (rx + cx) / 2 ry = (ry + cy) / 2 ax.scatter(rx, ry, s=0.5, c='b') print('\t\t', ['|', '/', '-', '\\'][i % 4], end='\r') ax.add_patch(tr) ax.set_title("Serpenski Triangle") ax.axes.axis('equal') ax.axes.axis('off') plt.show()
import numpy as np from matplotlib import pyplot as plt from matplotlib import animation from matplotlib.patches import RegularPolygon # First set up the figure, the axis, and the plot element we want to animate fig = plt.figure() ax = plt.axes(xlim=(-2.5, 2.5), ylim=(-2.5, 2.5), aspect='equal') # Add lines and patches lines = ax.plot(np.zeros((2, 4)), np.zeros((2, 2)), lw=2, color='black') squares = [ RegularPolygon((np.sqrt(2) * x, np.sqrt(2) * y), 4, radius=0.6, orientation=0, color='black') for (x, y) in [(1, 0), (-1, 0), (0, 1), (0, -1)] ] for sq in squares: ax.add_patch(sq) # initialization function: plot the background of each frame def init(): for line in lines: line.set_data([], []) for sq in squares: sq.set_alpha(0) return lines + squares
def plot_radial_power_distribution(power, save): ''' Plots radial power distribution. Parameters: ----------- power: [numpy array] contains the values in MW of the power produced in each fuel column the reactor model includes only a 1/6th of the reactor (only 11 columns). save: [string] name of the figure ''' P = 36 # pitch F = P / np.sqrt(3) coord = [] # 1 - 2 coord.append(np.array([0, 3*P])) coord.append(np.array([0, 4*P])) # 3 - 5 coord.append(np.array([1*(F+F/2), 3*P-P/2])) coord.append(np.array([1*(F+F/2), 4*P-P/2])) coord.append(np.array([1*(F+F/2), 5*P-P/2])) # 6 - 8 coord.append(np.array([2*(F+F/2), 2*P])) coord.append(np.array([2*(F+F/2), 3*P])) coord.append(np.array([2*(F+F/2), 4*P])) # 9 - 10 coord.append(np.array([3*(F+F/2), 3*P-P/2])) coord.append(np.array([3*(F+F/2), 4*P-P/2])) # 11 coord.append(np.array([4*(F+F/2), 3*P])) coord = np.array(coord) patches = [] xmax, ymax = [-np.inf, ] * 2 xmin, ymin = [np.inf, ] * 2 for i in range(len(coord)): h = RegularPolygon(coord[i], 6, F, np.pi/2) patches.append(h) verts = h.get_verts() vmins = verts.min(0) vmaxs = verts.max(0) xmax = max(xmax, vmaxs[0]) xmin = min(xmin, vmins[0]) ymax = max(ymax, vmaxs[1]) ymin = min(ymin, vmins[1]) patches = np.array(patches, dtype=object) pc = PatchCollection(patches) ax = gca() pc.set_array(power) ax.add_collection(pc) ax.set_xlim(xmin, xmax) ax.set_ylim(ymin, ymax) cbar = plt.colorbar(pc) cbar.ax.set_ylabel('Power [MW]') for i in range(11): plt.text(x=coord[i][0]-F/3, y=coord[i][1]-2.5, s=np.round(power[i], 2), fontsize=12, color='w') plt.axis('equal') plt.xlabel('X [cm]') plt.ylabel('Y [cm]') plt.savefig(save, dpi=300, bbox_inches="tight") plt.close()
n_cols = int(EW / w) + 1 # Approximate number of hexagons per column = NS/d n_rows = int(NS / d) + 10 # Make a hexagonal grid to cover the entire area from matplotlib.patches import RegularPolygon ax = TIME_EDGES.boundary.plot(edgecolor='black', figsize=(20, 60)) w = (xmax - xmin) / n_cols # width of hexagon d = w / np.sin(np.pi / 3) # diameter of hexagon array_of_hexes = [] for rows in range(0, n_rows): hcoord = np.arange(xmin, xmax, w) + (rows % 2) * w / 2 vcoord = [ymax - rows * d * 0.75] * n_cols for x, y in zip(hcoord, vcoord): # , colors): hexes = RegularPolygon((x, y), numVertices=6, radius=d / 2, alpha=0.2, edgecolor='k') verts = hexes.get_path().vertices trans = hexes.get_patch_transform() points = trans.transform(verts) array_of_hexes.append(Polygon(points)) ax.add_patch(hexes) ax.set_xlim([xmin, xmax]) ax.set_ylim([ymin, ymax]) hex_grid = gpd.GeoDataFrame({'geometry': array_of_hexes}, crs={'init': 'epsg:4326'}) # hex_grid = gpd.GeoDataFrame({'geometry':array_of_hexes},crs={'init':'epsg:3035'}) # hex_grid.plot() ############################################################################################# # create basemap
def _draw_beam_schematic(self, ax): """Auxiliary function for plotting the beam object and its applied loads. """ # Adjust y-axis ymin, ymax = -5, 5 ylim = (min(ax.get_ylim()[0], ymin), max(ax.get_ylim()[1], ymax)) ax.set_ylim(ylim) xspan = ax.get_xlim()[1] - ax.get_xlim()[0] yspan = ylim[1] - ylim[0] # Draw beam body beam_left, beam_right = self._x0, self._x1 beam_length = beam_right - beam_left beam_height = yspan * 0.06 beam_bottom = -(0.75) * beam_height beam_top = beam_bottom + beam_height beam_body = Rectangle((beam_left, beam_bottom), beam_length, beam_height, fill=True, facecolor="brown", clip_on=False, alpha=0.7) ax.add_patch(beam_body) # Markers at beam supports pinned_support = Polygon( np.array([ self.pinned_support + 0.01 * xspan * np.array( (-1, -1, 0, 1, 1)), beam_bottom + 0.05 * np.array( (-1.5, -1, 0, -1, -1.5)) * yspan ]).T) rolling_support = [ Polygon( np.array([ self.rolling_support + 0.01 * xspan * np.array((-1, 0, 1)), beam_bottom + 0.05 * np.array((-1, 0, -1)) * yspan ]).T), Polygon( np.array([ self.rolling_support + 0.01 * xspan * np.array( (-1, -1, 1, 1)), beam_bottom + 0.05 * np.array( (-1.5, -1.25, -1.25, -1.5)) * yspan ]).T) ] supports = PatchCollection([pinned_support, *rolling_support], facecolor="black") ax.add_collection(supports) # Draw arrows at point loads arrowprops = dict(arrowstyle="simple", color="darkgreen", shrinkA=0.1, mutation_scale=18) for load in self._point_loads_y(): x0 = x1 = load[1] if load[0] < 0: y0, y1 = beam_top, beam_top + 0.17 * yspan else: y0, y1 = beam_bottom, beam_bottom - 0.17 * yspan ax.annotate("", xy=(x0, y0), xycoords='data', xytext=(x1, y1), textcoords='data', arrowprops=arrowprops) for load in self._point_loads_x(): x0 = load[1] y0 = y1 = (beam_top + beam_bottom) / 2.0 if load[0] < 0: x1 = x0 + xspan * 0.05 else: x1 = x0 - xspan * 0.05 ax.annotate("", xy=(x0, y0), xycoords='data', xytext=(x1, y1), textcoords='data', arrowprops=arrowprops) # Draw a round arrow at point torques for load in self._point_torques(): xc = load[1] yc = (beam_top + beam_bottom) / 2.0 width = yspan * 0.17 height = xspan * 0.05 arc_len = 180 if load[0] < 0: start_angle = 90 endX = xc + (height / 2) * np.cos( np.radians(arc_len + start_angle)) endY = yc + (width / 2) * np.sin( np.radians(arc_len + start_angle)) else: start_angle = 270 endX = xc + (height / 2) * np.cos(np.radians(start_angle)) endY = yc + (width / 2) * np.sin(np.radians(start_angle)) orientation = start_angle + arc_len arc = Arc([xc, yc], width, height, angle=start_angle, theta2=arc_len, capstyle='round', linestyle='-', lw=2.5, color="darkgreen") arrow_head = RegularPolygon((endX, endY), 3, height * 0.35, np.radians(orientation), color="darkgreen") ax.add_patch(arc) ax.add_patch(arrow_head) ax.axes.get_yaxis().set_visible(False) ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) ax.spines['left'].set_visible(False)
fig.canvas.mpl_connect('button_press_event', self.on_press) fig.canvas.mpl_connect('button_release_event', self.on_release) fig.canvas.mpl_connect('motion_notify_event', self.on_motion) def on_press(self, event): for patch in reversed(self.ax.patches): if patch.contains_point((event.x, event.y)): self.selected_patch = patch self.start_mouse_pos = np.array([event.xdata, event.ydata]) self.start_patch_pos = patch.xy break def on_motion(self, event): if self.selected_patch is not None: pos = np.array([event.xdata, event.ydata]) self.selected_patch.xy = self.start_patch_pos + pos - self.start_mouse_pos self.ax.figure.canvas.draw() def on_release(self, event): self.selected_patch = None fig, ax = plt.subplots() ax.set_aspect("equal") for i in range(10): poly = RegularPolygon(rand(2), randint(3, 10), rand()*0.1+0.1, facecolor=rand(3)) ax.add_patch(poly) ax.relim() ax.autoscale() pm = PatchMover(ax) plt.show()
if patch.contains_point((event.x, event.y)): self.selected_patch = patch self.start_mouse_pos = np.array([event.xdata, event.ydata]) self.start_patch_pos = patch.xy break def on_motion(self, event): if self.selected_patch is not None: pos = np.array([event.xdata, event.ydata]) self.selected_patch.xy = self.start_patch_pos + pos - self.start_mouse_pos self.ax.figure.canvas.draw_idle() def on_release(self, event): self.selected_patch = None if __name__ == '__main__': fig, ax = plt.subplots() ax.set_aspect("equal") for i in range(10): poly = RegularPolygon(rand(2), randint(3, 10), rand() * 0.1 + 0.1, facecolor=rand(3), zorder=randint(10, 100)) ax.add_patch(poly) ax.relim() ax.autoscale() pm = PatchMover(ax) plt.show()
height_ratios=[1], width_ratios=[1, 0.075, 1, 0.075]) ax7 = fig.add_subplot(gspec[0, 0]) xx, yy = SOM_DTLZ2.get_euclidean_coordinates() umatrix = SOM_DTLZ2.distance_map() weights = SOM_DTLZ2.get_weights() for i in range(weights.shape[0]): for j in range(weights.shape[1]): wy = yy[(i, j)] * 2 / np.sqrt(3) * 3 / 4 hex = RegularPolygon((xx[(i, j)], wy), numVertices=6, radius=.95 / np.sqrt(3), facecolor=cm.Greens(umatrix[i, j]), alpha=.8, edgecolor='gray') ax7.add_patch(hex) ax7.set_xlim([-1, 14]) ax7.set_ylim([-1, 13]) ax7.set_title('SOM: 4 Obj DTLZ 2') ax_cb = fig.add_subplot(gspec[0, 1]) cb1 = colorbar.ColorbarBase(ax_cb, cmap=cm.Greens, orientation='vertical', alpha=.4) cb1.ax.get_yaxis().set_ticks_position('left') cb1.ax.get_yaxis().set_label_position('left') cb1.ax.get_yaxis().labelpad = 12
def reset(self): """ Reset obstacles and agents location Args: Return: obs: map image """ # Prepare self.step_counter = 0 self.evaders = dict( name=['e-0'], position=np.inf * np.ones((1, 2)), velocity=np.zeros((1, 2)), trajectory=[], status=['deactivated'], ) self.pursuers = dict( name=['p-0'], position=np.inf * np.ones((1, 2)), velocity=np.zeros((1, 2)), trajectory=[], status=['deactivated'], ) self.spawning_pool = random.uniform( -self.world_length / 2 + .5, self.world_length / 2 - .5, size=(2, 2)) # .5 threshold to avoid spawning too close to the walls obs = np.zeros((self.resolution[0], self.resolution[1], 3), dtype=np.uint8) # Reset obstacles: you can add more shapes in the section below self.obstacle_patches = [] circle = Circle(xy=[0, 0], radius=1, fc='grey') self.obstacle_patches.append(circle) north_box = Rectangle(xy=[-2, 3], width=4, height=2, fc='grey') self.obstacle_patches.append(north_box) south_box = Rectangle(xy=[-2, -5], width=4, height=2, fc='grey') self.obstacle_patches.append(south_box) obs[:, :, 1] = 255 * self._get_image( patch_list=self.obstacle_patches, radius=self.world_length / np.min(self.resolution) / 2) # Reset Evaders self.evaders['position'][0] = self.spawning_pool[0] while any([ self._is_occluded(self.evaders['position'][0], radius=self.evader_radius), self._is_interfered(self.evaders['position'][0], radius=2 * self.evader_radius) ]): # evaders are sneaky so that they can stay closer to each other self.evaders['position'][0] = random.uniform( -self.world_length / 2 + .3, self.world_length / 2 - .3, 2) self.evaders['velocity'] = np.zeros((self.num_evaders, 2)) self.evaders['trajectory'].append(self.evaders['position'].copy()) self.evaders['status'] = ['active'] * self.num_evaders self.spawning_pool[0] = self.evaders['position'][0].copy() ## create evader patches, 八面玲珑 self.evader_patches = [] octagon = RegularPolygon(xy=self.evaders['position'][0], numVertices=8, radius=self.evader_radius, fc='orangered') self.evader_patches.append(octagon) obs[:, :, 0] = 255 * self._get_image(patch_list=[octagon], radius=self.evader_radius) # Reset Pursuers self.pursuers['position'][0] = self.spawning_pool[-1] while any( [ self._is_occluded(self.pursuers['position'][0], radius=self.pursuer_radius), self._is_interfered(self.pursuers['position'][0], radius=2 * self.interfere_radius) ] ): # pursuer has to work safely so that they don't want to start too close to others self.pursuers['position'][0] = random.uniform( -self.world_length / 2 + .3, self.world_length / 2 - .3, 2) self.pursuers['velocity'] = np.zeros((self.num_pursuers, 2)) self.pursuers['trajectory'].append(self.pursuers['position'].copy()) self.pursuers['status'] = ['active'] * self.num_pursuers self.spawning_pool[-1] = self.pursuers['position'][0].copy() ## create pursuer patches, 圆滑世故 self.pursuer_patches = [] circle = Circle(xy=self.pursuers['position'][0], radius=self.pursuer_radius, fc='deepskyblue') self.pursuer_patches.append(circle) obs[:, :, -1] = 255 * self._get_image(patch_list=[circle], radius=self.pursuer_radius) # Create map image self.image[:, :, 0] = obs[:, :, 0] self.image[:, :, 1] = obs[:, :, 1] self.image[:, :, 2] = obs[:, :, 2] return obs
def __init__( self, geometry, image=None, ax=None, title=None, norm="lin", cmap=None, allow_pick=False, autoupdate=True, autoscale=True, ): self.axes = ax if ax is not None else plt.gca() self.pixels = None self.colorbar = None self.autoupdate = autoupdate self.autoscale = autoscale self._active_pixel = None self._active_pixel_label = None self._axes_overlays = [] self.geom = geometry if title is None: title = geometry.cam_id # initialize the plot and generate the pixels as a # RegularPolyCollection patches = [] if not hasattr(self.geom, "mask"): self.geom.mask = np.ones_like(self.geom.pix_x.value, dtype=bool) pix_x = self.geom.pix_x.value[self.geom.mask] pix_y = self.geom.pix_y.value[self.geom.mask] pix_area = self.geom.pix_area.value[self.geom.mask] for x, y, area in zip(pix_x, pix_y, pix_area): if self.geom.pix_type.startswith("hex"): r = sqrt(area * 2 / 3 / sqrt(3)) + 2 * PIXEL_EPSILON poly = RegularPolygon( (x, y), 6, radius=r, orientation=self.geom.pix_rotation.to_value(u.rad), fill=True, ) else: r = sqrt(area) + PIXEL_EPSILON poly = Rectangle( (x - r / 2, y - r / 2), width=r, height=r, angle=self.geom.pix_rotation.to_value(u.deg), fill=True, ) patches.append(poly) self.pixels = PatchCollection(patches, cmap=cmap, linewidth=0) self.axes.add_collection(self.pixels) self.pixel_highlighting = copy.copy(self.pixels) self.pixel_highlighting.set_facecolor('none') self.pixel_highlighting.set_linewidth(0) self.axes.add_collection(self.pixel_highlighting) # Set up some nice plot defaults self.axes.set_aspect('equal', 'datalim') self.axes.set_title(title) self.axes.set_xlabel(f"X position ({self.geom.pix_x.unit})") self.axes.set_ylabel(f"Y position ({self.geom.pix_y.unit})") self.axes.autoscale_view() # set up a patch to display when a pixel is clicked (and # pixel_picker is enabled): self._active_pixel = copy.copy(patches[0]) self._active_pixel.set_facecolor('r') self._active_pixel.set_alpha(0.5) self._active_pixel.set_linewidth(2.0) self._active_pixel.set_visible(False) self.axes.add_patch(self._active_pixel) self._active_pixel_label = self.axes.text(self._active_pixel.xy[0], self._active_pixel.xy[1], "0", horizontalalignment='center', verticalalignment='center') self._active_pixel_label.set_visible(False) # enable ability to click on pixel and do something (can be # enabled on-the-fly later as well: if allow_pick: self.enable_pixel_picker() if image is not None: self.image = image else: self.image = np.zeros_like(self.geom.pix_id, dtype=np.float) self.norm = norm
def plotFocalPlaneQuicklook(dra, ddec, pa, scale, ifu_centers, ra, dec, CD, im_size, color='green', linewidth=0.2): """Patrol circles collection Plot the region of IFUs and patrol circle and return as a :class:`~matplotlib.collections.PatchCollection`, which can be added to a plot using :meth:`~matplotlib.Axes.add_collection`. .. todo:: `ifu_size` is hard coded to 0.012. Move to optional argument Rename the function: function does not plot! Parameters ---------- dra, ddec : float ? coordinates pa : float ? scale : float pixel scale ifu_centers : list list of ifu coordinates? ra, dec : flat reference coordinates CD : ? ?? im_size : float size of the image color : matplotlib color, optional color of the circles linewidth : float, optional width of the line of the circles Returns ------- :class:`~matplotlib.collection.PatchCollection` instance collection of patrol circles """ ifu_size = 0.012 patches = [] rpa = pa / 180. * np.pi # plot all IFU regions for c in ifu_centers: xr, yr = wcs2pix(c[0], c[1], ra, dec, CD=CD, scale=scale, im_size=im_size) # still need to correct the xr? rpol = RegularPolygon( (xr, yr), 4, radius=pyhwcs.deg2pix(ifu_size, scale) / np.sqrt(2.), orientation=rpa - np.pi / 4., linewidth=100.) patches.append(rpol) return PatchCollection(patches, edgecolor=color, facecolor='none')
def plot_hextensor(tensor, image_range=(0, None), channel_range=(0, None), cmap='Greys', figname='figure', mask=[]): r"""Plot the hexagonal representation of a 4D tensor according to the addressing sheme used by HexagDLy. Args: tensor: torch tensor or numpy array containing the hexagonal data points image_range: tuple of ints, range defining the images to be plotted channel_range: tuple of ints, range defining the channels to be plotted cmap: colourmap figname: str, name of figure mask: list of ints that depict the pixels to skip in plots counting top to bottom left to right from the top left pixel """ try: tensor = tensor.data.numpy() except Exception as e: print('Input not given as pytorch tensor!') pass inshape = np.shape(tensor[image_range[0]:image_range[1], channel_range[0]:channel_range[1]]) inexamples = inshape[0] inchannels = inshape[1] if inexamples != 1 and inchannels != 1: print( 'Choose one image and n channels or one channel an n images to display!' ) sys.exit() nimages = max(inexamples, inchannels) hexagons = [[] for i in range(nimages)] intensities = [[] for i in range(nimages)] fig = plt.figure(figname, (5, 5)) fig.clear() nrows = int(np.ceil(np.sqrt(nimages))) gs = gridspec.GridSpec(nrows, nrows) gs.update(wspace=0, hspace=0) for i in range(nimages): if inexamples >= inchannels: a = i b = 0 else: a = 0 b = i npixel = 0 for x in range( np.shape(tensor[image_range[0] + a, channel_range[0] + b])[1]): for y in range( np.shape(tensor[image_range[0] + a, channel_range[0] + b])[0]): if npixel not in mask: intensity = tensor[image_range[0] + a, channel_range[0] + b, y, x] hexagon = RegularPolygon( (x * np.sqrt(3) / 2, -(y + np.mod(x, 2) * 0.5)), 6, 0.577349, orientation=np.pi / 6) intensities[i].append(intensity) hexagons[i].append(hexagon) npixel += 1 ax = fig.add_subplot(gs[i]) ax.set_xlim([ -1, np.shape(tensor[image_range[0] + a, channel_range[0] + b])[0] ]) ax.set_ylim([ -1.15 * np.shape(tensor[image_range[0] + a, channel_range[0] + b])[1] - 1, 1 ]) ax.set_axis_off() p = PatchCollection(np.array(hexagons[i]), cmap=cmap, alpha=0.9, edgecolors='k', linewidth=1) p.set_array(np.array(np.array(intensities[i]))) ax.add_collection(p) ax.set_aspect('equal') plt.subplots_adjust(top=0.95, bottom=0.05) plt.tight_layout()
def plot_spi(self, with_pseudo_detectors=True, show_detector_number=True, cmap='viridis', pseudo_cmap='plasma'): fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'}) radius = 2 * 1.732 # first get the colors based of the contents colors, pseudo_colors = self._get_colors_from_contents( cmap, pseudo_cmap) # color iterators n = 0 pseudo_n = 0 # now we loop over all the detectors and if they have contents # we will plot them for detector in self._detectors: # first the real detectors if not detector.is_pseudo_detector: if detector.contents is not None: # create a ploygon and color it based of the contents p = RegularPolygon(xy=detector.origin, numVertices=6, radius=radius, facecolor=colors[n], ec='k', lw=3) ax.add_patch(p) # show the detector number if show_detector_number: ax.text(detector.origin[0], detector.origin[1], detector.detector_number, ha="center", va="center", color='k', size=14) n += 1 # TODO: plot the double event detectors # TODO: plot the triple event detectos # now the pseudo detectors if we have chosen to plot them # # if detector.is_pseudo_detector and with_pseudo_detectors: # # if detector.contents is not None: # p = RegularPolygon(xy=detector.origin, # numVertices=6, # radius=radius, # facecolor=pseudo_colors[pseudo_n], alpha=.5) # # ax.add_patch(p) # # # show the detector number # if show_detector_number: # ax.text(detector.origin[0], detector.origin[1], detector.detector_number, ha="center", va="center", # color='k', size=14) # # pseudo_n += 1 ax.set_xlim(-16, 16) ax.set_ylim(-16, 16) ax.set_yticks([]) ax.set_xticks([])