示例#1
0
def show_disc(newx, x):  # for showing converted disc
    global c
    temp = []
    for i in newx:
        temp.append(i[0])
    newx = temp
    c += 1

    maximum = max(max(x), max(newx))
    minimum = min(min(x), min(newx))
    conversion_label = str(c) + " Conversion"
    #generating random colors for every conversion
    new_ellipse = Ellipse(
        xy=(newx[0], newx[1]),
        width=2 * newx[2],
        height=2 * newx[3],
        color=[round(uni(0, 1), 1),
               round(uni(0, 1), 1),
               round(uni(0, 1), 1)],
        label=conversion_label)
    ax.add_patch(new_ellipse)
    ax.set_xlim((minimum - maximum) * 2, (maximum + x[2]) * 2)
    ax.set_ylim((minimum - maximum) * 2, (maximum + x[2]) * 2)
    ax.legend()  #for showing labels on graph
    plt.pause(0.0001)
示例#2
0
def show_polygon(newx):  # for showing converted polygon
    global c
    temp = []
    newy = []
    for i in newx:
        newy.append(i[1][0])
        temp.append(i[0][0])
    newx = temp

    maximum = max(max(newx), max(newy))
    minimum = min(min(newx), min(newy))
    if minimum > 0:
        minimum = 0

    plt.xlim(minimum - maximum, maximum * 2)
    plt.ylim(minimum - maximum, maximum * 2)
    c += 1
    conversion_label = str(c) + " Conversion"
    plt.plot(
        newx,
        newy,
        color=[round(uni(0, 1), 1),
               round(uni(0, 1), 1),
               round(uni(0, 1), 1)],
        label=conversion_label)
    plt.legend()
    plt.pause(0.0001)
示例#3
0
 def ballcollide(self):
     global balls
     for w in balls:
         if w != self:
             xdist = self.x - w.x
             ydist = self.y - w.y
             realdist = sqrt(xdist**2 + ydist**2)
             if realdist < self.r + w.r:
                 self.xvel = uni(-tem, tem)
                 self.yvel = uni(-tem, tem)
示例#4
0
def benchmark():
    """
    ...

    PARAMS:     ...
    RETURN:     ...
    """
    from random import uniform as uni

    particles = [
        Particle(uni(-1.0, 1.0), uni(-1.0, 1.0), uni(-1.0, 1.0))
        for _ in range(1000)
    ]
    simulator = ParticleSimulator(particles)
    simulator.evolve(0.1)
示例#5
0
	def act(self, actionParams=None):
		"""
		Moves robot/particle in direction denoted by self.angle by STEP_SIZE.
		If there is a wall on the way, robot stays where he is and sets
		self.lastPointFree to False, otherwise sets it to True.
		It returns (dx, dy) where he wanted to move,
		no matter did he actually go there or not.
		actionParams parameter is not currently used.
		"""
		dx = self.STEP_SIZE * np.sin(self.angle)
		dy = self.STEP_SIZE * np.cos(self.angle)
		x, y = (self.p[0] + dx, self.p[1] + dy)
		deltaAngle = 0
		if self.maze.isFree((x, y)):
			self.p = x, y
			self.lastPointFree = True
		else:
			# change direction so that robot don't stick in the wall
			if not actionParams is None:
				deltaAngle = actionParams
				self.angle += deltaAngle
			else:
				newAngle = uni(0, 2*np.pi)
				deltaAngle = newAngle - self.angle
				self.angle += deltaAngle
			self.lastPointFree = False
		if oneDistanceOnly:
			self.distFromBeacon = self.maze.distFromBeacon(self.p)
		else:
			self.distsFromBeacons = self.maze.distsFromBeacons(self.p)
		return deltaAngle
示例#6
0
	def pick(self):
		try:
			idx = bisect.bisect_left(self.distribution, uni(0, self.totalWeight))
			return self.items[idx]
		except IndexError:
			# No items in distribution
			return None
