Exemple #1
0
def checkOverlap(flag, n, a1, b1, a2, b2):
    ## Generate the sets of points and find their hulls
    if flag:
        setA = generateUniform(n, a1, b1)
        setB = generateUniform(n, a2, b2)
    else:
        setA = generateNormal(n, a1, b1)
        setB = generateNormal(n, a2, b2)
    hullA = jarvisMarch(setA)
    hullB = jarvisMarch(setB)

    ## Do all the plotting
    setAx, setAy = extractCoords(setA)
    setBx, setBy = extractCoords(setB)
    hullAx, hullAy = extractCoords(hullA)
    hullBx, hullBy = extractCoords(hullB)
    plt.plot(setAx, setAy, 'b.')
    plt.plot(setBx, setBy, 'c.')
    plt.plot(hullAx, hullAy, 'ro')
    plt.plot(hullBx, hullBy, 'mo')

    ## Approximate the centers of the hulls
    centerA = (avg(hullAx), avg(hullAy))
    centerB = (avg(hullBx), avg(hullBy))
    ## Find the maximum radii of the hulls and add the bounding
    ## circles to the plot
    rA = radius(centerA, hullA)
    rB = radius(centerB, hullB)
    circleA = plt.Circle(centerA, rA, color='r', fill=False)
    circleB = plt.Circle(centerB, rB, color='m', fill=False)
    ax = plt.gca()
    ax.add_patch(circleA)
    ax.add_patch(circleB)
    plt.axis('scaled')
    plt.show()
    ## If the distance between the centers is less than the sum
    ## of the radii the circles overlap
    if rA + rB >= dist(centerA, centerB):
        return 1
    return 0
Exemple #2
0
def draw_neural_net(ax, left, right, bottom, top, layer_sizes):
    '''
    Draw a neural network cartoon using matplotilb.

    :usage:
        >>> fig = plt.figure(figsize=(12, 12))
        >>> draw_neural_net(fig.gca(), .1, .9, .1, .9, [4, 7, 2])

    :parameters:
        - ax : matplotlib.axes.AxesSubplot
            The axes on which to plot the cartoon (get e.g. by plt.gca())
        - left : float
            The center of the leftmost node(s) will be placed here
        - right : float
            The center of the rightmost node(s) will be placed here
        - bottom : float
            The center of the bottommost node(s) will be placed here
        - top : float
            The center of the topmost node(s) will be placed here
        - layer_sizes : list of int
            List of layer sizes, including input and output dimensionality
    '''
    n_layers = len(layer_sizes)
    v_spacing = (top - bottom) / float(max(layer_sizes))
    h_spacing = (right - left) / float(len(layer_sizes) - 1)
    # Nodes
    for n, layer_size in enumerate(layer_sizes):
        layer_top = v_spacing * (layer_size - 1) / 2. + (top + bottom) / 2.
        for m in range(layer_size):
            circle = plt.Circle(
                (n * h_spacing + left, layer_top - m * v_spacing),
                v_spacing / 4.,
                color='w',
                ec='k',
                zorder=4)
            ax.add_artist(circle)
    # Edges
    for n, (layer_size_a,
            layer_size_b) in enumerate(zip(layer_sizes[:-1], layer_sizes[1:])):
        layer_top_a = v_spacing * (layer_size_a - 1) / 2. + (top + bottom) / 2.
        layer_top_b = v_spacing * (layer_size_b - 1) / 2. + (top + bottom) / 2.
        for m in range(layer_size_a):
            for o in range(layer_size_b):
                line = plt.Line2D(
                    [n * h_spacing + left, (n + 1) * h_spacing + left],
                    [layer_top_a - m * v_spacing, layer_top_b - o * v_spacing],
                    c='k')
                ax.add_artist(line)
