コード例 #1
0
class ClipWindow:
    def __init__(self, ax, line):
        self.ax = ax
        ax.set_title('drag polygon around to test clipping')
        self.canvas = ax.figure.canvas
        self.line = line
        self.poly = RegularPolygon(
            (200, 200), numVertices=10, radius=100,
            facecolor='yellow', alpha=0.25,
            transform=transforms.identity_transform())

        ax.add_patch(self.poly)
        self.canvas.mpl_connect('button_press_event', self.onpress)
        self.canvas.mpl_connect('button_release_event', self.onrelease)
        self.canvas.mpl_connect('motion_notify_event', self.onmove)
        self.x, self.y = None, None


    def onpress(self, event):
        self.x, self.y = event.x, event.y

    def onrelease(self, event):
        self.x, self.y = None, None

    def onmove(self, event):

        if self.x is None: return
        dx = event.x - self.x
        dy = event.y - self.y
        self.x, self.y = event.x, event.y
        x, y = self.poly.xy
        x += dx
        y += dy
        #print self.y, event.y, dy, y
        self.poly.xy = x,y
        self._clip()

    def _clip(self):
        fig = self.ax.figure
        l,b,w,h = fig.bbox.get_bounds()
        path = agg.path_storage()

        for i, xy in enumerate(self.poly.get_verts()):
            x,y = xy
            y = h-y
            if i==0: path.move_to(x,y)
            else:    path.line_to(x,y)
        path.close_polygon()
        self.line.set_clip_path(path)
        self.canvas.draw_idle()
コード例 #2
0
def plot_radial_power_distribution(coord, power, pitch, figname):
    '''
    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).
    figname: [string]
        name of the figure
    '''

    F = pitch / np.sqrt(3)

    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 / 1e3)  # converts [W] into [kW]
    ax.add_collection(pc)
    ax.set_xlim(xmin, xmax)
    ax.set_ylim(ymin, ymax)
    cbar = plt.colorbar(pc)
    cbar.ax.set_ylabel('Power [kW]')
    plt.axis('equal')
    plt.xlabel('X [cm]')
    plt.ylabel('Y [cm]')
    plt.savefig(figname, dpi=300, bbox_inches="tight")
    plt.close()
コード例 #3
0
def plot_radial_power_distribution(pitch, power, compare=False, rel=False):
    '''
    Plots radial power distribution.
    Parameters:
    -----------
    pitch: [float]
        pitch between elements
    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).
    compare: [bool]
        True if printing both power and relative error in same figure
        False if printing only either the power or the relative error
    rel: [bool]
        True is plotting the relative error
        False is plotting the power
    Return:
    -------
    None
    '''

    P = pitch
    F = P / np.sqrt(2)
    coord = []

    side = int(np.sqrt(len(power)))
    for j in range(side):
        for i in range(side):
            coord.append(np.array([i * P + P / 2, j * P + P / 2]))

    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], 4, F, np.pi / 4)
        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()
    ax.set_xlim(ymin, xmax)
    ax.set_ylim(ymin, ymax)

    if compare is True:
        if rel is False:
            pc.set_array(power)
            ax.add_collection(pc)
            cbar = plt.colorbar(pc)
            cbar.ax.set_ylabel('Power [W]', fontsize=18)
            cbar.ax.tick_params(labelsize=18)
            for i in range(len(coord)):
                plt.text(x=coord[i][0] - F / 4,
                         y=coord[i][1] + F / 5,
                         s=np.round(power[i], 3),
                         fontsize=20,
                         color='w')
        else:
            for i in range(len(coord)):
                plt.text(x=coord[i][0] - F / 4,
                         y=coord[i][1] - F / 5,
                         s=np.round(power[i], 3),
                         fontsize=20,
                         color='w')
    else:
        pc.set_array(power)
        ax.add_collection(pc)
        cbar = plt.colorbar(pc)
        cbar.ax.tick_params(labelsize=18)
        if rel is False:
            cbar.ax.set_ylabel('Power [W]', fontsize=18)
        else:
            cbar.ax.set_ylabel('Relative error [%]', fontsize=18)

    ax.tick_params(axis="x", labelsize=18)
    ax.tick_params(axis="y", labelsize=18)
    plt.xlabel('X [cm]', fontsize=16)
    plt.ylabel('Y [cm]', fontsize=16)
    return None
コード例 #4
0
ファイル: VicsekFractal.py プロジェクト: Tabish-99/chaos-game
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,
                     radius=20,
                     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)
vrt = np.append(vrt, [sqr.xy], axis=0)

rx, ry = 5, 4
while sqr.contains_point((rx, ry), 0):
    rx = rd.choice(x)
    ry = rd.choice(y)

l = [*range(0, sqr.numvertices + 1)]

n = int(input("Enter iteration(min 2000): "))
for i in range(0, n):
    pix = rd.choice(l)
    cx, cy = vrt[pix]
    rx = (2 * cx + rx) / 3
    ry = (2 * cy + ry) / 3
    ax.scatter(rx, ry, s=0.25, c='b')
    print('\t\t', ['|', '/', '-', '\\'][i % 4], end='\r')