示例#7
0
    def __init__(self, coords: tuple, count: int = 10, eps: float = 1):
        """
        Coords -> ((x,y),(x,y))
        Count -> default = 10
        eps -> default = 1"""
        if len(coords) > 2:
            raise ("So much points")
        self.eps = eps
        self.coords = coords
        self.count = count

        self.points1 = [(self.coords[0][0] + uni(-self.eps, self.eps),
                         self.coords[0][1] + uni(-self.eps, self.eps))
                        for i in range(self.count)]
        self.points2 = [(self.coords[1][0] + uni(-self.eps, self.eps),
                         self.coords[1][1] + uni(-self.eps, self.eps))
                        for i in range(self.count)]
示例#8
0
def Rand(boolean):

    if boolean == True:
        #seconds = rnd(427, 604)
        seconds = round(np.random.normal(loc=60 * 15 + 9, scale=64))
    else:
        seconds = round(uni(0.4, 3.1), 2)

    return seconds
示例#9
0
 def run(self):
     while True:
         global mut, maxIn, qin, qout, h, href, R0, R1, H
         mut.acquire()
         qout = uni(0.5, 1) * (h[-1]**(1 / 2))
         #print("qout - ", qout)
         h.append(self.RungeKuttaSimples())
         mut.release()
         time.sleep(0.05)
         #print("entrou")
     self._stop()
示例#10
0
    def atualiza(self):
        upas = sorted(self.upas, key = lambda x: x.fit)
        temp = []
        temp2 = []
        mut = 0.75
        for cUPA1 in upas:
            for cUPA2 in upas:
                if uni(0,1) > 1:
                    temp.append(cUPA1.mutacao(self.c))

                temp.append(self.transa(cUPA1, cUPA2))
            temp.append(cUPA1)
        temp = sorted(temp, key = lambda y: y.fit)
        for i in range(len(upas) - 1):
            temp2.append(temp[i])
        self.upas = temp2
示例#11
0
def simulation_output(kpd,Apd,pgrid,transit,nsim,kindex,Aindex,sindex):

    # we start with capital of index kindex
    # with foreign assets of index Aindex
    # with initial state of index sindex
    # we then simulate the model over nsim periods 

    from random import uniform as uni

    klin1 = np.linspace(pgrid['kmin'],pgrid['kmax'],pgrid['nk'])
    Alin1 = np.linspace(pgrid['Amin'],pgrid['Amax'],pgrid['nA'])

    ssim = np.zeros( nsim  )
    ksim = np.zeros( nsim + 1 ) 
    Asim = np.zeros( nsim + 1 )
    
    ssim[0] = sindex
    ksim[0] = klin1[kindex]
    Asim[0] = Alin1[Aindex]
    
    # first decision

    ksim[1] = kpdecided[sindex,Aindex,kindex]
    Asim[1] = Apdecided[sindex,Aindex,kindex]
    
    for i in xrange(1,nsim):
    
        draw = uni(0,1)
        kindex1 = np.where( klin1  == ksim[i] )[0][0]
        Aindex1 = np.where( Alin1  == Asim[i] )[0][0]
    
        if draw <= stoch_transit[ssim[i-1],0]:
            ssim[i] = 0
        elif  (draw > stoch_transit[ssim[i-1],0]) and (draw<= stoch_transit[ssim[i-1],0]+stoch_transit[ssim[i-1],1]):
            ssim[i] = 1
        elif  (draw > stoch_transit[ssim[i-1],0]+stoch_transit[ssim[i-1],1]) and (draw<= stoch_transit[ssim[i-1],0]+stoch_transit[ssim[i-1],1]+stoch_transit[ssim[i-1],2]):
            ssim[i] = 2
        else:
            ssim[i] = 3
    
        ksim[i+1] = kpdecided[ssim[i],Aindex1,kindex1]
        Asim[i+1] = Apdecided[ssim[i],Aindex1,kindex1]
    
    
    return np.array([ksim,Asim,ssim])
示例#12
0
def get_cordinates():
    return (uni(0, 1), uni(0, 1))
示例#13
0
def generate_periodic(periodic_value):
    """ takes a set periodic time and returns a randomly uniformly distributed value +/- 20%"""
    half_range = periodic_value / 5
    random_uniform_time = uni(periodic_value - half_range, periodic_value + half_range)
    return random_uniform_time