Exemple #3
0
    def __init__(self, nodeid, bs, period, packetlen):
        self.nodeid = nodeid
        self.period = period
        self.bs = bs
        self.x = 0
        self.y = 0

        # this is very complex prodecure for placing nodes
        # and ensure minimum distance between each pair of nodes
        found = 0
        rounds = 0
        global nodes
        while (found == 0 and rounds < 100):
            a = random.random()
            b = random.random()
            if b<a:
                a,b = b,a
            posx = b*maxDist*math.cos(2*math.pi*a/b)+bsx
            posy = b*maxDist*math.sin(2*math.pi*a/b)+bsy
            if len(nodes) > 0:
                for index, n in enumerate(nodes):
                    dist = np.sqrt(((abs(n.x-posx))**2)+((abs(n.y-posy))**2))
                    if dist >= 10:
                        found = 1
                        self.x = posx
                        self.y = posy
                    else:
                        rounds = rounds + 1
                        if rounds == 100:
                            print ("could not place new node, giving up")
                            exit(-1)
            else:
                print ("first node")
                self.x = posx
                self.y = posy
                found = 1
        self.dist = np.sqrt((self.x-bsx)*(self.x-bsx)+(self.y-bsy)*(self.y-bsy))
        print('node %d' %nodeid, "x", self.x, "y", self.y, "dist: ", self.dist)

        self.packet = myPacket(self.nodeid, packetlen, self.dist)
        self.sent = 0

        # graphics for node
        global graphics
        if (graphics == 1):
            global ax
            ax.add_artist(plt.Circle((self.x, self.y), 2, fill=True, color='blue'))
    def Gershgorin(self):
        if is_square(self.x) != True:
            print('Please enter a square matrix')
            return []
        else:

            row_sum = []
            list_diagonals = []
            list_diagonals.append(np.array(self.x).diagonal())
            self.x = np.absolute(self.x)

            row_sum.append(
                np.array(self.x).sum(axis=1) - np.array(self.x).diagonal())
            y, z = row_sum, list_diagonals
            z = np.array(z).tolist()
            y = np.array(y).tolist()
            circles = list(map(list, zip(z[0], y[0])))
            index, radi = zip(*circles)

            Xupper = max(index) + np.std(index)
            Xlower = min(index) - np.std(index)
            Ylimit = max(radi) + np.std(index)
            fig, ax = plt.subplots()

            ax = plt.gca()

            ax.cla()
            ax.set_xlim((Xlower, Xupper))
            ax.set_ylim((-Ylimit, Ylimit))
            plt.xlabel('Real Axis')
            plt.ylabel('Imaginary Axis')
            plt.title('Gershgorin circles')
            for x in range(0, len(circles)):

                circ = plt.Circle((index[x], 0), radius=radi[x])
                ax.add_artist(circ)

            ax.plot([Xlower, Xupper], [0, 0], 'k--')
            ax.plot([0, 0], [-Ylimit, Ylimit], 'k--')
            ax.yaxis.grid(True, linestyle="--")
            ax.xaxis.grid(True, linestyle="--")
            for i in index:

                plt.axvline(x=i, linestyle='--', color='r')  # vertical lines

            plt.show()
Exemple #5
0
def sim_pi(total_sim):
    np.random.seed(
        0
    )  #creating a random seed to save the previous random numbers generated
    x_new = []  #creating an empty list for x values
    y_new = []  #creating an empty list for y values
    circle = [
    ]  #creating an empty list to save the values that fall inside the circle

    radius = 0.5
    cir_plot = plt.Circle((0.5, 0.5), 0.5, color='r',
                          fill=False)  #plotting a circle
    sq_plot = plt.Rectangle((0, 0), 1, 1, color='b',
                            fill=False)  #plotting a rectangle
    fig = plt.gcf()
    ax = fig.gca(adjustable='box')
    ax.set_aspect('equal')
    ax.add_artist(cir_plot)
    ax.add_artist(sq_plot)

    dots = 0

    for i in np.arange(total_sim):
        x = np.random.rand(1, 1)
        y = np.random.rand(1, 1)
        x_new = np.append(x_new, x)
        y_new = np.append(y_new, y)

        if (x - 0.5)**2 + (y - 0.5)**2 < radius**2:
            circle = np.append(circle, "red")
            dots += 1
        else:
            circle = np.append(circle, "blue")

    plot = plt.scatter(x_new, y_new, s=1.5, color=circle)

    pi_val = (dots / total_sim) * 4
    diff = round(abs(pi_val - 3.14159), 4)
    print("This simulation gives a pi value of",
          str(pi_val) + ". The difference between the known pi value of",
          str(3.14) + " and our simulated value is",
          str(diff) + ".")