コード例 #5
0
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()
コード例 #6
0
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()
コード例 #7
0
    def hexPlot(self,
                what='tallies',
                fixed=None,
                ax=None,
                cmap=None,
                logColor=False,
                xlabel=None,
                ylabel=None,
                logx=False,
                logy=False,
                loglog=False,
                title=None,
                normalizer=None,
                cbarLabel=None,
                borderpad=2.5,
                **kwargs):
        """
        Create and return a hexagonal mesh plot.

        Parameters
        ----------
        what: {'tallies', 'errors', 'scores'}
            Quantity to plot
        fixed: None or dict
            Dictionary of slicing arguments to pass to :meth:`slice`
        {ax}
        {cmap}
        {logColor}
        {xlabel}
        {ylabel}
        {logx}
        {logy}
        {loglog}
        {title}
        borderpad: int or float
            Percentage of total plot to apply as a border. A value of
            zero means that the extreme edges of the hexagons will touch
            the x and y axis.
        {kwargs} :class:`matplotlib.patches.RegularPolygon`

        Raises
        ------
        AttributeError
            If :attr:`pitch` and :attr:`hexType` are not set.
        """
        borderpad = max(0, float(borderpad))
        if fixed and ('xcoord' in fixed or 'ycoord' in fixed):
            raise KeyError("Refusing to restrict along one of the hexagonal "
                           "dimensions {x/y}coord")
        for attr in {'pitch', 'hexType'}:
            if getattr(self, attr) is None:
                raise AttributeError("{} is not set.".format(attr))

        for key in {'color', 'fc', 'facecolor', 'orientation'}:
            checkClearKwargs(key, 'hexPlot', **kwargs)
        ec = kwargs.get('ec', None) or kwargs.get('edgecolor', None)
        if ec is None:
            ec = 'k'
        kwargs['ec'] = kwargs['edgecolor'] = ec
        if 'figure' in kwargs and kwargs['figure'] is not None:
            fig = kwargs['figure']
            if not isinstance(fig, Figure):
                raise TypeError(
                    "Expected 'figure' to be of type Figure, is {}".format(
                        type(fig)))
            if len(fig.axes) != 1 and not ax:
                raise TypeError("Don't know where to place the figure since"
                                "'figure' argument has multiple axes.")
            if ax and fig.axes and ax not in fig.axes:
                raise IndexError("Passed argument for 'figure' and 'ax', "
                                 "but ax is not attached to figure.")
            ax = ax or (fig.axes[0] if fig.axes else axes())
        alpha = kwargs.get('alpha', None)

        ny = len(self.indexes['ycoord'])
        nx = len(self.indexes['xcoord'])
        data = self.slice(fixed, what)
        if data.shape != (ny, nx):
            raise IndexError("Constrained data does not agree with hexagonal "
                             "grid structure. Coordinate grid: {}. "
                             "Constrained shape: {}".format((ny, nx),
                                                            data.shape))
        nItems = ny * nx
        patches = empty(nItems, dtype=object)
        values = empty(nItems)
        coords = self.grids['COORD']

        ax = ax or axes()
        pos = 0
        xmax, ymax = [
            -inf,
        ] * 2
        xmin, ymin = [
            inf,
        ] * 2
        radius = self.pitch / sqrt(3)

        for xy, val in zip(coords, data.flat):
            values[pos] = val
            h = RegularPolygon(xy, 6, radius, self.__hexRot, **kwargs)
            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[pos] = h
            pos += 1
        normalizer = normalizerFactory(values, normalizer, logColor,
                                       coords[:, 0], coords[:, 1])
        pc = PatchCollection(patches, cmap=cmap, alpha=alpha)
        pc.set_array(values)
        pc.set_norm(normalizer)
        ax.add_collection(pc)

        addColorbar(ax, pc, None, cbarLabel)

        formatPlot(
            ax,
            loglog=loglog,
            logx=logx,
            logy=logy,
            xlabel=xlabel or "X [cm]",
            ylabel=ylabel or "Y [cm]",
            title=title,
        )
        setAx_xlims(ax, xmin, xmax, pad=borderpad)
        setAx_ylims(ax, ymin, ymax, pad=borderpad)

        return ax
コード例 #8
0
    p2=np.array(p2)
    return round(np.linalg.norm(p2-p1),3)

def ang(rp,vrt,cnt):
    rp=np.array(rp)
    vrt=np.array(vrt)
    cnt=np.array(cnt)
    rv=vrt-rp
    rc=cnt-rp
    csx=rv.dot(rc)/np.linalg.norm(rv)/np.linalg.norm(rc)
    return np.arccos(csx)
    
fg,ax=plt.subplots(figsize=(10,10))
sq=RegularPolygon((5,4),4,5,edgecolor='k',fill=False,orientation=np.pi/4)
cr=Circle((5,4),1,edgecolor='r',fill=False)
pnt=sq.get_verts()[:4]

x=np.linspace(pnt.min(0)[0],pnt.max(0)[0],100)
y=np.linspace(pnt.min(0)[1],pnt.max(0)[1],100)

rx,ry=5,4
while not cr.contains_point((rx,ry),0):
    rx=rd.choice(x)
    ry=rd.choice(y)

sx=-2;ix=-1

i=0
inp = int(input("Enter no. of iterations(min 1000):"))
while i<inp:
    ix=rd.choice(range(0,4))