示例#14
0
文件: Flags.py 项目: saeedxxx/Python
def Wind_Oscillation(m):
    tmp = (time.time() + uni(0, 2)) % 5
    if tmp >= 2 and abs(min(rx0) - m.rx) > 10:
        return tmp
    else:
        return 0
示例#15
0
文件: modules.py 项目: AV272/Python
choice([3,7,234,43])
Out[14]: 234

## Можно экспортировать все функции из модуля, но лучше этого не делать
from random import *

gauss(0,1)
Out[16]: -1.063993696883884



## Можно двать модулям клички (alias)

from random import uniform as uni

uni(0,1)
Out[18]: 0.8462290298994931

import numpy as np

np.arccos(0.5)
Out[20]: 1.0471975511965979


## Модули могут иметь подмодули. Если модуль импортирован, то подмодуль 
# не импортируется автоматически.

 from os.path import abspath

abspath('..')
Out[22]: 'C:\\Users\\Алексей'
示例#16
0
            if w != self:
                xdist = self.x - w.x
                ydist = self.y - w.y
                realdist = sqrt(xdist**2 + ydist**2)
                if realdist < self.r + w.r:
                    self.xvel = uni(-tem, tem)
                    self.yvel = uni(-tem, tem)


balls = []

j = 0
while j != 120:
    tem += 0.05
    j += 1
    radius = uni(2, 10)
    x = uni(radius, width - radius)
    y = uni(radius, height - radius)
    nope = False
    for w in balls:
        xdist = x - w.x
        ydist = y - w.y
        if xdist**2 + ydist**2 < (radius + w.r)**2:
            j -= 1
            nope = True
            break
    if nope == False:
        balls.append(ball(x, y, uni(-1, 1), uni(-1, 1), r=radius))
    print(j)

while True:
示例#17
0
	def rndParams():
		x, y = maze.randomFreePlace()
		angle = uni(0, 2*np.pi)
		return [x, y, angle]
示例#18
0
import sys
from random import uniform as uni
# k = 50 & n = 1000000 for the contest
k = int(sys.argv[1])
n = int(sys.argv[2])

print(k)
print(n)
for i in range(k+n):
	print("%f %f %f" %(uni(-100,100), uni(-100,100), uni(-100,100)))

示例#19
0
	def noiser(params):
		return [x + uni(-noiseLevel, noiseLevel) for x in params]
示例#20
0
def parabolic_select_helper(fun, a, b, n):
    for _ in range(0, n):
        x = sorted([uni(a, b) for _ in range(0, 3)])
        if fun(x[0]) >= fun(x[1]) <= fun(x[2]):
            return x
    raise Exception("Most likely your function is not unimodal")
示例#21
0
	def noiser(params):
		x = params[0] + uni(-nlimit, nlimit)
		y = params[1] + uni(-nlimit, nlimit)
		angle = params[2] + uni(-np.pi/100, np.pi/100)
		return [x, y, angle]
示例#22
0
for i in range(qual):
    summ += exp(sqrt(xr[i])) / (2 * sqrt(xr[i]))
print('inegral 1 linear = ', summ / qual)

summ = 0
for i in range(qual):
    summ += (exp(xr[i]) + exp(1 - xr[i])) / 2
print('inegral 1 sim = ', summ / qual)

print('=====================================================================')
# counting 2nd integral =========================================== 2222222

N = 0
n = 0

xr = [uni(0, pi / 2) for i in range(qual)]
yr = [uni(0, pi / 2) for i in range(qual)]
norma = pi / 2
for i in range(qual):
    if yr[i] < sin(xr[i]):
        N += 1
        n += 1
    else:
        N += 1

print('inegral 2 geometric = ', norma * norma * n / N)

summ = 0
c = 2 / pi
for i in range(qual):
    summ += sin(xr[i]) / c
示例#23
0
def gen(xy, e, c):
    return [(xy[0] + uni(-e, e), xy[1] + uni(-e, e)) for i in range(c)]
示例#24
0
from matplotlib.widgets import TextBox
import random
import math

initial_text = "0,0"


def distance(a: tuple, b: tuple):
    return math.sqrt((a[0] - b[0])**2 + (a[1] - b[1])**2)