Exemple #6
0
def checkCircle(data):
    import matplotlib as plot
    # Transform data by rotation so that all data appears in the firt and
    # second quadrants (so that positive square root solution is valid)
    rot = np.arctan2(data[-1, 1] - data[0, 1], data[-1, 0] - data[0, 0])
    R = getRotMat(rot + np.pi)
    trans = np.matmul(data, R)
    trans[:, 1] *= -1

    # Display transformed data used for the actual fit
    plot.figure(2)
    plot.clf()
    plot.plot(trans[:, 0], trans[:, 1], '*')
    plot.axis("equal")

    thresh = 0.01
    E = 10
    count = 0
    # Perform gradient descent up to four times with slightly different guesses
    # until a low E solution is found.
    while E > thresh and count < 4:
        count += 1
        xBar = np.mean(trans[:, 0]) * (0.95 + np.random.rand(1) * 0.1)[0]
        yBar = np.min(trans[:, 1]) * (0.95 + np.random.rand(1) * 0.1)[0]
        rBar = np.abs((trans[0, 0] - trans[-1, 0]) /
                      2) * (0.95 + np.random.rand(1) * 0.1)[0]
        x0, y0, r, E = descent(trans, xBar, yBar, rBar)
        print(E)

    # More plotting of transformed data
    circle = plot.Circle((x0, y0), r, color='r', fill=False)
    plot.gca().add_artist(circle)

    # Rotate back to original coordinates
    y0 *= -1
    center = np.matmul([x0, y0], np.linalg.inv(R))
    if E < thresh:
        return center, r
    else:
        return None, None
Exemple #7
0
def udaljenost_tocke(x1,y1,x2,y2,r):
    plt.xlim([0,10])
    plt.ylim([0,10])
    kruznica = plt.Circle((x2,y2),r,color='r')
    plt.gca().add_artist(kruznica)
    plt.plot(x1,y1, 'bo')
    x = (x1-x2)**2 + (y1-y2)**2
    d = sqrt(x)
    nacin = int(input('Unesi 1 za prikaz slike, 2 za spremanje'))
    if znak ==1:
        plt.show()
    elif znak ==2:
        naziv = input('Unesite naziv slike:')
        plt.savefig(f'{naziv}.pdf')

    epsilon = 0.01
    if d < r:
        print(f'Točka je unutar kružnice, a udaljenost je {d}.')
    elif r-epsilon < d < r+epsilon:
        print(f'Točka se nalazi na kružnici.')
    else:
        print(f'Točka je izvan kružnice, a udaljenost je {d}.')
Exemple #8
0
def plot_station(fig,
                 ax,
                 station: Station,
                 station_v_cat,
                 C,
                 scale,
                 bar=True,
                 scale_bar=10):
    i = station.ind
    node = station.node
    crd = node.crd
    station_v = [station_v_cat[:, 0], station_v_cat[:, 1:]]

    queue = station_v[0].cpu().numpy()

    scalex, scaley = scale
    font_size = scaley * 800

    ax.add_patch(plt.Circle(crd, radius=30, color=C[i]))
    ax.text(crd[0],
            crd[1] - 70,
            "{}".format(int(sum(queue))),
            ha='center',
            va='center',
            fontsize=font_size)

    if bar:
        bar_scale_x = scalex * 10
        bar_scale_y = scaley * 10

        crd_base_bar = [crd[0], crd[1] + 40]
        pix_crd_base_bar = ax.transData.transform(crd_base_bar)
        bar_x, bar_y = ax.transAxes.inverted().transform(pix_crd_base_bar)
        ax_bar = fig.add_axes(
            [bar_x - bar_scale_x / 2, bar_y, bar_scale_x, bar_scale_y * 10])
        ax_bar.bar(np.arange(len(queue)), queue, color=C)
        ax_bar.set_ylim(0, scale_bar * 10)
        ax_bar.axis('off')
Exemple #9
0
Emax = 3
E = sqrt(vx**2 + vy**2)
k = find(E.flat[:]>Emax)
vx.flat[k] = nan
vy.flat[k] = nan

# plot vecor field
quiver(x, y, vx, vy, pivot='middle', headwidth=4, headlength=6)
xlabel('$x$')
ylabel('$y$')
axis('image')

fig = plt.gcf()

beacon1 = plt.Circle(beaXY,bR, color='g', fill=True)
fig.gca().add_artist(beacon1)

bealin1 = FancyArrowPatch((beaXY[0] - 2 * bR, beaXY[1]),(beaXY[0] + 2*bR, beaXY[1]), arrowstyle = '-', mutation_scale=1)
fig.gca().add_artist(bealin1)
bealin2 = FancyArrowPatch((beaXY[0], beaXY[1] - 2 * bR),(beaXY[0], beaXY[1] + 2 * bR), arrowstyle = '-', mutation_scale=1)
fig.gca().add_artist(bealin2)

desiredRadius = plt.Circle(beaXY, dR, color='b', fill=False, linestyle='dashdot')
fig.gca().add_artist(desiredRadius)

sensorRadius = plt.Circle(beaXY, sR, color='g', fill=False, linestyle='dashdot')
fig.gca().add_artist(sensorRadius)

desiredDistToRobot = plt.Circle(robXY, dD, color='b', fill=False, linestyle='dashdot')
fig.gca().add_artist(desiredDistToRobot)
def Problem3():
    import matplotlib.pyplot as plt
    import numpy as np
    import random
    import math

    random.seed()
    ntrials = 10
    nwalks = 10
    nsteps = 100000
    MFP = .1  #mean free path
    r_circle = 10  #radius of circle
    d = np.array([])
    d2 = np.array([])

    ichoose = 0

    if ichoose == 0:
        fig, ax = plt.subplots()
    else:
        fig, ax = plt.subplots(1, 2)

    for iwalk in range(nwalks):

        xpos = 0
        ypos = 0
        rpos = 0
        nstep = np.array([])
        xarr = np.array([])
        yarr = np.array([])
        nstep = np.append(nstep, 0)
        xarr = np.append(xarr, xpos)
        yarr = np.append(yarr, ypos)

        count = 1
        xpos = 0
        ypos = 0
        d2pos = 0

        for step in range(nsteps):

            #generate theta between 0 and 2pi
            theta = 2 * np.pi * random.random()

            xpoint = MFP * np.cos(theta)
            ypoint = MFP * np.sin(theta)

            #normalize these so the length of the step is 1
            xnorm = xpoint / np.sqrt(xpoint**2 + ypoint**2)
            ynorm = ypoint / np.sqrt(xpoint**2 + ypoint**2)

            #add xnorm to xpos, ynorm to ypos
            xpos += xnorm
            ypos += ynorm

            r = np.sqrt(xpos**2 + ypos**2)

            count += 1
            xarr = np.append(xarr, xpos)  #append xpos to the xarr array
            yarr = np.append(yarr, ypos)  #append ypos to the yarr array
            nstep = np.append(nstep, count)  #append count to the nstep array

            #conditions for reaching the edge of the circle
            if r >= r_circle:
                break
            else:
                continue

        if ichoose == 0:
            ax.plot(xarr, yarr, 'r')

        d = np.append(d, xpos)
        d2 = np.append(d2, (xpos**2 + ypos**2))


#print the average amount of steps it takes to reach the edge of the circle
    print("the average number of steps is " +
          "{:.0f}".format(np.average(nstep)))

    #graph it just because it lpoks cool
    if ichoose == 0:
        circle = plt.Circle((0, 0), 10)
        ax.set(title='title', xlabel='steps', ylabel='distance')
        ax.set_xlim(-15., 15.)
        ax.set_ylim(-15., 15.)
        ax.add_artist(circle)
        ax.grid()
        plt.savefig("circlewalks.png")
        plt.show()
    elif ichoose == 1:
        ax[0].hist(d, bins=50, range=(-15., 15.), histtype='step')
        ax[0].set(title='title', xlabel='xpos', ylabel='number')
        ax[0].grid()

        print(np.mean(d2))
        ax[1].hist(d2, bins=50, range=(0., 1000.), histtype='step')
        ax[1].set(title='title', xlabel='displacement**2', ylabel='number')
        ax[1].grid()

        plt.savefig("circlewalks.png")
        plt.show()