if __name__ == '__main__':
    coords = ((1, 1), (2, 2))
    eps = 0.5
    count = 100
    points1 = [(coords[0][0] + uni(-eps, eps), coords[0][1] + uni(-eps, eps))
               for i in range(count)]
    points2 = [(coords[1][0] + uni(-eps, eps), coords[1][1] + uni(-eps, eps))
               for i in range(count)]

    p1 = random.choice(points1)
    p2 = random.choice(points2)

    plt.plot([x for x, y in points1 + points2],
             [y for x, y in points1 + points2], "ob")
    plt.plot([p1[0], p2[0]], [p1[1], p2[1]], 'og')

    for i in points1 + points2:
        to = p1 if distance(i, p1) < distance(i, p2) else p2
        plt.annotate('',
                     xy=to,
示例#25
0
ax = fig.add_subplot(111, projection='3d')

#  input x1
x1 = [0, 0, 1, 1, 1, 4, 0, 4]

#  input x2
x2 = [0, 1, 0, 1, 1, 0, 4, 4]

#  input x3
x3 = [0, 1, 1, 1, 0, 4, 4, 4]

#  expected output
y = [1, 1, 1, 1, 1, 0, 0, 0]

# Generating random weights
w1 = uni(-2.0, 3)
w2 = uni(-2.0, 3)
w3 = uni(-2.0, 3)

# Fixing bias to 1
w = 1

#Learning rate
lr = 0.01

output = []

flag = False
count = 1
k = np.linspace(-6, 6, 5)
m = np.linspace(-6, 6, num=5)
示例#26
0
	def randomParams():
		return [uni(0, sqwid), uni(0,sqhei)]
示例#27
0
    if sys.argv[1] != "random":
        for i in range(nb_body):
            attributes = f.readline().split()
            position = Vector2(float(attributes[0]), float(attributes[1]))
            velocity = speed_scale * Vector2(float(attributes[2]),
                                             float(attributes[3]))
            mass = float(attributes[4])
            color = (int(attributes[5]), int(attributes[6]),
                     int(attributes[7]))
            real_radius = float(attributes[8])
            draw_radius = float(attributes[9])
            b = Body(position, velocity, mass, color, real_radius, draw_radius)
            world.add(b)
    else:
        for i in range(nb_body):
            position = Vector2(uni(-200, 200), uni(-200, 200))
            velocity = Vector2(uni(-5, 5), uni(-5, 5))
            mass = uni(1, 50)
            color = (random.randrange(255), random.randrange(255),
                     random.randrange(255))
            real_radius = random.randrange(10)
            draw_radius = 2 * real_radius
            b = Body(position, velocity, mass, color, real_radius, draw_radius)
            world.add(b)

    f.close()

    #Permet de contrôler l'affichage des traçantes
    should_erase_background = True

    #simulator = Simulator(world, DummyEngine, DummySolver)
示例#28
0
	def randomPlace(self):
		return uni(0, self.totalWidth()), uni(0, self.totalHeight())
示例#29
0
for epoch in range(epochs):

    if (lookup):
        break

    if (training_mode):

        noise1Array = []
        noise2Array = []
        discriminatorLossesArray = []
        generatorLossesArray = []
        seedsArray = []

        for batch in range(len(training_loader)):

            seedsArray.append(uni(0.0, 1.0))

            noise = noiseGenerator.generate(batchSize, channels,
                                            (noiseHeight, noiseWidth))
            noise1Array.append(noise)

            noise = noiseGenerator.generate(batchSize, channels,
                                            (noiseHeight, noiseWidth))
            noise2Array.append(noise)

            discriminatorIterationLosses = []

        for imageIndex, image in enumerate(training_loader, 0):

            if (imageIndex % tempDiscriminatorRatio == 0):
                random = uni(0.00, 1.00)
#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Generate and print float matrix of specified dimensions
# (first two arguments). The elements are separated by '\t'.
#
# Example usage:
#   ./random_matrix.py 4 5

import sys
from random import uniform as uni

for _ in range(0, int(sys.argv[1])):
    sys.stdout.write(
        '\t'.join([str(uni(0, 99))
                   for x in range(0, int(sys.argv[2]))]) + '\n')