for j, dz in enumerate(tide.normdz):
    if switch[j]:
        ax2.plot(tide.norme, dz, '-r', linewidth=0.5, alpha=0.3)
        print tide.name[j]
    else:
        ax2.plot(tide.norme, dz, '-k', linewidth=0.5, alpha=0.3)
ax2.plot(columbia.norme, columbia.normdz[0], '--k', linewidth=1., alpha=0.6)
ax2.plot(hubbard.norme, hubbard.normdz[0], '-.k', linewidth=1., alpha=0.6)
ax.plot(wolverine.norme, wolverine.normdz[0], '--k', linewidth=1., alpha=0.6)
ax.plot(gulkana.norme, gulkana.normdz[0], '-.k', linewidth=1., alpha=0.6)

#PLOTTING FLUXES AS CIRCLES
termidz = [dz[0] for dz in tide.normdz]

for i, flx in enumerate(tide.eb_bm_flx.astype(float)):
    circle1 = plt.Circle([0, termidz[i]], flx**0.5 / 10, color='r', zorder=-1)
    pth = ax2.add_patch(circle1)
plt.show()

fig.savefig(
    "/Users/igswahwsmcevan/Papers/AK_altimetry/Figures/dhdtprofiles.jpg",
    dpi=500)

#plt.legend(loc=4,fontsize=11)

#sort = N.argsort([dz[2] for dz in data.normdz])

#print data.name[sort[0]],data.name[sort[1]],data.name[sort[2]],data.name[sort[0]],data.name[sort[-2]],data.name[sort[-1]]
#print data.name[sort[0]], data.norme[25], data.normdz[sort[0]][25]
#ax.annotate(data.name[sort[0]], xy=(data.norme[25], data.normdz[sort[0]][25]), xytext=(0.4, -8),arrowprops=dict(facecolor='black', headwidth=6, width=0.4,shrink=0.02))
#ax.annotate(data.name[sort[1]], xy=(data.norme[20], data.normdz[sort[1]][20]), xytext=(0.4, -6),arrowprops=dict(facecolor='black', headwidth=6, width=0.4,shrink=0.02))
import numpy as np
import matplotlib as plt
matplotlib.use('Agg')
import matplotlib.pyplot as plt

#Descargar y almacenar los datos de Canal_ionico.txt
data = np.genfromtxt("Canal_ionico.txt")


#Hacer una grafica del corculo maximo obtenido y de las posiciones en xy (ver figura).
#Guardar dicha grafica sin mostrarla en Canal.png.

fig, ax = plt.subplots()
plt.axis('equal')
circle1 = plt.Circle(data[:,0], data[:,1], np.max(r_walk), color ='r',fill=False)
ax.add_artist(circle1)
plt.savefig("Canal.png")
plt.close()

Exemple #13
0
from matplotlib.gridspec import GridSpec
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')


# In[23]:


labels = list(data1['AgeGroup'])
sizes = list(data1['TotalCases'])
explode = []
for i in labels:
    explode.append(0.05)    
plt.figure(figsize= (15,10))
plt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=9, explode =explode)
centre_circle = plt.Circle((0,0),0.70,fc='white')
fig = plt.gcf()
fig.gca().add_artist(centre_circle)
plt.title('India - Age Group wise Distribution',fontsize = 20)
plt.axis('equal')  
plt.tight_layout()


# ## Importing and Reading the Dataset
# HospitalBedsIndia.csv

# In[24]:


data2 = pd.read_csv(r"D:\DATA SCIENCE\Covid19 analysis\557629_1323860_bundle_archive\HospitalBedsIndia.csv")
Exemple #14
0
x, y = meshgrid(x, y)

# calculate vector field
#vx = -y/sqrt(x**2+y**2)*exp(-(x**2+y**2))
#vy =  x/sqrt(x**2+y**2)*exp(-(x**2+y**2))

#repulsor do beacon
#vx = x - beaXY[0]
#vy = y - beaXY[1]

#atrator do beacon
#vx = -x + beaXY[0]
#vy = -y + beaXY[1]

#rotacao no beacon anti-horaria
vx = -(y - beaXY[1])
vy = x - beaXY[0]

# plot vecor field
quiver(x, y, vx, vy, pivot='middle', headwidth=4, headlength=6)
xlabel('$x$')
ylabel('$y$')
axis('image')

fig = plt.gcf()

beacon1 = plt.Circle(beaXY, bR, color='g', fill=True)
fig.gca().add_artist(beacon1)

show()
savefig('visualization_vector_fields_1.png')
Exemple #15
0
rotx, roty = rotacionador(x, y, beaXY[0], beaXY[1], dR, 0.1)
atrx, atry = atrator(x, y, beaXY[0], beaXY[1], dR, sR)
repx, repy = repulsor(x, y, beaXY[0], beaXY[1], dR)

vx = rotx + (atrx + repx) / 2
vy = roty + (atry + repy) / 2

# plot vecor field
quiver(x, y, vx, vy, pivot='middle', headwidth=4, headlength=6)
xlabel('$x$')
ylabel('$y$')
axis('image')

fig = plt.gcf()

beacon1 = plt.Circle(beaXY, bR, color='g', fill=True)
fig.gca().add_artist(beacon1)

bealin1 = FancyArrowPatch((beaXY[0] - 2 * bR, beaXY[1]),
                          (beaXY[0] + 2 * bR, beaXY[1]),
                          arrowstyle='-',
                          mutation_scale=1)
fig.gca().add_artist(bealin1)
bealin2 = FancyArrowPatch((beaXY[0], beaXY[1] - 2 * bR),
                          (beaXY[0], beaXY[1] + 2 * bR),
                          arrowstyle='-',
                          mutation_scale=1)
fig.gca().add_artist(bealin2)

desiredRadius = plt.Circle(beaXY,
                           dR,
def main():

    file_name = 'simpleattack-random-NNdefense'
    num_trials = 1
    method = 'random-out'
    #    method = 'nearest-out'

    #    defense_method = 'grid'
    defense_method = 'NN'
    #    defense_method = 'none'

    radius = 2.45
    target = [3, 1]
    attacker_percentage = .25
    max_iterations = 10000
    plot_num = max_iterations / 10

    data_window = 200
    buffer_window = 50
    num_neighbors = 10

    avg_precision = []
    avg_recall = []
    avg_false_positives = []
    avg_false_negatives = []
    avg_iterations = []

    for tr in range(num_trials):

        data = Dataset(p=2, n=10000, phi=0.05)
        data.generate_data(standard=True)

        (min_x, min_y) = np.min(data.X, axis=0)
        (max_x, max_y) = np.max(data.X, axis=0)
        min_x -= 10
        min_y -= 10
        max_x += 10
        max_y += 10
        xFine = 100
        yFine = 100
        thresh = 0.01

        m = mesh(min_x, max_x, min_y, max_y, xFine, yFine, radius=.05)

        if defense_method == 'grid':
            detector = Anomaly_Detector(method,
                                        data.X[:1],
                                        data.Y[:1],
                                        radius,
                                        data_window,
                                        NNdefense_on=False)
            for t in data[1:]:
                old_center = detector.get_center()
                detector.add_point(np.reshape(t.X, (1, len(t))), t.Y)
                new_center = detector.get_center()
                m.addLine(old_center, new_center)

            detector.set_grid_width(m.width)
            baseline = m.percentage()
            m.center = detector.get_center()
            m.mode = 'test'

        if defense_method == 'NN':
            detector = Anomaly_Detector(method,
                                        data.X,
                                        data.Y,
                                        radius,
                                        data_window,
                                        time_window=buffer_window,
                                        percent=attacker_percentage,
                                        NN=num_neighbors,
                                        NNdefense_on=True)

        if defense_method == 'none':
            detector = Anomaly_Detector(method,
                                        data.X,
                                        data.Y,
                                        radius,
                                        data_window,
                                        NNdefense_on=False)

        normal_pts = []
        iterations = 0
        for k in range(max_iterations):
            iterations += 1
            print iterations
            old_center = detector.get_center()
            if random.random() < attacker_percentage:
                if method == 'random-out' or method == 'average-out':
                    new_point = simple_attack(detector.get_data(), target,
                                              detector.get_r())
                else:
                    new_point = greedy_optimal_attack(detector.get_data(),
                                                      target, detector.get_r())
                new_point = np.reshape(new_point, (1, len(new_point)))
                detector.add_point(new_point, 2)
            else:
                pt = data.generate_new_points(1)
                (true_value, new_point) = (pt[0], pt[1][0])
                normal_pts.append((new_point, true_value))
                new_point = np.reshape(new_point, (1, len(new_point)))
                detector.add_point(new_point, true_value)

            if defense_method == 'grid':
                new_center = detector.get_center()
                m.addLine(old_center, new_center)
                c, w = m.checkPoints(baseline, thresh)
                for cen in c:
                    detector.add_grid_center(cen)

                rec = detector.get_grid_centers()
                w = detector.get_grid_width()
                w = w / 2
                line = [old_center, new_center]
                recs = []
                for r in rec:
                    x1 = r[0] - w
                    x2 = r[0] + w
                    y1 = r[1] - w
                    y2 = r[1] + w
                    recs.append([[x1, y1], [x2, y2]])

                should_delete = False
                for r in recs:
                    if m.line_rec_intersection(line, r):
                        should_delete = True

                if should_delete:
                    detector.remove_point()

            if (k % plot_num) == 0:

                fig = plt.figure()

                ax = fig.add_subplot(1, 1, 1)
                circ = plt.Circle(detector.get_center(), radius, fill=False)
                ax.add_patch(circ)

                plt.scatter(target[0],
                            target[1],
                            color='g',
                            marker='x',
                            s=35,
                            label='target point')
                plt.scatter(detector.get_data()[detector.get_labels() == True,
                                                0],
                            detector.get_data()[detector.get_labels() == True,
                                                1],
                            color='r',
                            marker='o',
                            s=10,
                            label='anomalous points')
                plt.scatter(detector.get_data()[detector.get_labels() == False,
                                                0],
                            detector.get_data()[detector.get_labels() == False,
                                                1],
                            color='k',
                            marker='+',
                            s=20,
                            label='nominal points')
                if attacker_percentage > 0:
                    plt.scatter(detector.get_data()[detector.get_labels() == 2,
                                                    0],
                                detector.get_data()[detector.get_labels() == 2,
                                                    1],
                                color='b',
                                marker='^',
                                s=10,
                                label='attack points')

                plt.xlim([-5, 5])
                plt.ylim([-5, 5])
                plt.gca().set_aspect('equal', adjustable='box')
                #                plt.axis('equal')
                #                plt.legend(loc=0)
                fig.savefig(file_name + get_new_num() + '.png',
                            bbox_inches='tight')

#                plt.show()

            if detector.classify_point(target):
                print 'Target achieved'
                print detector.get_center()
                break

        normal_pts = np.array(normal_pts)
        true_positive = 0
        true_negative = 0
        false_positive = 0
        false_negative = 0

        X = []
        Y = []
        true_y = []
        for n in normal_pts:
            X.append(n[0])
            Y.append(detector.classify_point(n[0]))
            true_y.append(n[1])
            if detector.classify_point(n[0]) and not n[1]:
                true_negative += 1
            if detector.classify_point(n[0]) and n[1]:
                false_negative += 1
            if not detector.classify_point(n[0]) and not n[1]:
                false_positive += 1
            if not detector.classify_point(n[0]) and n[1]:
                true_positive += 1

        print 'Number of iterations: ', iterations
        print 'True positive: ', true_positive
        print 'True negative: ', true_negative
        print 'False positive: ', false_positive
        print 'False negative: ', false_negative

        avg_iterations.append(iterations)
        avg_recall.append(
            float(true_positive) / (true_positive + false_negative))
        avg_precision.append(
            float(true_positive) / (true_positive + false_positive))
        avg_false_positives.append(
            float(false_positive) / (false_positive + true_negative))
        avg_false_negatives.append(
            float(false_negative) / (false_negative + true_positive))

    avg_iterations = np.array(avg_iterations)
    avg_recall = np.array(avg_recall)
    avg_precision = np.array(avg_precision)
    avg_false_positives = np.array(avg_false_positives)
    avg_false_negatives = np.array(avg_false_negatives)

    print 'Average iterations: ', np.mean(avg_iterations)
    print 'Average recall: ', np.mean(avg_recall)
    print 'Average precision: ', np.mean(avg_precision)
    print 'Average false positives: ', np.mean(avg_false_positives)
    print 'Average false negatives: ', np.mean(avg_false_negatives)
Exemple #17
0
def pitch(ax):
    # size of the pitch is 120, 80
    #Create figure

    #Pitch Outline & Centre Line
    plt.plot([0, 0], [0, 80], color="black")
    plt.plot([0, 120], [80, 80], color="black")
    plt.plot([120, 120], [80, 0], color="black")
    plt.plot([120, 0], [0, 0], color="black")
    plt.plot([60, 60], [0, 80], color="black")

    #Left Penalty Area
    plt.plot([14.6, 14.6], [57.8, 22.2], color="black")
    plt.plot([0, 14.6], [57.8, 57.8], color="black")
    plt.plot([0, 14.6], [22.2, 22.2], color="black")

    #Right Penalty Area
    plt.plot([120, 105.4], [57.8, 57.8], color="black")
    plt.plot([105.4, 105.4], [57.8, 22.5], color="black")
    plt.plot([120, 105.4], [22.5, 22.5], color="black")

    #Left 6-yard Box
    plt.plot([0, 4.9], [48, 48], color="black")
    plt.plot([4.9, 4.9], [48, 32], color="black")
    plt.plot([0, 4.9], [32, 32], color="black")

    #Right 6-yard Box
    plt.plot([120, 115.1], [48, 48], color="black")
    plt.plot([115.1, 115.1], [48, 32], color="black")
    plt.plot([120, 115.1], [32, 32], color="black")

    #Prepare Circles
    centreCircle = plt.Circle((60, 40), 8.1, color="black", fill=False)
    centreSpot = plt.Circle((60, 40), 0.71, color="black")
    leftPenSpot = plt.Circle((9.7, 40), 0.71, color="black")
    rightPenSpot = plt.Circle((110.3, 40), 0.71, color="black")

    #Draw Circles
    ax.add_patch(centreCircle)
    ax.add_patch(centreSpot)
    ax.add_patch(leftPenSpot)
    ax.add_patch(rightPenSpot)

    #Prepare Arcs
    # arguments for arc
    # x, y coordinate of centerpoint of arc
    # width, height as arc might not be circle, but oval
    # angle: degree of rotation of the shape, anti-clockwise
    # theta1, theta2, start and end location of arc in degree
    leftArc = Arc((9.7, 40),
                  height=16.2,
                  width=16.2,
                  angle=0,
                  theta1=310,
                  theta2=50,
                  color="black")
    rightArc = Arc((110.3, 40),
                   height=16.2,
                   width=16.2,
                   angle=0,
                   theta1=130,
                   theta2=230,
                   color="black")

    #Draw Arcs
    ax.add_patch(leftArc)
    ax.add_patch(rightArc)
Exemple #18
0
    Lpl = Ptx - minsensi
    maxDist = d0*(math.e**((Lpl-Lpld0)/(10.0*gamma)))

    # base station placement
    bsx = maxDist+10
    bsy = maxDist+10
    xmax = bsx + maxDist + 20
    ymax = bsy + maxDist + 20

    # prepare graphics and add sink
    if (graphics == 1):
        plt.ion()
        plt.figure()
        ax = plt.gcf().gca()
        # XXX should be base station position
        ax.add_artist(plt.Circle((bsx, bsy), 3, fill=True, color='green'))
        ax.add_artist(plt.Circle((bsx, bsy), maxDist, fill=False, color='green'))


    for i in range(0,nrNodes):
        # myNode takes period (in ms), base station id packetlen (in Bytes)
        # 1000000 = 16 min
        node = myNode(i,bsId, avgSendTime,20)
        nodes.append(node)
    for i in nodes:
        env.process(transmit(env,i))

    #prepare show
    if (graphics == 1):
        plt.xlim([0, xmax])
        plt.ylim([0, ymax])